code
stringlengths
2
1.05M
import _ from 'lodash' const DO_NOT_LOG = [ 'EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED' ] export default store => next => action => { const state = store.getState() if( (! _.includes( DO_NOT_LOG, action.type ) ) ) { console.info( 'Dispatching: ', action ) } let result = next( action ) if( ( ! _.includes( DO_NOT_LOG, action.type ) ) ) { console.log( 'Next State: ', store.getState() ) } return result }
'use strict'; var Batch = require("./batch.js"); var Tile = require("./tile.js"); var Rectangle = require("../math/rectangle.js"); /** * Map constructor * @param {Game} game reference to game object * @param {Number} x the x position of the map (default 0) * @param {Number} y the y position of the map (default 0) * @param {Number} w the width of this map (default 0) * @param {Number} h the height of this map (default 0) */ var Map = function(game, x, y, w, h) { // inherit from PIXI.particles.ParticleContainer //PIXI.particles.ParticleContainer.call(this); PIXI.Container.call(this); this.x = x || 0; this.y = y || 0; this.w = w || 0; this.h = h || 0; /** * @type {Game} */ this.game = game; /** * @type {Number} */ this.tilesize = game.settings.tilesize; /** * @type {Rectangle} */ this.rectangle = new Rectangle( this.x, this.y, this.w * (game.settings.tilesize * this.game.settings.scale), this.h * (game.settings.tilesize * this.game.settings.scale) ); /** * @type {Array} */ this.nodes = []; /** * @type {Batch} * NOTE: this should be removed eventually */ this.entities = new Batch(); }; // inherit PIXI.particles.ParticleContainer // Map.prototype = Object.create(PIXI.particles.ParticleContainer.prototype); // Map.prototype.constructor = Map; Map.prototype = Object.create(PIXI.Container.prototype); Map.prototype.constructor = Map; Map.prototype.initialize = function() { for(var y = 0; y < this.h; ++y) { this.nodes[y] = []; for(var x = 0; x < this.w; ++x) { var tile = new Tile(); var id = this.game.loader.resources["assets/image.json"].textures; if(y === 0 || y === this.h - 1 || x === 0 || x === this.w - 1) { tile.sprite = new PIXI.Sprite(id["blue.png"]); } else { tile.sprite = new PIXI.Sprite(id["pink.png"]); } tile.sprite.position.x = x * this.tilesize; tile.sprite.position.y = y * this.tilesize; this.addChild(tile.sprite); this.nodes[y][x] = tile; } } this.game.world.addChild(this); }; Map.prototype.addEntity = function(entity) { if (entity.hasComponent("position")) { var x = entity.getComponent("position").x; var y = entity.getComponent("position").y; entity.sprite.position.x = x * this.tilesize; entity.sprite.position.y = y * this.tilesize; this.nodes[y][x].addEntity(entity); } this.entities.addChild(entity.sprite); }; Map.prototype.removeEntity = function(x, y, entity) { this.entities.removeChild(entity.sprite); }; module.exports = Map;
//# sourceURL=addWarehouse.js $(function () { $('.layui-layer-btn0').addClass('btn-primary'); $('.layui-layer-btn1').addClass('btn-default').css('color','#FFFFFF'); $("#warehoseFrm").jValidate({ rules:{ warehouseName:{ required:true, minlength:1, maxlength:64, checkRepeat1:["/admin/goods/warehouse/checkName",'$value'] } } }); });
/** * * Loading Indicator * */ import React from 'react'; import './style.scss' function LoadingIndicator({post}) { return ( <div className="LoadingIndicator"> <div className="bounce1"></div> <div className="bounce2"></div> <div className="bounce3"></div> </div> ) } LoadingIndicator.propTypes = { } export default LoadingIndicator
'use strict'; var fs = require('fs'); module.exports = function (app) { // load all the other controllers in this directory fs.readdirSync(__dirname). filter(function (file) { return file !== "index.js" && (/.js$/).test(file); }). forEach(function (file) { var name = file.substr(0, file.indexOf('.')); require('./' + name)(app); }); // define our root controller app.get('/', function (req, res) { var allRoutes = []; for (var method in app.routes) { var methodRoutes = app.routes[method]; for (var i = 0; i < methodRoutes.length; i++) { var route = methodRoutes[i]; allRoutes.push(method.toUpperCase() + " " + route.path); } } res.send({ routes: allRoutes }); }); };
import fs from 'fs'; import RBAC from 'rbac'; import extend from 'node.extend'; import defaultOptions from './options'; import Router from './router'; import App from './app'; import Secure from './secure'; import Models from './models'; import debug from 'debug'; import domain from 'domain'; import { EventEmitter } from 'events'; import ok from 'okay'; import { each } from 'async'; const log = debug('maglev:server'); const portOffset = parseInt(process.env.NODE_APP_INSTANCE || 0, 10); function walk(path, fileCallback, callback) { fs.readdir(path, ok(callback, (files) => { each(files, (file, cb) => { const newPath = path + '/' + file; fs.stat(newPath, ok(cb, (stat) => { if (stat.isFile()) { if (/(.*)\.(js$|coffee$)/.test(file)) { const model = require(newPath); return fileCallback(model, newPath, file, cb); } } else if (stat.isDirectory()) { return walk(newPath, fileCallback, cb); } cb(); })); }, callback); })); } export default class Server extends EventEmitter { constructor(options, callback) { super(); if (!callback) { throw new Error('Please use callback for server'); } options = extend(true, {}, defaultOptions, options); if (!options.db) { throw new Error('Db is not defined'); } this._options = options; this._db = options.db; this.catchErrors(() => { this.init(options, callback); }); } handleError(err) { log(err); this.emit('err', err); this.closeGracefully(); } catchErrors(callback) { const dom = domain.create(); dom.id = 'ServerDomain'; dom.on('error', (err) => this.handleError(err)); try { dom.run(callback); } catch (err) { process.nextTick(() => this.handleError(err)); } } init(options, callback) { // catch system termination const signals = ['SIGINT', 'SIGTERM', 'SIGQUIT']; signals.forEach((signal) => { process.on(signal, () => this.closeGracefully()); }); // catch PM2 termination process.on('message', (msg) => { if (msg === 'shutdown') { this.closeGracefully(); } }); this._rbac = new RBAC(options.rbac.options, ok(callback, () => { this._router = new Router(options.router); // router is used in app this._models = new Models(this, options.models); // models is used in secure this._secure = new Secure(this); this._app = new App(this, options); this._loadRoutes(ok(callback, () => { this._loadModels(ok(callback, () => { callback(null, this); })); })); })); } notifyPM2Online() { if (!process.send) { return; } // after callback process.nextTick(function notify() { process.send('online'); }); } get options() { return this._options; } get rbac() { return this._rbac; } get db() { return this._db; } get secure() { return this._secure; } get app() { return this._app; } get router() { return this._router; } get models() { return this._models; } listen(callback) { if (!callback) { throw new Error('Callback is undefined'); } if (this._listening) { callback(new Error('Server is already listening')); return this; } this._listening = true; const options = this.options; this.app.listen(options.server.port + portOffset, options.server.host, ok(callback, () => { log(`Server is listening on port: ${this.app.httpServer.address().port}`); this.notifyPM2Online(); callback(null, this); })); return this; } close(callback) { if (!callback) { throw new Error('Callback is undefined'); } if (!this._listening) { callback(new Error('Server is not listening')); return this; } this._listening = false; this.app.close(callback); return this; } closeGracefully() { log('Received kill signal (SIGTERM), shutting down gracefully.'); if (!this._listening) { log('Ended without any problem'); process.exit(0); return; } let termTimeoutID = null; this.close(function closeCallback(err) { if (termTimeoutID) { clearTimeout(termTimeoutID); termTimeoutID = null; } if (err) { log(err.message); process.exit(1); return; } log('Ended without any problem'); process.exit(0); }); const options = this.options; termTimeoutID = setTimeout(function timeoutCallback() { termTimeoutID = null; log('Could not close connections in time, forcefully shutting down'); process.exit(1); }, options.shutdown.timeout); } _loadModels(callback) { const models = this._models; const path = this.options.root + '/models'; walk(path, (model, modelPath, file, cb) => { try { log(`Loading model: ${modelPath}`); models.register(model); cb(); } catch (err) { log(`Problem with model: ${modelPath}`); cb(err); } }, ok(callback, () => { // preload all models models.preload(callback); })); } _loadRoutes(callback) { const router = this.router; const path = this.options.root + '/routes'; walk(path, (route, routePath, file, cb) => { try { log(`Loading route: ${routePath}`); const routeFn = route.default ? route.default : route; routeFn(router); cb(); } catch (err) { log(`Problem with route: ${routePath}`); cb(err); } }, callback); } }
;(function() { "use strict"; angular.module('RDash') .service('commpropHTTP', ['$http', 'authService', function($http, authService) { this.add = function add(client) { return $http.post("/api/commprop", client); }; this.read = function read(criteria) { var criteria_ = criteria || { }; if (!criteria_.id) { return $http.get("/api/commprop", { params: criteria_ }); } if (criteria_.id) { return $http.get("/api/commprop/" + criteria.id); } }; this.remove = function remove(client) { return $http.delete("/api/commprop/" + client.id); }; this.update = function update(client) { return $http.put("/api/commprop/" + client.id, client); }; }]); })();
/** * Created by Nobay on 28/06/2017. */ var compareTo = function() { return { require: "ngModel", scope: { otherModelValue: "=compareTo" }, link: function(scope, element, attributes, ngModel) { ngModel.$validators.compareTo = function(modelValue) { return modelValue === scope.otherModelValue; }; scope.$watch("otherModelValue", function() { ngModel.$validate(); }); } }; }; retail.directive("compareTo", compareTo);
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { bindRoutineCreators } from 'redux-saga-routines'; import { createStructuredSelector } from 'reselect'; import { push } from 'react-router-redux'; import { ThemeProvider } from 'styled-components'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import loadTheme from 'utils/theme'; import { ImmutableLoadingBar as LoadingBar } from 'react-redux-loading-bar'; import Header from 'components/Header'; import SidebarLeft from 'components/SidebarLeft'; import Navigation from 'components/Navigation'; import SidebarRight from 'components/SidebarRight'; import AppError from 'components/AppError'; import AppInfo from 'components/AppInfo'; import Alert from 'components/Alert'; import { breakpoints } from 'utils/variables'; import { deleteSession } from 'hocs/Session/routines'; import { makeSelectToken } from 'hocs/Session/selectors'; import currentUser from 'hocs/CurrentUser'; import { toggleSidebarLeft, toggleSidebarRight, hideAppError, hideAppInfo, reloadAndUpdateVersion } from './actions'; import { makeSelectShowSidebarLeft, makeSelectSidebarRight, makeSelectAppError, makeSelectAppInfo, makeSelectPrinting, makeSelectCurrentVersion, makeSelectLatestVersion, } from './selectors'; import { Container, AppWrapper, MainContentWrapper } from './Wrappers'; const muiTheme = getMuiTheme(loadTheme('medi')); const gridStyledTheme = { breakpoints, }; @currentUser export class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { current: true, }; } componentWillUpdate() { const { version, latestVersion } = this.props; if (version && this.state.current) { const shouldForceRefresh = semverGreaterThan(latestVersion, version); if (shouldForceRefresh) { this.setState({ current: false }); } } } componentDidUpdate(prev) { if (prev.version !== this.props.version && this.props.version === this.props.latestVersion) { try { if (caches) { // Service worker cache should be cleared with caches.delete() caches.keys().then((names) => { // eslint-disable-next-line no-restricted-syntax for (const name of names) caches.delete(name); }); } } catch (error) { // probably ie bugs here // eslint-disable-next-line no-console console.log(error); } window.location.reload(true); } } render() { const isLoggedIn = !!this.props.token; return ( <MuiThemeProvider muiTheme={muiTheme}> <ThemeProvider theme={gridStyledTheme}> <section> <LoadingBar style={{ backgroundColor: muiTheme.palette.accent1Color }} /> <Container> <AppWrapper className="app-wrapper"> { isLoggedIn && <Header toggleSidebarLeft={this.props.toggleSidebarLeft} changeRoute={this.props.changeRoute} currentPath={this.props.location.pathname} deleteSession={this.props.deleteSession.trigger} printing={this.props.printing} isAdmin={this.props.isAdmin} isSuperAdmin={this.props.isSuperAdmin} isTeamleader={this.props.isTeamleader} location={this.props.location} username={this.props.username} reloadAndUpdateVersion={this.props.reloadAndUpdateVersion} version={this.props.version} /> } <main> { this.props.showSidebarLeft && <SidebarLeft toggleSidebarLeft={this.props.toggleSidebarLeft}> <Navigation changeRoute={this.props.changeRoute} currentPath={this.props.location.pathname} isAdmin={this.props.isAdmin} isMobile /> </SidebarLeft> } <MainContentWrapper className="mainContent">{React.Children.toArray(this.props.children)}</MainContentWrapper> { !this.state.current && this.props.token && <Alert msg="Die Applikation wird in 5 Sekunden aktualisiert" time={5000} type={'info'} onClose={this.props.reloadAndUpdateVersion} /> } { this.props.sidebarRight.show && <SidebarRight toggleSidebarRight={this.props.toggleSidebarRight} name={this.props.sidebarRight.name} /> } </main> <AppError appError={this.props.appError} hideAppError={this.props.hideAppError} /> <AppInfo appInfo={this.props.appInfo} hideAppInfo={this.props.hideAppInfo} /> </AppWrapper> </Container> </section> </ThemeProvider> </MuiThemeProvider> ); } } App.propTypes = { // properties children: PropTypes.node, isTeamleader: PropTypes.bool, isAdmin: PropTypes.bool, isSuperAdmin: PropTypes.bool, username: PropTypes.string, token: PropTypes.string, location: PropTypes.object.isRequired, showSidebarLeft: PropTypes.bool.isRequired, sidebarRight: PropTypes.object.isRequired, appError: PropTypes.object, appInfo: PropTypes.object, printing: PropTypes.bool.isRequired, version: PropTypes.string.isRequired, latestVersion: PropTypes.string, // actions changeRoute: PropTypes.func.isRequired, toggleSidebarLeft: PropTypes.func.isRequired, toggleSidebarRight: PropTypes.func.isRequired, hideAppError: PropTypes.func.isRequired, hideAppInfo: PropTypes.func.isRequired, reloadAndUpdateVersion: PropTypes.func.isRequired, // routines deleteSession: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ showSidebarLeft: makeSelectShowSidebarLeft(), sidebarRight: makeSelectSidebarRight(), appError: makeSelectAppError(), appInfo: makeSelectAppInfo(), printing: makeSelectPrinting(), token: makeSelectToken(), version: makeSelectCurrentVersion(), latestVersion: makeSelectLatestVersion(), }); function mapDispatchToProps(dispatch) { return { changeRoute: (url) => dispatch(push(url)), toggleSidebarLeft: bindActionCreators(toggleSidebarLeft, dispatch), toggleSidebarRight: bindActionCreators(toggleSidebarRight, dispatch), reloadAndUpdateVersion: bindActionCreators(reloadAndUpdateVersion, dispatch), hideAppError: bindActionCreators(hideAppError, dispatch), hideAppInfo: bindActionCreators(hideAppInfo, dispatch), ...bindRoutineCreators({ deleteSession }, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(App); // version from response - first param, local version second param const semverGreaterThan = (versionA, versionB) => { if (!versionA || !versionB) { return true; } const versionsA = versionA.split(/\./g); const versionsB = versionB.split(/\./g); while (versionsA.length || versionsB.length) { const a = Number(versionsA.shift()); const b = Number(versionsB.shift()); // eslint-disable-next-line no-continue if (a === b) continue; // eslint-disable-next-line no-restricted-globals return a > b || isNaN(b); } return false; };
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/dsb",[],(function(){var n=["znamuško","znamušce","znamuška","znamuškow"],e=["zapisk","zapiska","zapiski","zapiskow"],u=function(n,e){return 1===n?e[0]:2===n?e[1]:n>2&&n<=4?e[2]:n>=5?e[3]:void 0};return{errorLoading:function(){return"Wuslědki njejsu se dali zacytaś."},inputTooLong:function(e){var a=e.input.length-e.maximum;return"Pšosym lašuj "+a+" "+u(a,n)},inputTooShort:function(e){var a=e.minimum-e.input.length;return"Pšosym zapódaj nanejmjenjej "+a+" "+u(a,n)},loadingMore:function(){return"Dalšne wuslědki se zacytaju…"},maximumSelected:function(n){return"Móžoš jano "+n.maximum+" "+u(n.maximum,e)+"wubraś."},noResults:function(){return"Žedne wuslědki namakane"},searching:function(){return"Pyta se…"},removeAllItems:function(){return"Remove all items"}}})),n.define,n.require}();
/* app/views/partials/album.js * detail view for image galleries in photography and books */ 'use strict'; define([ 'jquery', 'backbone', 'underscore', 'tpl/jst', 'app/views/showcases/video', 'app/views/showcases/gallery', 'app/views/partials/filterviews', 'utils/spinner', 'slick', 'imagesLoaded' ], function( $, Backbone, _, TPL, V, G, FilterBar, Spinner ) { var TagRow = Backbone.View.extend({ tagName : 'li', className : 'row', template : TPL.tagLinks, tag : TPL.tag, render : function() { this.$el.html( this.template({ type : this.options.type }) ) this.options.tags.forEach( function(tag, index, tags) { this.$('#tagLinks').append( this.tag({ section : this.options.section, tag : tag.title, className : tag.className }) ) if ( index < tags.length -1 ) { this.$('#tagLinks').append( ', ' ) } }, this ) return this.el } }) var Details = Backbone.View.extend({ events : { 'click a' : function(e) { e.preventDefault() Backbone.dispatcher.trigger('navigate:section', e, this) } }, template : TPL.projectDetails, render : function(options) { this.$el.prepend( this.template({ htmlDate : this.model.get('htmlDate'), date : this.model.get('date').year(), title : this.model.get('title') }) ) if ( this.model.get('brand_tags').length ) { this.$('#tags') .append( new TagRow({ section : options.section, type : 'Brand', tags : this.model.get('brand_tags') }).render() ) } if ( this.model.get('industry_tags').length ) { this.$('#tags') .append( new TagRow({ section : options.section, type : 'Industry', tags : this.model.get('industry_tags') }).render() ) } if ( this.model.get('type_tags').length ) { this.$('#tags') .append( new TagRow({ section : options.section, type : 'Project Type', tags : this.model.get('type_tags') }).render() ) } } }) var Gallery = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'keyHandler', 'next', 'goToSlide') if ( !$('#slickCSS').length ) { var link = document.createElement("link"); link.id = 'slickCSS' link.type = "text/css"; link.rel = "stylesheet"; link.href = '/bower_components/slick-carousel/slick/slick.css' document.getElementsByTagName("head")[0].appendChild(link); } }, render : function() { // initialize custom version of slick slider with this.model.get('media') var media = this.model.get('media'), $chooseSlide, $dots, $dot if ( media.gallery ) { _.each(media.gallery.images, function(image, i) { var d = document.createElement('div'), img = new Image() img.src = image.url img.className = 'project-image' d.appendChild(img) this.$el.append(d) }, this) } if ( media.videos ) { if ( media.videos.single ) { var d = document.createElement('div') d.appendChild( new V({ model : new Backbone.Model(media.videos) }).render() ) this.$el.append(d) } else { _.each(media.videos, function(video, i) { var d = document.createElement('div'), showcase = document.createElement('div'), inner = document.createElement('div') showcase.className = 'showcase video' inner.innerHTML = video.embed showcase.appendChild(inner) d.appendChild(showcase) this.$el.append(d) }, this) } } if ( media.summary ) { var d = document.createElement('div'), summary = document.createElement('div') summary.innerHTML = media.summary summary.className = 'project-summary' d.appendChild(summary) d.id = 'summary' this.$el.append(d) } $('#showcaseContainer').imagesLoaded().progress(function(il, image) { image.img.parentElement.classList.add('is-ready') }) this.$el.slick({ dots : true, fade : true, draggable : false, appendArrows : '#controls', dotsClass : 'slick-dots project-dots', pauseOnHover : false, onInit : function(slider) { this.resizeHandler() this.galleryControls(slider) $dot = $('#dot') $dots = $('.slick-dots li') $chooseSlide = $('#chooseSlide') $('.project-controls').addClass('is-ready') $(window).on('resize', _.debounce(this.resizeHandler, 50, false)) $(window).on('keyup', this.keyHandler) $('.slick-track').on('click', '.slick-slide', this.next) }.bind(this), // force bind b/c slick binds this to the slick object onBeforeChange : function(s, i) { // ideally we should change the dropdown menu here // but we don't know which directin the gallery is moving }, onAfterChange : function(s, i) { $chooseSlide.val(i) $dot.animate({ left: $dots.eq(i).position().left }) if ( $dots.eq(i).hasClass('text-slide') ) { $dot.addClass('square') } else { $dot.removeClass('square') } } }) }, next : function() { this.$el.slickNext() }, goToSlide : function(e) { this.$el.slickGoTo( e.target.options.selectedIndex ) }, resizeHandler : function() { var targetHeight = $('#showcaseContainer').height(), $slickTarget = $('.slick-list') $slickTarget.height(targetHeight) $slickTarget.find('iframe').height(targetHeight) $slickTarget.find('.video').width(targetHeight / 0.5625) }, keyHandler : function(e) { var key = e.which if ( key === 39 ) { // right arrow this.$el.slickNext() } else if ( key === 37 ) { // left arrow this.$el.slickPrev() } else if ( key === 27 ) { // excape key this.trigger('close') } }, galleryControls : function(slider) { var $dot = $('<div/>').attr('id','dot').addClass('dot'), $controls = $('#controls'), $dropdown, $option, summaryIndex, s = document.getElementById('summary') if ( slider.slideCount > 40 ) { $('.slick-dots').hide() $dropdown = $('<select />', { id : 'chooseSlide' }).addClass('project-dropdown') for (var i = 0; i < slider.slideCount; i++) { $option = $('<option />').val(i).text(i+1) $dropdown.append($option) } $dropdown.change(this.goToSlide) $controls.prepend( $dropdown ).addClass('project-controls--nodots') } else { $('.slick-dots').append($dot).appendTo($controls) summaryIndex = $('.slick-slide').index(s) if ( summaryIndex !== -1 && !!s ) { $controls.find('.slick-dots li').eq(summaryIndex).addClass('text-slide') } } } }) var AlbumView = Backbone.View.extend({ className : 'detail viewer', tagName : "div", baseTmpl : TPL.viewer, initialize : function(ops) { _.bindAll( this, 'render', 'renderOut', 'onClose', 'goBack' ) this.section = ops.section this.$back = $('<button/>').attr({ id : 'back', class : 'detail-back' }).text('X') this.filterbar = new FilterBar({ el : '#filter-bar', collection : this.collection, parentSection : this.section }) }, render : function( urlTitle, hidden, previous ) { this.previous = previous ? $.deparam.fragment(previous.hash) : null $('body').addClass('detail-view') $('#nav').addClass('is-notvisible') $(document).on('click', '#back', this.goBack) this.$el.html( this.baseTmpl() ) this.$back.appendTo('.site-header') this.delegateEvents() if ( this.collection.length && !hidden ) { this.model = this.collection.findWhere({ 'url-title' : urlTitle }) setTimeout(this.renderOut, 0) } else { this.model.fetch({ url : '/api/' + this.section + '/' + urlTitle + ( hidden ? '/private' : '' ), success : this.renderOut }) } return this.el }, renderOut : function( model, response, ops ) { $('<p class="copyright" />') .text('Copyright ' + new Date().getFullYear() + ', Peter Arnell') .attr('id', 'copyright') .appendTo($('#details')) this.details = new Details({ el : this.$('#details').addClass('details--detail'), model : this.model }).render({ section : this.section }) this.viewer = new Gallery({ className : 'slideshow', model : this.model }).on('close', this.goBack) this.filterbar.render({ mixitup : false, previous : this.previous }) this.filterbar.delegateEvents() this.$('#showcaseContainer') .addClass('container--detail') .append(this.viewer.el) // can change in TPL $('#showcaseContainer').after($('#details')) if ( _.isEmpty(this.model.get('media')) ) { this.viewer.$el.html('<p>No media for this project</p>') } else { this.viewer.render({ model : this.model }) } this.trigger('rendered') }, onClose : function() { $(window).off('resize') $(window).off('keyup') $(document).off('click', '#back', this.goBack) $('body').removeClass('detail-view') $('#copyright').remove() $('#nav').removeClass('is-notvisible') this.filterbar.close() this.$back.remove() }, goBack : function(e) { if (e) { e.preventDefault() } if (this.previous) { history.go(-1) } else { Backbone.dispatcher.trigger( 'navigate:section', '/' + this.section ) } } }) return AlbumView })
/* eslint-disable no-underscore-dangle */ require('colors'); var fs = require('fs'); var Q = require('q'); var path = require('path'); var connect = require('connect'); var finalhandler = require('finalhandler'); var http = require('http'); var serveStatic = require('serve-static'); var tinylr = require('tiny-lr-fork'); var lr = require('connect-livereload'); var globWatch = require('glob-watcher'); var request = require('request'); var proxyMiddleware = require('proxy-middleware'); var url = require('url'); var xml2js = require('xml2js'); var Utils = require('./utils'); var events = require('./events'); var ports = require('./ports'); var log = require('./logging').logger; var Serve = module.exports; var lrServer; var runningServer; var DEFAULT_HTTP_PORT = 8100; var DEFAULT_LIVE_RELOAD_PORT = 35729; var IONIC_LAB_URL = '/ionic-lab'; var IONIC_ANGULAR_URL = '/angular.min.js'; Serve.listenForServerCommands = function listenForServerCommands(options) { var readline = require('readline'); process.on('SIGINT', function() { process.exit(); }); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); if (process.platform === 'win32') { rl.on('SIGINT', function() { process.emit('SIGINT'); }); } rl.setPrompt('ionic $ '); rl.prompt(); rl.on('line', function(entry) { if (entry === null) return; var input = (entry + '').trim(); if (input === 'quit' || input === 'q') rl.close(); if (input === null) return; input = (input + '').trim(); if (input === 'restart' || input === 'r') { Serve._goToUrl('/?restart=' + Math.floor((Math.random() * 899999) + 100000), options); } else if (input.indexOf('goto ') === 0 || input.indexOf('g ') === 0) { var url = input.replace('goto ', '').replace('g ', ''); Serve._goToUrl(url, options); } else if (input === 'consolelogs' || input === 'c') { options.printConsoleLogs = !options.printConsoleLogs; log.info('Console log output: ' + (options.printConsoleLogs ? 'enabled' : 'disabled')); if (options.printConsoleLogs) { events.removeAllListeners('consoleLog'); events.on('consoleLog', console.log); } else { events.removeAllListeners('consoleLog'); } Serve._goToUrl('/?restart=' + Math.floor((Math.random() * 899999) + 100000), options); } else if (input === 'serverlogs' || input === 's') { options.printServerLogs = !options.printServerLogs; log.info('Server log output: ' + (options.printServerLogs ? 'enabled' : 'disabled')); } else if (input.match(/^go\([+\-]?[0-9]{1,9}\)$/)) { Serve._goToHistory(input, options); } else if (input === 'help' || input === 'h') { Serve.printCommandTips(); } else if (input === 'clear' || input === 'clr') { process.stdout.write('\u001b[2J\u001b[0;0H'); } else { log.error('\nInvalid ionic server command'); Serve.printCommandTips(); } // log.debug('input: ', input); rl.prompt(); }).on('close', function() { if (options.childProcess) { log.info('Closing Gulp process'); options.childProcess.kill('SIGTERM'); } process.exit(0); }); }; // isIonicServer = true when serving www directory, false when live reload Serve.checkPorts = function(isIonicServer, testPort, testHost, options) { log.debug('Serve.checkports isIonicServer', isIonicServer, 'testPort:', testPort, 'testHost', testHost, 'options:', options); var q = Q.defer(); var message = []; if (!isIonicServer) { testHost = null; } log.debug('Testing port:', testPort, 'Testing host:', testHost); ports.getPort({ port: testPort, host: testHost }, function(err, port) { if (err) { return q.reject(err); } if (port !== testPort) { message = ['The port ', testPort, ' was taken on the host ', options.address, ' - using port ', port, ' instead'].join(''); log.warn(message); if (isIonicServer) { options.port = port; } else { options.liveReloadPort = port; } } q.resolve(); }); return q.promise; }; // argv should be parsed out and put into a nice hash before getting here. Serve.loadSettings = function loadSettings(argv, project) { var errorMessage; if (!argv) { errorMessage = 'Serve.loadSettings - You must pass proper arguments to load settings from'; throw new Error(errorMessage); } if (!project) { errorMessage = 'Serve.loadSettings - You must pass a project object to pull out ' + 'project specific settings from'; throw new Error(errorMessage); } var options = {}; options.port = options.port || argv.port || argv.p || DEFAULT_HTTP_PORT; options.liveReloadPort = options.liveReloadPort || argv.livereloadport || argv.r || argv['livereload-port'] || argv.i || DEFAULT_LIVE_RELOAD_PORT; options.launchBrowser = !argv.nobrowser && !argv.b; options.launchLab = options.launchBrowser && (argv.lab || argv.l); options.runLivereload = !(argv.nolivereload || argv.d); options.mockCordova = !(argv.nocordovamock || argv.m); var noProxyFlag = argv.noproxy || argv.x || false; var proxies = project.get('proxies') || []; if (!noProxyFlag && proxies.length > 0) { options.useProxy = true; options.proxies = proxies; } else { options.useProxy = false; options.proxies = []; } options.watchSass = project.get('sass') === true && !argv.nosass && !argv.n; options.browser = argv.browser || argv.w || ''; options.browserOption = argv.browserOption || argv.o || ''; options.platform = argv.platform || argv.t || null; // Check for default browser being specified options.defaultBrowser = argv.defaultBrowser || argv.f || project.get('defaultBrowser'); if (options.defaultBrowser) { project.set('defaultBrowser', options.defaultBrowser); project.save(); } options.browser = options.browser || options.defaultBrowser; options.watchPatterns = project.get('watchPatterns') || ['www/**/*', '!www/lib/**/*']; options.printConsoleLogs = argv.consolelogs || argv['console-logs'] || argv.c; options.printServerLogs = argv.serverlogs || argv['server-logs'] || argv.s; options.isAddressCmd = argv._[0].toLowerCase() === 'address'; options.documentRoot = project.get('documentRoot') || 'www'; options.createDocumentRoot = project.get('createDocumentRoot') || null; options.contentSrc = path.join(options.documentRoot, Utils.getContentSrc(options.documentRoot)); if (argv.v2) { options.livereloadOptions = { livereload: path.resolve(path.join(__dirname, '/assets/livereload.js')) }; options.v2 = true; } return options; }; Serve.printCommandTips = function() { log.info('Ionic server commands, enter:'); log.info(' restart'.cyan + ' or ' + 'r'.cyan + ' to restart the client app from the root'); log.info(' goto'.cyan + ' or ' + 'g'.cyan + ' and a url to have the app navigate to the given url'); log.info(' consolelogs'.cyan + ' or ' + 'c'.cyan + ' to enable/disable console log output'); log.info(' serverlogs'.cyan + ' or ' + 's'.cyan + ' to enable/disable server log output'); log.info(' quit'.cyan + ' or ' + 'q'.cyan + ' to shutdown the server and exit'); log.info(''); }; Serve.openBrowser = function openBrowser(options) { if (options.launchLab || options.launchBrowser) { var open = require('open'); var openUrl = options.launchLab ? [Serve.host(options.address, options.port), IONIC_LAB_URL] : [Serve.host(options.address, options.port)]; if (options.browserOption) { openUrl.push(options.browserOption); } if (options.platform) { openUrl.push('?ionicplatform=', options.platform); } try { open(openUrl.join(''), options.browser); } catch (ex) { log.error('Error opening the browser - ', ex); } } }; Serve.checkForDocumentRoot = function checkForDocumentRoot(options) { if (!fs.existsSync(path.join(options.appDirectory, options.documentRoot))) { if (options.createDocumentRoot) { fs.mkdirSync(options.documentRoot); } else { log.info('"' + options.documentRoot + '" directory cannot be found. Please make ' + 'sure the working directory is an Ionic project.'); return false; } } return true; }; Serve.runLivereload = function runLivereload(options, app) { var q = Q.defer(); log.debug('Running Live Reload with options', options); try { if (!options.runLivereload) { q.resolve(); return q.promise; } // TODO - get file path with dir before it // EX They pass in /Users/joshbavari/Development/testing/facebooker // options.watchPatterns.forEach(function(watchPath, index) { // absoluteWatchPaths.push(path.join(options.appDirectory, watchPath)); // }); // log.debug('Absolute watch paths:', absoluteWatchPaths); var watcher = globWatch(options.watchPatterns); watcher.on('change', function(evt) { // TODO: Move prototype to Serve._changed Serve._changed(evt.path, options); }); var liveReloadPort = process.env.CONNECT_LIVE_RELOAD_PORT || options.liveReloadPort; options.liveReloadServer = Serve.host(options.address, liveReloadPort); lrServer = tinylr(options.livereloadOptions); lrServer.listen(liveReloadPort, function(err) { if (err) { q.reject(err); return Utils.fail('Unable to start live reload server:', err); } else { q.resolve(lrServer); } }); var connectLiveReload = lr({ port: liveReloadPort }); app.use(connectLiveReload); } catch (ex) { q.reject(ex); log.error('Live Reload failed to start, error: %s', ex, {}); throw ex; } return q.promise; }; Serve.setupProxy = function setupProxy(options, app) { if (options.useProxy) { for (var x = 0; x < options.proxies.length; x += 1) { var proxy = options.proxies[x]; var opts = url.parse(proxy.proxyUrl); if (proxy.proxyNoAgent) { opts.agent = false; } opts.rejectUnauthorized = !(proxy.rejectUnauthorized === false); app.use(proxy.path, proxyMiddleware(opts)); log.info('Proxy added:', proxy.path + ' => ' + url.format(proxy.proxyUrl)); } } }; Serve.startServer = function startServer(options, app) { options.devServer = Serve.host(options.address, options.port); log.debug('Starting server at host address - ' + options.devServer); var rootDirectory = path.join(options.appDirectory, options.documentRoot); // Serve up the www folder by default if (options.printConsoleLogs) { events.on('consoleLog', console.log); } else { events.removeAllListeners('consolelog'); } var serve = serveStatic(rootDirectory); // Create static server var server = http.createServer(function(req, res) { var done = finalhandler(req, res); var urlParsed = url.parse(req.url, true); var platformOverride = urlParsed.query && urlParsed.query.ionicplatform; var platformUrl = getPlatformUrl(req); if (options.mockCordova && platformUrl) { var platformWWW = path.join(options.appDirectory, getPlatformWWW(req)); if (options.isPlatformServe) { fs.readFile(path.resolve(path.join(platformWWW, platformUrl)), function(err, buf) { res.setHeader('Content-Type', 'application/javascript'); if (err) { res.end('// mocked cordova.js response to prevent 404 errors during development'); if (req.url === '/cordova.js') { Serve.serverLog(req, '(mocked)', options); } else { Serve.serverLog(req, '(Error ' + platformWWW + ')', options); } } else { Serve.serverLog(req, '(' + platformWWW + ')', options); res.end(buf); } }); } else { Serve.serverLog(req, '(mocked)', options); res.setHeader('Content-Type', 'application/javascript'); res.end('// mocked cordova.js response to prevent 404 errors during development'); } return; } if (options.printConsoleLogs && req.url === '/__ionic-cli/console') { Serve.consoleLog(req); res.end(''); return; } if (req.url === IONIC_LAB_URL) { var previewTemplate = options.v2 ? 'v2preview.html' : 'preview.html'; // Serve the lab page with the given object with template data function labServeFn(context) { // eslint-disable-line no-inner-declarations fs.readFile(path.resolve(path.join(__dirname, 'assets/' + previewTemplate)), function(err, buf) { var html; if (err) { res.end('404'); } else { html = buf.toString('utf8'); html = html.replace('//INSERT_JSON_HERE', 'var BOOTSTRAP = ' + JSON.stringify(context || {})); } res.setHeader('Content-Type', 'text/html'); res.end(html); }); } // If the config.xml file exists, let's parse it for some nice features like // showing the name of the app in the title if (fs.existsSync('config.xml')) { fs.readFile(path.resolve('config.xml'), function(err, buf) { // eslint-disable-line handle-callback-err var xml = buf.toString('utf8'); xml2js.parseString(xml, function(err, result) { // eslint-disable-line handle-callback-err labServeFn({ appName: result.widget.name[0] }); }); }); } else { labServeFn(); } return; } if (req.url === IONIC_ANGULAR_URL) { fs.readFile(path.resolve(path.join(__dirname, 'assets/angular.min.js')), function(err, buf) { if (err) { res.end('404'); } var jsFile = buf.toString('utf8'); res.setHeader('Content-Type', 'application/javascript'); res.end(jsFile); }); return; } if (req.url.split('?')[0] === '/') { var contentPath = path.join(options.appDirectory, options.contentSrc); fs.readFile(contentPath, 'utf8', function(err, buf) { res.setHeader('Content-Type', 'text/html'); if (err) { Serve.serverLog(req, 'ERROR!', options); res.end(err.toString()); } else { Serve.serverLog(req, '(' + options.contentSrc + ')', options); var html = injectGoToScript(buf.toString('utf8')); if (options.printConsoleLogs) { html = injectConsoleLogScript(html); } if (platformOverride && !options.v2) { html = injectPlatformScript(html, platformOverride); } res.end(html); } }); return; } // root www directory file Serve.serverLog(req, null, options); serve(req, res, done); }); // Listen app.use(server); try { runningServer = app.listen(options.port, options.address); } catch (ex) { Utils.fail('Failed to start the Ionic server: ', ex.message); } log.info('√ Running dev server: ', options.devServer.cyan); }; Serve.start = function start(options) { if (!options) { throw 'You cannot serve without options.'; } try { var app = connect(); options.childProcess = null; if (!Serve.checkForDocumentRoot(options)) { return Q.reject('"' + options.documentRoot + '" directory cannot be found. Please make ' + 'sure the working directory is an Ionic project.'); } return Q.when() .then(function() { if (options.useProxy) { return Serve.setupProxy(options, app); } }) .then(function() { return Serve.runLivereload(options, app); }) .then(function() { if (options.runLivereload) { log.info('Running live reload server:', options.liveReloadServer.cyan); } log.info('Watching:', options.watchPatterns.join(', ').cyan); return Serve.startServer(options, app); }) .then(function() { if (options.launchBrowser) { Serve.openBrowser(options); } }) .catch(function(error) { log.error('Ionic serve failed - error: %s', error, {}); }); } catch (e) { var msg; if (e && (e + '').indexOf('EMFILE') > -1) { msg = (e + '\n') + 'The watch process has exceed the default number of files to keep open.\n' + 'You can change the default with the following command:\n\n' + ' ulimit -n 1000\n\n' + 'In the command above, it\'s setting the default to watch a max of 1000 files.\n\n'; } else { msg = ('server start error: ' + e.stack); } log.error(msg); throw msg; } }; Serve.showFinishedServeMessage = function showFinishedServeMessage(options) { Serve.printCommandTips(options); Serve.listenForServerCommands(options); }; Serve.serverLog = function(req, msg, options) { if (options.printServerLogs) { var log = 'serve '; log += (req.url.length > 60 ? req.url.substr(0, 57) + '...' : req.url); if (msg) { log += ' ' + msg; } var ua = (req.headers && req.headers['user-agent'] || ''); if (ua.indexOf('Android') > 0) { log += ' Android'.small; } else if (ua.indexOf('iPhone') > -1 || ua.indexOf('iPad') > -1 || ua.indexOf('iPod') > -1) { log += ' iOS'.small; } else if (ua.indexOf('Windows Phone') > -1) { log += ' Windows Phone'.small; } events.emit('serverlog', log); } }; Serve.consoleLog = function(req) { var body = ''; req.on('data', function(data) { if (data) body += data; }); req.on('end', function() { if (!body) return; try { var log = JSON.parse(body); var msg = log.index + ' '; while (msg.length < 5) { msg += ' '; } msg += ' ' + (log.ts + '').substr(7) + ' '; msg += log.method; while (msg.length < 24) { msg += ' '; } var msgIndent = ''; while (msgIndent.length < msg.length) { msgIndent += ' '; } if (log.method === 'dir' || log.method === 'table') { var isFirstLine = true; log.args.forEach(function(argObj) { for (var objKey in argObj) { if (isFirstLine) { isFirstLine = false; } else { msg += '\n' + msgIndent; } msg += objKey + ': '; try { msg += (JSON.stringify(argObj[objKey], null, 1)).replace(/\n/g, ''); } catch (e) { msg += argObj[objKey]; } } }); } else if (log.args.length) { if (log.args.length === 2 && log.args[0] === '%o' && log.args[1] === '[object Object]') return; msg += log.args.join(', '); } if (log.method === 'error' || log.method === 'exception') msg = msg.red; else if (log.method === 'warn') msg = msg.yellow; else if (log.method === 'info') msg = msg.green; else if (log.method === 'debug') msg = msg.blue; events.emit('consoleLog', msg); } catch (e) {} // eslint-disable-line no-empty }); }; function getPlatformUrl(req) { if (req.url === '/cordova.js' || req.url === '/cordova_plugins.js' || req.url.indexOf('/plugins/') === 0) { return req.url; } } function getPlatformWWW(req) { var platformPath = 'www'; if (req && req.headers && req.headers['user-agent']) { var ua = req.headers['user-agent'].toLowerCase(); if (ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1 || ua.indexOf('ipod') > -1) { platformPath = path.join('platforms', 'ios', 'www'); } else if (ua.indexOf('android') > -1) { platformPath = path.join('platforms', 'android', 'assets', 'www'); } } return platformPath; } function injectConsoleLogScript(html) { try { var findTags = html.match(/<html(?=[\s>])(.*?)>|<head>|<meta charset(.*?)>/gi); var insertAfter = findTags[findTags.length - 1]; /* eslint-disable max-len */ return html.replace(insertAfter, insertAfter + '\n\ <script>\n\ // Injected Ionic CLI Console Logger\n\ (function() {\n\ var methods = "assert clear count debug dir dirxml error exception group groupCollapsed groupEnd info log markTimeline profile profileEnd table time timeEnd timeStamp trace warn".split(" ");\n\ var console = (window.console=window.console || {});\n\ var logCount = 0;\n\ window.onerror = function(msg, url, line) {\n\ if (msg && url) console.error(msg, url, (line ? "Line: " + line : ""));\n\ };\n\ function sendConsoleLog(method, args) {\n\ try {\n\ var xhr = new XMLHttpRequest();\n\ xhr.open("POST", "/__ionic-cli/console", true);\n\ xhr.send(JSON.stringify({ index: logCount, method: method, ts: Date.now(), args: args }));\n\ logCount++;\n\ } catch(e){}\n\ }\n\ for(var x=0; x<methods.length; x++) {\n\ (function(m){\n\ var orgConsole = console[m];\n\ console[m] = function() {\n\ try {\n\ sendConsoleLog(m, Array.prototype.slice.call(arguments));\n\ if (orgConsole) orgConsole.apply(console, arguments);\n\ } catch(e){}\n\ };\n\ })(methods[x]);\n\ }\n\ }());\n\ </script>'); /* eslint-enable max-len */ } catch (e) {} // eslint-disable-line no-empty return html; } function injectGoToScript(html) { try { var findTags = html.match(/<html(?=[\s>])(.*?)>|<head>|<meta charset(.*?)>/gi); var insertAfter = findTags[findTags.length - 1]; return html.replace(insertAfter, insertAfter + '\n\ <script>\n\ // Injected Ionic Go To URL Live Reload Plugin\n\ window.LiveReloadPlugin_IonicGoToUrl = (function() {\n\ var GOTO_KEY = "__ionic_goto_url__";\n\ var HISTORY_GO_KEY = "__ionic_history_go__";\n\ var GoToUrlPlugin = function(window, host) {\n\ this.window = window;\n\ this.host = host;\n\ }\n\ GoToUrlPlugin.identifier = "__ionic_goto_url__";\n\ GoToUrlPlugin.version = "1.0";\n\ GoToUrlPlugin.prototype.reload = function(path) {\n\ try {\n\ if (path) {\n\ if (path.indexOf(GOTO_KEY) === 0) {\n\ this.window.document.location = path.replace(GOTO_KEY, "");\n\ return true;\n\ }\n\ if (path.indexOf(HISTORY_GO_KEY) === 0) {\n\ this.window.document.history.go( parseInt(path.replace(HISTORY_GO_KEY, ""), 10));\n\ return true;\n\ }\n\ }\n\ } catch(e) {\n\ console.log(e);\n\ }\n\ return false;\n\ };\n\ return GoToUrlPlugin;\n\ })();\n\ </script>'); } catch (e) {} // eslint-disable-line no-empty return html; } /** * Inject the platform override for choosing Android or iOS during * development. */ function injectPlatformScript(html, platformOverride) { try { var findTags = html.toLowerCase().indexOf('</body>'); if (findTags < 0) { return html; } return html.slice(0, findTags) + '\n' + '<script>\n' + 'ionic && ionic.Platform && ionic.Platform.setPlatform("' + platformOverride + '");\n' + '</script>\n' + html.slice(findTags); } catch (e) {} // eslint-disable-line no-empty return html; } Serve._changed = function(filePath, options) { // Cleanup the path a bit // var pwd = process.cwd(); var pwd = path.join(options.appDirectory); filePath = filePath.replace(pwd + '/', ''); if (filePath.indexOf('.css') > 0) { log.info('CSS changed: ' + filePath); } else if (filePath.indexOf('.js') > 0) { log.info('JS changed: ' + filePath); } else if (filePath.indexOf('.html') > 0) { log.info('HTML changed: ' + filePath); } else { log.info('File changed: ' + filePath); } Serve._postToLiveReload([filePath], options); }; Serve._goToUrl = function(url, options) { log.info('Loading: ' + url); Serve._postToLiveReload(['__ionic_goto_url__' + url], options); }; Serve._goToHistory = function(goHistory, options) { goHistory = goHistory.replace('go(', '').replace(')', ''); log.info('History Go: ' + goHistory); Serve._postToLiveReload(['__ionic_history_go__' + goHistory], options); }; Serve._postToLiveReload = function(files, options) { var postUrl = [options.liveReloadServer, '/changed'].join(''); request.post(postUrl, { path: '/changed', method: 'POST', body: JSON.stringify({ files: files }) }, function(err) { if (err) { log.error('Unable to update live reload: %s', err, {}); } }); }; Serve.getAddress = function(options) { var q = Q.defer(); try { var addresses = []; var os = require('os'); var ifaces = os.networkInterfaces(); var ionicConfig = require('./config').load(); var addressConfigKey = (options.isPlatformServe ? 'platformServeAddress' : 'ionicServeAddress'); var tryAddress; if (options.isAddressCmd) { // reset any address configs ionicConfig.set('ionicServeAddress', null); ionicConfig.set('platformServeAddress', null); } else if (!options.address) { tryAddress = ionicConfig.get(addressConfigKey); } else { tryAddress = options.address; } if (ifaces) { for (var dev in ifaces) { if (!dev) continue; ifaces[dev].forEach(function(details) { if (details && details.family === 'IPv4' && !details.internal && details.address) { addresses.push({ address: details.address, dev: dev }); } }); } } if (tryAddress) { if (tryAddress === 'localhost') { options.address = tryAddress; q.resolve(); return q.promise; } for (var x = 0; x < addresses.length; x += 1) { // double check if this address is still available if (addresses[x].address === tryAddress) { options.address = addresses[x].address; q.resolve(); return q.promise; } } if (options.address) { Utils.fail('Address ' + options.address + ' not available.'); return q.promise; } } if (addresses.length > 0) { if (!options.isPlatformServe) { addresses.push({ address: 'localhost' }); } if (addresses.length === 1) { options.address = addresses[0].address; q.resolve(); return q.promise; } log.info('\nMultiple addresses available.'); log.info('Please select which address to use by entering its number from the list below:'); if (options.isPlatformServe) { log.info('Note that the emulator/device must be able to access the given IP address'); } for (var y = 0; y < addresses.length; y += 1) { log.info((' ' + (y + 1) + ') ' + addresses[y].address + (addresses[y].dev ? ' (' + addresses[y].dev + ')' : ''))); } var prompt = require('prompt'); var promptProperties = { selection: { name: 'selection', description: 'Address Selection: ', required: true } }; // prompt.override = argv; prompt.message = ''; prompt.delimiter = ''; prompt.colors = false; prompt.start(); prompt.get({ properties: promptProperties }, function(err, promptResult) { if (err && err.message !== 'canceled') { log.debug('User prompted to select address - an error occured: %s', err, {}); q.reject(err); return log.error(err); } if (err && err.message === 'canceled') { log.info('Canceled by user'); process.exit(1); } var selection = promptResult.selection; for (var x = 0; x < addresses.length; x += 1) { if (parseInt(selection) === (x + 1) || selection === addresses[x].address || selection === addresses[x].dev) { options.address = addresses[x].address; if (!options.isAddressCmd) { log.info('Selected address: ' + options.address); } ionicConfig.set(addressConfigKey, options.address); prompt.resume(); q.resolve(); return q.promise; } } Utils.fail('Invalid address selection'); }); } else if (options.isPlatformServe) { // no addresses found Utils.fail('Unable to find an IPv4 address for run/emulate live reload.\nIs WiFi disabled or LAN disconnected?'); } else { // no address found, but doesn't matter if it doesn't need an ip address and localhost will do options.address = 'localhost'; q.resolve(); } } catch (e) { Utils.fail('Error getting IPv4 address: ' + e); } return q.promise; }; Serve.host = function host(address, port) { var platformName = require('os').platform(); if ((platformName.indexOf('win') !== -1 && platformName !== 'darwin') && (address === '0.0.0.0' || address.indexOf('0.0.0.0') !== -1)) { // Windows doesnt understand 0.0.0.0 - direct to localhost instead address = 'localhost'; } var hostAddress = ['http://', address, ':', port].join(''); return hostAddress; }; Serve.stopServer = function stopServer() { if (runningServer) { runningServer.close(); lrServer.close(); log.info('Server closed'); } else { log.info('Server not running'); } };
export const female = {"viewBox":"0 0 512 512","children":[{"name":"path","attribs":{"d":"M288,284c55.2-14.2,96-64.3,96-124c0-70.7-57.3-128-128-128S128,89.3,128,160c0,59.6,40.8,109.7,96,124v68h-64v64h64v64h64\r\n\tv-64h64v-64h-64V284z M256,240c-44.1,0-80-35.9-80-80s35.9-80,80-80s80,35.9,80,80S300.1,240,256,240z"},"children":[]}]};
import { Platform } from 'react-native'; import getPlatformElevationIos from '../getPlatformElevation.ios'; import getPlatformElevationAndroid from '../getPlatformElevation.android'; import { black } from '../colors'; const elevation = 4; const iOSResult = { shadowColor: black, shadowOpacity: 0.3, shadowRadius: elevation, shadowOffset: { height: 2, width: 0 }, zIndex: 1, }; describe('getPlatformElevation', () => { it('returns empty object if elevation is not legal', () => { // //////////// // ACT // //////////// const result = getPlatformElevationIos(0); // //////////// // ASSERTS // //////////// expect(result).toEqual({}); }); it('iOS', () => { // //////////// // ACT // //////////// const result = getPlatformElevationIos(elevation); // //////////// // ASSERTS // //////////// expect(result).toEqual(iOSResult); }); it('android', () => { // //////////// // ACT // //////////// const result = getPlatformElevationAndroid(elevation); // //////////// // ASSERTS // //////////// expect(result.elevation).toBe(elevation); }); });
const Lang = imports.lang; const GObject = imports.gi.GObject; const Gtk = imports.gi.Gtk; const StructureView = imports.StructureView; const Utils = imports.Utils; const MatchTreeView = new Lang.Class({ Name: 'MatchTreeView', Extends: Gtk.ScrolledWindow, _init: function(args) { this.parent(args); this.visible = true; this.hscrollbar_policy = Gtk.PolicyType.AUTOMATIC; this.vscrollbar_policy = Gtk.PolicyType.AUTOMATIC; this._structureview = new StructureView.StructureView(); this.add(this._structureview); Utils.forwardCall(this, this._structureview, 'setData'); Utils.forwardCall(this, this._structureview, 'onClick'); Utils.forwardCall(this, this._structureview, 'onHover'); }, });
function checkTriangle(t) { const a = +t[0], b = +t[1], c = +t[2]; return a + b > c && a + c > b && b + c > a } require('./helpers').getFile(3, input => { const validTriangles = input.split('\n').filter(line => { const [match, first, second, third] = line.match(/(\d+)\s+(\d+)\s+(\d+)/); return checkTriangle([first, second, third]) ; }); const validColumnTriangles = input.replace(/\n/g, '').match(/(\d+)/g).reduce((sides, side, i) => { sides.groupsOf3[i % 3].push(side); // Check every 3 triangles and add to final list if it is a triangle if (i % 9 == 8) { let validGroups = sides.groupsOf3.filter(checkTriangle); sides.triangles = sides.triangles.concat(validGroups); sides.groupsOf3 = [[], [], []]; } return sides; }, { triangles: [], groupsOf3: [[], [], []]}).triangles; console.log('Number of valid triangles:', validTriangles.length); // 993 console.log('Number of valid triangles in columns:', validColumnTriangles.length); // 1849 });
/** * @author chrsmlls333 */ // Cam var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var VIEW_ANGLE = 55; var ASPECT = WIDTH / HEIGHT; var NEAR = 1; var FAR = 5000; var statswitch = false; var statcontainer, stats; var controlswitch = false; var camera, controls, scene, renderer; var mesh, texture, geometry, material; var clock = new THREE.Clock( true ); noise.seed( Math.random() ); var amb = 0xdadada; var ambinv = 0x252525; var blk = 0x000000; //Grid Generation var structure; var siz = 100; //100 var numlines = 50; //50 var divisions = numlines; var grasslength = 260; //26 var grassangle = 30; //degrees //Motion var period = 6; var amp = 0.92; //reset var interval = 25; //seconds /////////////////////////////////////////////////////////////////// init(); animate(); /////////////////////////////////////////////////////////////////// function init() { renderer = new THREE.WebGLRenderer( { antialias: false, alpha: true } ); renderer.setClearColor( ambinv, 1); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.sortObjects = false; document.getElementById( 'canv' ).appendChild( renderer.domElement ); if (statswitch) { stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; statcontainer = document.getElementById( 'container' ); statcontainer.innerHTML = ""; statcontainer.appendChild( stats.domElement ); } window.addEventListener( 'resize', onWindowResize, false ); // camera/controls ///////////////////////////////////////////////////////////// scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR ); camera.position.set(0, 0, 25); camera.lookAt(new THREE.Vector3(0, 0, 0)); if (controlswitch) { controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.target.set( 0, 0, 0 ); controls.enabled = false; } // document.addEventListener( 'keydown', onKeyDown, false ); document.addEventListener( 'keyup', onKeyUp, false ); // objects /////////////////////////////////////////////////////////////////////// material = new THREE.LineBasicMaterial( { color: amb } ); structure = new THREE.LineSegments( createGeometry(), material ); structure.name = "struct"; structure.matrixAutoUpdate = false; scene.add( structure ); setInterval(reset, interval*1000); } function animate() { requestAnimationFrame( animate ); var time = clock.getElapsedTime(); var mult = amp * Math.exp(Math.sin( (Math.PI*2) * (time%period)/period )); var mult2 = (amp*0.5) * Math.cos( (Math.PI*2) * (time%period)/period ); structure.position.y = mult2; structure.position.z = mult; structure.updateMatrix(); renderer.render(scene, camera); if (controlswitch) controls.update(); if (statswitch) stats.update(); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function onKeyDown( event ) { }; function onKeyUp( event ) { switch( event.keyCode ) { case 82: // r reset(); break; case 68: // d console.log(scene); break; } }; function reset() { var selectedObject = scene.getObjectByName("struct"); var geo = createGeometry(); selectedObject.geometry.dispose(); selectedObject.geometry = geo; // var hue = Math.random(); // selectedObject.material.color.setHSL( hue, 0.6 , 0.47 ); selectedObject.updateMatrix(); console.log("reset!"); } function clear() { for( var i = scene.children.length - 1; i >= 0; i--) { scene.remove(scene.children[i]); } } function center2( geo ) { geo.computeBoundingBox() var c = new THREE.Vector3(); c.addVectors( geo.boundingBox.min, geo.boundingBox.max ); c.divideScalar(2); return c; } function createGeometry() { var geometry = new THREE.Geometry(); var p = new Array(); p[0] = new THREE.Vector3(Math.random()*-siz/2, Math.random()*-siz/2, 0); p[1] = new THREE.Vector3(Math.random()*-siz/2, Math.random()*siz/2, 0); p[2] = new THREE.Vector3(Math.random()*siz/2, Math.random()*-siz/2, 0); p[3] = new THREE.Vector3(Math.random()*siz/2, Math.random()*siz/2, 0); var lift = Math.tan(grassangle*Math.PI/180) * grasslength; for (var i = 0; i < numlines; ++i) { var temp1 = new THREE.Vector3(); temp1.lerpVectors(p[0], p[1], i/(numlines-1)); var temp2 = new THREE.Vector3(); temp2.lerpVectors(p[2], p[3], i/(numlines-1)); //Calc var vec = new THREE.Vector3(); vec.subVectors(temp1, temp2); var pPerp = new THREE.Vector3(); pPerp = vec.clone(); pPerp.applyAxisAngle(new THREE.Vector3(0,0,1), Math.PI/2); var blade = pPerp.normalize(); blade.multiplyScalar(grasslength); blade.add(new THREE.Vector3(0, 0, lift)); for (var u = 0; u < divisions; ++u) { var start = new THREE.Vector3(); var end = new THREE.Vector3(); start.lerpVectors(temp1, temp2, u/(divisions-1)); end.addVectors(start, blade); geometry.vertices.push( start ); geometry.vertices.push( end ); } } geometry.center(); return geometry; }
'use strict'; var fs = require('graceful-fs'); var sinon = require('sinon'); var errorfn = false; function maybeCallAsync(module, func) { var original = module[func]; return sinon.stub(module, func, function() { var args = Array.prototype.slice.call(arguments); args.unshift(module, func); var err = typeof errorfn === 'function' && errorfn.apply(this, args); if (!err) { original.apply(this, arguments); } else { arguments[arguments.length - 1](err); } }); } module.exports = { setError: function(fn) { errorfn = fn; }, chmodSpy: maybeCallAsync(fs, 'chmod'), fchmodSpy: maybeCallAsync(fs, 'fchmod'), futimesSpy: maybeCallAsync(fs, 'futimes'), statSpy: maybeCallAsync(fs, 'stat'), fstatSpy: maybeCallAsync(fs, 'fstat'), };
(function() { /* global process:false */ "use strict"; var STORAGE_LOCATION = '/tmp', DEFAULT_RECORD_NAME = '_-temporary', LOG_LOCATION = STORAGE_LOCATION + '/x-tmp-macro.log', TMP_RUN_FILE = '/tmp/x-tmp-macro.run', EXTENSION = 'x-tmp-macro', DEFAULT_DELAY_TIME = 12; var current_modifiers = []; var map_to_xdotool_script = function(current_line, delay) { var codify_line = function(line) { var modifiers = [ 'Shift_L', 'Control_L', 'Alt_L', 'Super_L', 'Hyper_L', 'Shift_R', 'Control_R', 'Alt_R', 'Super_R', 'Hyper_R', 'ISO_Level3_Shift' ]; var is_key_down = function(line) { return line.match(/^KeyStrPress/) ? true : false; }; var is_key_up = function(line) { return line.match(/^KeyStrRelease/) ? true : false; }; var get_key = function(line) { return line.split(' ')[1]; }; var is_modifier_key = function(key) { return (modifiers.indexOf(key) > -1) ? true : false; }; var filter_out_key = function(key, ar) { return ar.filter(function(mk) { if (mk != key) { return true; } return false; }); }; var key; key = get_key(line); if (!is_key_down(line) && !is_key_up(line)) { return false; } if (is_modifier_key(key)) { if (is_key_down(line)) { current_modifiers.push(key); } else { current_modifiers = filter_out_key(key, current_modifiers); } return false; } if (is_key_down(line)) { return { modifiers: JSON.parse(JSON.stringify(current_modifiers)), key: key }; } return false; }; var codified = codify_line(current_line); if (codified === false) { return ''; } var ks = codified.modifiers.concat([codified.key]); return 'xdotool key --clearmodifiers --delay ' + delay + ' ' + ks.join('+') + "\n"; }; var transform = function(method, delay) { if (delay === undefined) { delay = 1; } var current_line = ''; process.stdin.resume(); process.stdin.on('data', function(data) { var lines = data.toString().split("\n"), i, l; for (i=0, l=lines.length; i<l ; i++) { current_line = current_line + lines[i]; process.stdout.write( map_to_xdotool_script(current_line, delay) ); if (i !== lines.length-1) { current_line = ''; } } }); }; var print_help = function() { /* global console: false, __filename */ var help = [ "Usage:", " " + __filename.replace(/.*\//,'') + " create: Starts a xmacro recording process saving the temporary play.", " " + __filename.replace(/.*\//,'') + " transform [method] [delay]: Takes STDIN input from a `xmacrorec2` file and converts it into a series of `xdotool` statements which is outputted to STDOUT.", " " + __filename.replace(/.*\//,'') + " run [method] [name] [delay]: Reads a stored play, transforms the contents using `index.js transform` and runs it.", " " + __filename.replace(/.*\//,'') + " save [name]: Saves the temporary play into the play name specified." ].join("\n"); console.log(help); }; var construct_path_from_play_name = function(play_name) { if (play_name.indexOf('-') === -1) { play_name = '_-' + play_name; } return STORAGE_LOCATION + "/" + play_name + '.' + EXTENSION; }; var run = function(method, play_name, delay, next) { var commands = [ // 'killall xmacrorec2', 'cat PLAY_LOCATION | node THIS_SCRIPT transform METHOD DELAY > TMP_RUN_FILE', 'chmod +x TMP_RUN_FILE', 'TMP_RUN_FILE', //'rm TMP_RUN_FILE' ], fs = require('fs'); if (delay === undefined) { delay = DEFAULT_DELAY_TIME; } if (!fs.existsSync(construct_path_from_play_name(play_name))) { fs.writeFileSync( LOG_LOCATION, "your play_name (" + play_name + ") does not exist." ); return; } var mapper = function(lineTemplate) { var command = lineTemplate.replace( /PLAY_LOCATION/, construct_path_from_play_name(play_name) ); command = command.replace(/THIS_SCRIPT/, __filename); command = command.replace(/TMP_RUN_FILE/, TMP_RUN_FILE); command = command.replace(/DELAY/, delay); command = command.replace(/METHOD/, method); return command; }; var q = require('async').queue(function(command, next) { /* global __filename: false */ require('child_process').exec(command, function(err) { if (err) { fs.writeFileSync( LOG_LOCATION, "Command '" + command + "' exited with error " + err ); } return next(err); }); }); q.drain = function() { if (next !== undefined) { return next(null); } }; for (var i=0; i<commands.length; i++) { q.push(mapper(commands[i])); } }; var create = function(next) { var cmd = 'xmacrorec2 -k 127 > ' + construct_path_from_play_name(DEFAULT_RECORD_NAME); require('child_process').exec(cmd, function(err) { if (err) { return next(err); } next(null); }); }; var escapeRegExp = function(string){ return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); }; var save = function(play_name, cb) { var fs = require('fs'), tmp = STORAGE_LOCATION + "/" + DEFAULT_RECORD_NAME + '.' + EXTENSION; if (!fs.existsSync(tmp)) { if (cb !== undefined) { cb([1, "there is no tempoary play to save."]); } return; } var re = /^(([^-]{1,2})\-)?([a-zA-Z0-9 ]+)$/; if (!play_name.match(re)) { return cb([2, "Invalid play name (must match /^(([^-]{1,2})\\-)?([a-zA-Z0-9 ]+)$/)"]); } fs.writeFileSync( construct_path_from_play_name(play_name), fs.readFileSync(tmp) ); }; var get_position_argument = function(name, position, the_default, process_arguments) { var r = the_default, fs = require('fs'); if (process_arguments.length > position) { r = process_arguments[position]; } if (r.match(/\//)) { fs.writeFileSync( LOG_LOCATION, "your " + name + " (" + r + ") should not include a '/'." ); return; } return r; }; var escape_shell_arg = function(arg) { return '"'+arg.replace(/(["\s'$`\\])/g,'\\$1')+'"'; }; var ui_get_play_name = function(title, message, entry, next) { var cmd = 'zenity --entry --title="' + escape_shell_arg(title) + '" --text=" ' + escape_shell_arg(message) + ':" --entry-text "' + escape_shell_arg(entry) +'"'; var exec = require('child_process').exec; exec(cmd, function(e, stdout) { if (e) { return next(e); } return next(null, stdout.trim()); }); }; var ui_save = function(next) { ui_get_play_name('Name your Macro', 'Enter a name for your macro', 'New Macro Name', function(e, inp) { if (e) { return next(e); } if (!inp.trim()) { return next(null); } save(inp, next); }); }; var ui_list = function(title, message, next) { var items = require('fs').readdirSync(STORAGE_LOCATION).filter(function(n) { return n.match(new RegExp(escapeRegExp(EXTENSION) + '$')); }).map(function(n) { return n.replace(new RegExp("\\." + escapeRegExp(EXTENSION) + '$'), ''); }).filter(function(n) { return (n.split('-').length == 2); }).map(function(n) { if (n.split('-')[0] == '_') { n = n.substr(1); } return n.split('-').reverse(); }).sort(function(a, b) { return a.join('-') < b.join('-') ? -1 : 1; }); var exec = require('child_process').exec, cmd = 'zenity --list --separator="*" --title="' + title + '" --column="Name" --column="Shortcut" ' + items.map(function(item) { return item.map(escape_shell_arg).join(' '); }).join(' '); exec(cmd, function(e, stdout) { var items; if (e) { if (e.hasOwnProperty('killed') && (e.killed === false)) { return next(null, null); } return next(e); } items = stdout.trim().split('*'); return next(null, items.length ? items[0] : null); }); }; var resolve_play_description_to_filenames = function(play_name) { return require('fs').readdirSync(STORAGE_LOCATION).filter(function(n) { return n.match(new RegExp(EXTENSION + '$')); }).filter(function(n) { var resrc = escapeRegExp('-') + play_name + '\\.' + escapeRegExp(EXTENSION) + '$'; return n.match(new RegExp(resrc)); }).map(function(n) { return STORAGE_LOCATION + '/' + n; }); }; var ui_delete = function(title, message, next) { ui_list(title, message, function(e, item) { if (item === null) { return next(null); } var items = resolve_play_description_to_filenames(item); items.forEach(function(item) { require('fs').unlinkSync(item); }); return next(null); }); }; var ui_move = function(select_title, select_message, input_title, input_message, input_placeholder, next) { ui_list(select_title, select_message, function(e, item) { if (e) { return next(e); } if (item === null) { return next(null); } ui_get_play_name(input_title, input_message, input_placeholder, function(e, play_name) { if (e) { return next(e); } if (!play_name.trim()) { return next(null); } var items = resolve_play_description_to_filenames(item); items.forEach(function(item) { var fs = require('fs'); fs.writeFileSync( construct_path_from_play_name(play_name), item ); fs.unlinkSync(item); }); return next(null); }); }); }; var filename_to_play_name = function(filename) { return filename.replace(/.*\//, '').replace(new RegExp('\\.' + EXTENSION), ''); }; var ui_run = function(select_title, select_message, next) { ui_list(select_title, select_message, function(e, item) { if (e) { return next(e); } if (item === null) { return next(null); } var items = resolve_play_description_to_filenames(item); var done = false; items.forEach(function(item) { run('xdotool', filename_to_play_name(item), DEFAULT_DELAY_TIME, function() { if (done) { return; } done = true; return next(null); }); }); }); }; var get_play_name = get_position_argument.bind(this, 'play name', 4, DEFAULT_RECORD_NAME); var get_method_name = get_position_argument.bind(this, 'method', 3, 'xdotool'); var errorDisplay = function(e) { if (e) { require('child_process').exec('zenity --error --text=' + (escape_shell_arg(e[0] + ': ' + e[1])), function() {}); } }; var errorLog = function(e) { require('fs').writeFileSync( LOG_LOCATION, JSON.stringify(e) ); }; var ui_create = function(next) { create(function(e) { if (e) { return next(e); } ui_save(next); }); }; var operations; var ui_menu = function(title, col_header, next) { var exec = require('child_process').exec, cmd = 'zenity --list --separator="*" --title=' + escape_shell_arg(title) + ' --column=' + escape_shell_arg(col_header) + ' ' + 'Run Create Move Delete'; exec(cmd, function(e, stdout) { var item; if (e) { if (e.hasOwnProperty('killed') && (e.killed === false)) { return next(null, null); } return next(e); } item = stdout.trim().split('*').length ? stdout.trim().split('*').shift() : null; if (item === null) { return next(null); } operations['ui-' + item.toLowerCase()](next); }); }; operations = { transform: transform.bind(this, get_method_name(process.argv), get_play_name(process.argv)), create: create.bind(this, errorLog), run: run.bind(this, get_method_name(process.argv), get_play_name(process.argv)), save: save.bind(this, get_play_name(process.argv), function(e) { console.log(e.join(': ')); }), 'ui-save': ui_save.bind(this, errorDisplay), 'ui-list': ui_list.bind(this, 'These are your macros', '', errorDisplay), 'ui-delete': ui_delete.bind(this, 'Select an item to delete', '', errorDisplay), 'ui-move': ui_move.bind(this, 'Select item to move', '', 'To Where', 'To where do you want to move it', '', errorDisplay), 'ui-run': ui_run.bind(this, 'Select an item to run', 'To run an item select it from the list below', errorDisplay), 'ui-create': ui_create.bind(this, errorDisplay), 'ui-menu': ui_menu.bind(this, 'Main Menu', '', errorDisplay) }; var valid_operations = (function(operations) { var r = []; for (var k in operations) { if (operations.hasOwnProperty(k)) { r.push(k); } } return r; }(operations)); if ( valid_operations.indexOf(process.argv[2]) === -1) { print_help(); return; } operations[process.argv[2]].apply(this, process.argv.slice(5)); }());
var app = angular.module('c3ExportTest', [ 'ngC3Export' ]); app.run(function () { console.log("ngC3Export module test initiated"); }); app.controller("SimplePieChartController", function () { var chart = c3.generate({ bindto: "#simple-pie-chart", data: { type: 'pie', columns: [ ['sampledata0', 10], ['sampledata1', 30], ['sampledata2', 20], ['sampledata3', 40], ['sampledata4', 120] ] } }); }); app.controller("DynamicPieChartController", function ($timeout) { var chart = c3.generate({ bindto: "#my-pie-chart", data: { type: 'pie', columns: [ ['sample', 30], ['sample2', 200] ] } }); $timeout(function () { chart.load({ columns:[ ['sample', 30,10,12], ['sample2',10,12,31] ], type: 'bar' }); },5000); }); app.directive("dynamicChartExample", function() { return { scope: true, replace: true, template: '<div><h4>{{ chartTitle }}</h4><div id="chart-container"></div></div>', link: function (scope, element, attrs) { scope.chart = c3.generate({ bindto: "#chart-container", padding: { bottom: 150 }, data: { json:[], keys: { x: 'title', value: ["price"] }, type: 'bar' }, axis: { rotated: false, // horizontal bar chart x: { type: 'category', outer: true } }, legend: { show: false } }); }, controller: function ($scope, MarvelService, $interval) { var dateDescriptors = MarvelService.dateDescriptors; $scope.chartTitle = MarvelService.getTitle(); loadComics(); var intervalPromise = $interval(function (i) { if(i == 15) { $interval.cancel(intervalPromise); } var currentDateDescriptorIndex = (i-1)% dateDescriptors.length; MarvelService.setCurrentDateDescriptor(dateDescriptors[currentDateDescriptorIndex]); $scope.chartTitle = MarvelService.getTitle(); loadComics(); },2500); $scope.$on("$destroy", function () { if(intervalPromise){ $interval.cancel(intervalPromise); } }); function loadComics(){ MarvelService.getComics().then(function (comics) { $scope.chart.load({ data: comics}); }); } } }; }); app.directive("lineChartExample", function() { return { scope: true, replace: true, template: '<div></div>', link: function (scope, element, attrs) { scope.chart = c3.generate({ bindto: element[0], data: { columns: [ ['sample', 30, 200, 12, 56, 123, 10, 11, 34, 245, 76] ] }, regions: [ {start: 0, end: 1}, {start: 2, end: 4, class: 'foo'} ] }); } }; }); app.directive("combinationChartExample", function() { return { scope: true, replace: true, template: '<div></div>', link: function (scope, element, attrs) { scope.chart = c3.generate({ bindto: element[0], data: { columns: [ ['data1', 30, 20, 50, 40, 60, 50], ['data2', 200, 130, 90, 240, 130, 220], ['data3', 300, 200, 160, 400, 250, 250], ['data4', 200, 130, 90, 240, 130, 220], ['data5', 130, 120, 150, 140, 160, 150], ['data6', 90, 70, 20, 50, 60, 120] ], type: 'bar', types: { data3: 'spline', data4: 'line', data6: 'area' }, groups: [ ['data1', 'data2'] ] } }); } }; }); app.factory("MarvelService", function ($http) { var dateDescriptors = ['thisWeek','lastWeek','thisMonth']; var topic = "Price of Marvel Comics"; var currentDateDescriptor = dateDescriptors[0]; var params = { orderBy:"title", limit:25, offset:0, noVariants: true, format: "comic" }; return { params: params, dateDescriptors: dateDescriptors, getTitle: function () { return topic + " " + currentDateDescriptor.replace("this", "this ").replace("last", "last "); }, setCurrentDateDescriptor: function (dsc) { currentDateDescriptor = dsc; }, getComics: function () { return $http({ type: "GET", url: "https://gateway.marvel.com/v1/public/comics?apikey=7dfa53fee28964c8c2c1b4cbe14ef610", params: generateParams() }) .then(function (result) { var comics = result.data.data.results; var transformedComics = comics.map(function (comic) { var transformedComic = { title: comic.title }; if (comic.prices.length == 1) { transformedComic.price = comic.prices[0].price; } else { transformedComic.price = 0; } return transformedComic; }); return transformedComics; }) } }; function generateParams(){ var newParams = angular.extend({ dateDescriptor: currentDateDescriptor },params); return newParams; } });
'use strict'; var jos = require('../'); var helpers = require('./helpers'); describe('parsing', function() { it('should abort if the root level item is neither an array or an object', function(done) { var json = 'hello world'; var stream = helpers.chunkedStream(json); stream.pipe(jos.parse()).on('error', function(err) { err.should.be.instanceof(Error); done(); }); }); it('should return a stream in object mode', function() { var json = 'hello world'; var stream = helpers.chunkedStream(json); stream.pipe(jos.parse())._readableState.objectMode.should.be.true(); }); });
require('colors') const numeral = require('numeral') const fs = require('fs') const path = require('path') const Table = require('cli-table') console.log() // const head = ['Project', '.swift', '.h .m', 'Swift LOC', 'Obj-C LOC'] const head = ['Project', '.swift', '.m', '.swift LOC', '.m LOC'] const table = new Table({ head: head, style: {compact: true} }) const data = [] const folders = require('./folders.json') folders.forEach(folder => { getStats(`${folder.path}`, folder.exclude) }) let totals = new Array(head.length).fill(0) data.forEach(row => { table.push(row) for(const index in row) { if(index != 0) { totals[index] += row[index] row[index] = numeral(row[index]).format('0,0') } } }) const totalFiles = totals[1] + totals[2] const totalLines = totals[3] + totals[4] const swiftPercent = numeral(totals[1] / totalFiles).format('0.0 %').bold.green const objPercent = numeral(totals[2] / totalFiles).format('0.0 %').bold.red totals = totals.map(total => { return `${numeral(total).format('0,0')}`.bold.black }) totals[0] = '' table.push(totals) table.push(['', swiftPercent, objPercent, '', '']) console.log(table.toString()) console.log() function getStats(directory, exclude = []) { const basename = path.basename(directory) const files = walkSync(directory, [], exclude) // const HFiles = files.filter( file => path.extname(file) == ".h" ) const MFiles = files.filter( file => { return path.extname(file) == ".m" && path.basename(file) != "main.m" } ) const SwiftFiles = files.filter( file => path.extname(file) == ".swift" ) let ObjectiveCLines = 0 // HFiles.forEach(file => { ObjectiveCLines += getLOC(file) }) MFiles.forEach(file => { ObjectiveCLines += getLOC(file) }) let SwiftLines = 0 SwiftFiles.forEach(file => { SwiftLines += getLOC(file) }) // console.log(basename.black.bold) // console.log(`Objective-C: ${HFiles.length + MFiles.length} Files, ${numeral(ObjectiveCLines).format('0,0')} LOC`.blue) // console.log(`Swift: ${SwiftFiles.length} Files, ${numeral(SwiftLines).format('0,0')} LOC`.cyan) // data.push([basename, SwiftFiles.length, HFiles.length + MFiles.length, SwiftLines, ObjectiveCLines]) data.push([basename, SwiftFiles.length, MFiles.length, SwiftLines, ObjectiveCLines]) } function getLOC(file) { // https://www.andrewzammit.com/blog/node-js-splitcount-number-of-lines-unicode-compatible/ const code = fs.readFileSync(file, 'utf8') const lines = code.toString('utf8').split(/\r\n|[\n\r\u0085\u2028\u2029]/g).length - 1 return lines } function walkSync (dir, filelist = [], exclude) { fs.readdirSync(dir).forEach(file => { // console.log(file) const isExcluded = exclude.includes(file) if(! isExcluded) { const isDirectory = fs.statSync(path.join(dir, file)).isDirectory() filelist = isDirectory ? walkSync(path.join(dir, file), filelist, exclude) : filelist.concat(path.join(dir, file)) } }) return filelist } function getDirectories(directory) { return fs.readdirSync(directory).filter(file => fs.statSync(path.join(directory, file)).isDirectory()) }
var ModelDatabase = require('./ModelDatabase.js'); class BaseModel { static get(id) { var modelDatabase = new ModelDatabase(); return modelDatabase.get(this._collection(), id, this); } static update(id, data) { var modelDatabase = new ModelDatabase(); return modelDatabase.update(this._collection(), id, data); } static remove(id) { var modelDatabase = new ModelDatabase(); return modelDatabase.remove(this._collection(), id); } static insert(data) { var modelDatabase = new ModelDatabase(); return modelDatabase.insert(this._collection(), data); } static list() { var modelDatabase = new ModelDatabase(); return modelDatabase.list(this._collection(), this); } } module.exports = BaseModel;
import React from 'react' import { FormatMessage } from 'react-easy-intl' export default ({title, children, size}) => { const customSize = size ? `is-${size}` : null return ( <section className={`hero is-primary ${customSize} is-bold`}> <div className='hero-body'> <div className='container'> <h1 className='title'> <FormatMessage>{title}</FormatMessage> </h1> {children && <h2 className='subtitle'> <FormatMessage>{children}</FormatMessage> </h2>} </div> </div> </section> ) }
Meteor.publish('allRecipes', function (limit, search) { var myRegExp = new RegExp(".*", "i"); if (search && search !== '') myRegExp = new RegExp(".*" + search + ".*", "i"); return Recipe.find({ $and: [{ $or: [ {private: false}, {owner: this.userId} ] }, { $or: [ {_id: search}, {title: {$regex: myRegExp}}, {username: {$regex: myRegExp}}, {'ingredients.name': {$regex: myRegExp}}, ] }] }, {sort: {createdAt: -1}, limit: limit}); });
"use strict"; var _chai = require("chai"); var _observer = require("../../dst/observer.js"); var _observer2 = _interopRequireDefault(_observer); var _reactiveVar = require("reactive-var"); var _reactiveVar2 = _interopRequireDefault(_reactiveVar); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } describe('observer class', function () { var newNode = { v: new _reactiveVar2.default(0), c: {}, p: null }; var observer = new _observer2.default(); describe('initial state', function () { var observer = new _observer2.default(); it('should have an empty tree data cache', function () { _chai.assert.deepEqual(observer._collections, newNode); }); it('should have an empty tree observer cache', function () { _chai.assert.deepEqual(observer._observers, newNode); }); it('should have an empty observer cache', function () { _chai.assert.deepEqual(observer._observerCache, {}); }); }); describe('vertex initializer', function () { it('should assign a new node at branch K to parent P and return the new node', function () { var node = observer._node('test-branch', observer._collections); _chai.assert.deepEqual(node, { v: new _reactiveVar2.default(0), c: {}, p: observer._collections }); _chai.assert.deepEqual(observer._collections.c['test-branch'], node); }); it('should return an existing node if it exists, and not make a new one.', function () { var existing = observer._collections.c['test-branch']; _chai.assert.isDefined(existing); var node = observer._node('test-branch', observer._collections); _chai.assert.equal(node, existing); }); }); describe('query canonicalization', function () { var observer = new _observer2.default(); it('should accept queries only with a group field.', function () { var q1 = { group: "some-collection", query: { some: { query: 3456 } } }; var r1 = observer._canonicalize(q1); _chai.assert.notEqual(r1, null); var q2 = { group: "some-collection" }; var r2 = observer._canonicalize(q2); _chai.assert.notEqual(r2, null); var q3 = { query: { some: { query: 4567 } } }; var r3 = observer._canonicalize(q3); _chai.assert.equal(r3, null); }); var observer = new _observer2.default(); it('should create a group branch on both roots if !E', function () { var branch = "testing-branch"; var existing1 = observer._collections.c[branch]; var existing2 = observer._observers.c[branch]; _chai.assert.equal(existing1, undefined); _chai.assert.equal(existing2, undefined); var q = { group: branch, query: { some: { query: "bar" } } }; observer._canonicalize(q); var new1 = observer._collections.c[branch]; var new2 = observer._observers.c[branch]; _chai.assert.deepEqual(new1, { v: new _reactiveVar2.default(0), c: {}, p: observer._collections }); _chai.assert.deepEqual(new2, { v: new _reactiveVar2.default(0), c: { id: { v: new _reactiveVar2.default(0), c: {}, p: new2 } }, p: observer._observers }); }); it('should create an id branch on both roots if !E', function () { var id = "randomId"; var branch = 'testing-branch'; var existing1 = observer._collections.c[branch].c[id]; var existing2 = observer._observers.c[branch].c['id']; _chai.assert.equal(existing1, undefined); _chai.assert.deepEqual(existing2, { v: new _reactiveVar2.default(0), c: {}, p: observer._observers.c[branch] }); var q = { group: branch, id: id, query: { some: { query: "foo" } } }; observer._canonicalize(q); var new1 = observer._collections.c[branch].c[id]; var new2 = observer._observers.c[branch].c['id']; _chai.assert.deepEqual(new1, { v: new _reactiveVar2.default(0), c: {}, p: observer._collections.c[branch] }); _chai.assert.deepEqual(new2, { v: new _reactiveVar2.default(0), c: {}, p: observer._observers.c[branch] }); }); }); describe('merging', function () { var observer = new _observer2.default(); it('should splice structured data into the tree', function () { var e1 = { name: "bob", job: { years: 45, name: "woodworker", salary: { monthly: 4670, yearly: 4670 * 12 + 8000 } } }; observer.merge({ group: "employees", id: "42", query: e1 }); var e2 = { name: "rob", job: { years: 21, name: "technologist", salary: { monthly: 7069, yearly: 7069 * 12 + 16000 } } }; observer.merge({ group: "employees", id: "23", query: e2 }); var c = observer._collections.c['employees']; var bob = c.c['42']; _chai.assert.equal(bob.c.name.c, 'bob'); _chai.assert.equal(bob.c.job.c.years.c, 45); _chai.assert.equal(bob.c.job.c.name.c, 'woodworker'); _chai.assert.equal(bob.c.job.c.salary.c.monthly.c, 4670); _chai.assert.equal(bob.c.job.c.salary.c.yearly.c, 4670 * 12 + 8000); var rob = c.c['23']; _chai.assert.equal(rob.c.name.c, 'rob'); _chai.assert.equal(rob.c.job.c.years.c, 21); _chai.assert.equal(rob.c.job.c.name.c, 'technologist'); _chai.assert.equal(rob.c.job.c.salary.c.monthly.c, 7069); _chai.assert.equal(rob.c.job.c.salary.c.yearly.c, 7069 * 12 + 16000); }); it('should update the versions of all nodes upon being added.', function () { var c = observer._collections.c['employees']; var rob = c.c['23']; _chai.assert.equal(rob.v.v, 5); _chai.assert.equal(rob.c.name.v.v, 1); _chai.assert.equal(rob.c.job.v.v, 4); _chai.assert.equal(rob.c.job.c.years.v.v, 1); _chai.assert.equal(rob.c.job.c.name.v.v, 1); _chai.assert.equal(rob.c.job.c.salary.v.v, 2); _chai.assert.equal(rob.c.job.c.salary.c.monthly.v.v, 1); _chai.assert.equal(rob.c.job.c.salary.c.yearly.v.v, 1); }); it('should collapse a tree node\'s contents into the data from which it was derived.', function () { var node = observer._collections.c['employees']; var employees = observer._collapse(node); var e1 = { name: "bob", job: { years: 45, name: "woodworker", salary: { monthly: 4670, yearly: 4670 * 12 + 8000 } } }; var e2 = { name: "rob", job: { years: 21, name: "technologist", salary: { monthly: 7069, yearly: 7069 * 12 + 16000 } } }; _chai.assert.deepEqual(employees['42'], e1); _chai.assert.deepEqual(employees['23'], e2); }); }); });
/// <reference path="../_definitions.d.ts" /> define(["require", "exports"], function (require, exports) { exports.mimeTypes = { "*": "application/octet-stream", 323: "text/h323", acx: "application/internet-property-stream", ai: "application/postscript", aif: "audio/x-aiff", aifc: "audio/x-aiff", aiff: "audio/x-aiff", asf: "video/x-ms-asf", asr: "video/x-ms-asf", asx: "video/x-ms-asf", au: "audio/basic", avi: "video/x-msvideo", axs: "application/olescript", bas: "text/plain", bcpio: "application/x-bcpio", bmp: "image/bmp", c: "text/plain", cat: "application/vnd.ms-pkiseccat", cdf: "application/x-cdf", netcdf: "application/x-netcdf", cer: "application/x-x509-ca-cert", clp: "application/x-msclip", cmx: "image/x-cmx", cod: "image/cis-cod", cpio: "application/x-cpio", crd: "application/x-mscardfile", crl: "application/pkix-crl", crt: "application/x-x509-ca-cert", csh: "application/x-csh", css: "text/css", csv: "text/csv", dcr: "application/x-director", der: "application/x-x509-ca-cert", dir: "application/x-director", djv: "image/vnd.djvu", djvu: "image/vnd.djvu", dll: "application/x-msdownload", doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", dot: "application/msword", dvi: "application/x-dvi", dxr: "application/x-director", eot: "application/vnd.ms-fontobject", eps: "application/postscript", etx: "text/x-setext", evy: "application/envoy", fif: "application/fractals", flr: "x-world/x-vrml", flv: "video/x-flv", gif: "image/gif", gtar: "application/x-gtar", gz: "application/x-gzip", h: "text/plain", hdf: "application/x-hdf", hlp: "application/winhlp", hqx: "application/mac-binhex40", hta: "application/hta", htc: "text/x-component", htm: "text/html", html: "text/html", htt: "text/webviewhtml", ico: "image/x-icon", ief: "image/ief", iii: "application/x-iphone", ins: "application/x-internet-signup", isp: "application/x-internet-signup", jfif: "image/pipeg", jpe: "image/jpeg", jpeg: "image/jpeg", jpg: "image/jpeg", js: "application/javascript", json: "application/json", latex: "application/x-latex", lsf: "video/x-la-asf", lsx: "video/x-la-asf", m13: "application/x-msmediaview", m14: "application/x-msmediaview", m3u: "audio/x-mpegurl", man: "application/x-troff-man", mdb: "application/x-msaccess", me: "application/x-troff-me", mht: "message/rfc822", mhtml: "message/rfc822", mid: "audio/mid", mny: "application/x-msmoney", mov: "video/quicktime", movie: "video/x-sgi-movie", mp2: "video/mpeg", mp3: "audio/mpeg", mp4: "video/mp4", mpa: "video/mpeg", mpe: "video/mpeg", mpeg: "video/mpeg", mpg: "video/mpeg", mpp: "application/vnd.ms-project", mpv2: "video/mpeg", ms: "application/x-troff-ms", msg: "application/vnd.ms-outlook", mvb: "application/x-msmediaview", nc: "application/x-netcdf", nws: "message/rfc822", oda: "application/oda", odb: "application/vnd.oasis.opendocument.database", odc: "application/vnd.oasis.opendocument.chart", odf: "application/vnd.oasis.opendocument.formula", odg: "application/vnd.oasis.opendocument.graphics", odi: "application/vnd.oasis.opendocument.image", odm: "application/vnd.oasis.opendocument.text-master", odp: "application/vnd.oasis.opendocument.presentation", ods: "application/vnd.oasis.opendocument.spreadsheet", odt: "application/vnd.oasis.opendocument.text", ogg: "application/ogg", otg: "application/vnd.oasis.opendocument.graphics-template", otp: "application/vnd.oasis.opendocument.presentation-template", ots: "application/vnd.oasis.opendocument.spreadsheet-template", ott: "application/vnd.oasis.opendocument.text-template", p10: "application/pkcs10", p12: "application/x-pkcs12", p7b: "application/x-pkcs7-certificates", p7c: "application/x-pkcs7-mime", p7m: "application/x-pkcs7-mime", p7r: "application/x-pkcs7-certreqresp", p7s: "application/x-pkcs7-signature", pbm: "image/x-portable-bitmap", pdf: "application/pdf", pfx: "application/x-pkcs12", pgm: "image/x-portable-graymap", pko: "application/ynd.ms-pkipko", pma: "application/x-perfmon", pmc: "application/x-perfmon", pml: "application/x-perfmon", pmr: "application/x-perfmon", pmw: "application/x-perfmon", pnm: "image/x-portable-anymap", png: "image/png", pot: "application/vnd.ms-powerpoint", ppm: "image/x-portable-pixmap", pps: "application/vnd.ms-powerpoint", ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation", prf: "application/pics-rules", ps: "application/postscript", pub: "application/x-mspublisher", qt: "video/quicktime", ra: "audio/x-pn-realaudio", ram: "audio/x-pn-realaudio", ras: "image/x-cmu-raster", rgb: "image/x-rgb", rmi: "audio/mid", roff: "application/x-troff", rtf: "application/rtf", rtx: "text/richtext", scd: "application/x-msschedule", sct: "text/scriptlet", setpay: "application/set-payment-initiation", setreg: "application/set-registration-initiation", sh: "application/x-sh", shar: "application/x-shar", sit: "application/x-stuffit", snd: "audio/basic", spc: "application/x-pkcs7-certificates", spl: "application/futuresplash", src: "application/x-wais-source", sst: "application/vnd.ms-pkicertstore", stl: "application/vnd.ms-pkistl", stm: "text/html", sv4cpio: "application/x-sv4cpio", sv4crc: "application/x-sv4crc", svg: "image/svg+xml", swf: "application/x-shockwave-flash", t: "application/x-troff", tar: "application/x-tar", tcl: "application/x-tcl", tex: "application/x-tex", texi: "application/x-texinfo", texinfo: "application/x-texinfo", tgz: "application/x-compressed", tif: "image/tiff", tiff: "image/tiff", tr: "application/x-troff", trm: "application/x-msterminal", tsv: "text/tab-separated-values", ttf: "application/font-sfnt", txt: "text/plain", uls: "text/iuls", ustar: "application/x-ustar", vcf: "text/x-vcard", vrml: "x-world/x-vrml", wav: "audio/x-wav", wcm: "application/vnd.ms-works", wdb: "application/vnd.ms-works", webm: "video/webm", wks: "application/vnd.ms-works", wma: "audio/x-ms-wma", wmf: "application/x-msmetafile", wmv: "video/x-ms-wmv", woff: "application/font-woff", wps: "application/vnd.ms-works", wri: "application/x-mswrite", wrl: "x-world/x-vrml", wrz: "x-world/x-vrml", xaf: "x-world/x-vrml", xbm: "image/x-xbitmap", xla: "application/vnd.ms-excel", xlc: "application/vnd.ms-excel", xlm: "application/vnd.ms-excel", xls: "application/vnd.ms-excel", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlt: "application/vnd.ms-excel", xlw: "application/vnd.ms-excel", xml: "text/xml", xof: "x-world/x-vrml", xpm: "image/x-xpixmap", xul: "application/vnd.mozilla.xul+xml", xwd: "image/x-xwindowdump", z: "application/x-compress", zip: "application/zip" }; exports.separator = "/"; /** Get file name from its path */ function getFileName(path) { var regex = /[\/\\]?([^\/\\]*)$/; return regex.test(path) ? path.match(regex)[1] : ""; } exports.getFileName = getFileName; /** Get Extension from file name or path */ function getExtension(path) { var regex = /\.([^\.]*)$/; return regex.test(path) ? path.match(regex)[1] : null; } exports.getExtension = getExtension; /** Get mime-type from file name or path */ function getMimeType(path) { var extension = getExtension(path); return extension ? getMimeTypeByExtension(extension) : exports.mimeTypes["*"]; } exports.getMimeType = getMimeType; /** Get mime-type associated with specified extension */ function getMimeTypeByExtension(extension) { return exports.mimeTypes[extension.toLowerCase()] || exports.mimeTypes["*"]; } exports.getMimeTypeByExtension = getMimeTypeByExtension; /** Get path without file name */ function getDirectory(path) { var regex = /^(.*)[\/\\]([^\/\\]*)$/; return regex.test(path) ? path.match(regex)[1] : null; } exports.getDirectory = getDirectory; /** Get current directory name */ function getDirectoryName(path) { var regex = /([^\/\\]*)[\/\\]([^\/\\]*)$/; return regex.test(path) ? path.match(regex)[1] : null; } exports.getDirectoryName = getDirectoryName; /** Combine multiple path to create a single path */ function combine() { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i - 0] = arguments[_i]; } return paths.join(exports.separator).replace(/[\/\\]+/g, exports.separator); } exports.combine = combine; /** Simplify a path by removing .. and . */ function simplify(path) { var paths = path.split(/[\/\\]+/), index; while ((index = paths.indexOf("..")) !== -1) { paths.splice(index - 1, 2); } while ((index = paths.indexOf(".")) !== -1) { paths.splice(index, 1); } return paths.join(exports.separator); } exports.simplify = simplify; });
version https://git-lfs.github.com/spec/v1 oid sha256:5202b17d6702a599dbd5af63824950982f2b1cadefcb0054a14a0798db26b8db size 4478
define( [ 'libs/math', 'models/entity', 'models/mesh', 'graphics', 'models/scene' ], function( math, Entity, Mesh, graphics, scene ) { var dian3 = math.dian3; var MergeGroup = graphics.MergeGroup; var utils = graphics.utils; var world = scene.world; var groupDrawable = graphics.groupDrawable; var map = -1; var buildCreator = -1; var blockList = []; var blockData = []; var blockStatus = []; var lastPosition = -1; var lastPositionChecked = -1; //blocks // lb,rb,rt,lt - 0,1,2,3 - x,z //proceduralID - care var pointLineSegDist = function( v, w , p ) { // http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment var l2 = Math.pow( v[ 0 ] - w[ 0 ], 2 ) + Math.pow( v[ 1 ] - w[ 1 ], 2 ); if ( l2 < 0.0001 ) { return Math.sqrt( Math.pow( v[ 0 ] - p[ 0 ], 2 ) + Math.pow( v[ 1 ] - p[ 1 ], 2 ) ); } var t = ( ( p[ 0 ] - v[ 0 ] )*( w[ 0 ] - v[ 0 ] ) + ( p[ 1 ] - v[ 1 ] )*( w[ 1 ] - v[ 1 ] ) )/l2; if ( t < 0.0001 ) { return Math.sqrt( Math.pow( v[ 0 ] - p[ 0 ], 2 ) + Math.pow( v[ 1 ] - p[ 1 ], 2 ) ); } else if ( t > 1.000 ) { return Math.sqrt( Math.pow( w[ 0 ] - p[ 0 ], 2 ) + Math.pow( w[ 1 ] - p[ 1 ], 2 ) ); } var proj = [ v[ 0 ] + t*( w[ 0 ] - v[ 0 ] ), v[ 1 ] + t*( w[ 1 ] - v[ 1 ] ) ]; return Math.sqrt( Math.pow( proj[ 0 ] - p[ 0 ], 2 ) + Math.pow( proj[ 1 ] - p[ 1 ], 2 ) ); }; var Map = { R : 50, miniMap : true, miniMapInited : false, canvasDrawBackground : function() { var canvas = $( "#map" )[ 0 ]; var ctx = canvas.getContext( '2d' ); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect ( 0, 0, 199, 199 ); ctx.fillStyle = "rgb(0,200,0)"; for ( var i in map.blocks ) { if ( blockList[ i ] === true ) { ctx.fillStyle = "rgb(0,200,0)"; } else { ctx.fillStyle = "rgb(0,0,0)"; } var p0 = map.blocks[ i ]; ctx.beginPath(); ctx.moveTo( p0[ 0 ][ 0 ], p0[ 0 ][ 2 ] ); for ( var u = 1; u < 4; u++ ) { ctx.lineTo( p0[ u ][ 0 ], p0[ u ][ 2 ] ); } ctx.fill(); } }, canvasDrawPlayer : function( pos ) { var canvas = $( "#map" )[ 0 ]; var ctx = canvas.getContext( '2d' ); ctx.fillStyle = "rgb(0,0,200)"; ctx.beginPath(); ctx.arc( pos[ 0 ], pos[ 2 ], Map.R, 0, Math.PI*2, true ); ctx.stroke(); }, canvasInit : function() { $( "body" ).append( '<canvas id="map" width="200" height="200"></canvas>' ); $( "#map" ).css( { position : "absolute", 'z-index' : 9009, right : 0, top : 0 } ); Map.canvasDrawBackground(); }, canvasUpdate : function( pos ) { Map.canvasDrawBackground(); Map.canvasDrawPlayer( pos ); }, loadMap : function( jMap ) { //todo check format if ( typeof jMap !== "object" ) { return false; } map = jMap; if ( Map.miniMap && !Map.miniMapInited ) { Map.canvasInit(); Map.miniMapInited = true; } if ( lastPosition !== -1 ) { map.update( lastPosition ); } return true; }, buildCreator : function ( callback ) { buildCreator = callback; }, removeBlock : function( ind ) { for ( var u in blockData[ ind ] ) { blockData[ ind ][ u ].remove(); } return; }, addBlock : function( ind ) { Map.removeBlock( ind ); blockData[ ind ] = buildCreator( ind, map.blocks[ ind ] ); return; }, blockComplete : function( ind ) { blockStatus[ ind ] = false; //console.log( "block ", ind, "completed.Can be removed now." ); }, update : function( pos ) { lastPosition = pos; if ( map === -1 || buildCreator === -1 ) { //map undefined return; } //find all blocks in range var newList = []; var p1 = [], p2 = [], p0 = []; p0[ 0 ] = pos[ 0 ]; p0[ 1 ] = pos[ 2 ]; for ( var i in map.blocks ) { newList[ i ] = false; for ( var u = 0; u < 4; u++ ) { p1[ 0 ] = map.blocks[ i ][ u ][ 0 ] + 0; p1[ 1 ] = map.blocks[ i ][ u ][ 2 ] + 0; p2[ 0 ] = map.blocks[ i ][ ( u+1 ) % 4 ][ 0 ] + 0; p2[ 1 ] = map.blocks[ i ][ ( u+1 ) % 4 ][ 2 ] + 0; var d = pointLineSegDist( p2, p1, p0 ); if ( d < Map.R ) { newList[ i ] = true; } } } //cross check with old, to erase obsolete var toRemove = [] for ( var i in map.blocks ) { //old blockList - new newList if ( blockList[ i ] === true && newList[ i ] === false ) { if ( blockStatus[ i ] === false ) { toRemove.push( i ); } else { //add it to current list, to erase later on newList[ i ] = true; } } } //cross check to add new ones var toAdd = []; for ( var i in map.blocks ) { if ( newList[ i ] === true && ( blockList[ i ] === false || blockList.length == 0 ) ) { toAdd.push( i ); } } //make new list, old for ( var i in map.blocks ) { blockList[ i ] = newList[ i ]; } //remove buildings for ( var i in toRemove ) { console.log( "DML : remove block ", toRemove[ i ] ); Map.removeBlock( toRemove[ i ] ); } //add buildigns for ( var i in toAdd ) { console.log( "DML : add block ", toAdd[ i ] ); blockStatus[ toAdd[ i ] ] = true;//locked till completion //console.log( "block ", toAdd[ i ], "locked till completion." ); Map.addBlock( toAdd[ i ] ); } if ( Map.miniMap ) { //update mini map if ( !Map.miniMapInited ) { Map.canvasInit(); Map.miniMapInited = true; } Map.canvasUpdate( pos ); } } }; return Map; } );
'use strict'; module.exports = { app: { title: 'FilmTrackr', description: 'Tracking films used in film cameras.', keywords: 'film, analog, kodak, photography, agfa, leica, 35mm' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js' ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
Ext.define('Packt.model.staticData.Country', { extend: 'Packt.model.sakila.Sakila', idProperty: 'country_id', fields: [ { name: 'country_id' }, { name: 'country', defaultValue: 'New Country*'} ] });
/* rite a script that finds the maximal sequence of equal elements in an array. */ var array = [2, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 1], tmpBestStart = 0, tmpBestCount = 0, bestStart = 0, bestCount = 0, len = array.length, i, result; for (i = 1; i < len; i += 1) { if (array[i - 1] === array[i]) { if (!tmpBestCount) { tmpBestCount = 1; tmpBestStart = i - 1; } tmpBestCount += 1; } else { tmpBestCount = 0; } if (tmpBestCount > bestCount) { bestCount = tmpBestCount; bestStart = tmpBestStart; } } result = ''; for (i = bestStart; i < bestCount + bestStart; i +=1) { result += array[i] + ' '; } console.log (result);
/** * Plugin: "remove_button" (selectize.js) * Copyright (c) 2013 Brian Reavis & contributors * * 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. * * @author Brian Reavis <brian@thirdroute.com> */ Selectize.define('remove_button', function(options) { options = $.extend({ label : '&times;', title : 'Remove', className : 'remove', append : true }, options); var self = this; var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>'; /** * Appends an element as a child (with raw HTML). * * @param {string} html_container * @param {string} html_element * @return {string} */ var append = function(html_container, html_element) { var pos = html_container.search(/(<\/[^>]+>\s*)$/); return html_container.substring(0, pos) + html_element + html_container.substring(pos); }; this.setup = (function() { var original = self.setup; return function() { // override the item rendering method to add the button to each if (options.append) { var render_item = self.settings.render.item; self.settings.render.item = function(data) { return append(render_item.apply(this, arguments), html); }; } original.apply(this, arguments); // add event listener this.$control.on('click', '.' + options.className, function(e) { e.preventDefault(); if (self.isLocked) return; if (self.settings.mode === 'single') { self.clear(); } else { var $item = $(e.currentTarget).parent(); self.setActiveItem($item); if (self.deleteSelection()) { self.setCaret(self.items.length); } } }); }; })(); });
'use strict'; (function ($) { $.wilson = $.wilson || {}; $.wilson.reporters = $.wilson.reporters || {}; $.wilson.reporters.memory = memory; var graph = new Rickshaw.Graph({ element: document.getElementById('memory'), width: 900, height: 500, renderer: 'area', stroke: true, preserve: true, series: [ { color: 'steelblue', name: 'Heap Used', data: [] }, { color: 'lightblue', name: 'RSS', data: [] }, { color: 'lightgreen', name: 'Heap Total', data: [] } ] }); var xAxis = new Rickshaw.Graph.Axis.Time({ graph: graph, ticksTreatment: 'glow', timeFixture: new Rickshaw.Fixtures.Time.Local() }); var yAxis = new Rickshaw.Graph.Axis.Y({ graph: graph, tickFormat: Rickshaw.Fixtures.Number.formatKMBT, ticksTreatment: 'glow' }); var legend = new Rickshaw.Graph.Legend({ element: document.querySelector('#memlegend'), graph: graph }); graph.render(); var updateHeapUsed = function (now, heapUsed) { if (graph.series[0].data.length > 50) { graph.series[0].data.shift(); } graph.series[0].data.push({ x: now, y: heapUsed }); }; var updateRss = function (now, rss) { if (graph.series[1].data.length > 50) { graph.series[1].data.shift(); } graph.series[1].data.push({ x: now, y: rss }); }; var updateHeapTotal = function (now, heapTotal) { if (graph.series[2].data.length > 50) { graph.series[2].data.shift(); } graph.series[2].data.push({ x: now, y: heapTotal }); }; function memory (message) { var now = new Date().getTime(); updateHeapUsed(now, message.data.heapUsed); updateHeapTotal(now, message.data.heapTotal); updateRss(now, message.data.rss); graph.update(); } })(jQuery);
import { REQUEST_ANIME_CHARACTERS, RECIEVE_ANIME_CHARACTERS_DATA, REQUEST_ANIME_CHARACTERS_FAILED, } from 'actions/characterCreators'; /** * App's initial state, Redux will use these values * to bootstrap our app, before having a generated state. * * @type {object} * */ const initialAnimeCharacters = { isFeching: false, characters: [], error: false, errorMessage: '', }; /** * Reducer - this part is in charge of changing the global state * * @typedef {object} initialAnimeCharacters * * @param {Object=initialAnimeCharacters} state - App's current state. * @param {object} action - This has the action will be Fired. * @returns {Object} Returns the app's new state. */ export default function animeCharacters(state = initialAnimeCharacters, action) { switch (action.type) { case REQUEST_ANIME_CHARACTERS: return { ...state, isFeching: true, error: false, }; case RECIEVE_ANIME_CHARACTERS_DATA: return { ...state, isFeching: false, characters: action.payload.characters, error: false, }; case REQUEST_ANIME_CHARACTERS_FAILED: return { ...state, isFeching: false, error: true, errorMessage: action.payload, }; default: return state; } }
import React, { Component, PropTypes } from 'react' import {walkState} from 'redux-operations'; import Counter from './Counter'; import {connect} from 'react-redux'; const mapStateToProps = state => { return { numberOfCounters: state.numberOfCounters } }; @connect(mapStateToProps) export default class AddDynamicCounters extends Component { render() { const { numberOfCounters } = this.props; const counterArr = []; for (let i = 0; i < numberOfCounters; i++) { counterArr.push(i); } return ( <div> <Counter location={['numberOfCounters']}/> {numberOfCounters ? <h3>ALL THE COUNTERS</h3> : null} <div className="allCounters">{counterArr.map(val => this.renderCounter(val))}</div> </div> ) } renderCounter = (counterIdx) => { return <Counter location={['counters', counterIdx]} key={`counter${counterIdx}`} />; }; }
var driver = require('selenium-webdriver'); var deferred = driver.promise.defer(); deferred.then(function(data){ console.log("I am the promised action - the data passed to me was: " + data); }); setTimeout(function() { deferred.fulfill('engineering report - shields at 50% captain'); }, 4000);
/*! jQuery UI - v1.11.2 - 2015-01-18 * http://jqueryui.com * This file has been modified to suit the needs of the Form builder / Widgets. * Includes: core.js, widget.js, mouse.js, position.js, draggable.js, droppable.js, resizable.js, selectable.js, sortable.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, menu.js, progressbar.js, selectmenu.js, slider.js, spinner.js, tabs.js, tooltip.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ module.exports = function($) { window.jQuery = $; (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.2", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Widget 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; (elem = elems[i]) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; /*! * jQuery UI Mouse 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/mouse/ */ var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); var mouse = $.widget("ui.mouse", { version: "1.11.2", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } this._mouseMoved = false; // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // Only check for mouseups outside the document if you've moved inside the document // at least once. This prevents the firing of mouseup in the case of IE<9, which will // fire a mousemove event if content is placed under the cursor. See #7778 // Support: IE <9 if ( this._mouseMoved ) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } } if ( event.which || event.button ) { this._mouseMoved = true; } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); /*! * jQuery UI Position 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ (function() { $.ui = $.ui || {}; var cachedScrollbarWidth, supportsOffsetFractions, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), // support: jQuery 1.6.x // jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(), height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !supportsOffsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function() { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); })(); var position = $.ui.position; /*! * jQuery UI Draggable 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ $.widget("ui.draggable", $.ui.mouse, { version: "1.11.2", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if ( this.options.helper === "original" ) { this._setPositionRelative(); } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._removeHandleClassName(); this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; this._blurActiveElement( event ); // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix ); return true; }, _blockFrames: function( selector ) { this.iframeBlocks = this.document.find( selector ).map(function() { var iframe = $( this ); return $( "<div>" ) .css( "position", "absolute" ) .appendTo( iframe.parent() ) .outerWidth( iframe.outerWidth() ) .outerHeight( iframe.outerHeight() ) .offset( iframe.offset() )[ 0 ]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _blurActiveElement: function( event ) { var document = this.document[ 0 ]; // Only need to blur if the event occurred on the draggable itself, see #10527 if ( !this.handleElement.is( event.target ) ) { return; } // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent( true ); this.offsetParent = this.helper.offsetParent(); this.hasFixedAncestor = this.helper.parents().filter(function() { return $( this ).css( "position" ) === "fixed"; }).length > 0; //The element's absolute position on the page minus margins this.positionAbs = this.element.offset(); this._refreshOffsets( event ); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } // Reset helper's right/bottom css if they're set and set explicit width/height instead // as this prevents resizing of elements with right/bottom set (see #7772) this._normalizeRightBottom(); this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _refreshOffsets: function( event ) { this.offset = { top: this.positionAbs.top - this.margins.top, left: this.positionAbs.left - this.margins.left, scroll: false, parent: this._getParentOffset(), relative: this._getRelativeOffset() }; this.offset.click = { left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.hasFixedAncestor ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function( event ) { this._unblockFrames(); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // Only need to focus if the event occurred on the draggable itself, see #10527 if ( this.handleElement.is( event.target ) ) { // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); } return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this.handleElement = this.options.handle ? this.element.find( this.options.handle ) : this.element; this.handleElement.addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.handleElement.removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helperIsFunction = $.isFunction( o.helper ), helper = helperIsFunction ? $( o.helper.apply( this.element[ 0 ], [ event ] ) ) : ( o.helper === "clone" ? this.element.clone().removeAttr( "id" ) : this.element ); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } // http://bugs.jqueryui.com/ticket/9446 // a helper function can return the original element // which wouldn't have been set to relative in _create if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) { this._setPositionRelative(); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _setPositionRelative: function() { if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) { this.element[ 0 ].style.position = "relative"; } }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"), 10) || 0), top: (parseInt(this.element.css("marginTop"), 10) || 0), right: (parseInt(this.element.css("marginRight"), 10) || 0), bottom: (parseInt(this.element.css("marginBottom"), 10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var isUserScrollable, c, ce, o = this.options, document = this.document[ 0 ]; this.relativeContainer = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) ); this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relativeContainer = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relativeContainer ){ co = this.relativeContainer.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, _normalizeRightBottom: function() { if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) { this.helper.width( this.helper.width() ); this.helper.css( "right", "auto" ); } if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) { this.helper.height( this.helper.height() ); this.helper.css( "bottom", "auto" ); } }, // From now on bulk stuff - mainly helpers _trigger: function( type, event, ui ) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); // Absolute position and offset (see #6884 ) have to be recalculated after plugins if ( /^(drag|start|stop)/.test( type ) ) { this.positionAbs = this._convertPositionTo( "absolute" ); ui.offset = this.positionAbs; } return $.Widget.prototype._trigger.call( this, type, event, ui ); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add( "draggable", "connectToSortable", { start: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.sortables = []; $( draggable.options.connectToSortable ).each(function() { var sortable = $( this ).sortable( "instance" ); if ( sortable && !sortable.options.disabled ) { draggable.sortables.push( sortable ); // refreshPositions is called at drag start to refresh the containerCache // which is used in drag. This ensures it's initialized and synchronized // with any changes that might have happened on the page since initialization. sortable.refreshPositions(); sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, draggable ) { var uiSortable = $.extend( {}, ui, { item: draggable.element }); draggable.cancelHelperRemoval = false; $.each( draggable.sortables, function() { var sortable = this; if ( sortable.isOver ) { sortable.isOver = 0; // Allow this sortable to handle removing the helper draggable.cancelHelperRemoval = true; sortable.cancelHelperRemoval = false; // Use _storedCSS To restore properties in the sortable, // as this also handles revert (#9675) since the draggable // may have modified them in unexpected ways (#8809) sortable._storedCSS = { position: sortable.placeholder.css( "position" ), top: sortable.placeholder.css( "top" ), left: sortable.placeholder.css( "left" ) }; sortable._mouseStop(event); // Once drag has ended, the sortable should return to using // its original helper, not the shared helper from draggable sortable.options.helper = sortable.options._helper; } else { // Prevent this Sortable from removing the helper. // However, don't set the draggable to remove the helper // either as another connected Sortable may yet handle the removal. sortable.cancelHelperRemoval = true; sortable._trigger( "deactivate", event, uiSortable ); } }); }, drag: function( event, ui, draggable ) { $.each( draggable.sortables, function() { var innermostIntersecting = false, sortable = this; // Copy over variables that sortable's _intersectsWith uses sortable.positionAbs = draggable.positionAbs; sortable.helperProportions = draggable.helperProportions; sortable.offset.click = draggable.offset.click; if ( sortable._intersectsWith( sortable.containerCache ) ) { innermostIntersecting = true; $.each( draggable.sortables, function() { // Copy over variables that sortable's _intersectsWith uses this.positionAbs = draggable.positionAbs; this.helperProportions = draggable.helperProportions; this.offset.click = draggable.offset.click; if ( this !== sortable && this._intersectsWith( this.containerCache ) && $.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if ( innermostIntersecting ) { // If it intersects, we use a little isOver variable and set it once, // so that the move-in stuff gets fired only once. if ( !sortable.isOver ) { sortable.isOver = 1; sortable.currentItem = ui.helper .appendTo( sortable.element ) .data( "ui-sortable-item", true ); // Store helper option to later restore it sortable.options._helper = sortable.options.helper; sortable.options.helper = function() { return ui.helper[ 0 ]; }; // Fire the start events of the sortable with our passed browser event, // and our own helper (so it doesn't create a new one) event.target = sortable.currentItem[ 0 ]; sortable._mouseCapture( event, true ); sortable._mouseStart( event, true, true ); // Because the browser event is way off the new appended portlet, // modify necessary variables to reflect the changes sortable.offset.click.top = draggable.offset.click.top; sortable.offset.click.left = draggable.offset.click.left; sortable.offset.parent.left -= draggable.offset.parent.left - sortable.offset.parent.left; sortable.offset.parent.top -= draggable.offset.parent.top - sortable.offset.parent.top; draggable._trigger( "toSortable", event ); // Inform draggable that the helper is in a valid drop zone, // used solely in the revert option to handle "valid/invalid". draggable.dropped = sortable.element; // Need to refreshPositions of all sortables in the case that // adding to one sortable changes the location of the other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); // hack so receive/update callbacks work (mostly) draggable.currentItem = draggable.element; sortable.fromOutside = draggable; } if ( sortable.currentItem ) { sortable._mouseDrag( event ); // Copy the sortable's position because the draggable's can potentially reflect // a relative position, while sortable is always absolute, which the dragged // element has now become. (#8809) ui.position = sortable.position; } } else { // If it doesn't intersect with the sortable, and it intersected before, // we fake the drag stop of the sortable, but make sure it doesn't remove // the helper by using cancelHelperRemoval. if ( sortable.isOver ) { sortable.isOver = 0; sortable.cancelHelperRemoval = true; // Calling sortable's mouseStop would trigger a revert, // so revert must be temporarily false until after mouseStop is called. sortable.options._revert = sortable.options.revert; sortable.options.revert = false; sortable._trigger( "out", event, sortable._uiHash( sortable ) ); sortable._mouseStop( event, true ); // restore sortable behaviors that were modfied // when the draggable entered the sortable area (#9481) sortable.options.revert = sortable.options._revert; sortable.options.helper = sortable.options._helper; if ( sortable.placeholder ) { sortable.placeholder.remove(); } // Recalculate the draggable's offset considering the sortable // may have modified them in unexpected ways (#8809) draggable._refreshOffsets( event ); ui.position = draggable._generatePosition( event, true ); draggable._trigger( "fromSortable", event ); // Inform draggable that the helper is no longer in a valid drop zone draggable.dropped = false; // Need to refreshPositions of all sortables just in case removing // from one sortable changes the location of other sortables (#9675) $.each( draggable.sortables, function() { this.refreshPositions(); }); } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( !i.scrollParentNotHidden ) { i.scrollParentNotHidden = i.helper.scrollParent( false ); } if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParentNotHidden.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, scrollParent = i.scrollParentNotHidden[ 0 ], document = i.document[ 0 ]; if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) { if ( !o.axis || o.axis !== "x" ) { if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed; } else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) { scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed; } } if ( !o.axis || o.axis !== "y" ) { if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed; } else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) { scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left - inst.margins.left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top - inst.margins.top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a, b) { return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); var draggable = $.ui.draggable; /*! * jQuery UI Droppable 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ $.widget( "ui.droppable", { version: "1.11.2", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode, event ) { if ( !droppable.offset ) { return false; } var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } // Run through all droppables and check their positions based on specific tolerance options $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter(function() { return $( this ).droppable( "instance" ).options.scope === scope; }); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if ( parentInstance && c === "isover" ) { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call( parentInstance, event ); } this[ c ] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call( this, event ); // we just moved out of a greedy child if ( parentInstance && c === "isout" ) { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call( parentInstance, event ); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; var droppable = $.ui.droppable; /*! * jQuery UI Resizable 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/resizable/ */ $.widget("ui.resizable", $.ui.mouse, { version: "1.11.2", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _num: function( value ) { return parseInt( value, 10 ) || 0; }, _isNumber: function( value ) { return !isNaN( parseInt( value, 10 ) ); }, _hasScroll: function( el, a ) { if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); // Wrap the element if it cannot hold child nodes if (this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); this.element = this.element.parent().data( "ui-resizable", this.element.resizable( "instance" ) ); this.elementIsWrapper = true; this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0 }); // support: Safari // Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); this._proportionallyResizeElements.push( this.originalElement.css({ position: "static", zoom: 1, display: "block" }) ); // support: IE9 // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); this._proportionallyResize(); } this.handles = o.handles || ( !$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" } ); if (this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for (i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-" + handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); axis.css({ zIndex: o.zIndex }); // TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } this.handles[handle] = ".ui-resizable-" + handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for (i in this.handles) { if (this.handles[i].constructor === String) { this.handles[i] = this.element.children( this.handles[ i ] ).first().show(); } if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } // TODO: What's that good for? There's not anything to be executed left if (!$(this.handles[i]).length) { continue; } } }; // TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } that.axis = axis && axis[1] ? axis[1] : "se"; } }); if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function() { if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp) .removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable") .removeData("ui-resizable") .unbind(".resizable") .find(".ui-resizable-handle") .remove(); }; // TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, el = this.element; this.resizing = true; this._renderProxy(); curleft = this._num(this.helper.css("left")); curtop = this._num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: this.helper.width(), height: this.helper.height() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { var data, props, smp = this.originalMousePosition, a = this.axis, dx = (event.pageX - smp.left) || 0, dy = (event.pageY - smp.top) || 0, trigger = this._change[a]; this._updatePrevProperties(); if (!trigger) { return false; } data = trigger.apply(this, [ event, dx, dy ]); this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); this._propagate("resize", event); props = this._applyChanges(); if ( !this._helper && this._proportionallyResizeElements.length ) { this._proportionallyResize(); } if ( !$.isEmptyObject( props ) ) { this._updatePrevProperties(); this._trigger( "resize", event, this.ui() ); this._applyChanges(); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if (this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && this._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updatePrevProperties: function() { this.prevPosition = { top: this.position.top, left: this.position.left }; this.prevSize = { width: this.size.width, height: this.size.height }; }, _applyChanges: function() { var props = {}; if ( this.position.top !== this.prevPosition.top ) { props.top = this.position.top + "px"; } if ( this.position.left !== this.prevPosition.left ) { props.left = this.position.left + "px"; } if ( this.size.width !== this.prevSize.width ) { props.width = this.size.width + "px"; } if ( this.size.height !== this.prevSize.height ) { props.height = this.size.height + "px"; } this.helper.css( props ); return props; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if (this._aspectRatio || forceAspectRatio) { pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if (pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if (pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if (pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if (pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (this._isNumber(data.left)) { this.position.left = data.left; } if (this._isNumber(data.top)) { this.position.top = data.top; } if (this._isNumber(data.height)) { this.size.height = data.height; } if (this._isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (this._isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (this._isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // Fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _getPaddingPlusBorderDimensions: function( element ) { var i = 0, widths = [], borders = [ element.css( "borderTopWidth" ), element.css( "borderRightWidth" ), element.css( "borderBottomWidth" ), element.css( "borderLeftWidth" ) ], paddings = [ element.css( "paddingTop" ), element.css( "paddingRight" ), element.css( "paddingBottom" ), element.css( "paddingLeft" ) ]; for ( ; i < 4; i++ ) { widths[ i ] = ( parseInt( borders[ i ], 10 ) || 0 ); widths[ i ] += ( parseInt( paddings[ i ], 10 ) || 0 ); } return { height: widths[ 0 ] + widths[ 2 ], width: widths[ 1 ] + widths[ 3 ] }; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var prel, i = 0, element = this.helper || this.element; for ( ; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; // TODO: Seems like a bug to cache this.outerDimensions // considering that we are in a loop. if (!this.outerDimensions) { this.outerDimensions = this._getPaddingPlusBorderDimensions( prel ); } prel.css({ height: (element.height() - this.outerDimensions.height) || 0, width: (element.width() - this.outerDimensions.width) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if (this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left + "px", top: this.elementOffset.top + "px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [ event, dx, dy ])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [ event, dx, dy ])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [ event, dx, dy ])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [ event, dx, dy ])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [ event, this.ui() ]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).resizable( "instance" ), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && that._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add( "resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $( this ).resizable( "instance" ), o = that.options, el = that.element, oc = o.containment, ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc; if ( !ce ) { return; } that.containerElement = $( ce ); if ( /document/.test( oc ) || oc === document ) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $( document ), left: 0, top: 0, width: $( document ).width(), height: $( document ).height() || document.body.parentNode.scrollHeight }; } else { element = $( ce ); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) { p[ i ] = that._num( element.css( "padding" + name ) ); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: ( element.innerHeight() - p[ 3 ] ), width: ( element.innerWidth() - p[ 1 ] ) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw ); height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ; that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event ) { var woset, hoset, isParent, isOffsetRelative, that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top: 0, left: 0 }, ce = that.containerElement, continueResize = true; if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) { cop = co; } if ( cp.left < ( that._helper ? co.left : 0 ) ) { that.size.width = that.size.width + ( that._helper ? ( that.position.left - co.left ) : ( that.position.left - cop.left ) ); if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } that.position.left = o.helper ? co.left : 0; } if ( cp.top < ( that._helper ? co.top : 0 ) ) { that.size.height = that.size.height + ( that._helper ? ( that.position.top - co.top ) : that.position.top ); if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } that.position.top = that._helper ? co.top : 0; } isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 ); isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) ); if ( isParent && isOffsetRelative ) { that.offset.left = that.parentData.left + that.position.left; that.offset.top = that.parentData.top + that.position.top; } else { that.offset.left = that.element.offset().left; that.offset.top = that.element.offset().top; } woset = Math.abs( that.sizeDiff.width + (that._helper ? that.offset.left - cop.left : (that.offset.left - co.left)) ); hoset = Math.abs( that.sizeDiff.height + (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) ); if ( woset + that.size.width >= that.parentData.width ) { that.size.width = that.parentData.width - woset; if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } } if ( hoset + that.size.height >= that.parentData.height ) { that.size.height = that.parentData.height - hoset; if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } } if ( !continueResize ){ that.position.left = that.prevPosition.left; that.position.top = that.prevPosition.top; that.size.width = that.prevSize.width; that.size.height = that.prevSize.height; } }, stop: function() { var that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $( that.helper ), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function() { var that = $(this).resizable( "instance" ), o = that.options, _store = function(exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function(exp) { _store(exp); }); } } else { _store(o.alsoResize); } }, resize: function(event, ui) { var that = $(this).resizable( "instance" ), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function(exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? [ "width", "height" ] : [ "width", "height", "top", "left" ]; $.each(css, function(i, prop) { var sum = (start[prop] || 0) + (delta[prop] || 0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); } else { _alsoResize(o.alsoResize); } }, stop: function() { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function() { var that = $(this).resizable( "instance" ); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).resizable( "instance" ); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var outerDimensions, that = $(this).resizable( "instance" ), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid, gridX = (grid[0] || 1), gridY = (grid[1] || 1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth += gridX; } if (isMinHeight) { newHeight += gridY; } if (isMaxWidth) { newWidth -= gridX; } if (isMaxHeight) { newHeight -= gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { if ( newHeight - gridY <= 0 || newWidth - gridX <= 0) { outerDimensions = that._getPaddingPlusBorderDimensions( this ); } if ( newHeight - gridY > 0 ) { that.size.height = newHeight; that.position.top = op.top - oy; } else { newHeight = gridY - outerDimensions.height; that.size.height = newHeight; that.position.top = op.top + os.height - newHeight; } if ( newWidth - gridX > 0 ) { that.size.width = newWidth; that.position.left = op.left - ox; } else { newWidth = gridY - outerDimensions.height; that.size.width = newWidth; that.position.left = op.left + os.width - newWidth; } } } }); var resizable = $.ui.resizable; /*! * jQuery UI Selectable 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectable/ */ var selectable = $.widget("ui.selectable", $.ui.mouse, { version: "1.11.2", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [ event.pageX, event.pageY ]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 }); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); if (!selectee) return; if (selectee.$element) selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); if (!selectee) return; if (selectee.$element) selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); /*! * jQuery UI Sortable 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/sortable/ */ var sortable = $.widget("ui.sortable", $.ui.mouse, { version: "1.11.2", widgetEventPrefix: "sort", ready: false, options: { appendTo: "parent", axis: false, connectWith: false, containment: false, cursor: "auto", cursorAt: false, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: "> *", opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000, // callbacks activate: null, beforeStop: null, change: null, deactivate: null, out: null, over: null, receive: null, remove: null, sort: null, start: null, stop: null, update: null }, _isOverAxis: function( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); }, _isFloating: function( item ) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); }, _create: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); this._setHandleClassName(); //We're ready to go this.ready = true; }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _setHandleClassName: function() { this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" ); $.each( this.items, function() { ( this.instance.options.handle ? this.item.find( this.instance.options.handle ) : this.item ) .addClass( "ui-sortable-handle" ); }); }, _destroy: function() { this.element .removeClass( "ui-sortable ui-sortable-disabled" ) .find( ".ui-sortable-handle" ) .removeClass( "ui-sortable-handle" ); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _mouseCapture: function(event, overrideHandle) { var currentItem = null, validHandle = false, that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type === "static") { return false; } //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items $(event.target).parents().each(function() { if($.data(this, that.widgetName + "-item") === that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + "-item") === that) { currentItem = $(event.target); } if(!currentItem) { return false; } if(this.options.handle && !overrideHandle) { $(this.options.handle, currentItem).find("*").addBack().each(function() { if(this === event.target) { validHandle = true; } }); if(!validHandle) { return false; } } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var i, body, o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] !== this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) { this._setContainment(); } if( o.cursor && o.cursor !== "auto" ) { // cursor option body = this.document.find( "body" ); // support: IE this.storedCursor = body.css( "cursor" ); body.css( "cursor", o.cursor ); this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) { this._storedOpacity = this.helper.css("opacity"); } this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) { this._storedZIndex = this.helper.css("zIndex"); } this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { this.overflowOffset = this.scrollParent.offset(); } //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) { this._cacheHelperProportions(); } //Post "activate" events to possible containers if( !noActivation ) { for ( i = this.containers.length - 1; i >= 0; i-- ) { this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); } } //Prepare possible droppables if($.ui.ddmanager) { $.ui.ddmanager.current = this; } if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { var i, item, itemElement, intersection, o = this.options, scrolled = false; //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; } if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper position if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } //Rearrange for (i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection item = this.items[i]; itemElement = item.item[0]; intersection = this._intersectsWithPointer(item); if (!intersection) { continue; } // Only put the placeholder inside the current Container, skip all // items from other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this, moving items in "sub-sortables" can cause // the placeholder to jitter between the outer and inner container. if (item.instance !== this.currentContainer) { continue; } // cannot intersect with itself // no useless actions that have been done before // no action if the item moved is the parent of the item checked if (itemElement !== this.currentItem[0] && this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && !$.contains(this.placeholder[0], itemElement) && (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) ) { this.direction = intersection === 1 ? "down" : "up"; if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } //Call callbacks this._trigger("sort", event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) { return; } //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) { $.ui.ddmanager.drop(this, event); } if(this.options.revert) { var that = this, cur = this.placeholder.offset(), axis = this.options.axis, animation = {}; if ( !axis || axis === "x" ) { animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); } if ( !axis || axis === "y" ) { animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); } this.reverting = true; $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { if(this.dragging) { this._mouseUp({ target: null }); if(this.options.helper === "original") { this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) { this.placeholder[0].parentNode.removeChild(this.placeholder[0]); } if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { this.helper.remove(); } $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected), str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); if (res) { str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); } }); if(!str.length && o.key) { str.push(o.key + "="); } return str.join("&"); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected), ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height, l = item.left, r = l + item.width, t = item.top, b = t + item.height, dyClick = this.offset.click.top, dxClick = this.offset.click.left, isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), isOverElement = isOverElementHeight && isOverElementWidth; if ( this.options.tolerance === "pointer" || this.options.forcePointerForContainers || (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) && // Right Half x2 - (this.helperProportions.width / 2) < r && // Left Half t < y1 + (this.helperProportions.height / 2) && // Bottom Half y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) { return false; } return this.floating ? ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta !== 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta !== 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this._setHandleClassName(); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var i, j, cur, inst, items = [], queries = [], connectWith = this._connectWith(); if(connectWith && connected) { for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for ( j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); } } } } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); function addItems() { items.push( this ); } for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each( addItems ); } return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] === item.item[0]) { return false; } } return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var i, j, cur, inst, targetData, _queries, item, queriesLength, items = this.items, queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for (j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } } } } for (i = queries.length - 1; i >= 0; i--) { targetData = queries[i][1]; _queries = queries[i][0]; for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { item = $(_queries[j]); item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); } } }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } var i, item, t, p; for (i = this.items.length - 1; i >= 0; i--){ item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { continue; } t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } p = t.offset(); item.left = p.left; item.top = p.top; } if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (i = this.containers.length - 1; i >= 0; i--){ p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); } } return this; }, _createPlaceholder: function(that) { that = that || this; var className, o = that.options; if(!o.placeholder || o.placeholder.constructor === String) { className = o.placeholder; o.placeholder = { element: function() { var nodeName = that.currentItem[0].nodeName.toLowerCase(), element = $( "<" + nodeName + ">", that.document[0] ) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper"); if ( nodeName === "tr" ) { that.currentItem.children().each(function() { $( "<td>&#160;</td>", that.document[0] ) .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) .appendTo( element ); }); } else if ( nodeName === "img" ) { element.attr( "src", that.currentItem.attr( "src" ) ); } if ( !className ) { element.css( "visibility", "hidden" ); } return element; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) { return; } //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis, innermostContainer = null, innermostIndex = null; // get innermost container that intersects with item for (i = this.containers.length - 1; i >= 0; i--) { // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) { continue; } if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { continue; } innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) { return; } // move the item into the container if it's not there already if(this.containers.length === 1) { if (!this.containers[innermostIndex].containerCache.over) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } } else { //When entering a new container, we will find the item with the least distance and append our item near it dist = 10000; itemWithLeastDistance = null; floating = innermostContainer.floating || this._isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; axis = floating ? "clientX" : "clientY"; for (j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { continue; } if(this.items[j].item[0] === this.currentItem[0]) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) { nearBottom = true; } if ( Math.abs( event[ axis ] - cur ) < dist ) { dist = Math.abs( event[ axis ] - cur ); itemWithLeastDistance = this.items[ j ]; this.direction = nearBottom ? "up": "down"; } } //Check if dropOnEmpty is enabled if(!itemWithLeastDistance && !this.options.dropOnEmpty) { return; } if(this.currentContainer === this.containers[innermostIndex]) { if ( !this.currentContainer.containerCache.over ) { this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() ); this.currentContainer.containerCache.over = 1; } return; } itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); this.currentContainer = this.containers[innermostIndex]; //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); //Add the helper to the DOM if that didn't happen already if(!helper.parents("body").length) { $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); } if(helper[0] === this.currentItem[0]) { this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; } if(!helper[0].style.width || o.forceHelperSize) { helper.width(this.currentItem.width()); } if(!helper[0].style.height || o.forceHelperSize) { helper.height(this.currentItem.height()); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } // This needs to be actually done for all browsers, since pageX/pageY includes this information // with an ugly IE fix if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var ce, co, over, o = this.options; if(o.containment === "parent") { o.containment = this.helper[0].parentNode; } if(o.containment === "document" || o.containment === "window") { this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; } if(!(/^(document|window|parent)$/).test(o.containment)) { ce = $(o.containment)[0]; co = $(o.containment).offset(); over = ($(ce).css("overflow") !== "hidden"); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var top, left, o = this.options, pageX = event.pageX, pageY = event.pageY, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) { pageX = this.containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < this.containment[1]) { pageY = this.containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > this.containment[2]) { pageX = this.containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > this.containment[3]) { pageY = this.containment[3] + this.offset.click.top; } } if(o.grid) { top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter === this.counter) { this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove } }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var i, delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) { this.placeholder.before(this.currentItem); } this._noFinalSort = null; if(this.helper[0] === this.currentItem[0]) { for(i in this._storedCSS) { if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { this._storedCSS[i] = ""; } } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); } if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed } // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers function delayEvent( type, instance, container ) { return function( event ) { container._trigger( type, event, instance._uiHash( instance ) ); }; } for (i = this.containers.length - 1; i >= 0; i--){ if (!noPropagation) { delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) ); } if(this.containers[i].containerCache.over) { delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) ); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if ( this.storedCursor ) { this.document.find( "body" ).css( "cursor", this.storedCursor ); this.storedStylesheet.remove(); } if(this._storedOpacity) { this.helper.css("opacity", this._storedOpacity); } if(this._storedZIndex) { this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); } this.dragging = false; if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if ( !this.cancelHelperRemoval ) { if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) { this.helper.remove(); } this.helper = null; } if(!noPropagation) { for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return !this.cancelHelperRemoval; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); /*! * jQuery UI Accordion 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/accordion/ */ var accordion = $.widget( "ui.accordion", { version: "1.11.2", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, hideProps: { borderTopWidth: "hide", borderBottomWidth: "hide", paddingTop: "hide", paddingBottom: "hide", height: "hide" }, showProps: { borderTopWidth: "show", borderBottomWidth: "show", paddingTop: "show", paddingBottom: "show", height: "show" }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " + "ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this._destroyIcons(); // clean up content panels contents = this.headers.next() .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " + "ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeUniqueId(); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown: function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { var prevHeaders = this.headers, prevPanels = this.panels; this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-state-default ui-corner-all" ); this.panels = this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter( ":not(.ui-accordion-content-active)" ) .hide(); // Avoid memory leaks (#10056) if ( prevPanels ) { this._off( prevHeaders.not( this.headers ) ); this._off( prevPanels.not( this.panels ) ); } }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function() { var header = $( this ), headerId = header.uniqueId().attr( "id" ), panel = header.next(), panelId = panel.uniqueId().attr( "id" ); header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }) .next() .attr({ "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }) .next() .attr({ "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split( " " ), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr({ "tabIndex": -1, "aria-expanded": "false" }); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr( "aria-hidden", "false" ) .prev() .attr({ "aria-selected": "true", tabIndex: 0, "aria-expanded": "true" }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( this.showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( this.hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( this.hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( this.showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className; } this._trigger( "activate", null, data ); } }); /*! * jQuery UI Menu 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/menu/ */ var menu = $.widget( "ui.menu", { version: "1.11.2", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, items: "> *", menus: "ul", position: { my: "left-1 top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // Flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item": function( event ) { event.preventDefault(); }, "click .ui-menu-item": function( event ) { var target = $( event.target ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.select( event ); // Only set the mouseHandled flag if the event will bubble, see #9469. if ( !event.isPropagationStopped() ) { this.mouseHandled = true; } // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { // Ignore mouse events while typeahead is active, see #10458. // Prevents focusing the wrong item when typeahead causes a scroll while the mouse // is over an item in the menu if ( this.previousFilter ) { return; } var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.find( this.options.items ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( this._closeOnDocumentClick( event ) ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .removeClass( "ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { var match, prev, character, skip, preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } match = this._filterMenuItems( character ); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); match = this._filterMenuItems( character ); } if ( match.length ) { this.focus( event, match ); this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.is( "[aria-haspopup='true']" ) ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, items, that = this, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-front" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.parent(), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); items = menus.find( this.options.items ); // Initialize menu-items containing spaces and/or dashes only as dividers items.not( ".ui-menu-item" ).each(function() { var item = $( this ); if ( that._isDivider( item ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Don't refresh list items that are already adapted items.not( ".ui-menu-item, .ui-menu-divider" ) .addClass( "ui-menu-item" ) .uniqueId() .attr({ tabIndex: -1, role: this._itemRole() }); // Add aria-disabled attribute to any disabled menu item items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { this.element.find( ".ui-menu-icon" ) .removeClass( this.options.icons.submenu ) .addClass( value.submenu ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.outerHeight(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( ".ui-state-active" ).not( ".ui-state-focus" ) .removeClass( "ui-state-active" ); }, _closeOnDocumentClick: function( event ) { return !$( event.target ).closest( ".ui-menu" ).length; }, _isDivider: function( item ) { // Match hyphen, em dash, en dash return !/[^\-\u2014\u2013\s]/.test( item.text() ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .find( this.options.items ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.find( this.options.items )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); }, _filterMenuItems: function(character) { var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ), regex = new RegExp( "^" + escapedCharacter, "i" ); return this.activeMenu .find( this.options.items ) // Only match on items, not dividers or other content (#10571) .filter( ".ui-menu-item" ) .filter(function() { return regex.test( $.trim( $( this ).text() ) ); }); } }); /*! * jQuery UI Autocomplete 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/autocomplete/ */ $.widget( "ui.autocomplete", { version: "1.11.2", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[ 0 ].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; this.isMultiLine = // Textareas are always multi-line isTextarea ? true : // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable isInput ? false : // All other element types are determined by whether or not they're contentEditable this.element.prop( "isContentEditable" ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete ui-front" ) .appendTo( this._appendTo() ) .menu({ // disable ARIA support, the live region takes care of that role: null }) .hide() .menu( "instance" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { var label, item; // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } // Announce the value in the liveRegion label = ui.item.attr( "aria-label" ) || item.value; if ( label && $.trim( label ).length ) { this.liveRegion.children().hide(); $( "<div>" ).text( label ).appendTo( this.liveRegion ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray( this.options.source ) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response([]); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // Search if the value has changed, or if the user retypes the same value (see #7434) var equalValues = this.term === this._value(), menuVisible = this.menu.element.is( ":visible" ), modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var index = ++this.requestIndex; return $.proxy(function( content ) { if ( index === this.requestIndex ) { this.__response( content ); } this.pending--; if ( !this.pending ) { this.element.removeClass( "ui-autocomplete-loading" ); } }, this ); }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[ 0 ].label && items[ 0 ].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend( {}, item, { label: item.label || item.value, value: item.value || item.label }); }); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position ) ); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ).text( item.label ).appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); }, filter: function( array, term ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" ); return $.grep( array, function( value ) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.children().hide(); $( "<div>" ).text( message ).appendTo( this.liveRegion ); } }); var autocomplete = $.ui.autocomplete; /*! * jQuery UI Button 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/button/ */ var lastActive, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "'][type=radio]" ); } else { radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.11.2", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : ""; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); // Can't use _focusable() because the element that receives focus // and the element that gets the ui-state-focus class are different this._on({ focus: function() { this.buttonElement.addClass( "ui-state-focus" ); }, blur: function() { this.buttonElement.removeClass( "ui-state-focus" ); } }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { that.refresh(); }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " ui-state-active " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); if ( value ) { if ( this.type === "checkbox" || this.type === "radio" ) { this.buttonElement.removeClass( "ui-state-focus" ); } else { this.buttonElement.removeClass( "ui-state-focus ui-state-active" ); } } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.11.2", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl", allButtons = this.element.find( this.options.items ), existingButtons = allButtons.filter( ":ui-button" ); // Initialize new buttons allButtons.not( ":ui-button" ).button(); // Refresh existing buttons existingButtons.button( "refresh" ); this.buttons = allButtons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); var button = $.ui.button; /*! * jQuery UI Datepicker 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ */ $.extend($.ui, { datepicker: { version: "1.11.2" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17, activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" ); if ( activeCell.length > 0 ) { datepicker_handleMouseover.apply( activeCell.get( 0 ) ); } inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), minSize = (match === "y" ? size : 1), digits = new RegExp("^\\d{" + minSize + "," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate( selector, "mouseover", datepicker_handleMouseover ); } function datepicker_handleMouseover() { if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.2"; var datepicker = $.datepicker; /*! * jQuery UI Dialog 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/dialog/ */ var dialog = $.widget( "ui.dialog", { version: "1.11.2", options: { appendTo: "body", autoOpen: true, buttons: [], closeOnEscape: true, closeText: "Close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: null, maxWidth: null, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // Ensure the titlebar is always visible using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, title: null, width: 300, // callbacks beforeClose: null, close: null, drag: null, dragStart: null, dragStop: null, focus: null, open: null, resize: null, resizeStart: null, resizeStop: null }, sizeRelatedOptions: { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions: { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, _create: function() { this.originalCss = { display: this.element[ 0 ].style.display, width: this.element[ 0 ].style.width, minHeight: this.element[ 0 ].style.minHeight, maxHeight: this.element[ 0 ].style.maxHeight, height: this.element[ 0 ].style.height }; this.originalPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.originalTitle = this.element.attr( "title" ); this.options.title = this.options.title || this.originalTitle; this._createWrapper(); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( this.uiDialog ); this._createTitlebar(); this._createButtonPane(); if ( this.options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( this.options.resizable && $.fn.resizable ) { this._makeResizable(); } this._isOpen = false; this._trackFocus(); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element && (element.jquery || element.nodeType) ) { return $( element ); } return this.document.find( element || "body" ).eq( 0 ); }, _destroy: function() { var next, originalPosition = this.originalPosition; this._destroyOverlay(); this.element .removeUniqueId() .removeClass( "ui-dialog-content ui-widget-content" ) .css( this.originalCss ) // Without detaching first, the following becomes really slow .detach(); this.uiDialog.stop( true, true ).remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = originalPosition.parent.children().eq( originalPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { next.before( this.element ); } else { originalPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, disable: $.noop, enable: $.noop, close: function( event ) { var activeElement, that = this; if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { return; } this._isOpen = false; this._focusedElement = null; this._destroyOverlay(); this._untrackInstance(); if ( !this.opener.filter( ":focusable" ).focus().length ) { // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { activeElement = this.document[ 0 ].activeElement; // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #4520 if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) { // Hiding a focused element doesn't trigger blur in WebKit // so in case we have nothing to focus on, explicitly blur the active element // https://bugs.webkit.org/show_bug.cgi?id=47182 $( activeElement ).blur(); } } catch ( error ) {} } this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); }, isOpen: function() { return this._isOpen; }, moveToTop: function() { this._moveToTop(); }, _moveToTop: function( event, silent ) { var moved = false, zIndicies = this.uiDialog.siblings( ".ui-front:visible" ).map(function() { return +$( this ).css( "z-index" ); }).get(), zIndexMax = Math.max.apply( null, zIndicies ); if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) { this.uiDialog.css( "z-index", zIndexMax + 1 ); moved = true; } if ( moved && !silent ) { this._trigger( "focus", event ); } return moved; }, open: function() { var that = this; if ( this._isOpen ) { if ( this._moveToTop() ) { this._focusTabbable(); } return; } this._isOpen = true; this.opener = $( this.document[ 0 ].activeElement ); this._size(); this._position(); this._createOverlay(); this._moveToTop( null, true ); // Ensure the overlay is moved to the top with the dialog, but only when // opening. The overlay shouldn't move after the dialog is open so that // modeless dialogs opened after the modal dialog stack properly. if ( this.overlay ) { this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 ); } this._show( this.uiDialog, this.options.show, function() { that._focusTabbable(); that._trigger( "focus" ); }); // Track the dialog immediately upon openening in case a focus event // somehow occurs outside of the dialog before an element inside the // dialog is focused (#10152) this._makeFocusTarget(); this._trigger( "open" ); }, _focusTabbable: function() { // Set focus to the first match: // 1. An element that was focused previously // 2. First element inside the dialog matching [autofocus] // 3. Tabbable element inside the content element // 4. Tabbable element inside the buttonpane // 5. The close button // 6. The dialog itself var hasFocus = this._focusedElement; if ( !hasFocus ) { hasFocus = this.element.find( "[autofocus]" ); } if ( !hasFocus.length ) { hasFocus = this.element.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialog; } hasFocus.eq( 0 ).focus(); }, _keepFocus: function( event ) { function checkFocus() { var activeElement = this.document[0].activeElement, isActive = this.uiDialog[0] === activeElement || $.contains( this.uiDialog[0], activeElement ); if ( !isActive ) { this._focusTabbable(); } } event.preventDefault(); checkFocus.call( this ); // support: IE // IE <= 8 doesn't prevent moving focus even with event.preventDefault() // so we check again later this._delay( checkFocus ); }, _createWrapper: function() { this.uiDialog = $("<div>") .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + this.options.dialogClass ) .hide() .attr({ // Setting tabIndex makes the div focusable tabIndex: -1, role: "dialog" }) .appendTo( this._appendTo() ); this._on( this.uiDialog, { keydown: function( event ) { if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { event.preventDefault(); this.close( event ); return; } // prevent tabbing out of dialogs if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) { return; } var tabbables = this.uiDialog.find( ":tabbable" ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { this._delay(function() { first.focus(); }); event.preventDefault(); } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { this._delay(function() { last.focus(); }); event.preventDefault(); } }, mousedown: function( event ) { if ( this._moveToTop( event ) ) { this._focusTabbable(); } } }); // We assume that any existing aria-describedby attribute means // that the dialog content is marked up properly // otherwise we brute force the content as the description if ( !this.element.find( "[aria-describedby]" ).length ) { this.uiDialog.attr({ "aria-describedby": this.element.uniqueId().attr( "id" ) }); } }, _createTitlebar: function() { var uiDialogTitle; this.uiDialogTitlebar = $( "<div>" ) .addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" ) .prependTo( this.uiDialog ); this._on( this.uiDialogTitlebar, { mousedown: function( event ) { // Don't prevent click on close button (#8838) // Focusing a dialog that is partially scrolled out of view // causes the browser to scroll it into view, preventing the click event if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) { // Dialog isn't getting focus when dragging (#8063) this.uiDialog.focus(); } } }); // support: IE // Use type="button" to prevent enter keypresses in textboxes from closing the // dialog in IE (#9312) this.uiDialogTitlebarClose = $( "<button type='button'></button>" ) .button({ label: this.options.closeText, icons: { primary: "ui-icon-closethick" }, text: false }) .addClass( "ui-dialog-titlebar-close" ) .appendTo( this.uiDialogTitlebar ); this._on( this.uiDialogTitlebarClose, { click: function( event ) { event.preventDefault(); this.close( event ); } }); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .prependTo( this.uiDialogTitlebar ); this._title( uiDialogTitle ); this.uiDialog.attr({ "aria-labelledby": uiDialogTitle.attr( "id" ) }); }, _title: function( title ) { if ( !this.options.title ) { title.html( "&#160;" ); } title.text( this.options.title ); }, _createButtonPane: function() { this.uiDialogButtonPane = $( "<div>" ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); this.uiButtonSet = $( "<div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( this.uiDialogButtonPane ); this._createButtons(); }, _createButtons: function() { var that = this, buttons = this.options.buttons; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { this.uiDialog.removeClass( "ui-dialog-buttons" ); return; } $.each( buttons, function( name, props ) { var click, buttonOptions; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[ 0 ], arguments ); }; buttonOptions = { icons: props.icons, text: props.showText }; delete props.icons; delete props.showText; $( "<button></button>", props ) .button( buttonOptions ) .appendTo( that.uiButtonSet ); }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ).addClass( "ui-dialog-dragging" ); that._blockFrames(); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var left = ui.offset.left - that.document.scrollLeft(), top = ui.offset.top - that.document.scrollTop(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-dragging" ); that._unblockFrames(); that._trigger( "dragStop", event, filteredUi( ui ) ); } }); }, _makeResizable: function() { var that = this, options = this.options, handles = options.resizable, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css("position"), resizeHandles = typeof handles === "string" ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass( "ui-dialog-resizing" ); that._blockFrames(); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var offset = that.uiDialog.offset(), left = offset.left - that.document.scrollLeft(), top = offset.top - that.document.scrollTop(); options.height = that.uiDialog.height(); options.width = that.uiDialog.width(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-resizing" ); that._unblockFrames(); that._trigger( "resizeStop", event, filteredUi( ui ) ); } }) .css( "position", position ); }, _trackFocus: function() { this._on( this.widget(), { focusin: function( event ) { this._makeFocusTarget(); this._focusedElement = $( event.target ); } }); }, _makeFocusTarget: function() { this._untrackInstance(); this._trackingInstances().unshift( this ); }, _untrackInstance: function() { var instances = this._trackingInstances(), exists = $.inArray( this, instances ); if ( exists !== -1 ) { instances.splice( exists, 1 ); } }, _trackingInstances: function() { var instances = this.document.data( "ui-dialog-instances" ); if ( !instances ) { instances = []; this.document.data( "ui-dialog-instances", instances ); } return instances; }, _minHeight: function() { var options = this.options; return options.height === "auto" ? options.minHeight : Math.min( options.minHeight, options.height ); }, _position: function() { // Need to show the dialog to get the actual offset in the position plugin var isVisible = this.uiDialog.is( ":visible" ); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( this.options.position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resize = false, resizableOptions = {}; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in that.sizeRelatedOptions ) { resize = true; } if ( key in that.resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); this._position(); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; if ( key === "dialogClass" ) { uiDialog .removeClass( this.options.dialogClass ) .addClass( value ); } if ( key === "disabled" ) { return; } this._super( key, value ); if ( key === "appendTo" ) { this.uiDialog.appendTo( this._appendTo() ); } if ( key === "buttons" ) { this._createButtons(); } if ( key === "closeText" ) { this.uiDialogTitlebarClose.button({ // Ensure that we always pass a string label: "" + value }); } if ( key === "draggable" ) { isDraggable = uiDialog.is( ":data(ui-draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } } if ( key === "position" ) { this._position(); } if ( key === "resizable" ) { // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(ui-resizable)" ); if ( isResizable && !value ) { uiDialog.resizable( "destroy" ); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable(); } } if ( key === "title" ) { this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) ); } }, _size: function() { // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content // divs will both have width and height set, so we need to reset them var nonContentHeight, minContentHeight, maxContentHeight, options = this.options; // Reset content sizing this.element.show().css({ width: "auto", minHeight: 0, maxHeight: "none", height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); maxContentHeight = typeof options.maxHeight === "number" ? Math.max( 0, options.maxHeight - nonContentHeight ) : "none"; if ( options.height === "auto" ) { this.element.css({ minHeight: minContentHeight, maxHeight: maxContentHeight, height: "auto" }); } else { this.element.height( Math.max( 0, options.height - nonContentHeight ) ); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } }, _blockFrames: function() { this.iframeBlocks = this.document.find( "iframe" ).map(function() { var iframe = $( this ); return $( "<div>" ) .css({ position: "absolute", width: iframe.outerWidth(), height: iframe.outerHeight() }) .appendTo( iframe.parent() ) .offset( iframe.offset() )[0]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _allowInteraction: function( event ) { if ( $( event.target ).closest( ".ui-dialog" ).length ) { return true; } // TODO: Remove hack when datepicker implements // the .ui-front logic (#8989) return !!$( event.target ).closest( ".ui-datepicker" ).length; }, _createOverlay: function() { if ( !this.options.modal ) { return; } // We use a delay in case the overlay is created from an // event that we're going to be cancelling (#2804) var isOpening = true; this._delay(function() { isOpening = false; }); if ( !this.document.data( "ui-dialog-overlays" ) ) { // Prevent use of anchors and inputs // Using _on() for an event handler shared across many instances is // safe because the dialogs stack and must be closed in reverse order this._on( this.document, { focusin: function( event ) { if ( isOpening ) { return; } if ( !this._allowInteraction( event ) ) { event.preventDefault(); this._trackingInstances()[ 0 ]._focusTabbable(); } } }); } this.overlay = $( "<div>" ) .addClass( "ui-widget-overlay ui-front" ) .appendTo( this._appendTo() ); this._on( this.overlay, { mousedown: "_keepFocus" }); this.document.data( "ui-dialog-overlays", (this.document.data( "ui-dialog-overlays" ) || 0) + 1 ); }, _destroyOverlay: function() { if ( !this.options.modal ) { return; } if ( this.overlay ) { var overlays = this.document.data( "ui-dialog-overlays" ) - 1; if ( !overlays ) { this.document .unbind( "focusin" ) .removeData( "ui-dialog-overlays" ); } else { this.document.data( "ui-dialog-overlays", overlays ); } this.overlay.remove(); this.overlay = null; } } }); /*! * jQuery UI Progressbar 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/progressbar/ */ var progressbar = $.widget( "ui.progressbar", { version: "1.11.2", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); /*! * jQuery UI Selectmenu 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/selectmenu */ var selectmenu = $.widget( "ui.selectmenu", { version: "1.11.2", defaultElement: "<select>", options: { appendTo: null, disabled: null, icons: { button: "ui-icon-triangle-1-s" }, position: { my: "left top", at: "left bottom", collision: "none" }, width: null, // callbacks change: null, close: null, focus: null, open: null, select: null }, _create: function() { var selectmenuId = this.element.uniqueId().attr( "id" ); this.ids = { element: selectmenuId, button: selectmenuId + "-button", menu: selectmenuId + "-menu" }; this._drawButton(); this._drawMenu(); if ( this.options.disabled ) { this.disable(); } }, _drawButton: function() { var that = this, tabindex = this.element.attr( "tabindex" ); // Associate existing label with the new button this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button ); this._on( this.label, { click: function( event ) { this.button.focus(); event.preventDefault(); } }); // Hide original select element this.element.hide(); // Create button this.button = $( "<span>", { "class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all", tabindex: tabindex || this.options.disabled ? -1 : 0, id: this.ids.button, role: "combobox", "aria-expanded": "false", "aria-autocomplete": "list", "aria-owns": this.ids.menu, "aria-haspopup": "true" }) .insertAfter( this.element ); $( "<span>", { "class": "ui-icon " + this.options.icons.button }) .prependTo( this.button ); this.buttonText = $( "<span>", { "class": "ui-selectmenu-text" }) .appendTo( this.button ); this._setText( this.buttonText, this.element.find( "option:selected" ).text() ); this._resizeButton(); this._on( this.button, this._buttonEvents ); this.button.one( "focusin", function() { // Delay rendering the menu items until the button receives focus. // The menu may have already been rendered via a programmatic open. if ( !that.menuItems ) { that._refreshMenu(); } }); this._hoverable( this.button ); this._focusable( this.button ); }, _drawMenu: function() { var that = this; // Create menu this.menu = $( "<ul>", { "aria-hidden": "true", "aria-labelledby": this.ids.button, id: this.ids.menu }); // Wrap menu this.menuWrap = $( "<div>", { "class": "ui-selectmenu-menu ui-front" }) .append( this.menu ) .appendTo( this._appendTo() ); // Initialize menu widget this.menuInstance = this.menu .menu({ role: "listbox", select: function( event, ui ) { event.preventDefault(); // support: IE8 // If the item was selected via a click, the text selection // will be destroyed in IE that._setSelection(); that._select( ui.item.data( "ui-selectmenu-item" ), event ); }, focus: function( event, ui ) { var item = ui.item.data( "ui-selectmenu-item" ); // Prevent inital focus from firing and check if its a newly focused item if ( that.focusIndex != null && item.index !== that.focusIndex ) { that._trigger( "focus", event, { item: item } ); if ( !that.isOpen ) { that._select( item, event ); } } that.focusIndex = item.index; that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) ); } }) .menu( "instance" ); // Adjust menu styles to dropdown this.menu .addClass( "ui-corner-bottom" ) .removeClass( "ui-corner-all" ); // Don't close the menu on mouseleave this.menuInstance._off( this.menu, "mouseleave" ); // Cancel the menu's collapseAll on document click this.menuInstance._closeOnDocumentClick = function() { return false; }; // Selects often contain empty items, but never contain dividers this.menuInstance._isDivider = function() { return false; }; }, refresh: function() { this._refreshMenu(); this._setText( this.buttonText, this._getSelectedItem().text() ); if ( !this.options.width ) { this._resizeButton(); } }, _refreshMenu: function() { this.menu.empty(); var item, options = this.element.find( "option" ); if ( !options.length ) { return; } this._parseOptions( options ); this._renderMenu( this.menu, this.items ); this.menuInstance.refresh(); this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ); item = this._getSelectedItem(); // Update the menu to have the correct item focused this.menuInstance.focus( null, item ); this._setAria( item.data( "ui-selectmenu-item" ) ); // Set disabled state this._setOption( "disabled", this.element.prop( "disabled" ) ); }, open: function( event ) { if ( this.options.disabled ) { return; } // If this is the first time the menu is being opened, render the items if ( !this.menuItems ) { this._refreshMenu(); } else { // Menu clears focus on close, reset focus to selected item this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" ); this.menuInstance.focus( null, this._getSelectedItem() ); } this.isOpen = true; this._toggleAttr(); this._resizeMenu(); this._position(); this._on( this.document, this._documentClick ); this._trigger( "open", event ); }, _position: function() { this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) ); }, close: function( event ) { if ( !this.isOpen ) { return; } this.isOpen = false; this._toggleAttr(); this.range = null; this._off( this.document ); this._trigger( "close", event ); }, widget: function() { return this.button; }, menuWidget: function() { return this.menu; }, _renderMenu: function( ul, items ) { var that = this, currentOptgroup = ""; $.each( items, function( index, item ) { if ( item.optgroup !== currentOptgroup ) { $( "<li>", { "class": "ui-selectmenu-optgroup ui-menu-divider" + ( item.element.parent( "optgroup" ).prop( "disabled" ) ? " ui-state-disabled" : "" ), text: item.optgroup }) .appendTo( ul ); currentOptgroup = item.optgroup; } that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-selectmenu-item", item ); }, _renderItem: function( ul, item ) { var li = $( "<li>" ); if ( item.disabled ) { li.addClass( "ui-state-disabled" ); } this._setText( li, item.label ); return li.appendTo( ul ); }, _setText: function( element, value ) { if ( value ) { element.text( value ); } else { element.html( "&#160;" ); } }, _move: function( direction, event ) { var item, next, filter = ".ui-menu-item"; if ( this.isOpen ) { item = this.menuItems.eq( this.focusIndex ); } else { item = this.menuItems.eq( this.element[ 0 ].selectedIndex ); filter += ":not(.ui-state-disabled)"; } if ( direction === "first" || direction === "last" ) { next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 ); } else { next = item[ direction + "All" ]( filter ).eq( 0 ); } if ( next.length ) { this.menuInstance.focus( event, next ); } }, _getSelectedItem: function() { return this.menuItems.eq( this.element[ 0 ].selectedIndex ); }, _toggle: function( event ) { this[ this.isOpen ? "close" : "open" ]( event ); }, _setSelection: function() { var selection; if ( !this.range ) { return; } if ( window.getSelection ) { selection = window.getSelection(); selection.removeAllRanges(); selection.addRange( this.range ); // support: IE8 } else { this.range.select(); } // support: IE // Setting the text selection kills the button focus in IE, but // restoring the focus doesn't kill the selection. this.button.focus(); }, _documentClick: { mousedown: function( event ) { if ( !this.isOpen ) { return; } if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) { this.close( event ); } } }, _buttonEvents: { // Prevent text selection from being reset when interacting with the selectmenu (#10144) mousedown: function() { var selection; if ( window.getSelection ) { selection = window.getSelection(); if ( selection.rangeCount ) { this.range = selection.getRangeAt( 0 ); } // support: IE8 } else { this.range = document.selection.createRange(); } }, click: function( event ) { this._setSelection(); this._toggle( event ); }, keydown: function( event ) { var preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.TAB: case $.ui.keyCode.ESCAPE: this.close( event ); preventDefault = false; break; case $.ui.keyCode.ENTER: if ( this.isOpen ) { this._selectFocusedItem( event ); } break; case $.ui.keyCode.UP: if ( event.altKey ) { this._toggle( event ); } else { this._move( "prev", event ); } break; case $.ui.keyCode.DOWN: if ( event.altKey ) { this._toggle( event ); } else { this._move( "next", event ); } break; case $.ui.keyCode.SPACE: if ( this.isOpen ) { this._selectFocusedItem( event ); } else { this._toggle( event ); } break; case $.ui.keyCode.LEFT: this._move( "prev", event ); break; case $.ui.keyCode.RIGHT: this._move( "next", event ); break; case $.ui.keyCode.HOME: case $.ui.keyCode.PAGE_UP: this._move( "first", event ); break; case $.ui.keyCode.END: case $.ui.keyCode.PAGE_DOWN: this._move( "last", event ); break; default: this.menu.trigger( event ); preventDefault = false; } if ( preventDefault ) { event.preventDefault(); } } }, _selectFocusedItem: function( event ) { var item = this.menuItems.eq( this.focusIndex ); if ( !item.hasClass( "ui-state-disabled" ) ) { this._select( item.data( "ui-selectmenu-item" ), event ); } }, _select: function( item, event ) { var oldIndex = this.element[ 0 ].selectedIndex; // Change native select element this.element[ 0 ].selectedIndex = item.index; this._setText( this.buttonText, item.label ); this._setAria( item ); this._trigger( "select", event, { item: item } ); if ( item.index !== oldIndex ) { this._trigger( "change", event, { item: item } ); } this.close( event ); }, _setAria: function( item ) { var id = this.menuItems.eq( item.index ).attr( "id" ); this.button.attr({ "aria-labelledby": id, "aria-activedescendant": id }); this.menu.attr( "aria-activedescendant", id ); }, _setOption: function( key, value ) { if ( key === "icons" ) { this.button.find( "span.ui-icon" ) .removeClass( this.options.icons.button ) .addClass( value.button ); } this._super( key, value ); if ( key === "appendTo" ) { this.menuWrap.appendTo( this._appendTo() ); } if ( key === "disabled" ) { this.menuInstance.option( "disabled", value ); this.button .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); this.element.prop( "disabled", value ); if ( value ) { this.button.attr( "tabindex", -1 ); this.close(); } else { this.button.attr( "tabindex", 0 ); } } if ( key === "width" ) { this._resizeButton(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _toggleAttr: function() { this.button .toggleClass( "ui-corner-top", this.isOpen ) .toggleClass( "ui-corner-all", !this.isOpen ) .attr( "aria-expanded", this.isOpen ); this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen ); this.menu.attr( "aria-hidden", !this.isOpen ); }, _resizeButton: function() { var width = this.options.width; if ( !width ) { width = this.element.show().outerWidth(); this.element.hide(); } this.button.outerWidth( width ); }, _resizeMenu: function() { this.menu.outerWidth( Math.max( this.button.outerWidth(), // support: IE10 // IE10 wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping this.menu.width( "" ).outerWidth() + 1 ) ); }, _getCreateOptions: function() { return { disabled: this.element.prop( "disabled" ) }; }, _parseOptions: function( options ) { var data = []; options.each(function( index, item ) { var option = $( item ), optgroup = option.parent( "optgroup" ); data.push({ element: option, index: index, value: option.attr( "value" ), label: option.text(), optgroup: optgroup.attr( "label" ) || "", disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" ) }); }); this.items = data; }, _destroy: function() { this.menuWrap.remove(); this.button.remove(); this.element.show(); this.element.removeUniqueId(); this.label.attr( "for", this.ids.element ); } }); /*! * jQuery UI Slider 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slider/ */ var slider = $.widget( "ui.slider", $.ui.mouse, { version: "1.11.2", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, // number of pages in a slider // (how many times can you page up/down to go through the whole range) numPages: 5, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this._calculateNewMax(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { if ( this.range ) { this.range.remove(); } this.range = null; } }, _setupEvents: function() { this._off( this.handles ); this._on( this.handles, this._handleEvents ); this._hoverable( this.handles ); this._focusable( this.handles ); }, _destroy: function() { this.handles.remove(); if ( this.range ) { this.range.remove(); } this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length - 1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } if ( key === "disabled" ) { this.element.toggleClass( "ui-state-disabled", !!value ); } this._super( key, value ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); // Reset positioning from previous orientation this.handles.css( value === "horizontal" ? "bottom" : "left", "" ); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "step": case "min": case "max": this._animateOff = true; this._calculateNewMax(); this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i += 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _calculateNewMax: function() { var remainder = ( this.options.max - this._valueMin() ) % this.options.step; this.max = this.options.max - remainder; }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); /*! * jQuery UI Spinner 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/spinner/ */ function spinner_modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } var spinner = $.widget( "ui.spinner", { version: "1.11.2", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // Only format if there is a value, prevents the field from being marked // as invalid in Firefox, see #9573. if ( this.value() !== "" ) { // Format the value, but don't constrain. this._value( this.element.val(), true ); } this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._stop(); this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } if ( key === "icons" ) { this.buttons.first().find( ".ui-icon" ) .removeClass( this.options.icons.up ) .addClass( value.up ); this.buttons.last().find( ".ui-icon" ) .removeClass( this.options.icons.down ) .addClass( value.down ); } this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); this.buttons.button( value ? "disable" : "enable" ); } }, _setOptions: spinner_modifier(function( options ) { this._super( options ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, isValid: function() { var value = this.value(); // null is invalid if ( value === null ) { return false; } // if value gets adjusted, it's invalid return value === this._adjustValue( value ); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: spinner_modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * this.options.step ); this._stop(); } }, stepDown: spinner_modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * -this.options.step ); this._stop(); } }, pageUp: spinner_modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: spinner_modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } spinner_modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); /*! * jQuery UI Tabs 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ */ var tabs = $.widget( "ui.tabs", { version: "1.11.2", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _isLocal: (function() { var rhash = /#.*$/; return function( anchor ) { var anchorUrl, locationUrl; // support: IE7 // IE7 doesn't normalize the href property when set via script (#9317) anchor = anchor.cloneNode( false ); anchorUrl = anchor.href.replace( rhash, "" ); locationUrl = location.href.replace( rhash, "" ); // decoding may throw an error if the URL isn't UTF-8 (#9518) try { anchorUrl = decodeURIComponent( anchorUrl ); } catch ( error ) {} try { locationUrl = decodeURIComponent( locationUrl ); } catch ( error ) {} return anchor.hash.length > 1 && anchorUrl === locationUrl; }; })(), _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-hidden": "false" }); } }, _processTabs: function() { var that = this, prevTabs = this.tabs, prevAnchors = this.anchors, prevPanels = this.panels; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ) // Prevent users from focusing disabled tabs via click .delegate( "> li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( that._isLocal( anchor ) ) { selector = anchor.hash; panelId = selector.substring( 1 ); panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { // If the tab doesn't already have aria-controls, // generate an id by using a throw-away element panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id; selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": panelId, "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); // Avoid memory leaks (#10056) if ( prevTabs ) { this._off( prevTabs.not( this.tabs ) ); this._off( prevAnchors.not( this.anchors ) ); this._off( prevPanels.not( this.panels ) ); } }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.tablist || this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = {}; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); // Always prevent the default action, even when disabled this._on( true, this.anchors, { click: function( event ) { event.preventDefault(); } }); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr( "aria-hidden", "true" ); eventData.oldTab.attr({ "aria-selected": "false", "aria-expanded": "false" }); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr( "aria-hidden", "false" ); eventData.newTab.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tablist.unbind( this.eventNamespace ); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( this._isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); /*! * jQuery UI Tooltip 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tooltip/ */ var tooltip = $.widget( "ui.tooltip", { version: "1.11.2", options: { content: function() { // support: IE<9, Opera in jQuery <1.7 // .text() can't accept undefined, so coerce to a string var title = $( this ).attr( "title" ) || ""; // Escape title, since we're going from an attribute to raw HTML return $( "<a>" ).text( title ).html(); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _addDescribedBy: function( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); }, _removeDescribedBy: function( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } // Append the aria-live region so tooltips announce correctly this.liveRegion = $( "<div>" ) .attr({ role: "log", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, tooltipData ) { that._updateContent( tooltipData.element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, tooltipData ) { var event = $.Event( "blur" ); event.target = event.currentTarget = tooltipData.element[ 0 ]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .removeAttr( "title" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltipData, tooltip, events, delayedShow, a11yContent, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltipData = this._find( target ); if ( tooltipData ) { tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltipData = this._tooltip( target ); tooltip = tooltipData.tooltip; this._addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); // Support: Voiceover on OS X, JAWS on IE <= 9 // JAWS announces deletions even when aria-relevant="additions" // Voiceover will sometimes re-read the entire log region's contents from the beginning this.liveRegion.children().hide(); if ( content.clone ) { a11yContent = content.clone(); a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" ); } else { a11yContent = content; } $( "<div>" ).html( a11yContent ).appendTo( this.liveRegion ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = this.delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } } }; // Only bind remove handler for delegated targets. Non-delegated // tooltips will handle this in destroy. if ( target[ 0 ] !== this.element[ 0 ] ) { events.remove = function() { this._removeTooltip( tooltip ); }; } if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var tooltip, that = this, target = $( event ? event.currentTarget : this.element ), tooltipData = this._find( target ); // The tooltip may already be closed if ( !tooltipData ) { return; } tooltip = tooltipData.tooltip; // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( tooltipData.closing ) { return; } // Clear the interval for delayed tracking tooltips clearInterval( this.delayedShow ); // only set title if we had one before (see comment in _open()) // If the title attribute has changed since open(), don't restore if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } this._removeDescribedBy( target ); tooltipData.hiding = true; tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[ 0 ] !== this.element[ 0 ] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } tooltipData.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); if ( !tooltipData.hiding ) { tooltipData.closing = false; } }, _tooltip: function( element ) { var tooltip = $( "<div>" ) .attr( "role", "tooltip" ) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ), id = tooltip.uniqueId().attr( "id" ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); return this.tooltips[ id ] = { element: element, tooltip: tooltip }; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? this.tooltips[ id ] : null; }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, tooltipData ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ), element = tooltipData.element; event.target = event.currentTarget = element[ 0 ]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { // If the title attribute has changed since open(), don't restore if ( !element.attr( "title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } element.removeData( "ui-tooltip-title" ); } }); this.liveRegion.remove(); } }); /*! * jQuery UI Effects 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/effects-core/ */ var dataSpace = "ui-effects-", // Create a local jQuery because jQuery Color relies on it and the // global may not exist with AMD and a custom build (#10199) jQuery = $; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch ( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.11.2", // Saves a set of properties in a data storage save: function( element, set ) { for ( var i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for ( i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch ( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); var effect = $.effects; /*! * jQuery UI Effects Blind 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/blind-effect/ */ var effectBlind = $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/, props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( !motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Bounce 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/bounce-effect/ */ var effectBounce = $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Clip 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/clip-effect/ */ var effectClip = $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Drop 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/drop-effect/ */ var effectDrop = $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Explode 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/explode-effect/ */ var effectExplode = $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for ( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for ( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; /*! * jQuery UI Effects Fade 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fade-effect/ */ var effectFade = $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; /*! * jQuery UI Effects Fold 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/fold-effect/ */ var effectFold = $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; /*! * jQuery UI Effects Highlight 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/highlight-effect/ */ var effectHighlight = $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; /*! * jQuery UI Effects Size 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/size-effect/ */ var effectSize = $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function() { var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Scale 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/scale-effect/ */ var effectScale = $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || [ "middle", "center" ]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; /*! * jQuery UI Effects Puff 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/puff-effect/ */ var effectPuff = $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; /*! * jQuery UI Effects Pulsate 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/pulsate-effect/ */ var effectPulsate = $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; /*! * jQuery UI Effects Shake 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/shake-effect/ */ var effectShake = $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round( o.duration / anims ), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; /*! * jQuery UI Effects Slide 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slide-effect/ */ var effectSlide = $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; /*! * jQuery UI Effects Transfer 1.11.2 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/transfer-effect/ */ var effectTransfer = $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop, left: endPosition.left - fixLeft, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop, left: startPosition.left - fixLeft, height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })); return $; }
'use strict'; describe('Playlist Services', function () { beforeEach(module('septWebRadioApp')); var $cacheFactory, scope, Playlists, swrNotification, $modal, playlistServices, cache; var $httpBackend, userServices, utilities; var playlistsMock = [ {name: 'Playlist 1', _id: 1}, {name: 'Playlist 2', _id: 2, items: [ {musicId: 12, position: 1}, {musicId: 34, position: 2} ]} ]; beforeEach(inject(function ($rootScope, _Playlists_, _$cacheFactory_, _swrNotification_, _$modal_, _playlistServices_, _$httpBackend_, _userServices_, _utilities_) { scope = $rootScope.$new(); Playlists = _Playlists_; swrNotification = _swrNotification_; $cacheFactory = _$cacheFactory_; $modal = _$modal_; playlistServices = _playlistServices_; $httpBackend = _$httpBackend_; userServices = _userServices_; utilities = _utilities_; cache = $cacheFactory.get('playlistServices'); spyOn(userServices, 'getName').andCallFake(function () { return 'jimmy'; }); })); afterEach(function () { cache.removeAll(); }); describe('Init', function () { it('should init the variables', inject(function () { expect(playlistServices.playlists).toBeUndefined(); expect(playlistServices.cache).toBe(cache); })); it('should return the playlists set', inject(function () { playlistServices.playlists = playlistsMock; expect(playlistServices.getPlaylists()).toBe(playlistsMock); })); }); describe('initPlaylists', function () { it('should get the playlists from the query', inject(function () { spyOn(Playlists, 'query').andCallFake(function (userId, callback) { return callback(playlistsMock); }); expect(playlistServices.playlists).toBeUndefined(); expect(Playlists.query).not.toHaveBeenCalled(); playlistServices.initPlaylists(); expect(playlistServices.playlists).toBe(playlistsMock); expect(Playlists.query).toHaveBeenCalled(); })); it('should set the playlists in cache', inject(function () { spyOn(Playlists, 'query').andCallFake(function (userId, callback) { return callback(playlistsMock); }); expect(cache.get('playlists')).toBeUndefined(); playlistServices.initPlaylists(); expect(cache.get('playlists')).toBe(playlistsMock); })); it('should set the playlists form the cache', inject(function () { // Set the cache cache.put('playlists', playlistsMock); expect(playlistServices.playlists).toBeUndefined(); playlistServices.initPlaylists(); expect(playlistServices.playlists).toBe(playlistsMock); })); it('should not call the query when the playlists are in cache', inject(function () { spyOn(Playlists, 'query'); expect(Playlists.query).not.toHaveBeenCalled(); // Set the cache cache.put('playlists', playlistsMock); playlistServices.initPlaylists(); expect(Playlists.query).not.toHaveBeenCalled(); })); }); describe('createPlaylistItem and createPlaylistItems', function () { it('should return an empty array', inject(function () { var items = playlistServices.createPlaylistItems(); expect(items).toEqual([]); })); it('should have as much items as the one provided', inject(function () { var itemIdsMock = ['1']; var items = playlistServices.createPlaylistItems(itemIdsMock); expect(items.length).toEqual(1); itemIdsMock = ['1', '2', '3', '4']; items = playlistServices.createPlaylistItems(itemIdsMock); expect(items.length).toEqual(4); })); it('should return the correct item', inject(function () { var item = playlistServices.createPlaylistItem('1'); expect(item).toEqual({provider: 'soundcloud', musicId: '1'}); item = playlistServices.createPlaylistItem('53652'); expect(item).toEqual({provider: 'soundcloud', musicId: '53652'}); })); }); describe('findPlaylistById', function () { it('should return undefined', inject(function () { var playlist = playlistServices.findPlaylistById(); expect(playlist).toBeUndefined(); })); it('should return the correct playlist', inject(function () { playlistServices.playlists = playlistsMock; var playlist = playlistServices.findPlaylistById(1); expect(playlist).toEqual({name: 'Playlist 1', _id: 1}); })); it('should return undefined when this id is not presents', inject(function () { playlistServices.playlists = playlistsMock; var playlist = playlistServices.findPlaylistById(52); expect(playlist).toBeUndefined(); })); }); describe('createOrUpdatePlaylist', function () { it('should call the createPlaylistModal when there is no playlistId specified', inject(function () { spyOn(playlistServices, 'createPlaylistModal'); expect(playlistServices.createPlaylistModal).not.toHaveBeenCalled(); var itemIds = ['1', '2', '3']; playlistServices.createOrUpdatePlaylist(undefined, itemIds); expect(playlistServices.createPlaylistModal).toHaveBeenCalledWith(itemIds); })); it('should call the addItemsToPlaylists when there is some playlistId and items specified', inject(function () { spyOn(playlistServices, 'addItemsToPlaylists'); expect(playlistServices.addItemsToPlaylists).not.toHaveBeenCalled(); var itemIds = ['1', '2', '3']; var playlistIds = ['4', '5', '6']; playlistServices.createOrUpdatePlaylist(playlistIds, itemIds); expect(playlistServices.addItemsToPlaylists).toHaveBeenCalledWith(playlistIds, itemIds); })); it('should call the createPlaylistModal when there is no items specified but some playlist', inject(function () { spyOn(playlistServices, 'createPlaylistModal'); expect(playlistServices.createPlaylistModal).not.toHaveBeenCalled(); var playlistIds = ['1', '2', '3']; playlistServices.createOrUpdatePlaylist(playlistIds, undefined); expect(playlistServices.createPlaylistModal).toHaveBeenCalledWith(undefined); })); }); describe('createPlaylistWithItems', function () { it('should call the createPlaylistItems and call the create a new Playlist service', inject(function () { var itemIds = ['1', '2', '3']; var playlistName = 'playlist Name'; var finalItems = playlistServices.createPlaylistItems(itemIds); var finalPlaylist = {name: playlistName, items: finalItems}; var returnPlaylist = {_id: 51, name: playlistName, items: finalItems}; var done = function (response) { expect(response).toMatch(returnPlaylist); }; spyOn(playlistServices, 'createPlaylistItems').andCallThrough(); $httpBackend.expectPOST('/api/jimmy/playlists', finalPlaylist) .respond(returnPlaylist); playlistServices.createPlaylistWithItems(playlistName, itemIds, done); expect(playlistServices.createPlaylistItems).toHaveBeenCalledWith(itemIds, 0); $httpBackend.flush(); })); it('should push the new playlist', inject(function () { playlistServices.playlists = []; var itemIds = ['1', '2', '3']; var playlistName = 'playlist Name'; var finalItems = playlistServices.createPlaylistItems(itemIds); var finalPlaylist = {name: playlistName, items: finalItems}; var returnPlaylist = {_id: 51, name: playlistName, items: finalItems}; var done = function (response) { expect(response).toMatch(returnPlaylist); }; spyOn(playlistServices.playlists, 'push').andCallThrough(); $httpBackend.expectPOST('/api/jimmy/playlists', finalPlaylist) .respond(returnPlaylist); playlistServices.createPlaylistWithItems(playlistName, itemIds, done); expect(playlistServices.playlists.push).not.toHaveBeenCalled(); expect(playlistServices.playlists.length).toBe(0); $httpBackend.flush(); expect(playlistServices.playlists.push).toHaveBeenCalled(); expect(playlistServices.playlists.length).toBe(1); })); it('should call the swrNotification.addSuccessMessage', inject(function () { var itemIds = ['1', '2', '3']; var playlistName = 'playlist Name'; var finalItems = playlistServices.createPlaylistItems(itemIds); var finalPlaylist = {name: playlistName, items: finalItems}; var returnPlaylist = {_id: 51, name: playlistName, items: finalItems}; var done = function (response) { expect(response).toMatch(returnPlaylist); }; spyOn(swrNotification, 'message'); $httpBackend.expectPOST('/api/jimmy/playlists', finalPlaylist) .respond(returnPlaylist); playlistServices.createPlaylistWithItems(playlistName, itemIds, done); expect(swrNotification.message).not.toHaveBeenCalled(); $httpBackend.flush(); expect(swrNotification.message).toHaveBeenCalledWith('Playlist successfully created!'); })); }); describe('addItemsToPlaylists', function () { it('should call the addItemsToPlaylist method', inject(function () { var playlistIds = [3, 4, 5]; var itemIds = ['1', '2']; spyOn(playlistServices, 'addItemsToPlaylist'); var items = playlistServices.addItemsToPlaylists(playlistIds, itemIds); expect(playlistServices.addItemsToPlaylist.calls.length).toEqual(3); expect(playlistServices.addItemsToPlaylist.calls[0].args).toEqual([3, itemIds]); expect(playlistServices.addItemsToPlaylist.calls[1].args).toEqual([4, itemIds]); expect(playlistServices.addItemsToPlaylist.calls[2].args).toEqual([5, itemIds]); })); }); describe('addItemsToPlaylist', function () { it('should call the two functions create and find', inject(function () { var playlistId = 3; var itemIds = ['1', '2']; spyOn(playlistServices, 'createPlaylistItems'); spyOn(playlistServices, 'findPlaylistById'); playlistServices.addItemsToPlaylist(playlistId, itemIds); expect(playlistServices.findPlaylistById).toHaveBeenCalledWith(playlistId); expect(playlistServices.createPlaylistItems).toHaveBeenCalledWith(itemIds, 0); })); it('should call the error notification if no playlist are found', inject(function () { var playlistId = 3; var itemIds = ['1', '2']; spyOn(swrNotification, 'error'); spyOn(playlistServices, 'findPlaylistById').andCallFake(function () { return undefined; }); playlistServices.addItemsToPlaylist(playlistId, itemIds); expect(swrNotification.error).toHaveBeenCalledWith('You have to select a valid playlist!'); })); it('should initialize the items with an array with single item', inject(function () { var playlistId = 3; var itemIds = ['1']; spyOn(playlistServices, 'findPlaylistById').andCallFake(function () { return new Playlists({ _id: 3, name: 'Name' }); }); spyOn(swrNotification, 'message'); var finalItems = playlistServices.createPlaylistItems(itemIds); var finalPlaylist = {name: 'Name', _id: 3, items: finalItems}; $httpBackend.expectPUT('/api/jimmy/playlists/3', finalPlaylist) .respond(200); playlistServices.addItemsToPlaylist(playlistId, itemIds); expect(swrNotification.message).not.toHaveBeenCalled(); $httpBackend.flush(); expect(swrNotification.message).toHaveBeenCalledWith('1 music has been added'); })); it('should initialize the items with an array with multiple items', inject(function () { var playlistId = 3; var itemIds = ['1', '2']; spyOn(playlistServices, 'findPlaylistById').andCallFake(function () { return new Playlists({ _id: 3, name: 'Name' }); }); spyOn(swrNotification, 'message'); var finalItems = playlistServices.createPlaylistItems(itemIds); var finalPlaylist = {name: 'Name', _id: 3, items: finalItems}; $httpBackend.expectPUT('/api/jimmy/playlists/3', finalPlaylist) .respond(200); playlistServices.addItemsToPlaylist(playlistId, itemIds); expect(swrNotification.message).not.toHaveBeenCalled(); $httpBackend.flush(); expect(swrNotification.message).toHaveBeenCalledWith('2 musics have been added'); })); }); describe('createPlaylistModal', function () { it('should call the modal.open method', inject(function () { spyOn($modal, 'open'); var itemIds = ['1', '2']; playlistServices.createPlaylistModal(itemIds); expect($modal.open).toHaveBeenCalled(); })); }); describe('controllerCreatePlaylistModal', function () { it('should init the variables', inject(function () { var itemIds = ['1', '2']; var modal = playlistServices.createPlaylistModal(itemIds); playlistServices.controllerCreatePlaylistModal(scope, modal, itemIds); expect(scope.itemIds).toBe(itemIds); expect(scope.playlist).toEqual({}); })); it('should dismiss the modal', inject(function () { var itemIds = ['1', '2']; var modal = playlistServices.createPlaylistModal(itemIds); playlistServices.controllerCreatePlaylistModal(scope, modal, itemIds); spyOn(modal, 'dismiss'); expect(modal.dismiss).not.toHaveBeenCalled(); scope.cancel(); expect(modal.dismiss).toHaveBeenCalledWith('cancel'); })); it('should not call the createPlaylistWithItems', inject(function () { var itemIds = ['1', '2']; var modal = playlistServices.createPlaylistModal(itemIds); playlistServices.controllerCreatePlaylistModal(scope, modal, itemIds); spyOn(playlistServices, 'createPlaylistWithItems'); expect(playlistServices.createPlaylistWithItems).not.toHaveBeenCalled(); scope.createPlaylist({$valid: false}); expect(playlistServices.createPlaylistWithItems).not.toHaveBeenCalled(); })); it('should call the createPlaylistWithItems', inject(function () { var itemIds = ['1', '2']; var modal = playlistServices.createPlaylistModal(itemIds); playlistServices.controllerCreatePlaylistModal(scope, modal, itemIds); spyOn(playlistServices, 'createPlaylistWithItems'); expect(playlistServices.createPlaylistWithItems).not.toHaveBeenCalled(); scope.createPlaylist({$valid: true}); expect(playlistServices.createPlaylistWithItems).toHaveBeenCalled(); })); it('should close the modal with the correct params', inject(function () { var itemIds = ['1', '2']; var modal = playlistServices.createPlaylistModal(itemIds); playlistServices.controllerCreatePlaylistModal(scope, modal, itemIds); var response = {status: true}; spyOn(modal, 'close'); spyOn(playlistServices, 'createPlaylistWithItems').andCallFake(function (name, itemIds, func) { func(response); }); expect(modal.close).not.toHaveBeenCalled(); scope.createPlaylist({$valid: true}); expect(modal.close).toHaveBeenCalledWith(response); })); }); describe('getTrackIds', function () { it('should return an empty array', inject(function () { var trackIds = playlistServices.getTrackIds(1); expect(trackIds).toEqual([]); })); it('should return the music id of the playlist items', inject(function () { playlistServices.currentPlaylists = playlistsMock; var trackIds = playlistServices.getTrackIds(2); expect(trackIds).toEqual([12, 34]); })); }); describe('mergeItemPositions', function () { it('should return the second array when there is no playlist', inject(function () { var soundCloudItems = [ {id: 12}, {id: 34} ]; var mergeItems = playlistServices.mergeItemPositions(1, soundCloudItems); expect(mergeItems).toEqual(soundCloudItems); })); it('should return the second array mapped with the id of the playlistItem and the position', inject(function () { var soundCloudItems = [ {id: 12}, {id: 34} ]; playlistServices.currentPlaylists = playlistsMock; var mergeItems = playlistServices.mergeItemPositions(2, soundCloudItems); expect(mergeItems).toEqual([ { id: 12, position: 1 }, { id: 34, position: 2 } ]); })); }); describe('updateMusicPositions', function () { it('should do nothing if the playlist is undefined', inject(function () { spyOn(_, 'each'); playlistServices.playlists = playlistsMock; playlistServices.updateMusicPositions(3, 0, 1); expect(_.each).not.toHaveBeenCalled(); })); it('should do nothing if the two positions are equals', inject(function () { spyOn(_, 'each'); playlistServices.playlists = playlistsMock; playlistServices.updateMusicPositions(2, 1, 1); expect(_.each).not.toHaveBeenCalled(); })); it('should update the position of the items', inject(function () { playlistServices.playlists = playlistsMock; spyOn(utilities, 'getItemById').andCallFake(function () { return new Playlists({ _id: 2, name: 'Name', items: [ {musicId: 12, position: 1}, {musicId: 34, position: 2} ] }); }); var expectedPlaylist = { _id: 2, name: 'Name', items: [ {musicId: 34, position: 0}, {musicId: 12, position: 1} ] }; playlistServices.updateMusicPositions(2, 0, 1); $httpBackend.expectPUT('/api/jimmy/playlists/2', expectedPlaylist) .respond(200); $httpBackend.flush(); })); }); describe('getUserPlaylists', function () { it('should call the query method', inject(function () { spyOn(Playlists, 'query'); playlistServices.getUserPlaylists(1); expect(Playlists.query.mostRecentCall.args[0]).toEqual({userId: 1}); })); it('should set the currentPlaylists variables', inject(function () { spyOn(Playlists, 'query').andCallFake(function (userId, callback) { callback(playlistsMock); }); playlistServices.getUserPlaylists(1); expect(playlistServices.currentPlaylists).toEqual(playlistsMock); })); it('should call the callback function', inject(function () { spyOn(Playlists, 'query').andCallFake(function (userId, callback) { callback(playlistsMock); }); var done = jasmine.createSpy('done'); playlistServices.getUserPlaylists(1, done); expect(done).toHaveBeenCalledWith(playlistsMock); })); }); describe('getFeaturedPlaylists', function () { it('should call the query method with limit set to 5', inject(function () { spyOn(Playlists, 'getFeaturedPlaylists'); playlistServices.getFeaturedPlaylists(); expect(Playlists.getFeaturedPlaylists).toHaveBeenCalledWith({limit: 5}); })); it('should call the query method with the correct limit', inject(function () { spyOn(Playlists, 'getFeaturedPlaylists'); playlistServices.getFeaturedPlaylists(15); expect(Playlists.getFeaturedPlaylists).toHaveBeenCalledWith({limit: 15}); })); }); });
relay_4ch = (function() { var dim = { x: 76, y: 56, z: 15, folga: 0.3, parede: 1.2, altura_pcb: 7, screw_r: 1.6, gap_screw_shell: 3.4, // distância da parede ao centro do screw z_displacement: 0 } function shell() { var shell = cube({ size: [ dim.x + (dim.parede + dim.folga) * 2, dim.y + (dim.parede + dim.folga) * 2, dim.z + dim.z_displacement], center: [1, 1, 0], radius: [1, 1, 0] }) hollow = cube({ size: [ dim.x + dim.folga * 2, dim.y + dim.folga * 2, dim.z + dim.folga * 2], center: [1, 1, 0], radius: [1, 1, 0] }).translate([0, 0, dim.parede + dim.z_displacement]) return shell.subtract(hollow) } function screw_hole(pos) { // return cylinder({r: 1.6 + dim.parede, h: dim.altura_pcb, center: [true, true, false]}) var screw_hole = cube({ size:[16, 16, dim.altura_pcb], fn: 16, //32, // center:[1, 1, 0], radius: [dim.screw_r + dim.parede, dim.screw_r + dim.parede, 0]}) .intersect(cube({ size: [ dim.screw_r + dim.parede + dim.folga + dim.gap_screw_shell, dim.screw_r + dim.parede + dim.folga + dim.gap_screw_shell, dim.altura_pcb]})) .translate([-dim.parede - dim.screw_r, -dim.parede - dim.screw_r , 0]) .subtract(cylinder({r: dim.screw_r, h: dim.altura_pcb, center: [true, true, false]})) .setColor([1,0,0]) if (pos != null) { if (pos.indexOf("S") != -1) { screw_hole = screw_hole.mirroredY() .translate([0, -dim.y/2 + dim.gap_screw_shell, 0]) } else { screw_hole = screw_hole.translate([0, dim.y/2 - dim.gap_screw_shell, 0]) } if (pos.indexOf("W") != -1) { screw_hole = screw_hole.mirroredX() .translate([-dim.x/2 + dim.gap_screw_shell, 0, 0]) } else { screw_hole = screw_hole.translate([dim.x/2 - dim.gap_screw_shell, 0, 0]) } } return screw_hole.translate([0, 0, dim.z_displacement]) } function cable_hole() { return cube({ size: [dim.x + dim.folga * 2, dim.parede * 3, dim.z], center: [1, 1, 0] }) .setColor([1, 0, 0]) .translate([0, dim.y/2 + dim.parede, dim.altura_pcb + dim.z_displacement]) } function base() { return shell() .union(screw_hole("NW")) .union(screw_hole("NE")) .union(screw_hole("SW")) .union(screw_hole("SE")) .subtract(cable_hole()) } function tampa() { lid = cube({ size:[dim.x, 10, dim.altura_pcb + 13 + dim.parede + dim.folga], center: [1, 0, 0], radius: [1,1,1], fn: 16 }) .intersect(cube({ size:[dim.x, 10, 13 + dim.parede + dim.folga], center: [1, 0, 0], }).translate([0,0, dim.altura_pcb])) hollow = cube({ size:[dim.x - 12, 15, dim.altura_pcb + 13 + dim.folga], center: [1, 0, 0], radius: [0, 3, 3], fn: 16 }).translate([0, -dim.parede - 5, 0]) hollow2 = cube({ size:[dim.x - 12, 10, dim.altura_pcb + 7 + dim.folga], center: [1, 0, 0] }) screw1 = cylinder({r: dim.screw_r, h: 17, center: [true, true, false]}) .translate([dim.x/2 - dim.gap_screw_shell, dim.y/2 - dim.gap_screw_shell, dim.altura_pcb]) screw2 = cylinder({r: dim.screw_r, h: 17, center: [true, true, false]}) .translate([-dim.x/2 + dim.gap_screw_shell, dim.y/2 - dim.gap_screw_shell, dim.altura_pcb]) return lid .subtract(hollow) .subtract(hollow2) .translate([0, dim.y/2 - 10, 0]) .subtract(screw1) .subtract(screw2) } return {base, tampa, dim} })() function main() { return relay_4ch.base() }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Acta = mongoose.model('Acta'), config = require('meanio').loadConfig(), _ = require('lodash'); module.exports = function(Actas) { return { /** * Find acta by id */ acta: function(req, res, next, id) { Acta.load(id, function(err, acta) { if (err) return next(err); if (!acta) return next(new Error('Failed to load acta ' + id)); req.acta = acta; next(); }); }, /** * Create an acta */ create: function(req, res) { var acta = new Acta(req.body); acta.user = req.user; acta.save(function(err) { if (err) { return res.status(500).json({ error: 'Cannot save the acta' }); } Actas.events.publish({ action: 'created', user: { name: req.user.name }, url: config.hostname + '/actas/' + acta._id, name: acta.title }); res.json(acta); }); }, /** * Update an acta */ update: function(req, res) { var acta = req.acta; acta = _.extend(acta, req.body); acta.save(function(err) { if (err) { return res.status(500).json({ error: 'Cannot update the acta' }); } Actas.events.publish({ action: 'updated', user: { name: req.user.name }, name: acta.title, url: config.hostname + '/actas/' + acta._id }); res.json(acta); }); }, /** * Delete an acta */ destroy: function(req, res) { var acta = req.acta; acta.remove(function(err) { if (err) { return res.status(500).json({ error: 'Cannot delete the acta' }); } Actas.events.publish({ action: 'deleted', user: { name: req.user.name }, name: acta.title }); res.json(acta); }); }, /** * Show an acta */ show: function(req, res) { Actas.events.publish({ action: 'viewed', user: { name: req.user.name }, name: req.acta.title, url: config.hostname + '/actas/' + req.acta._id }); res.json(req.acta); }, /** * List of Actas */ all: function(req, res) { var query = req.acl.query('Acta'); query.find({}).sort('-created').populate('user', 'name username').exec(function(err, actas) { if (err) { return res.status(500).json({ error: 'Cannot list the actas' }); } res.json(actas) }); } }; }
class UserTableController{ constructor(NgTableParams,$state){ 'ngInject'; this.NgTableParams = NgTableParams; this.$state = $state; } $onInit(){ this.data = [{name: "Moroni", age: 50}]; this.selected = []; this.query = { order: 'name', limit: 5, page: 1 }; this.tableParams = new this.NgTableParams({}, { dataset: this.data}); } } export const UserTableComponent = { templateUrl: './views/app/components/user-table/user-table.component.html', controller: UserTableController, controllerAs: 'vm', bindings: {} }
var searchData= [ ['ue4_5fpagebody',['UE4_PageBody',['../class_u_e4___page_body.html',1,'']]], ['ue4_5fpageheader',['UE4_PageHeader',['../class_u_e4___page_header.html',1,'']]], ['ue4_5fui',['UE4_UI',['../class_u_e4___u_i.html',1,'']]], ['ue4_5fuimodal',['UE4_UIModal',['../class_u_e4___u_i_modal.html',1,'']]], ['ue4_5fuipage',['UE4_UIPage',['../class_u_e4___u_i_page.html',1,'']]], ['ue4_5fuitool',['UE4_UITool',['../class_u_e4___u_i_tool.html',1,'']]], ['ue4_5fuitool_5fdiv',['UE4_UITool_Div',['../class_u_e4___u_i_tool___div.html',1,'']]], ['ue4am',['UE4AM',['../class_u_e4_a_m.html',1,'']]], ['ue4am_5faccount',['UE4AM_Account',['../class_u_e4_a_m___account.html',1,'']]], ['ue4am_5faccounthandler',['UE4AM_AccountHandler',['../class_u_e4_a_m___account_handler.html',1,'']]], ['ue4am_5fapphandler',['UE4AM_AppHandler',['../class_u_e4_a_m___app_handler.html',1,'']]], ['ue4am_5fdbhandler',['UE4AM_DBHandler',['../class_u_e4_a_m___d_b_handler.html',1,'']]], ['ue4am_5fjsonhandler',['UE4AM_JsonHandler',['../class_u_e4_a_m___json_handler.html',1,'']]], ['ue4am_5flog',['UE4AM_Log',['../class_u_e4_a_m___log.html',1,'']]], ['ue4am_5fwebmenu',['UE4AM_WebMenu',['../class_u_e4_a_m___web_menu.html',1,'']]], ['ue4am_5fwebmenuitem',['UE4AM_WebMenuItem',['../class_u_e4_a_m___web_menu_item.html',1,'']]] ];
import * as THREE from 'three'; import * as CANNON from 'cannon'; import store from '../redux/store'; import socket, { playerArr } from '../socket'; import { PointerLockControls } from './PointerLockControls'; import Player from './Player'; import Bomb from './Bomb'; import { animateFire, animatePlayers, animateExplosion, animateBombs, deleteWorld, createMap, getShootDir } from './utils'; let sphereShape, world, physicsMaterial; let camera, scene, renderer, light; let geometry, material, mesh; let controls, time = Date.now(); let clock; export let listener; export let sphereBody; export let bombs = []; export let bombMeshes = []; export let boxes = []; export let boxMeshes = []; export let players = []; export let playerMeshes = []; export let yourBombs = []; export let yourBombMeshes = []; export let playerInstances = []; export const blocksObj = {}; export const blockCount = 50; let bombObjects = []; let count = 1; let dead = false; let nickname = ''; let allowBomb = true; const dt = 1 / 60; let prevStateLength = 0; let counter = 0; const spawnPositions = [ { x: 11.5, y: 1.5, z: -4 }, { x: -36, y: 1.5, z: 36 }, { x: 12.1, y: 1.5, z: 36.4 }, { x: -36.4, y: 1.5, z: -4 }, ] const bombMaterial = new THREE.MeshPhongMaterial({ color: 0x000000, specular: 0x050505, shininess: 100 }) export function initCannon() { /*----- SETS UP WORLD & CHECKS FOR OTHER PLAYERS -----*/ if (socket) { socket.emit('get_players', {}); } world = new CANNON.World(); world.quatNormalizeSkip = 0; world.quatNormalizeFast = false; const solver = new CANNON.GSSolver(); world.defaultContactMaterial.contactEquationStiffness = 1e9; world.defaultContactMaterial.contactEquationRelaxation = 4; solver.iterations = 7; solver.tolerance = 0.1; const split = true; if (split) { world.solver = new CANNON.SplitSolver(solver); } else { world.solver = solver; } /*----- INCREASE SOLVER ITERATIONS (DEF: 10) -----*/ world.solver.iterations = 20; /*----- FORCE SOLVER TO USE ALL ITERATIONS -----*/ world.solver.tolerance = 0; world.gravity.set(0, -40, 0); world.broadphase = new CANNON.NaiveBroadphase(); physicsMaterial = new CANNON.Material('groundMaterial'); /*----- ADJUSTS CONSTRAINT EQUATION PARAMS FOR GROUND/GROUND CONTACT -----*/ const physicsContactMaterial = new CANNON.ContactMaterial(physicsMaterial, physicsMaterial, { friction: 0.7, restitution: 0.3, contactEquationStiffness: 1e8, contactEquationRelaxation: 3, frictionEquationStiffness: 1e8, frictionEquationRegularizationTime: 3, }); /*----- ADD CONTACT MATERIALS TO WORLD -----*/ world.addContactMaterial(physicsContactMaterial); /*----- CREATE A SPHERE -----*/ const mass = 100; const radius = 1.3; sphereShape = new CANNON.Sphere(radius); sphereBody = new CANNON.Body({ mass: mass, material: physicsMaterial }); sphereBody.addShape(sphereShape); sphereBody.position.set(0, 5, 0); sphereBody.linearDamping = 0.9; world.addBody(sphereBody); /*----- CREATE A PLANE -----*/ const groundShape = new CANNON.Plane(); const groundBody = new CANNON.Body({ mass: 0 }); groundBody.addShape(groundShape); groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2); world.addBody(groundBody); } /*----- CANNON SPHERE RADIUS -----*/ const ballShape = new CANNON.Sphere(1.5); const ballGeometry = new THREE.SphereGeometry(ballShape.radius, 32, 32); const shootDirection = new THREE.Vector3(); const shootVelo = 8; const projector = new THREE.Projector(); export function init() { camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1500); camera.position.set(0, 3, 0) scene = new THREE.Scene(); const ambient = new THREE.AmbientLight(0xffffff); scene.add(ambient); light = new THREE.SpotLight(0xffffff); light.position.set(10, 30, 20); light.target.position.set(0, 5, 0); scene.add(light); /*----- CREATE CLOCK FOR FIRE ANIMATION -----*/ clock = new THREE.Clock() controls = new PointerLockControls(camera, sphereBody); scene.add(controls.getObject()); /*----- FLOOR -----*/ geometry = new THREE.PlaneBufferGeometry(125, 125, 50, 50); geometry.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2)); const texture = new THREE.TextureLoader().load('images/grass.png'); material = new THREE.MeshLambertMaterial({ map: texture }); /*----- REPEAT TEXTURE TILING FOR FLOOR -----*/ texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.x = 20; texture.repeat.y = 20; mesh = new THREE.Mesh(geometry, material); scene.add(mesh); /*----- SKYBOX -----*/ const skyGeo = new THREE.SphereGeometry(1000, 32, 32); const skyMaterial = new THREE.MeshBasicMaterial({ color: '#00bfff' }); const sky = new THREE.Mesh(skyGeo, skyMaterial); sky.material.side = THREE.BackSide; scene.add(sky); renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); window.addEventListener('resize', onWindowResize, false); createMap(); sphereBody.position.x = 100; sphereBody.position.y = 100; sphereBody.position.z = 100; listener = new THREE.AudioListener(); camera.add(listener); const others = store.getState().players; let newPlayer; for (let player in others) { if (others[player].nickname) { newPlayer = new Player(player, others[player].x, others[player].y, others[player].z, others[player].dead, others[player].nickname) newPlayer.init() players.push(newPlayer.playerBox) playerMeshes.push(newPlayer.playerMesh) playerInstances.push(newPlayer) } } function shootBomb(velocity) { if (controls.enabled == true && !dead && allowBomb) { /*----- GET CURRENT POSITION TO SHOOT -----*/ let x = sphereBody.position.x; let y = sphereBody.position.y; let z = sphereBody.position.z; const newBomb = new Bomb(count++, { x, y, z }, bombMaterial, socket.id); newBomb.init() allowBomb = false; setTimeout(() => { allowBomb = true; }, 3000) /*----- EMIT RELEVANT BOMB INFO -----*/ const bombInfo = { id: newBomb.id, position: newBomb.bombBody.position, created: Date.now() } socket.emit('add_bomb', { userId: socket.id, bombId: bombInfo.id, position: { x, y, z } }) /*----- REMOVE FROM YOUR FRONTEND BOMBS ARR -----*/ /*----- WILL UPDATE GAMESTATE ON NEXT FRAME -----*/ setTimeout(() => { yourBombs = yourBombs.filter((bomb) => { return bomb.id !== bombInfo.id }) yourBombMeshes = yourBombMeshes.filter(mesh => { return newBomb.bombMesh.id !== mesh.id }) }, 1800) /*----- ADD BOMB & MESH TO YOUR BOMBS ARR -----*/ yourBombs.push(bombInfo) bombObjects.push(newBomb) yourBombMeshes.push(newBomb.bombMesh); /*----- GET DIRECTION USING FUNCTION -----*/ getShootDir(projector, camera, shootDirection); /*----- GIVES BOMB A SHOOT VELOCITY -----*/ newBomb.bombBody.velocity.set(shootDirection.x * velocity, shootDirection.y * velocity, shootDirection.z * velocity); /*----- SHOOT YOUR BOMB -----*/ x += shootDirection.x * (sphereShape.radius * 1.02 + newBomb.bombShape.radius); y += shootDirection.y * (sphereShape.radius * 1.02 + newBomb.bombShape.radius); z += shootDirection.z * (sphereShape.radius * 1.02 + newBomb.bombShape.radius); newBomb.bombBody.position.set(x, y, z); newBomb.bombMesh.position.set(x, y, z); } } if (controls) { window.addEventListener('click', (e) => { shootBomb(shootVelo) }) window.addEventListener('keydown', (event) => { if (event.keyCode === 32) { shootBomb(40) } }) } /*----- PLAYERS STILL RECEIVE GAMESTATE WHEN INACTIVE-----*/ setInterval(() => { if (socket) { socket.emit('update_world', { playerId: socket.id, playerPosition: { x: sphereBody.position.x, y: sphereBody.position.y, z: sphereBody.position.z }, dead: dead, playerBombs: yourBombs }); } counter++; /*----- SETS PLAYER SPAWN AFTER GETTING INIT STATE FROM SOCKETS -----*/ if (counter === 50) { sphereBody.position.x = spawnPositions[playerArr.indexOf(socket.id)].x; sphereBody.position.y = 5 sphereBody.position.z = spawnPositions[playerArr.indexOf(socket.id)].z; } /*----- ALLOWS WALKING IN CANNONJS -----*/ world.step(dt); /*----- GETS CURRENT STATE -----*/ const state = store.getState(); const others = state.players; const playerIds = Object.keys(others) const allBombs = state.bombs; const stateBombs = []; for (let key in allBombs) { let userBombs = allBombs[key].map((bomb) => { bomb.userId = key return bomb }) stateBombs.push(...userBombs) } if (playerIds.length !== players.length) { players.forEach(body => { world.remove(body) }) playerMeshes.forEach(playermesh => { scene.remove(playermesh) }) players = []; playerMeshes = []; playerInstances = []; for (let player in others) { /*----- CHECKS IF PLAYER HAS NICKNAME BEFORE CREATING NEW PLAYER -----*/ if (others[player].nickname) { let newPlayer; newPlayer = new Player(player, others[player].x, others[player].y, others[player].z, false) newPlayer.init() players.push(newPlayer.playerBox) playerMeshes.push(newPlayer.playerMesh) playerInstances.push(newPlayer) } } } /*----- ADDS NEW BOMB IF THERE IS ONE -----*/ if (stateBombs.length > prevStateLength) { const mostRecentBomb = stateBombs[stateBombs.length - 1] const newBomb = new Bomb(mostRecentBomb.id, mostRecentBomb.position, bombMaterial, mostRecentBomb.userId) newBomb.init() bombs.push(newBomb.bombBody) bombObjects.push(newBomb) bombMeshes.push(newBomb.bombMesh) } /*----- RESTS PREV STATE LENGTH -----*/ prevStateLength = stateBombs.length /*----- ANIMATE FIRE W/ BOMB -----*/ dead = animateFire(bombObjects, clock, dead) /*----- UPDATE PLAYER POSITIONS -----*/ animatePlayers(players, playerIds, others, playerMeshes) /*----- ANIMATE EXPLOSION PARTICLES -----*/ animateExplosion(blocksObj) /*----- ANIMATE BOMB POSITIONS -----*/ animateBombs(yourBombs, yourBombMeshes, bombs, stateBombs, bombMeshes, prevStateLength) }, 1000 / 60) } export function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } /*----- ANIMATION GAME LOOP & THROTTLE LOOP-----*/ export function animate() { setTimeout(() => { requestAnimationFrame(animate); }, 1000 / 60) controls.update(Date.now() - time); renderer.render(scene, camera); time = Date.now(); } /*----- CLEAR AND REBUILD MAP TO RESTART & RESPAWN PLAYER -----*/ export function restartWorld() { deleteWorld(scene, world, boxMeshes, boxes, bombs, bombMeshes, yourBombs, bombObjects, yourBombMeshes, players, playerMeshes); boxMeshes = []; boxes = []; bombs = []; bombMeshes = []; yourBombs = []; bombObjects = []; yourBombMeshes = []; players = []; playerMeshes = []; playerInstances = []; createMap(); sphereBody.position.x = spawnPositions[playerArr.indexOf(socket.id)].x; sphereBody.position.y = 5; sphereBody.position.z = spawnPositions[playerArr.indexOf(socket.id)].z; dead = false; } export { scene, camera, renderer, controls, light, world, dead }
/* eslint-env qunit */ /* globals os:true */ module('Basics', { setup: function() { Optiscroll.globalSettings.checkFrequency = 300; os = new window.Optiscroll(document.querySelector('#os')); }, teardown: function() { os.destroy(); Optiscroll.G.instances.length = 0; os = null; }, }); test('It should be initialized', function () { equal(typeof os, 'object'); // check DOM elements equal(os.element.childNodes.length, 3); equal(os.scrollEl.childNodes.length, 7); // check globals equal(Optiscroll.G.instances.length, 1); ok(Optiscroll.G.checkTimer); }); asyncTest('Optiscroll should be destroyed', function () { expect(5); os.destroy(); setTimeout(function () { // check DOM elements style ok(!os.scrollEl); equal(os.element.childNodes.length, 7); equal(os.element.className.indexOf('is-enabled'), -1); // check globals equal(Optiscroll.G.instances.length, 0); equal(Optiscroll.G.checkTimer, null); start(); }, 1000); }); asyncTest('Optiscroll should auto update itself', function () { expect(4); os.element.style.width = '300px'; os.element.style.height = '300px'; setTimeout(function () { equal(os.cache.clientW, 300); equal(os.cache.clientH, 300); equal(os.cache.scrollW, 300); equal(os.cache.scrollH, 300); start(); }, 700); }); asyncTest('Optiscroll should auto destroy itself', function () { expect(2); os.element.parentNode.removeChild(os.element); setTimeout(function () { // check globals equal(Optiscroll.G.instances.length, 0); equal(Optiscroll.G.checkTimer, null); start(); }, 1000); });
var columnMeta = [ { "columnName": "id", "order": 1, "locked": false, "visible": true }, { "columnName": "name", "order": 2, "locked": false, "visible": true }, { "columnName": "city", "order": 3, "locked": false, "visible": true }, { "columnName": "state", "order": 4, "locked": false, "visible": true }, { "columnName": "country", "order": 5, "locked": false, "visible": true }, { "columnName": "company", "order": 6, "locked": false, "visible": true }, { "columnName": "favoriteNumber", "order": 7, "locked": false, "visible": true } ]; module.exports.columnMeta = columnMeta;
/*************************************************************** * JS-TrackBar * * Copyright (C) 2008 by Alexander Burtsev - http://webew.ru/ * and abarmot - http://abarmot.habrahabr.ru/ * and 1602 - http://1602.habrahabr.ru/ * desing: Ñâåòëàíà Ñîëîâüåâà - http://my.mail.ru/bk/concur/ * * This code is a public domain. ***************************************************************/ $.fn.trackbar = function(op){ op = $.extend({ onMove: function(){}, dual: true, width: 250, // px leftLimit: 0, // unit of value leftValue: 500, // unit of value rightLimit: 5000, // unit of value rightValue: 1500, // unit of value //roundUp: 50, // unit of value jq: this },op); $.trackbar.getObject().init(op); } $.trackbar = { // NAMESPACE archive : [], getObject : function(id) { if(typeof id == 'undefined')id = this.archive.length; if(typeof this.archive[id] == "undefined"){ this.archive[id] = new this.hotSearch(id); } return this.archive[id]; } }; $.trackbar.hotSearch = function(id) { // Constructor // Vars this.id = id; this.leftWidth = 0; // px this.rightWidth = 0; // px this.width = 0; // px this.intervalWidth = 0; // px this.leftLimit = 0; this.leftValue = 0; this.rightLimit = 0; this.rightValue = 0; this.valueInterval = 0; this.widthRem = 6; this.valueWidth = 0; this.roundUp = 0; this.x0 = 0; this.y0 = 0; this.blockX0 = 0; this.rightX0 = 0; this.leftX0 = 0; // Flags this.dual = true; this.moveState = false; this.moveIntervalState = false; this.debugMode = false; this.clearLimits = false; this.clearValues = false; // Handlers this.onMove = null; // Nodes this.leftBlock = null; this.rightBlock = null; this.leftBegun = null; this.rightBegun = null; this.centerBlock = null; this.itWasMove = false; } $.trackbar.hotSearch.prototype = { // Const ERRORS : { 1 : "Îøèáêà ïðè èíèöèàëèçàöèè îáúåêòà", 2 : "Ëåâûé áåãóíîê íå íàéäåí", 3 : "Ïðàâûé áåãóíîê íå íàéäåí", 4 : "Ëåâàÿ îáëàñòü ðåñàéçà íå íàéäåíà", 5 : "Ïðàâàÿ îáëàñòü ðåñàéçà íå íàéäåíà", 6 : "Íå çàäàíà øèðèíà îáëàñòè áåãóíêà", 7 : "Íå óêàçàíî ìàêñèìàëüíîå èçìåíÿåìîå çíà÷åíèå", 8 : "Íå óêàçàíà ôóíêöèÿ-îáðàáîò÷èê çíà÷åíèé", 9 : "Íå óêàçàíà îáëàñòü êëèêà" }, LEFT_BLOCK_PREFIX : "leftBlock", RIGHT_BLOCK_PREFIX : "rightBlock", LEFT_BEGUN_PREFIX : "leftBegun", RIGHT_BEGUN_PREFIX : "rightBegun", CENTER_BLOCK_PREFIX : "centerBlock", // Methods // Default gebi : function(id) { return this.jq.find('#'+id)[0]; }, addHandler : function(object, event, handler, useCapture) { if (object.addEventListener) { object.addEventListener(event, handler, useCapture ? useCapture : false); } else if (object.attachEvent) { object.attachEvent('on' + event, handler); } else alert(this.errorArray[9]); }, defPosition : function(event) { var x = y = 0; if (document.attachEvent != null) { x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } if (!document.attachEvent && document.addEventListener) { // Gecko x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } return {x:x, y:y}; }, absPosition : function(obj) { var x = y = 0; while(obj) { x += obj.offsetLeft; y += obj.offsetTop; obj = obj.offsetParent; } return {x:x, y:y}; }, // Common debug : function(keys) { if (!this.debugMode) return; var mes = ""; for (var i = 0; i < keys.length; i++) mes += this.ERRORS[keys[i]] + " : "; mes = mes.substring(0, mes.length - 3); alert(mes); }, init : function(hash) { try { this.dual = typeof hash.dual != "undefined" ? !!hash.dual : this.dual; this.leftLimit = hash.leftLimit || this.leftLimit; this.rightLimit = hash.rightLimit || this.rightLimit; this.width = hash.width || this.width; this.onMove = hash.onMove || this.onMove; this.clearLimits = hash.clearLimits || this.clearLimits; this.clearValues = hash.clearValues || this.clearValues; this.roundUp = hash.roundUp || this.roundUp; this.jq = hash.jq; // HTML Write this.jq.html('<table' + (this.width ? ' style="width:'+this.width+'px;"' : '') + 'class="trackbar" onSelectStart="return false;">\ <tr>\ <td class="l"><div id="leftBlock"><span></span><span class="limit"></span><img id="leftBegun" ondragstart="return false;" src="/catalog/Tel_shop/trackbar/imgtrackbar/b_l.gif" width="5" height="17" alt="" /></div></td>\ <td class="c" id="centerBlock"></td>\ <td class="r"><div id="rightBlock"><span></span><span class="limit"></span><img id="rightBegun" ondragstart="return false;" src="/catalog/Tel_shop/trackbar/imgtrackbar/b_r.gif" width="5" height="17" alt="" /></div></td>\ </tr>\ </table>'); // Is all right? if (this.onMove == null) { this.debug([1,8]); return; } // --- this.leftBegun = this.gebi(this.LEFT_BEGUN_PREFIX); if (this.leftBegun == null) { this.debug([1,2]); return; } this.rightBegun = this.gebi(this.RIGHT_BEGUN_PREFIX); if (this.rightBegun == null) { this.debug([1,3]); return; } this.leftBlock = this.gebi(this.LEFT_BLOCK_PREFIX); if (this.leftBlock == null) { this.debug([1,4]); return; } this.rightBlock = this.gebi(this.RIGHT_BLOCK_PREFIX); if (this.rightBlock == null) { this.debug([1,5]); return; } this.centerBlock = this.gebi(this.CENTER_BLOCK_PREFIX); if (this.centerBlock == null) { this.debug([1,9]); return; } // --- if (!this.width) { this.debug([1,6]); return; } if (!this.rightLimit) { this.debug([1,7]); return; } // Set default this.valueWidth = this.width - 2 * this.widthRem; this.rightValue = hash.rightValue || this.rightLimit; this.leftValue = hash.leftValue || this.leftLimit; if (!this.dual) this.rightValue = this.leftValue; this.valueInterval = this.rightLimit - this.leftLimit; this.leftWidth = parseInt((this.leftValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem; this.rightWidth = this.valueWidth - parseInt((this.rightValue - this.leftLimit) / this.valueInterval * this.valueWidth) + this.widthRem; // Set limits if (!this.clearLimits) { this.leftBlock.firstChild.nextSibling.innerHTML = this.leftLimit; this.rightBlock.firstChild.nextSibling.innerHTML = this.rightLimit; } // Do it! this.setCurrentState(); this.onMove(); // Add handers var _this = this; this.addHandler ( document, "mousemove", function(evt) { if (_this.moveState) _this.moveHandler(evt); if (_this.moveIntervalState) _this.moveIntervalHandler(evt); } ); this.addHandler ( document, "mouseup", function() { _this.moveState = false; _this.moveIntervalState = false; } ); this.addHandler ( this.leftBegun, "mousedown", function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; _this.moveState = "left"; _this.x0 = _this.defPosition(evt).x; _this.blockX0 = _this.leftWidth; } ); this.addHandler ( this.rightBegun, "mousedown", function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; _this.moveState = "right"; _this.x0 = _this.defPosition(evt).x; _this.blockX0 = _this.rightWidth; } ); this.addHandler ( this.centerBlock, "mousedown", function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; _this.moveIntervalState = true; _this.intervalWidth = _this.width - _this.rightWidth - _this.leftWidth; _this.x0 = _this.defPosition(evt).x; _this.rightX0 = _this.rightWidth; _this.leftX0 = _this.leftWidth; } ), this.addHandler ( this.centerBlock, "click", function(evt) { if (!_this.itWasMove) _this.clickMove(evt); _this.itWasMove = false; } ); this.addHandler ( this.leftBlock, "click", function(evt) { if (!_this.itWasMove)_this.clickMoveLeft(evt); _this.itWasMove = false; } ); this.addHandler ( this.rightBlock, "click", function(evt) { if (!_this.itWasMove)_this.clickMoveRight(evt); _this.itWasMove = false; } ); } catch(e) {this.debug([1]);} }, clickMoveRight : function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; var x = this.defPosition(evt).x - this.absPosition(this.rightBlock).x; var w = this.rightBlock.offsetWidth; if (x <= 0 || w <= 0 || w < x || (w - x) < this.widthRem) return; this.rightWidth = (w - x); this.rightCounter(); this.setCurrentState(); this.onMove(); }, clickMoveLeft : function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; var x = this.defPosition(evt).x - this.absPosition(this.leftBlock).x; var w = this.leftBlock.offsetWidth; if (x <= 0 || w <= 0 || w < x || x < this.widthRem) return; this.leftWidth = x; this.leftCounter(); this.setCurrentState(); this.onMove(); }, clickMove : function(evt) { evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; var x = this.defPosition(evt).x - this.absPosition(this.centerBlock).x; var w = this.centerBlock.offsetWidth; if (x <= 0 || w <= 0 || w < x) return; if (x >= w / 2) { this.rightWidth += (w - x); this.rightCounter(); } else { this.leftWidth += x; this.leftCounter(); } this.setCurrentState(); this.onMove(); }, setCurrentState : function() { this.leftBlock.style.width = this.leftWidth + "px"; if (!this.clearValues) this.leftBlock.firstChild.innerHTML = (!this.dual && this.leftWidth > this.width / 2) ? "" : this.leftValue; if(!this.dual) { var x = this.leftBlock.firstChild.offsetWidth; this.leftBlock.firstChild.style.right = (this.widthRem * (1 - 2 * (this.leftWidth - this.widthRem) / this.width) - ((this.leftWidth - this.widthRem) * x / this.width)) + 'px'; } this.rightBlock.style.width = this.rightWidth + "px"; if (!this.clearValues) this.rightBlock.firstChild.innerHTML = (!this.dual && this.rightWidth >= this.width / 2) ? "" : this.rightValue; if(!this.dual) { var x = this.rightBlock.firstChild.offsetWidth; this.rightBlock.firstChild.style.left = (this.widthRem * (1 - 2 * (this.rightWidth - this.widthRem) / this.width) - ((this.rightWidth - this.widthRem) * x / this.width)) + 'px'; } }, /* OLD setCurrentState : function() { this.leftBlock.style.width = this.leftWidth + "px"; this.leftBlock.firstChild.innerHTML = (!this.dual && this.leftWidth > this.width / 2) ? "" : this.leftValue; this.rightBlock.style.width = this.rightWidth + "px"; this.rightBlock.firstChild.innerHTML = (!this.dual && this.rightWidth >= this.width / 2) ? "" : this.rightValue; },*/ moveHandler : function(evt) { this.itWasMove = true; evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; if (this.moveState == "left") { this.leftWidth = this.blockX0 + this.defPosition(evt).x - this.x0; this.leftCounter(); } if (this.moveState == "right") { this.rightWidth = this.blockX0 + this.x0 - this.defPosition(evt).x; this.rightCounter(); } this.setCurrentState(); this.onMove(); }, moveIntervalHandler : function(evt) { this.itWasMove = true; evt = evt || window.event; if (evt.preventDefault) evt.preventDefault(); evt.returnValue = false; var dX = this.defPosition(evt).x - this.x0; if (dX > 0) { this.rightWidth = this.rightX0 - dX > this.widthRem ? this.rightX0 - dX : this.widthRem; this.leftWidth = this.width - this.rightWidth - this.intervalWidth; } else { this.leftWidth = this.leftX0 + dX > this.widthRem ? this.leftX0 + dX : this.widthRem; this.rightWidth = this.width - this.leftWidth - this.intervalWidth; } this.rightCounter(); this.leftCounter(); this.setCurrentState(); this.onMove(); }, rightCounter : function() { if (this.dual) { this.rightWidth = this.rightWidth > this.width - this.leftWidth ? this.width - this.leftWidth : this.rightWidth; this.rightWidth = this.rightWidth < this.widthRem ? this.widthRem : this.rightWidth; this.rightValue = this.leftLimit + this.valueInterval - parseInt((this.rightWidth - this.widthRem) / this.valueWidth * this.valueInterval); if (this.roundUp) this.rightValue = parseInt(this.rightValue / this.roundUp) * this.roundUp; if (this.leftWidth + this.rightWidth >= this.width) this.rightValue = this.leftValue; } else { this.rightWidth = this.rightWidth > (this.width - this.widthRem) ? this.width - this.widthRem : this.rightWidth; this.rightWidth = this.rightWidth < this.widthRem ? this.widthRem : this.rightWidth; this.leftWidth = this.width - this.rightWidth; this.rightValue = this.leftLimit + this.valueInterval - parseInt((this.rightWidth - this.widthRem) / this.valueWidth * this.valueInterval); if (this.roundUp) this.rightValue = parseInt(this.rightValue / this.roundUp) * this.roundUp; this.leftValue = this.rightValue; } }, leftCounter : function() { if (this.dual) { this.leftWidth = this.leftWidth > this.width - this.rightWidth ? this.width - this.rightWidth : this.leftWidth; this.leftWidth = this.leftWidth < this.widthRem ? this.widthRem : this.leftWidth; this.leftValue = this.leftLimit + parseInt((this.leftWidth - this.widthRem) / this.valueWidth * this.valueInterval); if (this.roundUp) this.leftValue = parseInt(this.leftValue / this.roundUp) * this.roundUp; if (this.leftWidth + this.rightWidth >= this.width) this.leftValue = this.rightValue; } else { this.leftWidth = this.leftWidth > (this.width - this.widthRem) ? this.width - this.widthRem : this.leftWidth; this.leftWidth = this.leftWidth < this.widthRem ? this.widthRem : this.leftWidth; this.rightWidth = this.width - this.leftWidth; this.leftValue = this.leftLimit + parseInt((this.leftWidth - this.widthRem) / this.valueWidth * this.valueInterval); if (this.roundUp) this.leftValue = parseInt(this.leftValue / this.roundUp) * this.roundUp; this.rightValue = this.leftValue; } } }
/* eslint-env jest */ /* global jasmine */ import { join } from 'path' import { renderViaHTTP, runNextCommand, nextServer, startApp, stopApp } from 'next-test-utils' jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 let app let appPort let server const appDir = join(__dirname, '../') describe('Legacy Packages', () => { beforeAll(async () => { await runNextCommand(['build', appDir]) app = nextServer({ dir: appDir, dev: false, quiet: true }) server = await startApp(app) appPort = server.address().port }) it('should support `node-gently` packages', async () => { const res = await renderViaHTTP(appPort, '/api/hello') expect(res).toMatch(/hello world/i) }) afterAll(() => stopApp(server)) })
'use strict'; angular.module("sselabWebApp").controller("BlogCtrl", function ($scope, $routeParams, $http, $sce) { // view blog detail var blogTitle = $routeParams.title; $scope.isDetail = !!blogTitle; // filter by tag var blogTag = $routeParams.tag; // pagination var limit = 5; var currentPage = $routeParams.currentPage || 1; var blogs = [ {"title": "blog template demo", "author": "x-web", "date": "2016-04-10", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["spark"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-13", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["spark", "hadoop"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-15", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["hive"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-09", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["mysql", "hbase"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["d3"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["zeppelin"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["flume"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["hive"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["logs"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-09", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["mysql", "hbase"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["d3"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["zeppelin"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["flume"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["hive"]}, {"title": "blog template demo", "author": "x-web", "date": "2016-04-14", "digest": "This is a simple blog demo by angular-sap(static).", "tags": ["logs"]} ]; // tags $scope.blogTags = {}; for (var i = 0; i < blogs.length; i++) { for (var j = 0; j < blogs[i].tags.length; j++) { var tag = blogs[i].tags[j]; if (typeof $scope.blogTags[tag] === 'undefined') { $scope.blogTags[tag] = tag; } } } // filter by tag $scope.blogs = []; for (var i = 0; i < blogs.length; i++) { if (!blogTag || blogs[i].tags.join('-').indexOf(blogTag) > -1) { $scope.blogs.push(blogs[i]); } } $scope.currentTag = blogTag || "all"; // sorted by date $scope.blogs.sort(function (a, b) { if (a.date > b.date) { return -1; } else if (a.date < b.date) { return 1; } else { return 0; } }); // pagination var pages = Math.ceil($scope.blogs.length / limit); var start = (currentPage - 1) * limit; var end = start + limit; $scope.blogs = $scope.blogs.slice(start, end); $scope.pages = []; for (var i = 0; i < pages; i++) { $scope.pages.push(i); } $scope.currentPage = currentPage; // blog detail if ($scope.isDetail) { $scope.blogData = {"title": "Not Found!", "date": "1970-01-01", "author": "none"}; for (var i = 0; i < $scope.blogs.length; i++) { if (blogTitle.substr(11) === $scope.blogs[i].title.trim().toLowerCase().replace(/[ ]+/g, '-')) { $scope.blogData = $scope.blogs[i]; $http.get("data/blog/" + blogTitle + ".md").success(function (d) { $scope.blogData.content = $sce.trustAsHtml(marked(d)); $scope.$watch("viewContentLoaded", function() { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); $scope.$watch("viewContentLoaded", function() { (function() { var d = document, s = d.createElement('script'); s.src = '//sselab.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); }); }).error(function () { console.warn(blogTitle + " not existed!"); $scope.blogData.content = $sce.trustAsHtml("<h2>No such file found.</h2>"); }); } } } else { $scope.$watch("viewContentLoaded", function() { (function() { var d = document, s = d.createElement('script'); s.src = '//sselab.disqus.com/count.js'; s.async = 'async'; s.id = 'dsq-count-scr'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); }); } }).filter("blogNameGenerator", function() { return function(title) { return title.trim().toLowerCase().replace(/[ ]+/g, "-"); }; });
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Transition from 'react-motion-ui-pack'; import Dialog from '../Dialog'; import DatetimePicker from '../DatetimePicker'; import A from '../A'; export const Container = styled.div` position: fixed; bottom: 0; left: 0; right: 0; `; export const Header = styled.header` height: ${props => props.theme.height.normal}; background-color: ${props => props.theme.color.white}; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid ${props => props.theme.color.grayBase}; `; export const StyledA = styled(A)` display: flex; align-items: center; justify-content: center; height: 100%; padding: 0 16px; `; class DatetimePickerDialog extends React.Component { static propTypes = { datetimePickerProps: PropTypes.shape({ defaultValue: PropTypes.number.isRequired, // Unix Timestamp (milliseconds) years: PropTypes.array, }), show: PropTypes.bool, onHide: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; static defaultProps = { show: false, }; constructor(props) { super(props); this.state = { value: props.datetimePickerProps.defaultValue }; } onChange = value => this.setState({ value }); onCancel = () => { this.setState({ value: this.props.datetimePickerProps.defaultValue }); this.props.onHide(); }; onSubmit = () => { this.props.onSubmit(this.state.value); this.props.onHide(); }; render() { const { onChange, onSubmit, onCancel } = this; const { show, datetimePickerProps } = this.props; return ( <Dialog show={show}> <Transition component={false} enter={{ translateY: 0 }} leave={{ translateY: 40 }} > <Container key="container"> <Header> <StyledA onClick={onCancel}>Cancel</StyledA> <StyledA onClick={onSubmit}>OK</StyledA> </Header> <DatetimePicker {...datetimePickerProps} onChange={onChange} /> </Container> </Transition> </Dialog> ); } } export default DatetimePickerDialog;
function battery_connect() { let serviceUuid = "battery_service"; let characteristicUuid = "battery_level" navigator.bluetooth.requestDevice ({ filters: [{ services: [serviceUuid] }] , optionalServices: [serviceUuid] }) .then(device => { return device.gatt.connect(); }) .then(server => { return server.getPrimaryService(serviceUuid); }) .then(service => { return service.getCharacteristic(characteristicUuid); }) .then(characteristic => { return characteristic.readValue(); }) .then(value => { var percentage = value.getUint8(0); setBatteryPercentage(percentage); log('Battery percentage is ' + percentage); }) .catch(error => { log('Error! ' + error); }); }
/* jslint node: true */ "use strict"; var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // app.use(bodyParser.urlencoded({ // extended: true // })); // app.use(bodyParser.json()); var http = require('http'); app.get('/', function(req, res) { http.request({ host: process.env.SERVER_NAME1 || 'server1', path: '/', port: '80', method: 'GET' }, function(resApi1) { http.request({ host: process.env.SERVER_NAME2 || 'server2', path: '/', port: '80', method: 'GET' }, function(resApi2) { res.writeHead(resApi1.statusCode); resApi1.pipe(res); resApi2.pipe(res); console.log("Response received!"); } ).end(); } ).end(); }); app.listen(process.env.PORT || 80, function() { console.log('server listen on port ' + (process.env.PORT || 80)); });
/*home View-Model*/ var about = (function (window, $, ko, app, undefined) { 'use strict'; /** * view{} is initialized to be the main object literal of about view. * */ var view = { observables : { initial : { content : { h1 : {text : 'SPA Prototyping Boilerplate for KnockoutJS / About'}, p : {text : 'This is a KnockoutJS boilerplate code for Prototyping a Single-Page Application.'}, a : {text : 'Go Home'} } }, content : { h1 : {text : ''}, p : {text : ''}, a : {text : ''} } }, el : { wrapper : document.getElementById('js-vm-about') }, /** * applyBinding() binds view-model for the specific view. * */ applyBinding : function () { app.applyBinding('about', view, view.el.wrapper); }, /** * init() can be used to initialize any module, invoke a method or function and etc. * */ init : function () { view.applyBinding(); } }; /** * DOMContentLoaded waits until the whole content loaded. * */ window.addEventListener("DOMContentLoaded", function() { view.init(); }, false); return { view : view } })(window, jQuery, ko, app);
process.env.NODE_ENV = process.env.NODE_ENV || `production`; const jsdom = require(`jsdom`); global.document = jsdom.jsdom(); global.window = document.defaultView; window.APP_META = { BROWSER: false }; require(`babel-register`); require(`./prod`);
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-highcharts', setupPreprocessorRegistry: function(type, registry) { var options = getOptions(this.parent && this.parent.options && this.parent.options['babel']); var plugin = { name : 'ember-cli-babel', ext : 'js', toTree : function(tree) { return require('broccoli-babel-transpiler')(tree, options); } }; registry.add('js', plugin); }, included: function(app) { this._super.included(app); var options = app.options.emberHighCharts || {includeHighCharts: true}; if (options.includeHighCharts) { app.import('vendor/highcharts-release/highcharts.src.js'); } if (options.includeHighStock) { app.import('vendor/highstock-release/highstock.src.js'); } if (options.includeHighMaps) { app.import('vendor/highmaps-release/highmaps.src.js'); } } }; function getOptions(options) { options = options || {}; // Ensure modules aren't compiled unless explicitly set to compile options.blacklist = options.blacklist || ['es6.modules']; if (options.compileModules === true) { if (options.blacklist.indexOf('es6.modules') >= 0) { options.blacklist.splice(options.blacklist.indexOf('es6.modules'), 1); } delete options.compileModules; } else { if (options.blacklist.indexOf('es6.modules') < 0) { options.blacklist.push('es6.modules'); } } // Ember-CLI inserts its own 'use strict' directive options.blacklist.push('useStrict'); return options; }
var SpaceAge = require('./space-age'); describe('Space Age', function() { it('age in seconds', function() { var age = new SpaceAge(1000000); expect(age.seconds).toEqual(1000000); }); it('age in earth years', function() { var age = new SpaceAge(1000000000); expect(age.onEarth()).toEqual(31.69); }); it('age in mercury years', function() { var age = new SpaceAge(2134835688); expect(age.onEarth()).toEqual(67.65); expect(age.onMercury()).toEqual(280.88); }); it('age in venus years', function() { var age = new SpaceAge(189839836); expect(age.onEarth()).toEqual(6.02); expect(age.onVenus()).toEqual(9.78); }); it('age in mars years', function() { var age = new SpaceAge(2329871239); expect(age.onEarth()).toEqual(73.83); expect(age.onMars()).toEqual(39.25); }); it('age in jupiter years', function() { var age = new SpaceAge(901876382); expect(age.onEarth()).toEqual(28.58); expect(age.onJupiter()).toEqual(2.41); }); it('age in saturn years', function() { var age = new SpaceAge(3000000000); expect(age.onEarth()).toEqual(95.06); expect(age.onSaturn()).toEqual(3.23); }); it('age in uranus years', function() { var age = new SpaceAge(3210123456); expect(age.onEarth()).toEqual(101.72); expect(age.onUranus()).toEqual(1.21); }); it('age in neptune year', function() { var age = new SpaceAge(8210123456); expect(age.onEarth()).toEqual(260.16); expect(age.onNeptune()).toEqual(1.58); }); });
// Regular expression that matches all symbols in the `Sharada` script as per Unicode v10.0.0: /\uD804[\uDD80-\uDDCD\uDDD0-\uDDDF]/;
// Generated by CoffeeScript 2.0.0 (function() { /* CoffeeScript Twitch Subscription Notifier v1.0 Released under the MIT License */ var ENDOFMOTD, MAGICNICK, Notifier, PINGREGEX, SUBNOTIFY, info; MAGICNICK = "justinfan427138773870"; ENDOFMOTD = /^:tmi.twitch.tv 376 /; PINGREGEX = /^PING :tmi.twitch.tv$/; SUBNOTIFY = /;display-name=(\w+);.*;msg-id=(?:re)?sub;msg-param-months=(\d+);/; info = function(msg) { return console.log(`[INFO] ${msg}`); }; Notifier = class Notifier { constructor(channel1, subCallback) { this.onOpen = this.onOpen.bind(this); this.onMessage = this.onMessage.bind(this); this.onPing = this.onPing.bind(this); this.channel = channel1; this.subCallback = subCallback; } start() { info("Connecting..."); this.ws = new WebSocket("ws://irc-ws.chat.twitch.tv", "irc"); this.ws.onopen = this.onOpen; return this.ws.onmessage = this.onMessage; } registerUser() { info("Registering user..."); return this.ws.send(`NICK ${MAGICNICK}\r\n`); } requestCaps() { info("Requesting extra capabilities..."); this.ws.send("CAP REQ :twitch.tv/tags\r\n"); return this.ws.send("CAP REQ :twitch.tv/commands\r\n"); } joinChannel() { info(`Joining #${this.channel}...`); return this.ws.send(`JOIN #${this.channel}\r\n`); } onOpen(evt) { info("Successfully opened connection."); this.registerUser(); return this.requestCaps(); } onMessage(evt) { var data, i, len, match, message, months, ref, results; data = evt.data.trim(); ref = data.split("\r\n"); results = []; for (i = 0, len = ref.length; i < len; i++) { message = ref[i]; switch (false) { case !PINGREGEX.test(message): results.push(this.onPing()); break; case !ENDOFMOTD.test(message): results.push(this.joinChannel()); break; case !/USERNOTICE/.test(message): match = SUBNOTIFY.exec(message); if (match != null) { months = parseInt(match[2]); results.push(this.subCallback(match[1], months)); } else { results.push(void 0); } break; default: results.push(void 0); } } return results; } onPing() { info("Responding to PING message..."); return this.ws.send("PONG\r\n"); } }; this.startNotifier = function(channel, callback) { var notifier; info(`Starting CoffeeScript Twitch Subscription Notifier for ${channel}`); notifier = new Notifier(channel, callback); return notifier.start(); }; }).call(this);
/*------------------------------------------------- SUPER for Router and Endpoint ---------------------------------------------------*/ /** * adding common functionality * * @constructor prototype * @private */ function Super ( extend ) { // extend prototype wich be created Object.assign.apply(Object,[this].concat(Array.prototype.slice.call(arguments, 0))); }; Super.prototype = { constructor: Super, /** * to adding a handlers for router endpoint methods * * @param secret: { Symbol } * @param method: { String } - name of method * @param listeners: { Array|Function } - listeners of request * @returns: { Object } */ on: function ( secret, method, listeners ) { var map = this[secret]; method = method.toUpperCase(); assert( // to add a listener to request it must exist isSupportedMethod(method), 'Node.js '+process.version+' doesn`t support method '+method ); assert( // listners must be a function or array with functions is.function(listeners)||is.array(listeners), 'listners must be a function or array with functions '+listeners ); // if it first listner map[method] = map[method] || []; if ( is.array(listeners) ) { for ( var key = 0; key < listeners.length; key ++ ) {// each listeners must be a function assert(is.function(listeners[key]), 'listners must be a function or array with functions '+listeners); } map[method] = map[method].concat(listeners); } else if ( is.function(listeners) ) map[method].push(listeners); // debug('add listner on '+method+' for '+this.instance+' "'+this.id+'"'); return this; }, /** * executed before queue point * * @param: { Array|Function } * @returns: { Object } */ use: function alias ( listeners ) { return this.on('PREPROCESSOR', listeners); }, }; /*------------------------------------------------- Create a method nammed like express ---------------------------------------------------*/ for ( var key = 0; key < supportedMethods.length; key ++ ) { Super.prototype[supportedMethods[key].toLowerCase()] = (function ( name ) { return function alias ( listeners ) { return this.on(name, listeners); } })(supportedMethods[key]); }
import path from 'path' import { argv } from 'yargs' const env = process.env.NODE_ENV || 'development' const envConfig = require('./' + env + '.json') const config = { env: env, // 项目结构 path_project : path.resolve(__dirname, '../'), dir_src : 'src', dir_dist : '.dist', dir_server: 'server', dir_test : 'tests', // 服务器配置 api_target: envConfig.api_target, server_host: 'localhost', server_port: envConfig.port || 4000, vendor_dependencies: [ 'react', 'react-redux', 'react-router', 'redux', 'redux-simple-router' ] } // Webpack配置 config.webpack_port = 3000 config.webpack_public_path = `http://${config.server_host}:${config.webpack_port}/` // ------------------------------------ // 配置相关环境变量 // ------------------------------------ config.globals = { 'process.env' : { 'NODE_ENV' : JSON.stringify(config.env) }, 'NODE_ENV' : config.env, '__DEV__' : config.env === 'development', '__PROD__' : config.env === 'production', '__DEBUG__' : !!argv.debug } // ------------------------------------ // 校验Vendor依赖是否正常加载 // ------------------------------------ const pkg = require('../package.json') config.vendor_dependencies = config.vendor_dependencies .filter(dep => { if (pkg.dependencies[dep]) return true console.warn( `Package "${dep}" was not found as an npm dependency in package.json; ` + `it won't be included in the webpack vendor bundle.\n` + `Consider removing it from vendor_dependencies in ~/config/index.js` ) }) // ------------------------------------ // Utilities // ------------------------------------ config.utils_paths = (() => { const base = [config.path_project]; const resolve = path.resolve; const project = (...args) => resolve.apply(resolve, [...base, ...args]); return { project : project, src : project.bind(null, config.dir_src), dist : project.bind(null, config.dir_dist) } })() export default config
//= require ../palette-color-picker //= require_self $(function() { setupColorPicker(); $(document).on('has_many_add:after', setupColorPicker); function setupColorPicker() { $('.color-picker').each(function(i, el) { $(el).paletteColorPicker({ clear_btn: 'last' }); }); } });
/* eslint-disable no-bitwise, no-process-exit */ "use strict" module.exports = new function init() { var spec = {}, subjects = [], results, only = null, ctx = spec, start, stack = 0, nextTickish, hasProcess = typeof process === "object", hasOwn = ({}).hasOwnProperty function o(subject, predicate) { if (predicate === undefined) { if (results == null) throw new Error("Assertions should not occur outside test definitions") return new Assert(subject) } else if (results == null) { ctx[unique(subject)] = predicate } else { throw new Error("Test definition shouldn't be nested. To group tests use `o.spec()`") } } o.before = hook("__before") o.after = hook("__after") o.beforeEach = hook("__beforeEach") o.afterEach = hook("__afterEach") o.new = init o.spec = function(subject, predicate) { var parent = ctx ctx = ctx[unique(subject)] = {} predicate() ctx = parent } o.only = function(subject, predicate, silent) { if (!silent) console.log(highlight("/!\\ WARNING /!\\ o.only() mode")) o(subject, only = predicate) } o.spy = function(fn) { var spy = function() { spy.this = this spy.args = [].slice.call(arguments) spy.callCount++ if (fn) return fn.apply(this, arguments) } if (fn) Object.defineProperties(spy, { length: {value: fn.length}, name: {value: fn.name} }) spy.args = [] spy.callCount = 0 return spy } o.run = function() { results = [] start = new Date test(spec, [], [], report) function test(spec, pre, post, finalize) { pre = [].concat(pre, spec["__beforeEach"] || []) post = [].concat(spec["__afterEach"] || [], post) series([].concat(spec["__before"] || [], Object.keys(spec).map(function(key) { return function(done, timeout) { timeout(Infinity) if (key.slice(0, 2) === "__") return done() if (only !== null && spec[key] !== only && typeof only === typeof spec[key]) return done() subjects.push(key) var type = typeof spec[key] if (type === "object") test(spec[key], pre, post, pop) if (type === "function") series([].concat(pre, spec[key], post, pop)) function pop() { subjects.pop() done() } } }), spec["__after"] || [], finalize)) } function series(fns) { var cursor = 0 next() function next() { if (cursor === fns.length) return var fn = fns[cursor++] if (fn.length > 0) { var timeout = 0, delay = 200, s = new Date var isDone = false var body = fn.toString() var arg = (body.match(/\(([\w$]+)/) || body.match(/([\w$]+)\s*=>/) || []).pop() if (body.indexOf(arg) === body.lastIndexOf(arg)) throw new Error("`" + arg + "()` should be called at least once") try { fn(function done() { if (timeout !== undefined) { timeout = clearTimeout(timeout) if (delay !== Infinity) record(null) if (!isDone) next() else throw new Error("`" + arg + "()` should only be called once") isDone = true } else console.log("# elapsed: " + Math.round(new Date - s) + "ms, expected under " + delay + "ms") }, function(t) {delay = t}) } catch (e) { record(e.message, e) subjects.pop() next() } if (timeout === 0) { timeout = setTimeout(function() { timeout = undefined record("async test timed out") next() }, Math.min(delay, 2147483647)) } } else { fn() nextTickish(next) } } } } function unique(subject) { if (hasOwn.call(ctx, subject)) { console.warn("A test or a spec named `" + subject + "` was already defined") while (hasOwn.call(ctx, subject)) subject += "*" } return subject } function hook(name) { return function(predicate) { if (ctx[name]) throw new Error("This hook should be defined outside of a loop or inside a nested test group:\n" + predicate) ctx[name] = predicate } } define("equals", "should equal", function(a, b) {return a === b}) define("notEquals", "should not equal", function(a, b) {return a !== b}) define("deepEquals", "should deep equal", deepEqual) define("notDeepEquals", "should not deep equal", function(a, b) {return !deepEqual(a, b)}) function isArguments(a) { if ("callee" in a) { for (var i in a) if (i === "callee") return false return true } } function deepEqual(a, b) { if (a === b) return true if (a === null ^ b === null || a === undefined ^ b === undefined) return false if (typeof a === "object" && typeof b === "object") { var aIsArgs = isArguments(a), bIsArgs = isArguments(b) if (a.constructor === Object && b.constructor === Object && !aIsArgs && !bIsArgs) { for (var i in a) { if ((!(i in b)) || !deepEqual(a[i], b[i])) return false } for (var i in b) { if (!(i in a)) return false } return true } if (a.length === b.length && (a instanceof Array && b instanceof Array || aIsArgs && bIsArgs)) { var aKeys = Object.getOwnPropertyNames(a), bKeys = Object.getOwnPropertyNames(b) if (aKeys.length !== bKeys.length) return false for (var i = 0; i < aKeys.length; i++) { if (!hasOwn.call(b, aKeys[i]) || !deepEqual(a[aKeys[i]], b[aKeys[i]])) return false } return true } if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime() if (typeof Buffer === "function" && a instanceof Buffer && b instanceof Buffer) { for (var i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false } return true } if (a.valueOf() === b.valueOf()) return true } return false } function Assert(value) {this.value = value} function define(name, verb, compare) { Assert.prototype[name] = function assert(value) { if (compare(this.value, value)) record(null) else record(serialize(this.value) + "\n" + verb + "\n" + serialize(value)) return function(message) { var result = results[results.length - 1] result.message = message + "\n\n" + result.message } } } function record(message, error) { var result = {pass: message === null} if (result.pass === false) { if (error == null) { error = new Error if (error.stack === undefined) new function() {try {throw error} catch (e) {error = e}} } result.context = subjects.join(" > ") result.message = message result.error = error.stack } results.push(result) } function serialize(value) { if (value === null || (typeof value === "object" && !(value instanceof Array)) || typeof value === "number") return String(value) else if (typeof value === "function") return value.name || "<anonymous function>" try {return JSON.stringify(value)} catch (e) {return String(value)} } function highlight(message) { return hasProcess ? "\x1b[31m" + message + "\x1b[0m" : "%c" + message + "%c " } function report() { var status = 0 for (var i = 0, r; r = results[i]; i++) { if (!r.pass) { var stackTrace = r.error.match(/^(?:(?!Error|[\/\\]ospec[\/\\]ospec\.js).)*$/m) console.error(r.context + ":\n" + highlight(r.message) + (stackTrace ? "\n\n" + stackTrace + "\n\n" : ""), hasProcess ? "" : "color:red", hasProcess ? "" : "color:black") status = 1 } } console.log( results.length + " assertions completed in " + Math.round(new Date - start) + "ms, " + "of which " + results.filter(function(result){return result.error}).length + " failed" ) if (hasProcess && status === 1) process.exit(1) } if(hasProcess) { nextTickish = process.nextTick } else { nextTickish = function fakeFastNextTick(next) { if (stack++ < 5000) next() else setTimeout(next, stack = 0) } } return o }
import AbstractKeyEventSimulator from './AbstractKeyEventSimulator'; import Configuration from '../config/Configuration'; import KeyEventType from '../../const/KeyEventType'; class GlobalKeyEventSimulator extends AbstractKeyEventSimulator{ handleKeyPressSimulation(options){ this._handleEventSimulation('handleKeyPress', {eventType: KeyEventType.keypress, ...options}); } handleKeyUpSimulation(options){ this._handleEventSimulation('handleKeyUp', {eventType: KeyEventType.keyup, ...options}); } _handleEventSimulation(handlerName, {event, eventType, key}) { if (this._shouldSimulate(eventType, key) && Configuration.option('simulateMissingKeyPressEvents')) { /** * If a key does not have a keypress event, we simulate one immediately after * the keydown event, to keep the behaviour consistent across all keys */ const _event = this.cloneAndMergeEvent(event, {key, simulated: true}); this._keyEventStrategy[handlerName](_event); } } } export default GlobalKeyEventSimulator;
/* @flow */ declare var require: { (id: string): any; ensure(ids: Array<string>, callback?: { (require: typeof require): void }, chunk?: string): void } declare var BASE_URL: bool;
search_result['693']=["topic_0000000000000177.html","TleceAccountController.EmailSender Property",""];
/* Modernizr 2.8.3 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load */ ; window.Modernizr = function (a, b, c) { function D(a) { j.cssText = a } function E(a, b) { return D(n.join(a + ";") + (b || "")) } function F(a, b) { return typeof a === b } function G(a, b) { return!!~("" + a).indexOf(b) } function H(a, b) { for (var d in a) { var e = a[d]; if (!G(e, "-") && j[e] !== c)return b == "pfx" ? e : !0 } return!1 } function I(a, b, d) { for (var e in a) { var f = b[a[e]]; if (f !== c)return d === !1 ? a[e] : F(f, "function") ? f.bind(d || b) : f } return!1 } function J(a, b, c) { var d = a.charAt(0).toUpperCase() + a.slice(1), e = (a + " " + p.join(d + " ") + d).split(" "); return F(b, "string") || F(b, "undefined") ? H(e, b) : (e = (a + " " + q.join(d + " ") + d).split(" "), I(e, b, c)) } function K() { e.input = function (c) { for (var d = 0, e = c.length; d < e; d++)u[c[d]] = c[d]in k; return u.list && (u.list = !!b.createElement("datalist") && !!a.HTMLDataListElement), u }("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")), e.inputtypes = function (a) { for (var d = 0, e, f, h, i = a.length; d < i; d++)k.setAttribute("type", f = a[d]), e = k.type !== "text", e && (k.value = l, k.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(f) && k.style.WebkitAppearance !== c ? (g.appendChild(k), h = b.defaultView, e = h.getComputedStyle && h.getComputedStyle(k, null).WebkitAppearance !== "textfield" && k.offsetHeight !== 0, g.removeChild(k)) : /^(search|tel)$/.test(f) || (/^(url|email)$/.test(f) ? e = k.checkValidity && k.checkValidity() === !1 : e = k.value != l)), t[a[d]] = !!e; return t }("search tel url email datetime date month week time datetime-local number range color".split(" ")) } var d = "2.8.3", e = {}, f = !0, g = b.documentElement, h = "modernizr", i = b.createElement(h), j = i.style, k = b.createElement("input"), l = ":)", m = {}.toString, n = " -webkit- -moz- -o- -ms- ".split(" "), o = "Webkit Moz O ms", p = o.split(" "), q = o.toLowerCase().split(" "), r = {svg: "http://www.w3.org/2000/svg"}, s = {}, t = {}, u = {}, v = [], w = v.slice, x, y = function (a, c, d, e) { var f, i, j, k, l = b.createElement("div"), m = b.body, n = m || b.createElement("body"); if (parseInt(d, 10))while (d--)j = b.createElement("div"), j.id = e ? e[d] : h + (d + 1), l.appendChild(j); return f = ["&#173;", '<style id="s', h, '">', a, "</style>"].join(""), l.id = h, (m ? l : n).innerHTML += f, n.appendChild(l), m || (n.style.background = "", n.style.overflow = "hidden", k = g.style.overflow, g.style.overflow = "hidden", g.appendChild(n)), i = c(l, a), m ? l.parentNode.removeChild(l) : (n.parentNode.removeChild(n), g.style.overflow = k), !!i }, z = function (b) { var c = a.matchMedia || a.msMatchMedia; if (c)return c(b) && c(b).matches || !1; var d; return y("@media " + b + " { #" + h + " { position: absolute; } }", function (b) { d = (a.getComputedStyle ? getComputedStyle(b, null) : b.currentStyle)["position"] == "absolute" }), d }, A = function () { function d(d, e) { e = e || b.createElement(a[d] || "div"), d = "on" + d; var f = d in e; return f || (e.setAttribute || (e = b.createElement("div")), e.setAttribute && e.removeAttribute && (e.setAttribute(d, ""), f = F(e[d], "function"), F(e[d], "undefined") || (e[d] = c), e.removeAttribute(d))), e = null, f } var a = {select: "input", change: "input", submit: "form", reset: "form", error: "img", load: "img", abort: "img"}; return d }(), B = {}.hasOwnProperty, C; !F(B, "undefined") && !F(B.call, "undefined") ? C = function (a, b) { return B.call(a, b) } : C = function (a, b) { return b in a && F(a.constructor.prototype[b], "undefined") }, Function.prototype.bind || (Function.prototype.bind = function (b) { var c = this; if (typeof c != "function")throw new TypeError; var d = w.call(arguments, 1), e = function () { if (this instanceof e) { var a = function () { }; a.prototype = c.prototype; var f = new a, g = c.apply(f, d.concat(w.call(arguments))); return Object(g) === g ? g : f } return c.apply(b, d.concat(w.call(arguments))) }; return e }), s.flexbox = function () { return J("flexWrap") }, s.canvas = function () { var a = b.createElement("canvas"); return!!a.getContext && !!a.getContext("2d") }, s.canvastext = function () { return!!e.canvas && !!F(b.createElement("canvas").getContext("2d").fillText, "function") }, s.webgl = function () { return!!a.WebGLRenderingContext }, s.touch = function () { var c; return"ontouchstart"in a || a.DocumentTouch && b instanceof DocumentTouch ? c = !0 : y(["@media (", n.join("touch-enabled),("), h, ")", "{#modernizr{top:9px;position:absolute}}"].join(""), function (a) { c = a.offsetTop === 9 }), c }, s.geolocation = function () { return"geolocation"in navigator }, s.postmessage = function () { return!!a.postMessage }, s.websqldatabase = function () { return!!a.openDatabase }, s.indexedDB = function () { return!!J("indexedDB", a) }, s.hashchange = function () { return A("hashchange", a) && (b.documentMode === c || b.documentMode > 7) }, s.history = function () { return!!a.history && !!history.pushState }, s.draganddrop = function () { var a = b.createElement("div"); return"draggable"in a || "ondragstart"in a && "ondrop"in a }, s.websockets = function () { return"WebSocket"in a || "MozWebSocket"in a }, s.rgba = function () { return D("background-color:rgba(150,255,150,.5)"), G(j.backgroundColor, "rgba") }, s.hsla = function () { return D("background-color:hsla(120,40%,100%,.5)"), G(j.backgroundColor, "rgba") || G(j.backgroundColor, "hsla") }, s.multiplebgs = function () { return D("background:url(https://),url(https://),red url(https://)"), /(url\s*\(.*?){3}/.test(j.background) }, s.backgroundsize = function () { return J("backgroundSize") }, s.borderimage = function () { return J("borderImage") }, s.borderradius = function () { return J("borderRadius") }, s.boxshadow = function () { return J("boxShadow") }, s.textshadow = function () { return b.createElement("div").style.textShadow === "" }, s.opacity = function () { return E("opacity:.55"), /^0.55$/.test(j.opacity) }, s.cssanimations = function () { return J("animationName") }, s.csscolumns = function () { return J("columnCount") }, s.cssgradients = function () { var a = "background-image:", b = "gradient(linear,left top,right bottom,from(#9f9),to(white));", c = "linear-gradient(left top,#9f9, white);"; return D((a + "-webkit- ".split(" ").join(b + a) + n.join(c + a)).slice(0, -a.length)), G(j.backgroundImage, "gradient") }, s.cssreflections = function () { return J("boxReflect") }, s.csstransforms = function () { return!!J("transform") }, s.csstransforms3d = function () { var a = !!J("perspective"); return a && "webkitPerspective"in g.style && y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}", function (b, c) { a = b.offsetLeft === 9 && b.offsetHeight === 3 }), a }, s.csstransitions = function () { return J("transition") }, s.fontface = function () { var a; return y('@font-face {font-family:"font";src:url("https://")}', function (c, d) { var e = b.getElementById("smodernizr"), f = e.sheet || e.styleSheet, g = f ? f.cssRules && f.cssRules[0] ? f.cssRules[0].cssText : f.cssText || "" : ""; a = /src/i.test(g) && g.indexOf(d.split(" ")[0]) === 0 }), a }, s.generatedcontent = function () { var a; return y(["#", h, "{font:0/0 a}#", h, ':after{content:"', l, '";visibility:hidden;font:3px/1 a}'].join(""), function (b) { a = b.offsetHeight >= 3 }), a }, s.video = function () { var a = b.createElement("video"), c = !1; try { if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ""), c.h264 = a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ""), c.webm = a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, "") } catch (d) { } return c }, s.audio = function () { var a = b.createElement("audio"), c = !1; try { if (c = !!a.canPlayType)c = new Boolean(c), c.ogg = a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ""), c.mp3 = a.canPlayType("audio/mpeg;").replace(/^no$/, ""), c.wav = a.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ""), c.m4a = (a.canPlayType("audio/x-m4a;") || a.canPlayType("audio/aac;")).replace(/^no$/, "") } catch (d) { } return c }, s.localstorage = function () { try { return localStorage.setItem(h, h), localStorage.removeItem(h), !0 } catch (a) { return!1 } }, s.sessionstorage = function () { try { return sessionStorage.setItem(h, h), sessionStorage.removeItem(h), !0 } catch (a) { return!1 } }, s.webworkers = function () { return!!a.Worker }, s.applicationcache = function () { return!!a.applicationCache }, s.svg = function () { return!!b.createElementNS && !!b.createElementNS(r.svg, "svg").createSVGRect }, s.inlinesvg = function () { var a = b.createElement("div"); return a.innerHTML = "<svg/>", (a.firstChild && a.firstChild.namespaceURI) == r.svg }, s.smil = function () { return!!b.createElementNS && /SVGAnimate/.test(m.call(b.createElementNS(r.svg, "animate"))) }, s.svgclippaths = function () { return!!b.createElementNS && /SVGClipPath/.test(m.call(b.createElementNS(r.svg, "clipPath"))) }; for (var L in s)C(s, L) && (x = L.toLowerCase(), e[x] = s[L](), v.push((e[x] ? "" : "no-") + x)); return e.input || K(), e.addTest = function (a, b) { if (typeof a == "object")for (var d in a)C(a, d) && e.addTest(d, a[d]); else { a = a.toLowerCase(); if (e[a] !== c)return e; b = typeof b == "function" ? b() : b, typeof f != "undefined" && f && (g.className += " " + (b ? "" : "no-") + a), e[a] = b } return e }, D(""), i = k = null, function (a, b) { function l(a, b) { var c = a.createElement("p"), d = a.getElementsByTagName("head")[0] || a.documentElement; return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild) } function m() { var a = s.elements; return typeof a == "string" ? a.split(" ") : a } function n(a) { var b = j[a[h]]; return b || (b = {}, i++, a[h] = i, j[i] = b), b } function o(a, c, d) { c || (c = b); if (k)return c.createElement(a); d || (d = n(c)); var g; return d.cache[a] ? g = d.cache[a].cloneNode() : f.test(a) ? g = (d.cache[a] = d.createElem(a)).cloneNode() : g = d.createElem(a), g.canHaveChildren && !e.test(a) && !g.tagUrn ? d.frag.appendChild(g) : g } function p(a, c) { a || (a = b); if (k)return a.createDocumentFragment(); c = c || n(a); var d = c.frag.cloneNode(), e = 0, f = m(), g = f.length; for (; e < g; e++)d.createElement(f[e]); return d } function q(a, b) { b.cache || (b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag()), a.createElement = function (c) { return s.shivMethods ? o(c, a, b) : b.createElem(c) }, a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + m().join().replace(/[\w\-]+/g, function (a) { return b.createElem(a), b.frag.createElement(a), 'c("' + a + '")' }) + ");return n}")(s, b.frag) } function r(a) { a || (a = b); var c = n(a); return s.shivCSS && !g && !c.hasCSS && (c.hasCSS = !!l(a, "article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")), k || q(a, c), a } var c = "3.7.0", d = a.html5 || {}, e = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i, f = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, g, h = "_html5shiv", i = 0, j = {}, k; (function () { try { var a = b.createElement("a"); a.innerHTML = "<xyz></xyz>", g = "hidden"in a, k = a.childNodes.length == 1 || function () { b.createElement("a"); var a = b.createDocumentFragment(); return typeof a.cloneNode == "undefined" || typeof a.createDocumentFragment == "undefined" || typeof a.createElement == "undefined" }() } catch (c) { g = !0, k = !0 } })(); var s = {elements: d.elements || "abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video", version: c, shivCSS: d.shivCSS !== !1, supportsUnknownElements: k, shivMethods: d.shivMethods !== !1, type: "default", shivDocument: r, createElement: o, createDocumentFragment: p}; a.html5 = s, r(b) }(this, b), e._version = d, e._prefixes = n, e._domPrefixes = q, e._cssomPrefixes = p, e.mq = z, e.hasEvent = A, e.testProp = function (a) { return H([a]) }, e.testAllProps = J, e.testStyles = y, e.prefixed = function (a, b, c) { return b ? J(a, b, c) : J(a, "pfx") }, g.className = g.className.replace(/(^|\s)no-js(\s|$)/, "$1$2") + (f ? " js " + v.join(" ") : ""), e }(this, this.document), function (a, b, c) { function d(a) { return"[object Function]" == o.call(a) } function e(a) { return"string" == typeof a } function f() { } function g(a) { return!a || "loaded" == a || "complete" == a || "uninitialized" == a } function h() { var a = p.shift(); q = 1, a ? a.t ? m(function () { ("c" == a.t ? B.injectCss : B.injectJs)(a.s, 0, a.a, a.x, a.e, 1) }, 0) : (a(), h()) : q = 0 } function i(a, c, d, e, f, i, j) { function k(b) { if (!o && g(l.readyState) && (u.r = o = 1, !q && h(), l.onload = l.onreadystatechange = null, b)) { "img" != a && m(function () { t.removeChild(l) }, 50); for (var d in y[c])y[c].hasOwnProperty(d) && y[c][d].onload() } } var j = j || B.errorTimeout, l = b.createElement(a), o = 0, r = 0, u = {t: d, s: c, e: f, a: i, x: j}; 1 === y[c] && (r = 1, y[c] = []), "object" == a ? l.data = c : (l.src = c, l.type = a), l.width = l.height = "0", l.onerror = l.onload = l.onreadystatechange = function () { k.call(this, r) }, p.splice(e, 0, u), "img" != a && (r || 2 === y[c] ? (t.insertBefore(l, s ? null : n), m(k, j)) : y[c].push(l)) } function j(a, b, c, d, f) { return q = 0, b = b || "j", e(a) ? i("c" == b ? v : u, a, b, this.i++, c, d, f) : (p.splice(this.i++, 0, a), 1 == p.length && h()), this } function k() { var a = B; return a.loader = {load: j, i: 0}, a } var l = b.documentElement, m = a.setTimeout, n = b.getElementsByTagName("script")[0], o = {}.toString, p = [], q = 0, r = "MozAppearance"in l.style, s = r && !!b.createRange().compareNode, t = s ? l : n.parentNode, l = a.opera && "[object Opera]" == o.call(a.opera), l = !!b.attachEvent && !l, u = r ? "object" : l ? "script" : "img", v = l ? "script" : u, w = Array.isArray || function (a) { return"[object Array]" == o.call(a) }, x = [], y = {}, z = {timeout: function (a, b) { return b.length && (a.timeout = b[0]), a }}, A, B; B = function (a) { function b(a) { var a = a.split("!"), b = x.length, c = a.pop(), d = a.length, c = {url: c, origUrl: c, prefixes: a}, e, f, g; for (f = 0; f < d; f++)g = a[f].split("="), (e = z[g.shift()]) && (c = e(c, g)); for (f = 0; f < b; f++)c = x[f](c); return c } function g(a, e, f, g, h) { var i = b(a), j = i.autoCallback; i.url.split(".").pop().split("?").shift(), i.bypass || (e && (e = d(e) ? e : e[a] || e[g] || e[a.split("/").pop().split("?")[0]]), i.instead ? i.instead(a, e, f, g, h) : (y[i.url] ? i.noexec = !0 : y[i.url] = 1, f.load(i.url, i.forceCSS || !i.forceJS && "css" == i.url.split(".").pop().split("?").shift() ? "c" : c, i.noexec, i.attrs, i.timeout), (d(e) || d(j)) && f.load(function () { k(), e && e(i.origUrl, h, g), j && j(i.origUrl, h, g), y[i.url] = 2 }))) } function h(a, b) { function c(a, c) { if (a) { if (e(a))c || (j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() }), g(a, j, b, 0, h); else if (Object(a) === a)for (n in m = function () { var b = 0, c; for (c in a)a.hasOwnProperty(c) && b++; return b }(), a)a.hasOwnProperty(n) && (!c && !--m && (d(j) ? j = function () { var a = [].slice.call(arguments); k.apply(this, a), l() } : j[n] = function (a) { return function () { var b = [].slice.call(arguments); a && a.apply(this, b), l() } }(k[n])), g(a[n], j, b, n, h)) } else!c && l() } var h = !!a.test, i = a.load || a.both, j = a.callback || f, k = j, l = a.complete || f, m, n; c(h ? a.yep : a.nope, !!i), i && c(i) } var i, j, l = this.yepnope.loader; if (e(a))g(a, 0, l, 0); else if (w(a))for (i = 0; i < a.length; i++)j = a[i], e(j) ? g(j, 0, l, 0) : w(j) ? B(j) : Object(j) === j && h(j, l); else Object(a) === a && h(a, l) }, B.addPrefix = function (a, b) { z[a] = b }, B.addFilter = function (a) { x.push(a) }, B.errorTimeout = 1e4, null == b.readyState && b.addEventListener && (b.readyState = "loading", b.addEventListener("DOMContentLoaded", A = function () { b.removeEventListener("DOMContentLoaded", A, 0), b.readyState = "complete" }, 0)), a.yepnope = k(), a.yepnope.executeStack = h, a.yepnope.injectJs = function (a, c, d, e, i, j) { var k = b.createElement("script"), l, o, e = e || B.errorTimeout; k.src = a; for (o in d)k.setAttribute(o, d[o]); c = j ? h : c || f, k.onreadystatechange = k.onload = function () { !l && g(k.readyState) && (l = 1, c(), k.onload = k.onreadystatechange = null) }, m(function () { l || (l = 1, c(1)) }, e), i ? k.onload() : n.parentNode.insertBefore(k, n) }, a.yepnope.injectCss = function (a, c, d, e, g, i) { var e = b.createElement("link"), j, c = i ? h : c || f; e.href = a, e.rel = "stylesheet", e.type = "text/css"; for (j in d)e.setAttribute(j, d[j]); g || (n.parentNode.insertBefore(e, n), m(c, 0)) } }(this, document), Modernizr.load = function () { yepnope.apply(window, [].slice.call(arguments, 0)) };
import React from 'react'; import H2Header from '../H2Header/H2Header'; import GridContainer from '../GridContainer/GridContainer'; import CloseHood from '../CloseHood/CloseHood'; const DashboardBackground = () => { return ( <div className="dashboard-background"> <H2Header /> <GridContainer /> <CloseHood /> </div> ); }; export default DashboardBackground;
{ "movies": [ { "title": "King Kong", "summary": "A love story about a big monkey and a blonde chick.", "thumbnail": "http://localhost:8080/images/king_kong.jpg", "video": "https://www.youtube.com/watch?v=aanYNjjoCQo", }, { "title": "E.T.", "summary": "A psychotropic movie about a kid that believes in aliens too much.", "thumbnail": "http://localhost:8080/images/et.jpg", "video": "https://www.youtube.com/watch?v=oR1-UFrcZ0k", }, { "title": "Jaws", "summary": "He ain't vegetarian and they are about to know it.", "thumbnail": "http://localhost:8080/images/jaws.jpg", "video": "https://www.youtube.com/watch?v=U1fu_sA7XhE", }, { "title": "Mars attack!", "summary": "They have lasers, we have Tom Jones", "thumbnail": "http://localhost:8080/images/mars_attacks.jpg", "video": "https://www.youtube.com/watch?v=DqtjHWlM4lQ", } ] }
var _ = require('lodash'); module.exports = function() { var service = this; var ontologiesKey = "__ONTOLOGIES__"; var viewsKey = "__VIEWS__"; service.views = {}; service.ontologies = {}; function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function storeOntology(ontology) { if (typeof (Storage) !== "undefined") { if (ontology.id) { var ontologyRecord = ontologyById(ontology.id); if(ontologyRecord) { localStorage.setItem(ontology.id, JSON.stringify(ontology)); } } else { if (ontology.name) { var ontologiesText = localStorage.getItem(ontologiesKey); var ontologies = JSON.parse(ontologiesText) || []; var newId = guid(); ontologies.push({ id : newId, name : ontology.name }); ontology.id = newId; localStorage.setItem(ontologiesKey, JSON .stringify(ontologies)); localStorage.setItem(ontology.id, JSON.stringify(ontology)); return JSON.parse(JSON.stringify(ontology)); } } } else { // Sorry! No Web Storage support.. } } function ontologyRecordByName(name) { var ontologiesList = getOntologiesList(); return ontologiesList.find(function(element) { return element.name === name; }); } function ontologyById(id) { var ontologyText = localStorage.getItem(id); if (ontologyText) { var ontologyObject = JSON.parse(ontologyText); return ontologyObject; } } function loadOntology(name) { if (typeof (Storage) !== "undefined") { var ontologiesList = getOntologiesList(); var found = ontologyRecordByName(name); if (found) { return ontologyById(found.id); } } } function removeOntology(ontology){ if(ontology.id) { var ontologiesList = getOntologiesList(); var found = ontologiesList.find(function(element) { return element.id === ontology.id; }); if(found) { ontologiesList = ontologiesList.filter(function(element) { return element.id !== ontology.id; }); localStorage.setItem(ontologiesKey, JSON .stringify(ontologiesList)); } var ontologyRecord = ontologyById(ontology.id); if(ontologyRecord) { localStorage.removeItem(ontology.id); var viewsText = localStorage.getItem(viewsKey); if (viewsText) { var views = JSON.parse(viewsText); if(views.hasOwnProperty(ontology.id)) { views[ontology.id].delete; localStorage.setItem(viewsKey, JSON.stringify(views)); } } } } } function getOntologiesList() { var ontologiesText = localStorage.getItem(ontologiesKey); var ontologies = JSON.parse(ontologiesText) || []; return ontologies; } function store(key,data) { localStorage.setItem(key, JSON.stringify(data)); } function retrieve(key) { var text = localStorage.getItem(key); if(text) { return JSON.parse(text); } } function replaceSubkey(key,subkey,newData) { var toUpdate = retrieve(key); toUpdate[subkey] = newData; store(key,toUpdate); } function storeView(view) { if (view.name && view.ontologyName || view.ontologyId) { if (!view.id) { view.id = guid(); } var ontology; if (view.ontologyId) { ontology = ontologyById(view.ontologyId); } else { ontology = loadOntology(view.ontologyName); } view.ontologyId = ontology.id; var viewsText = localStorage.getItem(viewsKey); var views; if (viewsText) { views = JSON.parse(viewsText); } else { views = {}; } var ontologySlot = views[view.ontologyId]; if (!ontologySlot) { ontologySlot = views[view.ontologyId] = {}; } view.saveDate = new Date(); ontologySlot[view.id] = view; localStorage.setItem(viewsKey, JSON.stringify(views)); return JSON.parse(JSON.stringify(view)); } } function getViewsObject(ontologyName) { var ontoRec = ontologyRecordByName(ontologyName); var viewsText = localStorage.getItem(viewsKey); var retval = {}; if (viewsText) { var views = JSON.parse(viewsText); var ontologySlot = views[ontoRec.id]; if (ontologySlot) { retval = ontologySlot; } } return retval; } function getView(ontologyName, viewName) { var ontoRec = ontologyRecordByName(ontologyName); var viewsObject = getViewsObject(ontologyName); if (viewsObject) { for ( var k in viewsObject) { if (!viewsObject.hasOwnProperty(k)) continue; var view = viewsObject[k]; if (view.name === viewName) { return view; } } } } function getDatabaseText() { var retval = {}; var viewsText = localStorage.getItem(viewsKey); if (viewsText) { var views = JSON.parse(viewsText); retval[viewsKey] = views; } var ontologiesList = getOntologiesList(); retval[ontologiesKey] = ontologiesList; ontologiesList.forEach(function(element) { var ontologyRecord = ontologyById(element.id); retval[ontologyRecord.id] = ontologyRecord; }); return JSON.stringify(retval); } function replaceDatabase(databaseJson) { deleteDatabase(); var databaseObject = JSON.parse(databaseJson); if(databaseObject[ontologiesKey] && databaseObject[viewsKey]) { store(ontologiesKey,databaseObject[ontologiesKey]); store(viewsKey,databaseObject[viewsKey]); databaseObject[ontologiesKey].forEach(function(element){ var curOntology = databaseObject[element.id]; if(curOntology) { store(element.id,curOntology); } }); } } function removeView(view) { if (view.id && view.ontologyId) { var views = retrieve(viewsKey); if(views) { var ontologySlot = views[view.ontologyId]; if(ontologySlot.hasOwnProperty(view.id)) { delete ontologySlot[view.id]; replaceSubkey(viewsKey,view.ontologyId,ontologySlot); } } } } function deleteDatabase() { var ontolgiesList = getOntologiesList(); ontolgiesList.forEach(function(element){ removeOntology(element); }); } function getDatabaseStatistics(databaseJson) { var retval = {valid: false}; return retval; } var retval = { storeOntology : storeOntology, getOntologiesList : getOntologiesList, loadOntology : loadOntology, removeOntology:removeOntology, storeView : storeView, getViewsObject : getViewsObject, getView : getView, removeView:removeView, getDatabaseText:getDatabaseText, replaceDatabase:replaceDatabase, getDatabaseStatistics:getDatabaseStatistics }; return retval; }
/* jshint devel: true, indent: 2, undef: true, unused: strict, strict: false, eqeqeq: true, trailing: true, curly: true, latedef: true, quotmark: single, maxlen: 120 */ /* global define */ define('collections/profile_pics', ['backbone', 'models/profile_pic'], function (Backbone, ProfilePic) { var ProfilePicsCollection = Backbone.Collection.extend({ model: ProfilePic }); return ProfilePicsCollection; });
import { startMirage } from '../../initializers/ember-cli-mirage'; export default function setupMirage() { return startMirage(); }
/* eslint-disable import/prefer-default-export */ export const INPUT_HEIGHT = 30; /* eslint-enable import/prefer-default-export */
$('#accordion').accordion();
'use strict'; const swal = require('sweetalert'); const AdminHeaderCtrl = (app) => { app.controller('AdminHeaderCtrl', ['$scope', '$log', '$window', '$location', ($scope, $log, $window, $location) => { // $scope.showAccountButton = $cookies.get(`strategy`) === `basic` || $cookies.get(`interopAdmin`) === `true` ? true : false; $scope.logout = () => { swal({ title: 'Logout?', type: 'warning', showCancelButton: true, closeOnConfirm: false, customClass: 'sweet-alert-hide-input' }, () => { let currentPath = $location.path(); $cookies.remove('strategy', {'path': '/'}); $cookies.remove('interopAdmin', {'path': '/'}); $window.location.reload(); }); } }]); }; module.exports = AdminHeaderCtrl;;
// @flow import { app, BrowserWindow } from 'electron'; import MenuBuilder from './menu'; /* eslint global-require: 1, flowtype-errors/show-errors: 0 */ let mainWindow = null; if (process.env.NODE_ENV === 'production') { const sourceMapSupport = require('source-map-support'); sourceMapSupport.install(); } if (process.env.NODE_ENV === 'development') { require('electron-debug')(); const path = require('path'); const p = path.join(__dirname, '..', 'app', 'node_modules'); require('module').globalPaths.push(p); } app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); const installExtensions = async () => { if (process.env.NODE_ENV === 'development') { const installer = require('electron-devtools-installer'); const extensions = [ 'REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS' ]; const forceDownload = !!process.env.UPGRADE_EXTENSIONS; // TODO: Use async interation statement. // Waiting on https://github.com/tc39/proposal-async-iteration // Promises will fail silently, which isn't what we want in development return Promise .all(extensions.map(name => installer.default(installer[name], forceDownload))) .catch(console.log); } }; app.on('ready', async () => { await installExtensions(); mainWindow = new BrowserWindow({ show: false, width: 1024, height: 728 }); mainWindow.loadURL(`file://${__dirname}/app.html`); mainWindow.webContents.on('did-finish-load', () => { if (!mainWindow) { throw new Error('"mainWindow" is not defined'); } mainWindow.show(); mainWindow.focus(); }); mainWindow.on('closed', () => { mainWindow = null; }); const menuBuilder = new MenuBuilder(mainWindow); menuBuilder.buildMenu(); });
(function (app) { 'use strict'; app.registerModule('carts'); })(ApplicationConfiguration);
var crypto = require("crypto"), jade = require("jade"), path = require("path"), juice = require("juice2"), sass = require("node-sass"); module.exports = (function() { var InvitationsManager = {}, transport = sails.config.mail.transport; InvitationsManager.send = function(options, callback) { var from = options.from, to = options.to, created_invite; function sentEmail(err, info) { sails.log("[InvitationsManager][send] Sent callback | err[" + err + "] info[" + info.response + "]"); if(err) { return callback(err, null); } else { return callback(null, created_invite); } } function sendMail(err, html) { if(err) { sails.log("[InvitationsManager][send] failed juicing"); return callback("failed juice", null); } var params = { from: "no-reply@loftili.com", to: process.env["TEST_EMAIL"] ? process.env["TEST_EMAIL"] : to, subject: "[loftili] you\"ve been invited!", html: html }; transport.sendMail(params, sentEmail); } function created(err, invite) { if(err) { sails.log("[InvitationsManager][send] unable to create or find the record based on params"); return callback(err, null); } created_invite = invite; sails.log("[InvitationsManager][send] using MailCompiler for html email"); MailCompiler.compile("invite.jade", {token: created_invite.token}, sendMail); } function generated(err, buffer) { var token = buffer.toString("hex").substring(0, 10), params = { from: from, to: to, token: token }; function alreadyExists(err, invitation) { if(err) { sails.log("[InvitationsManager][send] unable to create or find the record based on params"); return callback(err, null); } if(invitation.length > 0) { sails.log("[InvitationsManager][send] found existing invitation"); return callback(null, invitation); } else { sails.log("[InvitationsManager][send] unable to find existing invitation, creating a new one"); Invitation.findOrCreate(params, params, created); } } Invitation.find({from: from, to: to}, alreadyExists); } crypto.randomBytes(30, generated); }; return InvitationsManager; })();
'use strict'; import dispatcher from './../../infrastructure/dispatcher'; import api from './../../infrastructure/web.api'; export function getStudents(data) { return api.get('/api/v1/activity/students', data) .then(res => { if (!res.hasErrors) { dispatcher.dispatch({action: 'students.retrieved', data: res}); } }); } export function getSchedules(data) { return api.get('/api/v1/activity/schedules', data) .then(res => { if (!res.hasErrors) { dispatcher.dispatch({action: 'schedules.retrieved', data: res}); } }); } export function saveActivity(data) { return api.post('api/v1/activity/save', data) .then(res => { if (!res.hasErrors) { dispatcher.dispatch({action: 'activity.saved', data: res}); } }); } export function getActivities(data) { return api.get('/api/v1/activity/activities', data) .then(res => { if (!res.hasErrors) { dispatcher.dispatch({action: 'activities.retrieved', data: res}); } }); }
(function(){ window.app = {}; app.collections = {}; app.models = {}; app.views = {}; app.mixins = {}; // Defer initialization until doc ready. $(function(){ app.collections.paginatedItems = new app.collections.PaginatedCollection(); app.collections.paginatedItems.fetch({ success: function(){ app.collections.paginatedItems.pager(); app.views.table = new app.views.BrowserTableView({ collection: app.collections.paginatedItems, subviews: { renderer: Teeble.SortbarRenderer, header: Teeble.SortbarHeaderView }, pagination: true, table_class: 'table table-bordered', partials: [ { header: '<th class="sorting" data-sort="name">Name</th>', cell: "<td><%= name %></td>" } ] }); $('#content').html(app.views.table.render().el); } }); }); })();
Pong.Menu = function () { this.keyIsDown = false; }; Pong.Menu.prototype = { create: function () { Pong.onePlayer = true; // add all the text on the screen this.pongText = this.add.bitmapText(this.world.centerX, 50, 'bigFont', 'PONG', 128); this.pongText.anchor.set(0.5, 0); // on player is selected on start so it get scaled bigger this.onePlayerText = this.add.bitmapText(this.world.centerX - 100, 300, 'bigFont', '1 Player', 32); this.onePlayerText.anchor.set(0.5); this.onePlayerText.scale.set(2); this.twoPlayerText = this.add.bitmapText(this.world.centerX + 100, 300, 'bigFont', '2 Players', 32); this.twoPlayerText.anchor.set(0.5); this.bounce = this.add.audio('bounce'); var helpText = this.add.bitmapText(this.world.centerX, 370, 'smallFont', 'player one controls Up Arrow and Down Arrow', 18); helpText.anchor.set(0.5); var helpText2 = this.add.bitmapText(this.world.centerX, 390, 'smallFont', 'player two controls W and S', 18); helpText2.anchor.set(0.5); var helpText3 = this.add.bitmapText(this.world.centerX, 430, 'smallFont', 'Arrow Keys to select the number of players and Space to Start', 18); helpText3.anchor.set(0.5); var helpText4 = this.add.bitmapText(this.world.centerX, 460, 'smallFont', 'First to 5 points wins', 18); helpText4.anchor.set(0.5); }, update: function () { if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) { this.bounce.play(); this.state.start('game'); } if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT) || this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { if (this.keyIsDown) return; // only change if the key was not down in the previous frame this.keyIsDown = true; // scale the correct text based on the new selection if (Pong.onePlayer) { this.onePlayerText.scale.set(1.0); this.twoPlayerText.scale.set(2.0); Pong.onePlayer = false; } else { this.onePlayerText.scale.set(2.0); this.twoPlayerText.scale.set(1.0); Pong.onePlayer = true; } } else { this.keyIsDown = false; } } };
(function(factory) { // NOTE: // All techniques except for the "browser globals" fallback will extend the // provided QUnit object but return the isolated API methods // For AMD: Register as an anonymous AMD module with a named dependency on "qunit". if (typeof define === "function" && define.amd) { define(["qunit"], factory); } // For Node.js else if (typeof module !== "undefined" && module && module.exports && typeof require === "function") { module.exports = factory(require("qunitjs")); } // For CommonJS with `exports`, but without `module.exports`, like Rhino else if (typeof exports !== "undefined" && exports && typeof require === "function") { var qunit = require("qunitjs"); qunit.extend(exports, factory(qunit)); } // For browser globals else { factory(QUnit); } }(function(QUnit) { /** * Find an appropriate `Assert` context to `push` results to. * @param * context - An unknown context, possibly `Assert`, `Test`, or neither * @private */ function _getPushContext(context) { var pushContext; if (context && typeof context.push === "function") { // `context` is an `Assert` context pushContext = context; } else if (context && context.assert && typeof context.assert.push === "function") { // `context` is a `Test` context pushContext = context.assert; } else if ( QUnit && QUnit.config && QUnit.config.current && QUnit.config.current.assert && typeof QUnit.config.current.assert.push === "function" ) { // `context` is an unknown context but we can find the `Assert` context via QUnit pushContext = QUnit.config.current.assert; } else if (QUnit && typeof QUnit.push === "function") { pushContext = QUnit.push; } else { throw new Error("Could not find the QUnit `Assert` context to push results"); } return pushContext; } /** * Checks that the first two arguments are equal, or are numbers close enough to be considered equal * based on a specified maximum allowable difference. * * @example assert.close(3.141, Math.PI, 0.001); * * @param Number actual * @param Number expected * @param Number maxDifference (the maximum inclusive difference allowed between the actual and expected numbers) * @param String message (optional) */ function close(actual, expected, maxDifference, message) { var actualDiff = (actual === expected) ? 0 : Math.abs(actual - expected), result = actualDiff <= maxDifference, pushContext = _getPushContext(this); message = message || (actual + " should be within " + maxDifference + " (inclusive) of " + expected + (result ? "" : ". Actual: " + actualDiff)); pushContext.push(result, actual, expected, message); } /** * Checks that the first two arguments are equal, or are numbers close enough to be considered equal * based on a specified maximum allowable difference percentage. * * @example assert.close.percent(155, 150, 3.4); // Difference is ~3.33% * * @param Number actual * @param Number expected * @param Number maxPercentDifference (the maximum inclusive difference percentage allowed between the actual and expected numbers) * @param String message (optional) */ close.percent = function closePercent(actual, expected, maxPercentDifference, message) { var actualDiff, result, pushContext = _getPushContext(this); if (actual === expected) { actualDiff = 0; result = actualDiff <= maxPercentDifference; } else if (actual !== 0 && expected !== 0 && expected !== Infinity && expected !== -Infinity) { actualDiff = Math.abs(100 * (actual - expected) / expected); result = actualDiff <= maxPercentDifference; } else { // Dividing by zero (0)! Should return `false` unless the max percentage was `Infinity` actualDiff = Infinity; result = maxPercentDifference === Infinity; } message = message || (actual + " should be within " + maxPercentDifference + "% (inclusive) of " + expected + (result ? "" : ". Actual: " + actualDiff + "%")); pushContext.push(result, actual, expected, message); }; /** * Checks that the first two arguments are numbers with differences greater than the specified * minimum difference. * * @example assert.notClose(3.1, Math.PI, 0.001); * * @param Number actual * @param Number expected * @param Number minDifference (the minimum exclusive difference allowed between the actual and expected numbers) * @param String message (optional) */ function notClose(actual, expected, minDifference, message) { var actualDiff = Math.abs(actual - expected), result = actualDiff > minDifference, pushContext = _getPushContext(this); message = message || (actual + " should not be within " + minDifference + " (exclusive) of " + expected + (result ? "" : ". Actual: " + actualDiff)); pushContext.push(result, actual, expected, message); } /** * Checks that the first two arguments are numbers with differences greater than the specified * minimum difference percentage. * * @example assert.notClose.percent(156, 150, 3.5); // Difference is 4.0% * * @param Number actual * @param Number expected * @param Number minPercentDifference (the minimum exclusive difference percentage allowed between the actual and expected numbers) * @param String message (optional) */ notClose.percent = function notClosePercent(actual, expected, minPercentDifference, message) { var actualDiff, result, pushContext = _getPushContext(this); if (actual === expected) { actualDiff = 0; result = actualDiff > minPercentDifference; } else if (actual !== 0 && expected !== 0 && expected !== Infinity && expected !== -Infinity) { actualDiff = Math.abs(100 * (actual - expected) / expected); result = actualDiff > minPercentDifference; } else { // Dividing by zero (0)! Should only return `true` if the min percentage was `Infinity` actualDiff = Infinity; result = minPercentDifference !== Infinity; } message = message || (actual + " should not be within " + minPercentDifference + "% (exclusive) of " + expected + (result ? "" : ". Actual: " + actualDiff + "%")); pushContext.push(result, actual, expected, message); }; var api = { close: close, notClose: notClose, closePercent: close.percent, notClosePercent: notClose.percent }; QUnit.extend(QUnit.assert, api); return api; }));
'use strict'; var path = require('path'); var fs = require('fs'); var config_file_cache = new Map(); module.exports.niceName = 'Custom file (.gcc-flags.json)'; module.exports.settings = function () { var SETTINGS_FILENAME = ".gcc-flags.json"; var MAX_ITERATIONS = 30; var linted_file = atom.workspace.getActiveTextEditor().getPath(); var file_settings = linted_file + SETTINGS_FILENAME; var directory_settings = path.join(path.dirname(file_settings), SETTINGS_FILENAME); var config_file = ""; if (fs.existsSync(file_settings)) { config_file = file_settings; } else if (fs.existsSync(directory_settings)) { config_file = directory_settings; } let project_path = atom.project.relativizePath(linted_file)[0]; if (project_path === null) { project_path = path.dirname(linted_file); } if (config_file == "") { var current_path = path.dirname(file_settings); var current_file = ""; var counter = 0; while (path.relative(current_path, project_path) != "" && counter < MAX_ITERATIONS){ current_path = path.join(current_path, ".."); current_file = path.join(current_path, SETTINGS_FILENAME); if (fs.existsSync(current_file)) { config_file = current_file; break; } counter += 1; } } if (atom.config.get("linter-gcc.gccDebug")){ if (config_file.length > 0) { console.log("linter-gcc: Reading settings from: " + config_file); } else { console.log("linter-gcc: Using configuration page settings"); } } var commands_file = "" if (config_file != "") { var last_modified = fs.statSync(config_file).mtime.getTime(); var config_data = {}; if (config_file_cache.has(config_file) && config_file_cache.get(config_file).last_modified == last_modified) { config_data = config_file_cache.get(config_file).config_data; } else { config_data = JSON.parse(fs.readFileSync(config_file)); config_file_cache.set(config_file, {last_modified: last_modified, config_data: config_data}); } if ("compileCommandsFile" in config_data) { commands_file = config_data.compileCommandsFile; } else { commands_file = atom.config.get("linter-gcc.compileCommandsFile"); } return { execPath: config_data.execPath, gccIncludePaths: config_data.gccIncludePaths, gccISystemPaths: config_data.gccISystemPaths, gccSuppressWarnings: config_data.gccSuppressWarnings, gcc7orGreater: config_data.gcc7orGreater, gccDefaultCFlags: config_data.gccDefaultCFlags, gccDefaultCppFlags: config_data.gccDefaultCppFlags, gccErrorLimit: config_data.gccErrorLimit, gccErrorString: config_data.gccErrorString, gccWarningString: config_data.gccWarningString, gccNoteString: config_data.gccNoteString, compileCommandsFile: commands_file }; } else { return { execPath: atom.config.get("linter-gcc.execPath"), gccIncludePaths: atom.config.get("linter-gcc.gccIncludePaths"), gccISystemPaths: atom.config.get("linter-gcc.gccISystemPaths"), gccSuppressWarnings: atom.config.get("linter-gcc.gccSuppressWarnings"), gcc7orGreater: atom.config.get("linter-gcc.gcc7orGreater"), gccDefaultCFlags: atom.config.get("linter-gcc.gccDefaultCFlags"), gccDefaultCppFlags: atom.config.get("linter-gcc.gccDefaultCppFlags"), gccErrorLimit: atom.config.get("linter-gcc.gccErrorLimit"), gccErrorString: atom.config.get("linter-gcc.gccErrorString"), gccWarningString: atom.config.get("linter-gcc.gccWarningString"), gccNoteString: atom.config.get("linter-gcc.gccNoteString"), compileCommandsFile: atom.config.get("linter-gcc.compileCommandsFile"), }; } };
// Use default color scheme function save_scheme() { console.log("inside save_scheme "); var colors = {}; colors.bgColor = "#2f4f4f"; colors.paraColor = "#f5deb3"; colors.mainHeading = "#f1f1f1"; colors.closeColor = "#ffffff"; colors.subHeading = "#f5deb3" colors.subHeadingH3 = "#f5deb3" console.log("default color palette", { colors }); chrome.storage.sync.set({ "colors": colors, }, function() { // Update status to let user know options were saved. // console.log("just trhying for", a); var status = document.getElementById('status'); status.textContent = 'Options saved.'; setTimeout(function() { status.textContent = ''; }, 750); }); } // Use custom color scheme function save_colors() { console.log("inside save_colors "); var colors = {}; colors.bgColor = document.getElementById("bg-color").value; colors.paraColor = document.getElementById("para-font-color").value; colors.mainHeading = document.getElementById("main-head-font-color").value; colors.closeColor = document.getElementById("close-font-color").value; colors.subHeading = document.getElementById("sub-head-font-color").value; colors.subHeadingH3 = document.getElementById("sub-head-font-color").value; console.log("current color palette", { colors }); var enableDbClick = document.getElementById("enable-db-click").checked; // console.log("db click or not", enableDbClick); chrome.storage.sync.set({ "colors": colors, "isDbClick": enableDbClick }, function() { // Update status to let user know options were saved. // console.log("just trhying for", a); var status = document.getElementById('status'); status.textContent = 'Options saved.'; setTimeout(function() { status.textContent = ''; }, 750); }); } // Restores input values stored in chrome.storage. function restore_options() { console.log("restore called"); // chrome.storage.sync.clear(); chrome.storage.sync.get([ "colors", "isDbClick" ], function(items) { console.log( {items} ); if(items.colors) { document.getElementById("bg-color").value = items.colors.bgColor; document.getElementById("para-font-color").value = items.colors.paraColor; document.getElementById("main-head-font-color").value = items.colors.mainHeading; document.getElementById("close-font-color").value = items.colors.closeColor; document.getElementById("sub-head-font-color").value = items.colors.subHeading; document.getElementById("enable-db-click").checked = items.isDbClick; } }); } document.addEventListener('DOMContentLoaded', restore_options); document.getElementById('save-color-scheme').addEventListener('click', save_scheme); document.getElementById('save-each-color').addEventListener('click', save_colors);
module.exports = function (alchemy) { 'use strict'; alchemy.formula.define('slides.Testing-UI-02', [], function () { // - neu: ECS return { type: 'core.entities.Slide', state: { title: 'Testing - Wie lässt sich das UI testen?' }, children: [{ vdom: { renderer: function (ctx) { return ctx.h('div.diagram', null, ctx.renderAllChildren()); }, }, css: { typeRules: { '.diagram': { position: 'relative', width: '1000px', height: '700px', margin: '0 auto', }, }, }, children: [{ type: 'core.entities.Box', state: { title: 'UI', x: 75, y: 90, w: 325, h: 600, } }, { type: 'core.entities.Arrow', state: { dir: 'left', text: 'State', x: 400, y: 250, } }, { type: 'core.entities.Arrow', state: { dir: 'right', text: 'Message', x: 400, y: 400, background: true, } }, { type: 'core.entities.Box', state: { title: 'Application', x: 600, y: 90, w: 325, h: 600, background: true, } }, { type: 'core.entities.Box', state: { title: 'Entity Component System', }, css: { entityRules: function () { return { "top": "150px", 'left': '100px', 'width': '275px', 'height': '500px', 'background-color': 'rgba(200, 20, 255, 0.2)', '.box-title': { 'top': '100px', }, }; } }, }] }] }; }); };
/** * Copyright 2014 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * This module provides helpers for patterns regarding *takeActionRequest*, *willTakeAction* and * *didTakeAction* events. * * @module actions */ define( [ 'angular', 'laxar' ], function( ng, ax ) { 'use strict'; var $q; ng.injector( [ 'ng' ] ).invoke( [ '$q', function( _$q_ ) { $q = _$q_; } ] ); var NOOP = function() {}; var DELIVER_TO_SENDER = { deliverToSender: false }; var OUTCOME_SUCCESS = 'SUCCESS'; var OUTCOME_ERROR = 'ERROR'; /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates and returns a function to publish `takeActionRequest` events for a given action feature. The * action to publish is expected to be at the key `action` under the given feature path. * * Apart from that this function works just like {@link publisher}. * * @param {Object} scope * the scope the publisher works on. Needs at least an EventBus instance as `eventBus` property * @param {String} feature * the feature to take the action name from * @param {Object} [optionalOptions] * options for the publisher * @param {Boolean} optionalOptions.deliverToSender * the value is forward to `eventBus.publishAndGatherReplies`: if `true` the event will also be * delivered to the publisher. Default is `false` * @param {Function} optionalOptions.onSuccess * a function that is called when the overall outcome yields "SUCCESS" * @param {Function} optionalOptions.onError * a function that is called when the overall outcome yields "ERROR" * @param {Function} optionalOptions.onComplete * a function that is called always, independently of the overall outcome * * @returns {Function} * the publisher as described above */ function publisherForFeature( scope, feature, optionalOptions ) { var action = ax.object.path( scope.features, feature + '.action', null ); return publisher( scope, action, optionalOptions ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates and returns a function to publish `takeActionRequest` events for a given action. The outcomes of * all given `didTakeAction` events are interpreted and optional callbacks according to the overall outcome * are called. Interpretation is simple: If at least one `didTakeAction` event yields the outcome "ERROR", * the overall outcome is also erroneous. In any other case the overall outcome will be successful. * * The promise returned by the publisher is resolved, if the overall outcome is successful and rejected if * the outcome is erroneous. All callbacks, be it the `on*` handlers or the then handlers of the promise, * will receive the list of events and meta information of all `didTakeAction` events * (see `EventBus#publishAndGatherReplies()` for details). * * Example: * ```js * publisher = actions.publisher( scope, 'save', { * onSuccess: function() { closeApplication(); }, * onError: function() { displayError(); } * } ); * * $button.on( 'click', publisher ); * ``` * * @param {Object} scope * the scope the publisher works on. Needs at least an EventBus instance as `eventBus` property * @param {String} action * the action to publish on call of the publisher * @param {Object} [optionalOptions] * options for the publisher * @param {Boolean} optionalOptions.deliverToSender * the value is forward to `eventBus.publishAndGatherReplies`: if `true` the event will also be * delivered to the publisher. Default is `false` * @param {Function} optionalOptions.onSuccess * a function that is called when the overall outcome yields "SUCCESS" * @param {Function} optionalOptions.onError * a function that is called when the overall outcome yields "ERROR" * @param {Function} optionalOptions.onComplete * a function that is called always, independently of the overall outcome * * @returns {Function} * the publisher as described above */ function publisher( scope, action, optionalOptions ) { ax.assert( scope ).hasType( Object ).hasProperty( 'eventBus' ); ax.assert( action ).hasType( String ).isNotNull(); var options = ax.object.options( optionalOptions, { deliverToSender: false, onSuccess: NOOP, onError: NOOP, onComplete: NOOP } ); ax.assert( options.onSuccess ).hasType( Function ).isNotNull(); ax.assert( options.onError ).hasType( Function ).isNotNull(); ax.assert( options.onComplete ).hasType( Function ).isNotNull(); var eventBusOptions = { deliverToSender: options.deliverToSender }; if( options.timeout > 0 ) { eventBusOptions.pendingDidTimeout = options.timeout; } return function( optionalEvent ) { var event = ax.object.options( optionalEvent, { action: action } ); return scope.eventBus .publishAndGatherReplies( 'takeActionRequest.' + action, event, eventBusOptions ) .then( function( didResponses ) { var failed = didResponses.some( function( response ) { return response.event.outcome === OUTCOME_ERROR; } ); options.onComplete( didResponses.slice( 0 ) ); if( failed ) { options.onError( didResponses.slice( 0 ) ); throw didResponses; } options.onSuccess( didResponses.slice( 0 ) ); return didResponses; } ); }; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates a new action handler instance for `takeActionRequest` events. It handles sending of an optional * `willTakeAction` event and the final, possibly later asynchronously following `didTakeAction` event. * * @param {Object} scope * the scope the handler should work with. It is expected to find an `eventBus` property there with * which it can do the event handling * * @return {ActionHandler} * an action handler instance */ function handlerFor( scope ) { ax.assert( scope ).hasType( Object ).hasProperty( 'eventBus' ); return new ActionHandler( scope ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * * @param scope * * @constructor * @private */ function ActionHandler( scope ) { this.scope_ = scope; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Registers a handler for `takeActionRequest` events with actions from a feature. It is assumed that the * given feature has an `onActions` property, which is a set of actions to listen to. The set may be empty, * `null` or `undefined`, in which case the handler simply won't be attached to any event. * * Apart from that this function works just like {@link ActionHandler#registerActions}. * * Example: * Consider the following configuration for a widget: * ```json * { * "features": { * "open": { * "onActions": [ "openAction1", "openAction2" ] * }, * "save": { * "onActions": [ "save" ] * } * } * } * ``` * An example using that would be: * ```js * actions.handlerFor( scope ) * .registerActionsFromFeature( 'open', function( event, meta ) { * somethingSynchronous(); * return actions.OUTCOME_SUCCESS; * } ) * .registerActionsFromFeature( 'save', function( event, meta ) { * return $q.when( somethingAsynchronous() ); * } ); * ``` * * @param {String} feature * the feature to read the actions to watch from * @param {Function} handler * the handler to call whenever a `takeActionRequest` event with matching action is received * * @return {ActionHandler} * this instance for chaining */ ActionHandler.prototype.registerActionsFromFeature = function( feature, handler ) { var actions = ax.object.path( this.scope_.features, feature + '.onActions' ) || []; return this.registerActions( actions, handler ); }; /////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Registers a handler for `takeActionRequest` events for a set of actions. The set may be empty, in * which case the handler simply won't be attached to any event. * * The handler is assumed to be a function that receives the event and meta object of the underlying * `takeActionRequest` event when called. In order to send the correct `didTakeAction` event as response, * the return value of the handler is interpreted according to the following rules: * * - the handler throws an error * - the `didTakeAction` event is sent with outcome `ERROR` * - the error is re-thrown * - the handler returns a simple value or a promise, that is later resolved with a value * - if the value is a plain object, it is used as basis for the event object and * - if the object has a property `outcome` with value `ERROR`, the `didTakeAction` event is sent with * outcome `ERROR` * - otherwise, or if the value is no plain object, the `didTakeAction` event is sent with outcome * `SUCCESS` * - the handler returns a promise, that is later rejected with a value * - if the value is a plain object, it is used as basis for the event object and * - if the object has a property `outcome` with value `SUCCESS`, the `didTakeAction` event is sent with * outcome `SUCCESS` * - otherwise, or if the value is no plain object, the `didTakeAction` event is sent with outcome `ERROR` * * So basically simple return values or resolved promises are assumed to be successful if they don't state * otherwise, while rejected promises are assumed to be erroneous, if they don't state otherwise. * * Example: * ```js * actions.handlerFor( scope ) * .registerActions( [ 'open' ], function( event, meta ) { * return 42 * } ) * .registerActions( [ 'save' ], function( event, meta ) { * return $q.when( { resultValue: 42 } ); * } ); * ``` * * @param {String[]} actions * a set of actions to watch * @param {Function} handler * the handler to call whenever a `takeActionRequest` event with matching action is received * * @return {ActionHandler} * this instance for chaining */ ActionHandler.prototype.registerActions = function( actions, handler ) { ax.assert( actions ).hasType( Array ).isNotNull(); ax.assert( handler ).hasType( Function ).isNotNull(); var self = this; actions.forEach( function( action ) { self.scope_.eventBus.subscribe( 'takeActionRequest.' + action, function( event, meta ) { callHandler( self.scope_.eventBus, action, handler, event, meta ); } ); } ); return this; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////// function callHandler( eventBus, action, handler, event, meta ) { eventBus.publish( 'willTakeAction.' + action, { action: action }, DELIVER_TO_SENDER ); var responseEvent = { action: action, outcome: OUTCOME_SUCCESS }; var returnValue; try { returnValue = handler( event, meta ); } catch( error ) { responseEvent.outcome = OUTCOME_ERROR; eventBus.publish( 'didTakeAction.' + action + '.' + OUTCOME_ERROR, responseEvent, DELIVER_TO_SENDER ); throw error; } $q.when( returnValue ) .then( function( promiseValue ) { if( ng.isObject( promiseValue ) ) { responseEvent.outcome = promiseValue.outcome === OUTCOME_ERROR ? OUTCOME_ERROR : OUTCOME_SUCCESS; } return promiseValue; }, function( promiseValue ) { responseEvent.outcome = OUTCOME_ERROR; if( ng.isObject( promiseValue ) ) { responseEvent.outcome = promiseValue.outcome === OUTCOME_SUCCESS ? OUTCOME_SUCCESS : OUTCOME_ERROR; } return promiseValue; } ) .then( function( promiseValue ) { responseEvent = ax.object.options( responseEvent, promiseValue ); var eventName = 'didTakeAction.' + action + '.' + responseEvent.outcome; eventBus.publish( eventName, responseEvent, DELIVER_TO_SENDER ); } ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// return { publisher: publisher, publisherForFeature: publisherForFeature, handlerFor: handlerFor, OUTCOME_ERROR: OUTCOME_ERROR, OUTCOME_SUCCESS: OUTCOME_SUCCESS }; } );
import { Message } from './message'; describe('Message', () => { const MSG = new Message('message.action'); const MSGData = new Message('message.action', {}); const MSGDataFalse = new Message('message.action', false); const MSGDataMalformed = new Message('message.action', undefined); const MSGNoAction = new Message(); const MSGBadAction = new Message({}); it('should exist', () => { expect(typeof Message).toBe('function'); }); it('should expose a .action property', () => { expect(MSG.action).toBeDefined(); expect(MSGData.action).toBeDefined(); expect(MSGDataMalformed.action).toBeDefined(); expect(MSGNoAction.action).toBeDefined(); }); it('should expose a .data property', () => { expect(MSG.data).toBeDefined(); expect(MSGData.data).toBeDefined(); expect(MSGDataMalformed.data).toBeDefined(); expect(MSGNoAction.data).toBeDefined(); }); it('should have a .getAction() method', () => { expect(MSG.getAction).toBeDefined(); expect(typeof MSG.getAction).toBe('function'); }); it('should have a .getData() method', () => { expect(MSG.getData).toBeDefined(); expect(typeof MSG.getData).toBe('function'); }); it('should bind given action to .action property', () => { expect(MSG.action).toBe('message.action'); expect(MSGData.action).toBe('message.action'); expect(MSGDataMalformed.action).toBe('message.action'); expect(MSGNoAction.action).toBe(null); expect(MSGBadAction.action).toBe(null); }); describe(`#getAction()`, () => { it('should return given action', () => { expect(MSG.getAction()).toBe('message.action'); expect(MSGData.getAction()).toBe('message.action'); expect(MSGDataMalformed.getAction()).toBe('message.action'); expect(MSGNoAction.getAction()).toBe(null); expect(MSGBadAction.getAction()).toBe(null); }); }); describe(`#getData()`, () => { it('should return given data', () => { expect(MSG.getData()).toBe(null); expect(MSGData.getData()).toEqual({}); expect(MSGDataMalformed.getData()).toBe(null); expect(MSGNoAction.getData()).toBe(null); expect(MSGDataFalse.getData()).toBe(false); }); }); describe(`#hasData()`, () => { it('should return if data given', () => { expect(MSG.hasData()).toBe(false); expect(MSGData.hasData()).toEqual(true); expect(MSGDataMalformed.hasData()).toBe(false); expect(MSGNoAction.hasData()).toBe(false); expect(MSGDataFalse.hasData()).toBe(true); }); }); });
// @flow export { default } from './tab-size'
/*Coppy right : vuhongminh911@gmail.com*/ (function ($) { $.fn.convertHiKata = function (value , type , content) { valueTextInput = value ; Type = type ; Content = content; pos = $(Content).caret(); Convert (valueTextInput , Type); }; array_char = []; array_char2 = []; array_char3 = []; array_char4_a = []; array_char4_b = []; var StringCVAlpha = ''; var StringCVJp = ''; var StringCantCV = ''; checkCantCV = 0; useThis = 0; special1 = 0; valueBegin = ''; valueEnd = ''; special2 = 0; pile1 = 0; var checkRight = ''; var StringOld = ''; var StringTop = ''; var StringBot = ''; var StringCVCopyPast = ''; var name_regex = /[a-zA-Z,-]+/; array_CVJ = [{ char : 'a' , jp :'あ' } , { char : 'i' , jp :'い' } , { char : 'u' , jp :'う' } , { char : 'e' , jp :'え' } , { char : 'o' , jp :'お' } , { char : 'ka' , jp :'か' } , { char : 'ki' , jp :'き' } , { char : 'ku' , jp :'く' } , { char : 'ke' , jp :'け' } , { char : 'ko' , jp :'こ' } , { char : 'sa' , jp :'さ' } , { char : 'shi' , jp :'し' } , { char : 'si' , jp :'し' } , { char : 'su' , jp :'す' } , { char : 'se' , jp :'せ' } , { char : 'so' , jp :'そ' } , { char : 'ta' , jp :'た' } , { char : 'chi' , jp :'ち' } , { char : 'tsu' , jp :'つ' } , { char : 'te' , jp :'て' } , { char : 'to' , jp :'と' } , { char : 'na' , jp :'な' } , { char : 'ni' , jp :'に' } , { char : 'nu' , jp :'ぬ' } , { char : 'ne' , jp :'ね' } , { char : 'no' , jp :'の' } , { char : 'ha' , jp :'は' } , { char : 'hi' , jp :'ひ' } , { char : 'fu' , jp :'ふ' } , { char : 'he' , jp :'へ' } , { char : 'ho' , jp :'ほ' } , { char : 'ma' , jp :'ま' } , { char : 'mi' , jp :'み' } , { char : 'mu' , jp :'む' } , { char : 'me' , jp :'め' } , { char : 'mo' , jp :'も' } , { char : 'ra' , jp :'ら' } , { char : 'ri' , jp :'り' } , { char : 'ru' , jp :'る' } , { char : 're' , jp :'れ' } , { char : 'ro' , jp :'ろ' } , { char : 'wa' , jp :'わ' } , { char : 'wo' , jp :'を' } , { char : 'ya' , jp :'や' } , { char : 'yu' , jp :'ゆ' } , { char : 'yo' , jp :'よ' },{ char : 'nn' , jp :'ん' } , { char : 'ga' , jp :'が' } , { char : 'gi' , jp :'ぎ' } , { char : 'gu' , jp :'ぐ' } , { char : 'ge' , jp :'げ' } , { char : 'go' , jp :'ご' } , { char : 'za' , jp :'ざ' } , { char : 'zi' , jp :'じ' } , { char : 'zu' , jp :'ず' } , { char : 'ze' , jp :'ぜ' } , { char : 'zo' , jp :'ぞ' } , { char : 'da' , jp :'だ' } , { char : 'di' , jp :'ぢ' } , { char : 'du' , jp :'づ' } , { char : 'de' , jp :'で' } , { char : 'do' , jp :'ど' } , { char : 'ba' , jp :'ば' } , { char : 'bi' , jp :'び' } , { char : 'bu' , jp :'ぶ' } , { char : 'be' , jp :'べ' } , { char : 'bo' , jp :'ぼ' } , { char : 'pa' , jp :'ぱ' } , { char : 'pi' , jp :'ぴ' } , { char : 'pu' , jp :'ぷ' } , { char : 'pe' , jp :'ぺ' } , { char : 'po' , jp :'ぽ' } , { char : 'kyo' , jp :'きょ'} , { char : 'kya' , jp :'きゃ'} , { char : 'kyu' , jp :'きゅ'} , { char : 'ji' , jp :'じ' } , { char : 'ja' , jp :'じゃ' } , { char : 'ju' , jp :'じゅ' } , { char : 'jo' , jp :'じょ' } , { char : 'cho' , jp :'ちょ' } , { char : 'cha' , jp :'ちゃ' } , {char : 'chu' , jp :'ちゅ' } , { char : 'byo' , jp :'びょ' } , { char : 'bya' , jp :'びゃ' } , {char : 'byu' , jp :'びゅ' } , { char : 'pyo' , jp :'ぴょ' } , { char : 'pya' , jp :'ぴゃ' } , {char : 'pyu' , jp :'ぴゅ' } , { char : 'shu' , jp :'しゅ' } , { char : 'sha' , jp :'しゃ' } , {char : 'sho' , jp :'しょ' } , { char : 'tt' , jp :'っ' } , { char : 'kk' , jp :'っ' } , {char : 'ss' , jp :'っ' } , { char : 'pp' , jp :'っ' } , { char : 'bb' , jp :'っ' }] // array_KATA = [{ char : 'a' , jp :'ア' } , { char : 'i' , jp :'イ' } , { char : 'u' , jp :'ウ' } , { char : 'e' , jp :'エ' } , { char : 'o' , jp :'オ' } , { char : 'ka' , jp :'カ' } , { char : 'ki' , jp :'キ' } , { char : 'ku' , jp :'ク' } , { char : 'ke' , jp :'ケ' } , { char : 'ko' , jp :'コ' } , { char : 'sa' , jp :'サ' } , { char : 'shi' , jp :'シ' } , { char : 'si' , jp :'シ' } , { char : 'su' , jp :'ス' } , { char : 'se' , jp :'セ' } , { char : 'so' , jp :'ソ' } , { char : 'ta' , jp :'タ' } , { char : 'chi' , jp :'チ' } , { char : 'tsu' , jp :'ツ' } , { char : 'te' , jp :'テ' } , { char : 'to' , jp :'ト' } , { char : 'na' , jp :'ナ' } , { char : 'ni' , jp :'ニ' } , { char : 'nu' , jp :'ヌ' } , { char : 'ne' , jp :'ネ' } , { char : 'no' , jp :'ノ' } , { char : 'ha' , jp :'ハ' } , { char : 'hi' , jp :'ヒ' } , { char : 'fu' , jp :'フ' } , { char : 'he' , jp :'ヘ' } , { char : 'ho' , jp :'ホ' } , { char : 'ma' , jp :'マ' } , { char : 'mi' , jp :'ミ' } , { char : 'mu' , jp :'ム' } , { char : 'me' , jp :'メ' } , { char : 'mo' , jp :'モ' } , { char : 'ra' , jp :'ラ' } , { char : 'ri' , jp :'リ' } , { char : 'ru' , jp :'ル' } , { char : 're' , jp :'レ' } , { char : 'ro' , jp :'ロ' } , { char : 'wa' , jp :'ワ' } , { char : 'wo' , jp :'ヲ' } , { char : 'ya' , jp :'ヤ' } , { char : 'yu' , jp :'ユ' } , { char : 'yo' , jp :'ヨ ' },{ char : 'nn' , jp :'ン ' } , { char : 'ga' , jp :'ガ' } , { char : 'gi' , jp :'ギ' } , { char : 'gu' , jp :'グ' } , { char : 'ge' , jp :'ゲ' } , { char : 'go' , jp :'ゴ' } , { char : 'za' , jp :'ザ' } , { char : 'zi' , jp :'ジ' } , { char : 'zu' , jp :'ズ' } , { char : 'ze' , jp :'ゼ' } , { char : 'zo' , jp :'ゾ' } , { char : 'da' , jp :'ダ' } , { char : 'di' , jp :'ヂ' } , { char : 'du' , jp :'ヅ' } , { char : 'de' , jp :'デ' } , { char : 'do' , jp :'ド' } , { char : 'ba' , jp :'バ' } , { char : 'bi' , jp :'ビ' } , { char : 'bu' , jp :'ブ' } , { char : 'be' , jp :'ベ' } , { char : 'bo' , jp :'ボ' } , { char : 'pa' , jp :'パ' } , { char : 'pi' , jp :'ピ' } , { char : 'pu' , jp :'プ' } , { char : 'pe' , jp :'ペ' } , { char : 'po' , jp :'ポ' } , { char : 'kyo' , jp :'キョ'} , { char : 'kya' , jp :'キャ'} , { char : 'kyu' , jp :'キュ'} , { char : 'ji' , jp :'ジ' } , { char : 'ja' , jp :'ジャ' } , { char : 'ju' , jp :'ジュ' } , { char : 'jo' , jp :'ジョ' } , { char : 'cho' , jp :'チョ' } , { char : 'cha' , jp :'チャ' } , {char : 'chu' , jp :'チュ' } , { char : 'byo' , jp :'ビョ' } , { char : 'bya' , jp :'ビャ' } , {char : 'byu' , jp :'ビュ' } , { char : 'pyo' , jp :'ピョ' } , { char : 'pya' , jp :'ピャ' } , {char : 'pyu' , jp :'ピュ' } , { char : 'shu' , jp :'シュ' } , { char : 'sha' , jp :'シャ' } , {char : 'sho' , jp :'ショ' } , { char : 'tt' , jp :'ッ' } , { char : 'kk' , jp :'ッ' } , {char : 'ss' , jp :'ッ' } , { char : 'pp' , jp :'ッ' } , { char : 'bb' , jp :'ッ' } ,{ char : '-' , jp :'ー' }] Convert = function(valueTextInput , type) { typeC = type; var StringCV = valueTextInput.trim(); StringCV = valueTextInput.toLowerCase(); StringCVCopyPast = StringCV ; array_char = $.trim(StringCV).split(""); if(StringCV.length == 0 ) { StringOld = ''; StringCVAlpha = ''; } jQuery.each(array_char , function (i , val){ if(val != ' ') { if( !val.match(name_regex) && pile1 == 0) { StringCVAlpha = StringCV.substr(i+1,StringCV.length); StringCVJp = StringCV.substr(0, i+1 ); useThis = 1; } else if( StringCV != StringOld && i < StringCV.length && i >= 0 && StringCV.length >= StringOld.length + 1 && StringOld != '' && StringCV.length > 4) { StringCVAlpha = ''; jQuery.each(array_char , function (i3 , val3){ if(val3.match(name_regex)) { if( StringCV.search( (StringCVAlpha + val3) ) > -1 ) { StringCVAlpha = StringCVAlpha + val3; pile1 = 1; } } }); useThis = 1; if(StringCVAlpha.length +1 >= 2 && pile1 == 1) { special1 = 1; } } else if( StringCV != StringOld && StringCV.length <= 4 && StringCV.length > 2 && i != StringCV.length - 1 && StringCV.length >= StringOld.length && StringOld != '') { if( StringCV.length > 1) { StringCVAlpha = ''; jQuery.each(array_char , function (i3 , val3){ if(val3.match(name_regex)) { if( StringCV.search( (StringCVAlpha + val3) ) > -1 ) { StringCVAlpha = StringCVAlpha + val3; pile1 = 1; } } }); useThis = 1; if(StringCVAlpha.length +1 >= 2 && pile1 == 1) { special1 = 1; } } } } }); if( special1 == 1) { array_char2 = $.trim(StringCVAlpha).split(""); jQuery.each(array_char2 , function (i2 , val2){ if( i2 == 0) valueBegin = val2; if( i2 == array_char2.length - 1) valueEnd = val2; }); if(valueBegin != 0) { var begin = StringCV.search(valueBegin); StringTop = StringCV.substr(0, begin ); } else { StringTop = ''; } var end = StringCV.search(valueEnd); StringBot = StringCV.substr(end + 1, StringCV.length ); special2 = 1; } if( StringCVAlpha == '' && StringCVJp == '' && checkCantCV == 0 && StringCV.length > 0 && special1 == 0 ) { array_char4_a = array_char4_b = $.trim(StringCV).split(""); if(array_char4_a.length == StringCV.length && array_char4_a.length > 1) { jQuery.each(array_char4_a , function (i4_a , val4_a){ var dem = 0; checkRight = val4_a; jQuery.each(array_char4_b , function (i4_b , val4_b){ if (dem < 3 && StringCantCV == '') { if(i4_a < i4_b) { checkRight = checkRight + val4_b ; if(typeC == 'hira' && $.grep(array_CVJ , function(e){return e.char == checkRight}).length > 0 ) { var vitri = StringCV.search(checkRight); StringCantCV = StringCV.substr(0 , vitri); StringCV = StringCV.substr(vitri , StringCV.length); dem = 3; return true; } else if (typeC == 'kata' && $.grep(array_KATA , function(e){return e.char == checkRight}).length > 0 ) { var vitri = StringCV.search(checkRight); StringCantCV = StringCV.substr(0 , vitri); StringCV = StringCV.substr(vitri , StringCV.length); dem = 3; return true; } } else if(i4_b >= i4_a) dem++; } else if( dem == 3 && StringCantCV == '') { checkRight = ''; } }); if(dem == 3 && StringCantCV != '') { return true; } }); checkCantCV = 1; } else if (array_char4_a.length < StringCV.length && array_char4_a.length > 1) { jQuery.each(array_char4_a , function (i4_a , val4_a){ if(StringCVAlpha.length != array_char4_a.length) StringCVAlpha = StringCVAlpha + val4_a; }); var vitri = StringCV.search(StringCVAlpha); StringCantCV = StringCV.substr( 0 ,vitri); StringCV = StringCVAlpha; } } else if(StringCVJp != '') { StringCantCV = ''; } if(typeC == 'hira') { if(useThis == 1) var CVDone = $.grep(array_CVJ , function(e){return e.char == StringCVAlpha}) else var CVDone = $.grep(array_CVJ , function(e){return e.char == StringCV}) } else if(typeC == 'kata') { if(useThis == 1) var CVDone = $.grep(array_KATA , function(e){return e.char == StringCVAlpha}) else var CVDone = $.grep(array_KATA , function(e){return e.char == StringCV}) } useThis = 0; if (CVDone.length != 0) { if(special2 == 0) $(Content).val(StringCantCV.concat(StringCVJp , CVDone[0].jp)); else { $(Content).val(StringTop.concat( CVDone[0].jp , StringBot)); special2 = 0; special1 = 0; $(Content).caret(pos); } StringOld = document.getElementById("TextCV").value; CVDone = ''; pile1 = 0; StringCVAlpha = ''; } StringCantCV = ''; checkCantCV = 0; StringCVJp = ''; StringCV = ''; return 0; } })(jQuery)
import {rejectNotFound} from './rejectNotFound' import {ensureRequestKey} from './request' import isString from 'lodash/isString' import {markSafeSource, createSafeSource} from './source' // Require / prefix to make it easier to understand that these are routes. export const isPath = (path) => isString(path) && path[0] === '/' && path.indexOf('/', 1) === -1 const ensurePath = (path) => { if (!isPath(path)) throw new Error( `Path must start with and contain only one slash "/" (${path})` ) } const pathPiece = (path) => path.slice(1) export const currentPath = (path) => { const index = path.indexOf('/') return index === -1 ? path : path.slice(0, index) } export const nextPath = (path) => { const index = path.indexOf('/') return index === -1 ? '' : path.slice(index + 1) } // Deprecated. export const currentNextPath = (path) => [currentPath(path), nextPath(path)] export const isTokenPath = (path) => isPath(path) && path[1] === ':' const ensureTokenPath = (path) => { ensurePath(path) if (!isTokenPath(path)) throw new Error(`Token path must start with "/:" (${path})`) } const tokenPathKey = (path) => path.slice(2) export const pathToArray = (path) => Array.isArray(path) ? path : path.split('/').filter(Boolean) export const pathToString = (path) => (isString(path) ? path : path.join('/')) export const withPathToken = (path) => (source) => { source = createSafeSource(source) ensureTokenPath(path) const key = tokenPathKey(path) ensureRequestKey(key) return markSafeSource((request) => { const {path} = request return source( Object.assign({}, request, { path: nextPath(path), [key]: currentPath(path), }) ) }) } export const branchPaths = (paths) => (source) => { source = createSafeSource(source) const sources = {} for (const path in paths) { ensurePath(path) sources[pathPiece(path)] = createSafeSource(paths[path], path) } return markSafeSource((request) => { const {path} = request const thisPath = currentPath(path) if (Object.prototype.hasOwnProperty.call(sources, thisPath)) { const source = sources[thisPath] return source( Object.assign({}, request, { path: nextPath(path), }) ) } return source(request) }) } // Return source that branches requests based on url. // Supports one token path (e.g. '/:id'), all others are // matched exactly. // Token is added to the request using the given key. export const paths = (paths) => { let tokenSource const staticPaths = {} for (const path in paths) { if (isTokenPath(path)) { if (tokenSource) throw new Error(`Paths can only have one token (${path})`) tokenSource = withPathToken(path)(paths[path]) } else { staticPaths[path] = paths[path] } } return branchPaths(staticPaths)(tokenSource || rejectNotFound) }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Post Schema */ var PostSchema = new Schema({ textContent: { type: String, default: '', trim: true }, created: { type: Date, default: Date.now }, localisation: [ { name: { type: String }, lat: { type: String }, long: { type: String } } ], user_id: { type: Schema.ObjectId, ref: 'User' }, event_id: { type: Schema.ObjectId, ref: 'Event' }, coverImage: [ { contentType: { type: String }, width: { type: Number }, height: { type: Number }, dataUrl: { type: String } } ], type: { type: [{ type: String, enum: ['normal', 'flash', 'text'] }], default: ['normal'] }, guests: [ { _id: { type: Schema.ObjectId }, state: { type: [{ type: Boolean }], default: false } } ] }); mongoose.model('Post', PostSchema);
module.exports = { output: { library: 'ReduxRequests', libraryTarget: 'umd', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }, ], }, externals: { reselect: { commonjs: 'reselect', commonjs2: 'reselect', amd: 'reselect', root: 'Reselect', }, }, devtool: 'source-map', };
/*globals jQuery, window, XMLHttpRequest*/ /* * * Wijmo Library 2.2.1 * http://wijmo.com/ * * Copyright(c) GrapeCity, Inc. All rights reserved. * * Dual licensed under the Wijmo Commercial or GNU GPL Version 3 licenses. * licensing@wijmo.com * http://www.wijmo.com/license * * * Wijmo Upload widget. * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function ($) { "use strict"; var uploadClass = "wijmo-wijupload", uploadFileRowClass = "wijmo-wijupload-fileRow", isUploadFileRow = "." + uploadFileRowClass, uploadFilesListClass = "wijmo-wijupload-filesList", uploadCommandRowClass = "wijmo-wijupload-commandRow", uploadUploadAllClass = "wijmo-wijupload-uploadAll", uploadCancelAllClass = "wijmo-wijupload-cancelAll", uploadButtonContainer = "wijmo-wijupload-buttonContainer", uploadUploadClass = "wijmo-wijupload-upload", isUploadUpload = "." + uploadUploadClass, uploadCancelClass = "wijmo-wijupload-cancel", isUploadCancel = "." + uploadCancelClass, uploadFileClass = "wijmo-wijupload-file", uploadProgressClass = "wijmo-wijupload-progress", uploadLoadingClass = "wijmo-wijupload-loading", uiContentClass = "ui-widget-content", uiCornerClass = "ui-corner-all", uiHighlight = "ui-state-highlight", wijuploadXhr, wijuploadFrm, _getFileName = function (fileName) { // Trim path on IE. if (fileName.indexOf("\\") > -1) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } return fileName; }, _getFileNameByInput = function (fileInput) { var files = fileInput.files, name = ""; if (files) { $.each(files, function (i, n) { name += _getFileName(n.name) + "; "; }); if (name.length) { name = name.substring(0, name.lastIndexOf(";")); } } else { name = _getFileName(fileInput.value); } return name; }, _getFileSize = function (file) { var files = file.files, size = 0; if (files && files.length > 0) { $.each(files, function (i, n) { if (n.size) { size += n.size; } }); } return size; }; wijuploadXhr = function (uploaderId, fileRow, action) { var uploader, inputFile = $("input", fileRow), _cancel = function (xhr) { if (xhr) { xhr.abort(); xhr = null; } }, _destroy = function (xhr) { if (xhr) { xhr = null; } }, Uploader = function () { var self = this, files = inputFile.get(0).files, xhrs = [], idx = 0, uploadedSize = 0, createXHR = function (name, action) { var xhttpr = new XMLHttpRequest(); xhttpr.open("POST", action, true); xhttpr.setRequestHeader("Wijmo-RequestType", "XMLHttpRequest"); xhttpr.setRequestHeader("Cache-Control", "no-cache"); xhttpr.setRequestHeader("Wijmo-FileName", name); xhttpr.setRequestHeader("Content-Type", "application/octet-stream"); xhttpr.upload.onprogress = function (e) { if (e.lengthComputable) { var obj; if ($.isFunction(self.onProgress)) { obj = { supportProgress: true, loaded: uploadedSize + e.loaded, total: _getFileSize(inputFile[0]), fileName: _getFileName(self.currentFile.name), fileNameList: _getFileNameByInput(inputFile[0]) .split("; ") }; self.onProgress(obj); } } }; xhttpr.onreadystatechange = function (e) { if (this.readyState === 4) { var response = this.responseText, obj; uploadedSize += files[idx].size; idx++; if (files.length > idx) { _doAjax(files[idx]); } else if ($.isFunction(self.onComplete)) { obj = { e: e, response: response, supportProgress: true }; self.onComplete(obj); } } }; xhrs.push(xhttpr); return xhttpr; }, _doAjax = function (file) { var name = _getFileName(file.name), xhr = createXHR(name, action); self.currentFile = file; xhr.send(file); }; self.fileRow = fileRow; self.inputFile = inputFile; self.upload = function () { _doAjax(files[idx]); }; self.cancel = function () { $.each(xhrs, function (i, xhr) { _cancel(xhr); }); if ($.isFunction(self.onCancel)) { self.onCancel(); } }; self.destroy = function () { $.each(xhrs, function (i, xhr) { _destroy(xhr); }); }; self.updateAction = function (act) { action = act; }; self.onCancel = null; self.onComplete = null; self.onProgress = null; }; uploader = new Uploader(); return uploader; }; wijuploadFrm = function (uploaderId, fileRow, action) { var uploader, inputFile = $("input", fileRow), inputFileId = inputFile.attr("id"), formId = "wijUploadForm_" + uploaderId, form = $("#" + formId), iframeId = "wijUploadIfm_" + inputFileId, isFirstLoad = true, iframe = $("<iframe id=\"" + iframeId + "\" name=\"" + iframeId + "\">"), // ifm = $("<iframe src=\"javascript:false;\" id=\"" + // id + "\" name=\"" + id + "\">"); //"javascript".concat(":false;") //src="javascript:false;" removes ie6 prompt on https _upload = function (ifm, iptFile) { form.empty(); form.attr("target", ifm.attr("name")); if (iptFile) { iptFile.parent().append(iptFile.clone()); form.append(iptFile); } form.submit(); }, _cancel = function (ifm) { // to cancel request set src to something else // we use src="javascript:false;" because it doesn't // trigger ie6 prompt on https ifm.attr("src", "javascript".concat(":false;")); }, _destroy = function (ifm, removeForm) { if (removeForm && form) { form.remove(); form = null; } if (ifm) { ifm.remove(); ifm = null; } }, Uploader; if (form.length === 0) { form = $("<form method=\"post\" enctype=\"multipart/form-data\"></form>"); form .attr("action", action) .attr("id", formId) .attr("name", formId) .appendTo("body"); } iframe.css("position", "absolute") .css("top", "-1000px") .css("left", "-1000px"); iframe.appendTo("body"); Uploader = function () { var self = this; self.fileRow = fileRow; self.iframe = iframe; self.inputFile = inputFile; self.upload = function () { var obj; _upload(iframe, inputFile); if ($.isFunction(self.onProgress)) { obj = { supportProgress: false, loaded: 1, total: 1 }; self.onProgress(obj); } }; self.doPost = function () { _upload(iframe); }; self.cancel = function () { _cancel(iframe); if ($.isFunction(self.onCancel)) { self.onCancel(); } }; self.updateAction = function (act) { action = act; form.attr("action", act); }; self.destroy = function (removeForm) { _destroy(iframe, removeForm); }; self.onCancel = null; self.onComplete = null; self.onProgress = null; iframe.bind("load", function (e) { if (!$.browser.safari) { if (isFirstLoad && !self.autoSubmit) { isFirstLoad = false; return; } } if (iframe.attr("src") === "javascript".concat(":false;")) { return; } var target = e.target, response, doc, obj; try { doc = target.contentDocument ? target.contentDocument : window.frames[0].document; //if (doc.readyState && doc.readyState !== "complete") { // return; //} if (doc.XMLDocument) { response = doc.XMLDocument; } else if (doc.body) { response = doc.body.innerHTML; } else { response = doc; } if ($.isFunction(self.onComplete)) { obj = { e: e, response: response, supportProgress: false }; self.onComplete(obj); } } catch (ex) { response = ""; } finally { //iframe.unbind("load"); } }); }; uploader = new Uploader(); return uploader; }; $.widget("wijmo.wijupload", { options: { /// <summary> /// The server side handler which handle the post request. /// Type:String. /// Default:"". /// Code example: $(".selector").wijupload({action: "upload.php"}). /// </summary> action: "", /// <summary> /// The value indicates whether to submit file as soon as it's selected. /// Type:Boolean. /// Default: false. /// Code example: $(".selector").wijupload({autoSubmit: true}). /// </summary> autoSubmit: false, /// <summary> /// Fires when user selects a file. This event can be cancelled. /// "return false;" to cancel the event. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ change: function (e, data) { } }); /// Bind to the event by type: wijuploadchange /// $("#selector").bind("wijuploadchange", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> /// <param name="data" type="Object"> /// An object that contains the input file. /// </param> change: null, /// <summary> /// Fires before the file is uploaded. This event can be cancelled. /// "return false;" to cancel the event. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ upload: function (e, data) { } }); /// Bind to the event by type: wijuploadupload /// $("#selector").bind("wijuploadupload", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> /// <param name="data" type="Object"> /// An object that contains the input file. /// </param> upload: null, /// <summary> /// Fires when click the uploadAll button. This event can be cancelled. /// "return false;" to cancel the event. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ totalUpload: function (e, data) { } }); /// Bind to the event by type: wijuploadtotalupload /// $("#selector").bind("wijuploadtotalupload", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> totalUpload: null, /// <summary> /// Fires when file uploading. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ progress: function (e, data) { } }); /// Bind to the event by type: wijuploadprogress /// $("#selector").bind("wijuploadprogress", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> /// <param name="data" type="Object"> /// An object that contains the file info,loadedSize and totalSize /// </param> progress: null, /// <summary> /// Fires when click the uploadAll button adn file uploading. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ totalProgress: function (e, data) { } }); /// Bind to the event by type: wijuploadtotalprogress /// $("#selector").bind("wijuploadtotalprogress", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> /// <param name="data" type="Object"> /// An object that contains the loadedSize and totalSize /// </param> totalProgress: null, /// <summary> /// Fires when file upload is complete. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ complete: function (e, data) { } }); /// Bind to the event by type: wijuploadcomplete /// $("#selector").bind("wijuploadcomplete", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> /// <param name="data" type="Object"> /// An object that contains the file info. /// </param> complete: null, /// <summary> /// Fires when click the uploadAll button and file upload is complete. /// Default: null. /// Type: Function. /// Code example: /// Supply a function as an option. /// $(".selector").wijupload({ totalComplete: function (e, data) { } }); /// Bind to the event by type: wijuploadtotalcomplete /// $("#selector").bind("wijuploadtotalcomplete", function(e, data) { } ); /// </summary> /// <param name="e" type="eventObj"> /// jQuery.Event object. /// </param> totalComplete: null, /// <summary> /// Specifies the maxmized files number that can be uploaded. /// Default: 0. /// Type: Number. /// Code Example: /// $(".selector").wijupload("maximunFiles", 5) /// </summary> maximumFiles: 0, /// <summary> /// Determines whether support multiple selection. /// Default: false. /// Type: Boolean. /// Code Example: /// $(".selector").wijupload("multiple", true) /// </summary> multiple: false, /// <summary> /// Specifies the accept attribute of upload. /// Default: "". /// Type: String. /// Code Example: /// $(".selector").wijupload("accept", "image/*") /// </summary> accept: "", localization: {} }, _create: function () { var self = this, o = self.options, id = new Date().getTime(), useXhr = self.supportXhr(); // enable touch support: if (window.wijmoApplyWijTouchUtilEvents) { $ = window.wijmoApplyWijTouchUtilEvents($); } self.filesLen = 0; self.totalUploadFiles = 0; self.useXhr = useXhr; self.id = id; self._createContainers(); self._createUploadButton(); self._createFileInput(); self._bindEvents(); //Add for support disabled option at 2011/7/8 if (o.disabled) { self.disable(); } //end for disabled option if (self.element.is(":hidden") && self.element.wijAddVisibilityObserver) { self.element.wijAddVisibilityObserver(function () { self._applyInputPosition(); if (self.element.wijRemoveVisibilityObserver) { self.element.wijRemoveVisibilityObserver(); } }, "wijupload"); } }, _setOption: function (key, value) { var self = this; $.Widget.prototype._setOption.apply(this, arguments); //Add for support disabled option at 2011/7/8 if (key === "disabled") { self._handleDisabledOption(value, self.upload); } //end for disabled option else if (key === "accept") { if (self.input) { self.input.attr("accept", value); } } }, _handleDisabledOption: function (disabled, ele) { var self = this; if (disabled) { if (!self.disabledDiv) { self.disabledDiv = self._createDisabledDiv(ele); } self.disabledDiv.appendTo("body"); } else { if (self.disabledDiv) { self.disabledDiv.remove(); self.disabledDiv = null; } } }, _createDisabledDiv: function (outerEle) { var self = this, //Change your outerelement here ele = outerEle ? outerEle : self.upload, eleOffset = ele.offset(), disabledWidth = ele.outerWidth(), disabledHeight = ele.outerHeight(); return $("<div></div>") .addClass("ui-disabled") .css({ "z-index": "99999", position: "absolute", width: disabledWidth, height: disabledHeight, left: eleOffset.left, top: eleOffset.top }); }, destroy: function () { var self = this; self.upload.removeClass(uploadClass); self.upload.undelegate(self.widgetName) .undelegate("." + self.widgetName); self.input.remove(); self.addBtn.remove(); self.filesList.remove(); self.commandRow.remove(); if (self.isCreateByInput === true) { self.element.css({ display: "" }).unwrap(); } if (self.uploaders) { $.each(self.uploaders, function (idx, uploader) { if (uploader.destroy) { uploader.destroy(true); } uploader = null; }); self.uploaders = null; } //Add for support disabled option at 2011/7/8 if (self.disabledDiv) { self.disabledDiv.remove(); self.disabledDiv = null; } //end for disabled option }, widget: function () { return this.upload; }, supportXhr: function () { var useXhr = false; if (typeof (new XMLHttpRequest().upload) === "undefined") { useXhr = false; } else { useXhr = true; } return useXhr; }, _createContainers: function () { var self = this, filesList, commandRow, el = self.element; if (el.is(":input") && el.attr("type") === "file") { self.isCreateByInput = true; self.maxDisplay = (el.attr("multiple") || self.options.multiple) ? 0 : 1; self.upload = el.css({ display: "none" }).wrap("<div>") .parent(); } else if (self.element.is("div")) { self.upload = el; } else { throw 'The initial markup must be "DIV", "INPUT[type=file]"'; } self.upload.addClass(uploadClass); filesList = $("<ul>").addClass(uploadFilesListClass).appendTo(self.upload); commandRow = $("<div>").addClass(uploadCommandRowClass).appendTo(self.upload); self.filesList = filesList; commandRow.hide(); self.commandRow = commandRow; self._createCommandRow(commandRow); }, _createCommandRow: function (commandRow) { var self = this, uploadAllBtn = $("<a>").attr("href", "#") .text("uploadAll") .addClass(uploadUploadAllClass) .button({ icons: { primary: "ui-icon-circle-arrow-n" }, label: self._getLocalization("uploadAll", "Upload All") }), cancelAllBtn = $("<a>").attr("href", "#") .text("cancelAll") .addClass(uploadCancelAllClass) .button({ icons: { primary: "ui-icon-cancel" }, label: self._getLocalization("cancelAll", "Cancel All") }); commandRow.append(uploadAllBtn).append(cancelAllBtn); }, _getLocalization: function (key, defaultVal) { var lo = this.options.localization; return (lo && lo[key]) || defaultVal; }, _createUploadButton: function () { var self = this, addBtn = $("<a>").attr("href", "#").button({ label: self._getLocalization("uploadFiles", "Upload files") }); addBtn.mousemove(function (e) { var disabled = addBtn.data("button").options.disabled; if (self.input) { var pageX = e.pageX, pageY = e.pageY; if (!disabled) { self.input.offset({ left: pageX + 10 - self.input.width(), top: pageY + 10 - self.input.height() }); } } }); self.addBtn = addBtn; self.upload.prepend(addBtn); }, _applyInputPosition: function () { var self = this, addBtn = self.addBtn, addBtnOffset = addBtn.offset(), fileInput = self.cuurentInput; fileInput.offset({ left: addBtnOffset.left + addBtn.width() - fileInput.width(), top: addBtnOffset.top }).height(addBtn.height()); }, _createFileInput: function () { var self = this, addBtn = self.addBtn, addBtnOffset = addBtn.offset(), accept = self.element.attr("accept") || self.options.accept, id = "wijUpload_" + self.id + "_input" + self.filesLen, fileInput = $("<input>").attr("type", "file").prependTo(self.upload), maxFiles = self.options.maximumFiles || self.maxDisplay; if (maxFiles !== 1 && self.maxDisplay === 0) { fileInput.attr("multiple", "multiple"); } if (accept) { fileInput.attr("accept", accept); } self.cuurentInput = fileInput; self.filesLen++; fileInput.attr("id", id) .attr("name", id) .css("position", "absolute") .offset({ left: addBtnOffset.left + addBtn.width() - fileInput.width(), top: addBtnOffset.top }) .css("z-index", "9999") .css("opacity", 0) .height(addBtn.height()) .css("cursor", "pointer"); self.input = fileInput; fileInput.bind("change", function (e) { var fileRow, uploadBtn; if (self._trigger("change", e, $(this)) === false) { return false; } self._createFileInput(); fileRow = self._createFileRow($(this)); self._setAddBtnState(); if (self.options.autoSubmit) { uploadBtn = $(isUploadUpload, fileRow); if (uploadBtn) { uploadBtn.click(); } } fileInput.unbind("change"); }); self.uploadAll = false; }, _setAddBtnState: function () { var self = this, maxFiles = self.options.maximumFiles || self.maxDisplay, addBtn = self.addBtn, files; if (!maxFiles) { return; } if (!addBtn) { return; } if (!self.maskDiv) { self.maskDiv = $("<div></div>") .css("position", "absolute") //.css("background-color", "red") .css("z-index", "9999") .width(addBtn.outerWidth()) .height(addBtn.outerHeight()) .appendTo(self.upload) .offset(addBtn.offset()); } files = $("li", self.filesList); if (files.length >= maxFiles) { addBtn.button({ disabled: true }); self.maskDiv.show(); if (self.input) { self.input.css("left", "-1000px"); } } else { addBtn.button({ disabled: false }); self.maskDiv.hide(); } }, _createFileRow: function (uploadFile) { var self = this, fileRow = $("<li>"), //fileName = uploadFile.val(), file, progress, fileRows, buttonContainer = $("<span>").addClass(uploadButtonContainer), uploadBtn = $("<a>").attr("href", "#") .text("upload") .addClass(uploadUploadClass) .button({ text: false, icons: { primary: "ui-icon-circle-arrow-n" }, label: self._getLocalization("upload", "upload") }), cancelBtn = $("<a>").attr("href", "#") .text("cancel") .addClass(uploadCancelClass) .button({ text: false, icons: { primary: "ui-icon-cancel" }, label: self._getLocalization("cancel", "cancel") }); fileRow.addClass(uploadFileRowClass) .addClass(uiContentClass) .addClass(uiCornerClass); fileRow.append(uploadFile); uploadFile.hide(); file = $("<span>" + _getFileNameByInput(uploadFile[0]) + "</span>") .addClass(uploadFileClass) .addClass(uiHighlight) .addClass(uiCornerClass); fileRow.append(file); fileRow.append(buttonContainer); progress = $("<span />").addClass(uploadProgressClass); buttonContainer.append(progress); buttonContainer.append(uploadBtn).append(cancelBtn); fileRow.appendTo(self.filesList); fileRows = $(isUploadFileRow, self.upload); if (fileRows.length) { self.commandRow.show(); self._createUploader(fileRow); self._resetProgressAll(); } return fileRow; }, _createUploader: function (fileRow) { var self = this, inputFile = $("input", fileRow), action = self.options.action, uploader; if (self.useXhr) { uploader = wijuploadXhr(self.id, fileRow, action); } else { uploader = wijuploadFrm(self.id, fileRow, action); } uploader.onCancel = function () { var t = this; self._trigger("cancel", null, t.inputFile); self.totalUploadFiles--; if (self.totalUploadFiles === 0 && self.uploadAll) { self._trigger("totalComplete"); } }; if (self._wijUpload()) { uploader.onProgress = function (obj) { var progressSpan = $("." + uploadProgressClass, this.fileRow), data = { sender: obj.fileName, loaded: obj.loaded, total: obj.total }, id = this.inputFile.attr("id"); if (obj.supportProgress) { progressSpan.html(Math.round(1000 * obj.loaded / obj.total) / 10 + "%"); if (obj.fileNameList) { data.fileNameList = obj.fileNameList; } self._trigger("progress", null, data); self._progressTotal(id, obj.loaded); } else { progressSpan.addClass(uploadLoadingClass); } }; uploader.onComplete = function (obj) { var t = this, id = t.inputFile.attr("id"), uploader = self.uploaders[id], //fileName = _getFileName(t.inputFile.val()), fileSize = _getFileSize(t.inputFile[0]), progressSpan = $("." + uploadProgressClass, t.fileRow); //xhr = obj.e.currentTarget; // if (xhr.status != 200) { // throw xhr; // } self._trigger("complete", obj.e, t.inputFile); progressSpan.removeClass(uploadLoadingClass); progressSpan.html("100%"); self._removeFileRow(t.fileRow, uploader, true); self._progressTotal(id, fileSize); self.totalUploadFiles--; if (self.totalUploadFiles === 0 && self.uploadAll) { self._trigger("totalComplete", obj.e, obj); } }; } if (typeof (self.uploaders) === "undefined") { self.uploaders = {}; } self.uploaders[inputFile.attr("id")] = uploader; }, _progressTotal: function (fileName, loadedSize) { var self = this, progressAll = self.progressAll, loaded, total; if (!self.uploadAll) { return; } if (progressAll && progressAll.loadedSize) { progressAll.loadedSize[fileName] = loadedSize; loaded = self._getLoadedSize(progressAll.loadedSize); total = progressAll.totalSize; } self._trigger("totalProgress", null, { loaded: loaded, total: total }); }, _getLoadedSize: function (loadedSize) { var loaded = 0; $.each(loadedSize, function (key, value) { loaded += value; }); return loaded; }, _getTotalSize: function () { var self = this, total = 0; if (self.uploaders) { $.each(self.uploaders, function (key, uploader) { total += _getFileSize(uploader.inputFile[0]); }); } return total; }, _resetProgressAll: function () { this.progressAll = { totalSize: 0, loadedSize: {} }; }, _wijUpload: function () { //return this.widgetName === "wijupload"; return true; }, _wijcancel: function (fileInput) { }, _upload: function (fileRow) { }, _bindEvents: function () { var self = this, progressAll = self.progressAll; self.upload.delegate(isUploadCancel, "click." + self.widgetName, function (e) { var cancelBtn = $(this), fileRow = cancelBtn.parents(isUploadFileRow), fileInput = $("input", fileRow[0]), uploader = self.uploaders[fileInput.attr("id")]; /* if (!self._wijUpload()) { self._wijcancel(fileInput); if (uploader) { uploader.cancel(); } } */ self._wijcancel(fileInput); if (self._wijUpload() && uploader) { uploader.cancel(); } if (progressAll) { progressAll.totalSize -= _getFileSize(fileInput[0]); if (progressAll.loadedSize[fileInput.val()]) { delete progressAll.loadedSize[fileInput.val()]; } } self._removeFileRow(fileRow, uploader, false); }); self.upload.delegate(isUploadUpload, "click." + self.widgetName, function (e) { var uploadBtn = $(this), fileRow = uploadBtn.parents(isUploadFileRow), fileInput = $("input", fileRow[0]), uploader = self.uploaders[fileInput.attr("id")]; if (self._trigger("upload", e, fileInput) === false) { return false; } if (self.options.autoSubmit) { //when autoSubmit set to "true", will trigger "totalUpload" immediately. //self.uploadAll = true; //fixed bug 23877 uploader.autoSubmit = true; if (self._trigger("totalUpload", e, null) === false) { return false; } } self.totalUploadFiles++; self._upload(fileRow); if (uploader && self._wijUpload()) { uploader.upload(); } }); self.upload.delegate("." + uploadUploadAllClass, "click." + self.widgetName, function (e) { self.uploadAll = true; if (!self.progressAll) { self._resetProgressAll(); } if (self._trigger("totalUpload", e, null) === false) { return false; } self.progressAll.totalSize = self._getTotalSize(); self._wijuploadAll($(isUploadUpload, self.filesList[0])); if (self._wijUpload()) { $(isUploadUpload, self.filesList[0]) .each(function (idx, uploadBtn) { $(uploadBtn).click(); }); } }); self.upload.delegate("." + uploadCancelAllClass, "click." + self.widgetName, function (e) { self._resetProgressAll(); $(isUploadCancel, self.filesList[0]).each(function (idx, cancelBtn) { $(cancelBtn).click(); }); }); }, _wijuploadAll: function (uploadBtns) { }, _wijFileRowRemoved: function (fileRow, fileInput, isComplete) { this._setAddBtnState(); }, _removeFileRow: function (fileRow, uploader, isComplete) { var self = this, inputFileId, files; if (uploader) { inputFileId = uploader.inputFile.attr("id"); } fileRow.fadeOut(1500, function () { fileRow.remove(); self._wijFileRowRemoved(fileRow, uploader.inputFile, isComplete); if (self.uploaders[inputFileId]) { delete self.uploaders[inputFileId]; } files = $(isUploadFileRow, self.upload); if (files.length) { self.commandRow.show(); if (uploader && uploader.destroy) { uploader.destroy(); } } else { self.commandRow.hide(); self._resetProgressAll(); if (uploader && uploader.destroy) { uploader.destroy(true); } } }); }, // Used by C1Upload. _getFileName: function (fileName) { return _getFileName(fileName); }, _getFileNameByInput: function (fileInput) { return _getFileNameByInput(fileInput); }, _getFileSize: function (fileInput) { return _getFileSize(fileInput); } }); } (jQuery));
export const barChart = {"viewBox":"0 0 2048 1792","children":[{"name":"path","attribs":{"d":"M640 896v512h-256v-512h256zM1024 384v1024h-256v-1024h256zM2048 1536v128h-2048v-1536h128v1408h1920zM1408 640v768h-256v-768h256zM1792 256v1152h-256v-1152h256z"}}]};
var clientSockets = function (){ socket.on('newPlayer',function (data){ if(data.name !== name) actors[data.name] = new Actor(data.x,data.y,data.name,data.color,data.rune); }); socket.on('yourTurn',function(data){ document.getElementById("WhoseTurn").innerHTML = "Current Turn: "+data.whoseTurn; currentTurn = data.whoseTurn; if(data.whoseTurn === name) actors[name].act(); }); socket.on('initData',function (data){ map = data.map; actors = data.actors; freeCells = data.freeCells; drawMap(); for (actor in data.actors){ actors[actor] = new Actor(data.actors[actor].x,data.actors[actor].y,data.actors[actor].name,data.actors[actor].color,data.actors[actor].rune); }; var index = Math.floor(ROT.RNG.getUniform() * freeCells.length); var key = freeCells.splice(index, 1)[0]; var parts = key.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); actors[name] = new Player2(x,y,color,name); actors[name].sight(); socket.emit('newPlayer',actors[name]); window.addEventListener("keydown", actors[name]); }); socket.on('updateData',function (data){ console.log('updateData'); map = data.map; actors = data.actors; freeCells = data.freeCells; drawMap(); for (actor in data.actors){ actors[actor] = new Actor(data.actors[actor].x,data.actors[actor].y,data.actors[actor].name,data.actors[actor].color,data.actors[actor].rune); }; var index = Math.floor(ROT.RNG.getUniform() * freeCells.length); var key = freeCells.splice(index, 1)[0]; var parts = key.split(","); var x = parseInt(parts[0]); var y = parseInt(parts[1]); actors[name] = new Player2(x,y,color,name); socket.emit('newPlayer',actors[name]); window.addEventListener("keydown", actors[name]); }); }; var Player2 = function(xCoord, yCoord, color, name) { this.x = xCoord; this.y = yCoord; this.rune = "@"; this.color = color; this.name = name; this.tilesSeen = {}; this.draw = function(){ display.draw(this.x,this.y,this.rune,this.color); }; this.draw(); this.handleEvent = function(e){ var keyMap = {}; keyMap[38] = 0; keyMap[33] = 1; keyMap[39] = 2; keyMap[34] = 3; keyMap[40] = 4; keyMap[35] = 5; keyMap[37] = 6; keyMap[36] = 7; var code = e.keyCode; if (!(code in keyMap)) { return; } var diff = ROT.DIRS[8][keyMap[code]]; var newX = this.x + diff[0]; var newY = this.y + diff[1]; var newKey = newX + "," + newY; if (!(newKey in map)) { return; } // cannot move in this direction else if(map[newKey] == "#"){return;} //Cannot move through walls (#s) socket.emit('somethingMoved',{what: name, newX : newX, newY : newY}); this.sight(); }; this.sight = function(){ this.tilesSeen = {}; var lightPasses = function(x,y){ var key = x+","+y; if (key in map) { if(map[key] !== "#"){ return true; } return false; } return false; }; var fov = new ROT.FOV.RecursiveShadowcasting(lightPasses); display.clear(); fov.compute(this.x, this.y, 50, function(x, y, r, visibility) { var ch = (r ? map[x+","+y] : "@"); var color = (map[x+","+y] ? "#aa0": "#660"); var alreadyDrew = false; for(dude in actors){ if(actors[dude].x === x && actors[dude].y === y){ actors[dude].draw(); alreadyDrew = true; } }; if(!alreadyDrew) display.draw(x, y, ch); actors[name].tilesSeen[x+","+y] = true; }); }; this.update = function(newX,newY){ this.x = newX; this.y = newY; this.draw(); }; };
/** * Manapaho (https://github.com/manapaho/) * * Copyright © 2015 Manapaho. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; /** * Import Mutations. */ /** * Import Components. */ /** * Import UX components. */ import Button from 'react-toolbox/lib/button'; import ToolboxApp from 'react-toolbox/lib/app'; import AppBar from 'react-toolbox/lib/app_bar'; import Navigation from 'react-toolbox/lib/navigation'; import Link from 'react-toolbox/lib/link'; import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap'; import FontIcon from 'react-toolbox/lib/font_icon'; /** * Import styles. */ import style from './style'; /** * Import Internationalization. */ import {IntlProvider, FormattedMessage} from 'react-intl'; /** * The component. */ class App extends React.Component { // Expected properties. static propTypes = { viewer: React.PropTypes.object.isRequired, children: React.PropTypes.node.isRequired }; // Expected context properties. static contextTypes = { setLocale: React.PropTypes.func }; // Initialize the component. constructor(props) { super(props); } // Invoked once, both on the client and server, immediately before the initial rendering occurs. // If you call setState within this method, // render() will see the updated state and will be executed only once despite the state change. componentWillMount() { // Update the application language if necessary. this.context.setLocale(this.props.viewer.language); } // Invoked when a component is receiving new props. This method is not called for the initial render. // Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). // The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render. componentWillReceiveProps(nextProps, nextContext) { if (nextProps.viewer.language !== this.props.viewer.language) { // Update the application language if necessary. this.context.setLocale(nextProps.viewer.language); } } // User wants to change his language setting. handleLanguageChange = (eventKey) => { // We commit the update directly to the database. // This will cause the viewer.language property to change // which will then result in a call to setLocale. Relay.Store.commitUpdate(new UpdatePersonMutation({ person: this.props.viewer, language: eventKey }), { onFailure: (err) => { // TODO: Deal with it! console.log(err); }, onSuccess: (result) => { // TODO: Maybe nothing todo here? } }); }; // Render the component. render() { // Get the properties. const {viewer, children} = this.props; // let className = style.root; // Return the component UI. return ( <ToolboxApp className={className}> <AppBar className={style.appbar}> <FontIcon value='insert_chart' /> <a href="/home">Reporting</a> <Navigation /> </AppBar> <Navigation type='vertical' className={style.navigation}> <IndexLinkContainer to={`/`}> <Link label='Home' icon='home'/> </IndexLinkContainer> <IndexLinkContainer to={`/users`}> <Link label='Data' icon='description'/> </IndexLinkContainer> <IndexLinkContainer to={`/charts`}> <Link label='Charts' icon='insert_chart'/> </IndexLinkContainer> <IndexLinkContainer to={`/users`}> <Link label='Reports' icon='format_shapes'/> </IndexLinkContainer> </Navigation> <div className={style.features}> {children} </div> </ToolboxApp> ); } } /** * The data container. */ export default Relay.createContainer(App, { fragments: { viewer: () => Relay.QL` fragment on User { language }` } });
'use strict'; require('./lib/mock-env'); const expect = require('chai').expect; const request = require('superagent'); const mongoose = require('mongoose'); const Promise = require('bluebird'); mongoose.Promise = Promise; const server = require('../server.js'); const User = require('../src/model/user.js'); const serverToggle = require('./lib/server-toggle.js'); const url = `http://localhost:${process.env.PORT}`; const mockUser = { password: '123456', email: 'test-user@test.com', }; describe('Auth Routes', function() { before( done => { serverToggle.serverOn(server, done); }); after( done => { serverToggle.serverOff(server, done); }); describe('POST: /api/signup', function() { after(done => { User.remove({}) .then(() => done()) .catch(err => done(err)); }); describe('with a valid body', function() { it('should return a token', done => { request.post(`${url}/api/signup`) .send(mockUser) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); expect(res.text).to.be.a('string'); done(); }); }); }); }); describe('GET: /api/signin', function() { describe('with a valid body', function() { before(done => { let user = new User(mockUser); user.generatePasswordHash(mockUser.password) .then(user => user.save()) .then(user => { this.tempUser = user; done(); }) .catch(done); }); after(done => { User.remove({}) .then(() => done()) .catch(done); }); it('should return a token', done => { request.get(`${url}/api/signin`) .auth(mockUser.email, mockUser.password) .end((err, res) => { if (err) return done(err); expect(res.status).to.equal(200); done(); }); }); }); }); });
$(function(){ var $statusMsg = $("#status-msg"); /* Bind Events */ KDBCONNECT.bind("event","ws_event",function(data){ // Data is default message that is set in monitor.js $statusMsg.html(data); }); KDBCONNECT.bind("event","error",function(data){ $statusMsg.html("Error - " + data); }); /* Bind data - Data type "start" will execute the callback function */ KDBCONNECT.bind("data","start",function(data){ // Check that data is not empty if(data.hbtable.length !== 0){ $("#heartbeat-table").html(MONITOR.jsonTable(data.hbtable)); } // Write HTML table to div element with id heartbeat-table if(data.lmtable.length !== 0){ $("#logmsg-table").html(MONITOR.jsonTable(data.lmtable)); } // Write HTML table to div element with id logmsg-table if(data.lmchart.length !== 0){ MONITOR.barChart(data.lmchart,"logmsg-chart","Error Count","myTab"); } // Log message error chart }); KDBCONNECT.bind("data","upd",function(data){ if(data.tabledata.length===0) return; if(data.tablename === "heartbeat"){ $("#heartbeat-table").html(MONITOR.jsonTable(data.tabledata)); } if(data.tablename === "logmsg"){ $("#logmsg-table").html(MONITOR.jsonTable(data.tabledata)); } if(data.tablename === "lmchart"){ MONITOR.barChart(data.tabledata,"logmsg-chart","Error Count","myTab"); } }); KDBCONNECT.bind("data","bucketlmchart",function(data){ if(data[0].length>0){ MONITOR.barChart(data[0],"logmsg-chart","Error Count","myTab");} }); /* UI - Highlighting highlightRow(tableId,colNumber,conditionArray,cssClass); */ MONITOR.highlightRow('#heartbeat-table',5,["=","true"],"warning-row"); MONITOR.highlightRow('#heartbeat-table',6,["=","true"],"error-row"); MONITOR.highlightColCell('#logmsg-table','logmsg-error',4); /* Bucket chart input - Grab value from input and send function argument */ MONITOR.bucketChart('#bucket-time',"bucketlmchart"); /* Extra UI configurations - Logmsg tabs */ $('#myTab a').click(function (e) { e.preventDefault(); $(this).tab('show'); $(window).scrollTop($(this).offset().top); }); $('#bucket-time').click(function (e) { e.preventDefault(); $(window).scrollTop($(this).offset().top); }); });
/* http://keith-wood.name/calendars.html Maltese localisation for Gregorian/Julian calendars for jQuery. Written by Chritian Sciberras (uuf6429@gmail.com). */ (function($) { $.calendars.calendars.gregorian.prototype.regionalOptions['mt'] = { name: 'Gregorian', epochs: ['BCE', 'CE'], monthNames: ['Jannar','Frar','Marzu','April','Mejju','Ġunju', 'Lulju','Awissu','Settembru','Ottubru','Novembru','Diċembru'], monthNamesShort: ['Jan', 'Fra', 'Mar', 'Apr', 'Mej', 'Ġun', 'Lul', 'Awi', 'Set', 'Ott', 'Nov', 'Diċ'], dayNames: ['Il-Ħadd', 'It-Tnejn', 'It-Tlieta', 'L-Erbgħa', 'Il-Ħamis', 'Il-Ġimgħa', 'Is-Sibt'], dayNamesShort: ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'], dayNamesMin: ['Ħ','T','T','E','Ħ','Ġ','S'], digits: null, dateFormat: 'dd/mm/yyyy', firstDay: 1, isRTL: false }; if ($.calendars.calendars.julian) { $.calendars.calendars.julian.prototype.regionalOptions['mt'] = $.calendars.calendars.gregorian.prototype.regionalOptions['mt']; } })(jQuery);
import React from 'react'; import ValidateInput from './ValidateInput'; class Form extends React.Component { constructor(props) { super(props); this.state = { title: { value: '', error: '' } } } updateTitle(e) { this.setState({ title: { value: e.target.value, error: '' } }) } validateTitle(e) { const value = e.target.value; if (value.length > 5) { this.setState({ title: { value, error: 'Input has exceeded the maximum length' } }) } else { this.updateTitle(e); } } submitForm() { console.log('Submitting form ...'); } render () { return ( <form> <ValidateInput label='Title' placeHolder='Enter title' value={this.state.title.value} update={this.updateTitle.bind(this)} validate={this.validateTitle.bind(this)} errorMsg={this.state.title.error} /> <button type="submit" onClick={this.submitForm.bind(this)}>Submit</button> </form> ) } } export default Form;
import React, { Component } from 'react'; import AuthService from './AuthService'; export default function withAuth(AuthComponent) { const Auth = new AuthService(); return class AuthWrapped extends Component { constructor() { super(); this.state = { user: null }; } componentWillMount() { try { if (Auth.tokenExist && !Auth.loggedIn()) { Auth.refreshToken() .then(res => { try { const profile = Auth.getProfile(); this.setState({ user: profile }); } catch (err) { Auth.logout(); this.props.history.replace('/login'); } }) .catch(error => { Auth.logout(); this.props.history.replace('/login'); }); } else { if (!Auth.loggedIn()) { this.props.history.replace('/login'); } else { try { const profile = Auth.getProfile(); this.setState({ user: profile }); } catch (err) { Auth.logout(); this.props.history.replace('/login'); } } } } catch (err) { console.log('Erorr 2'); Auth.logout(); this.props.history.replace('/login'); } } render() { if (this.state.user) { return <AuthComponent {...this.props} />; } else { return null; } } }; }