code
stringlengths
2
1.05M
import { createStore, createReducer } from 'shasta' import localReducers from 'reducers/.lookup' import plugins from '../plugins' import initialState from './initialState' export default createStore({ plugins: plugins, reducers: [ createReducer(localReducers) ], initialState: initialState })
import ArrayUtilities from "../../common/js/ArrayUtilities.js"; import InputValidator from "../../common/js/InputValidator.js"; import CardResolver from "../../artifact/js/CardResolver.js"; import CardType from "../../artifact/js/CardType.js"; import EnemyCard from "../../artifact/js/EnemyCard.js"; import GameMode from "../../artifact/js/GameMode.js"; import LocationCard from "../../artifact/js/LocationCard.js"; import ObjectiveCard from "../../artifact/js/ObjectiveCard.js"; import QuestCard from "../../artifact/js/QuestCard.js"; import Scenario from "../../artifact/js/Scenario.js"; import TreacheryCard from "../../artifact/js/TreacheryCard.js"; import CardInstance from "./CardInstance.js"; var DeckBuilders = []; var PassageThroughMirkwoodDeckBuilder = new ScenarioDeckBuilder(Scenario.PASSAGE_THROUGH_MIRKWOOD, "Passage Through Mirkwood (Core #1)", 2011, "Passage Through Mirkwood", function(store) { var questKeys = QuestCard.keysByScenario(Scenario.PASSAGE_THROUGH_MIRKWOOD); // Choose one of the 3B paths randomly. var removeMe = ArrayUtilities.randomElement([QuestCard.PTM3B1_BEORNS_PATH, QuestCard.PTM3B2_DONT_LEAVE_THE_PATH]); questKeys = ArrayUtilities.remove(questKeys, removeMe); return questKeys.map(function(cardKey) { var card = QuestCard.properties[cardKey]; return new CardInstance(store, card); }); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.PASSAGE_THROUGH_MIRKWOOD); }); DeckBuilders.push(PassageThroughMirkwoodDeckBuilder); var JourneyAlongTheAnduinDeckBuilder = new ScenarioDeckBuilder(Scenario.JOURNEY_ALONG_THE_ANDUIN, "Journey Along the Anduin (Core #2)", 2011, "Journey Along the Anduin", function(store) { return questBuildFunction(store, Scenario.JOURNEY_ALONG_THE_ANDUIN); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.JOURNEY_ALONG_THE_ANDUIN); }); DeckBuilders.push(JourneyAlongTheAnduinDeckBuilder); var EscapeFromDolGuldurDeckBuilder = new ScenarioDeckBuilder(Scenario.ESCAPE_FROM_DOL_GULDUR, "Escape from Dol Guldur (Core #3)", 2011, "Escape from Dol Guldur", function(store) { return questBuildFunction(store, Scenario.ESCAPE_FROM_DOL_GULDUR); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.ESCAPE_FROM_DOL_GULDUR); }); DeckBuilders.push(EscapeFromDolGuldurDeckBuilder); var ReturnToMirkwoodDeckBuilder = new ScenarioDeckBuilder(Scenario.RETURN_TO_MIRKWOOD, "Return to Mirkwood (Shadows of Mirkwood #6)", 2011, "Return to Mirkwood", function(store) { return questBuildFunction(store, Scenario.RETURN_TO_MIRKWOOD); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.RETURN_TO_MIRKWOOD); }); DeckBuilders.push(ReturnToMirkwoodDeckBuilder); var TheDeadMarshesDeckBuilder = new ScenarioDeckBuilder(Scenario.THE_DEAD_MARSHES, "The Dead Marshes (Shadows of Mirkwood #5)", 2011, "The Dead Marshes", function(store) { return questBuildFunction(store, Scenario.THE_DEAD_MARSHES); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.THE_DEAD_MARSHES); }); DeckBuilders.push(TheDeadMarshesDeckBuilder); var TheHillsOfEmynMuilDeckBuilder = new ScenarioDeckBuilder(Scenario.THE_HILLS_OF_EMYN_MUIL, "The Hills of Emyn Muil (Shadows of Mirkwood #4)", 2011, "The Hills of Emyn Muil", function(store) { return questBuildFunction(store, Scenario.THE_HILLS_OF_EMYN_MUIL); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.THE_HILLS_OF_EMYN_MUIL); }); DeckBuilders.push(TheHillsOfEmynMuilDeckBuilder); var TheHuntForGollumDeckBuilder = new ScenarioDeckBuilder(Scenario.THE_HUNT_FOR_GOLLUM, "The Hunt for Gollum (Shadows of Mirkwood #1)", 2011, "The Hunt for Gollum", function(store) { return questBuildFunction(store, Scenario.THE_HUNT_FOR_GOLLUM); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.THE_HUNT_FOR_GOLLUM); }); DeckBuilders.push(TheHuntForGollumDeckBuilder); var ConflictAtTheCarrockDeckBuilder = new ScenarioDeckBuilder(Scenario.CONFLICT_AT_THE_CARROCK, "Conflict at the Carrock (Shadows of Mirkwood #2)", 2011, "Conflict at the Carrock", function(store) { return questBuildFunction(store, Scenario.CONFLICT_AT_THE_CARROCK); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.CONFLICT_AT_THE_CARROCK); }); DeckBuilders.push(ConflictAtTheCarrockDeckBuilder); var AJourneyToRhosgobelDeckBuilder = new ScenarioDeckBuilder(Scenario.A_JOURNEY_TO_RHOSGOBEL, "A Journey to Rhosgobel (Shadows of Mirkwood #3)", 2011, "A Journey to Rhosgobel", function(store) { return questBuildFunction(store, Scenario.A_JOURNEY_TO_RHOSGOBEL); }, function(store, gameModeKey) { return encounterBuildFunction(store, gameModeKey, Scenario.A_JOURNEY_TO_RHOSGOBEL); }); DeckBuilders.push(AJourneyToRhosgobelDeckBuilder); function ScenarioDeckBuilder(scenarioKey, name, year, description, questBuildFunction, encounterBuildFunction) { InputValidator.validateIsString("scenarioKey", scenarioKey); InputValidator.validateIsString("name", name); InputValidator.validateIsNumber("year", year); InputValidator.validateIsString("description", description); InputValidator.validateIsFunction("questBuildFunction", questBuildFunction); InputValidator.validateIsFunction("encounterBuildFunction", encounterBuildFunction); this.scenarioKey = function() { return scenarioKey; }; this.name = function() { return name; }; this.year = function() { return year; }; this.description = function() { return description; }; this.buildDeck = function(store, gameModeKeyIn) { InputValidator.validateNotNull("store", store); // gameModeKeyIn optional. default: GameMode.STANDARD var gameModeKey = (gameModeKeyIn !== undefined ? gameModeKeyIn : GameMode.STANDARD); var questInstances = questBuildFunction(store); var encounterInstances = encounterBuildFunction(store, gameModeKey); return ( { scenarioKey: scenarioKey, gameModeKey: gameModeKey, questInstances: questInstances, encounterInstances: encounterInstances }); }; } ScenarioDeckBuilder.findByScenario = function(scenarioKey) { InputValidator.validateIsString("scenarioKey", scenarioKey); var answer; var deckBuilders = DeckBuilders; for (var i = 0; i < deckBuilders.length; i++) { var deckBuilder = deckBuilders[i]; if (deckBuilder.scenarioKey() === scenarioKey) { answer = deckBuilder; break; } } return answer; }; function createCards(store, cardTypeKey, cardKey, gameModeKey) { InputValidator.validateNotNull("store", store); InputValidator.validateNotNull("cardTypeKey", cardTypeKey); InputValidator.validateNotNull("cardKey", cardKey); InputValidator.validateNotNull("gameModeKey", gameModeKey); var card = CardResolver.get(cardTypeKey, cardKey); var gameModeMap = card.gameModeMap; var count = determineCount(gameModeMap, gameModeKey); var answer = []; for (var i = 0; i < count; i++) { answer.push(new CardInstance(store, card)); } return answer; } function determineCount(gameModeMap, gameModeKey) { InputValidator.validateNotNull("gameModeMap", gameModeMap); InputValidator.validateNotNull("gameModeKey", gameModeKey); var count = gameModeMap[GameMode.EASY]; if (gameModeKey === GameMode.STANDARD || gameModeKey === GameMode.NIGHTMARE) { count += gameModeMap[GameMode.STANDARD]; } if (gameModeKey === GameMode.NIGHTMARE) { count += gameModeMap[GameMode.NIGHTMARE]; } return count; } function encounterBuildFunction(store, gameModeKey, scenarioKey) { InputValidator.validateNotNull("store", store); InputValidator.validateNotNull("gameModeKey", gameModeKey); InputValidator.validateNotNull("scenarioKey", scenarioKey); var enemyKeys = EnemyCard.keysByScenario(scenarioKey); var enemyTokens = enemyKeys.reduce(function(accumulator, cardKey) { return accumulator.concat(createCards(store, CardType.ENEMY, cardKey, gameModeKey)); }, []); var locationKeys = LocationCard.keysByScenario(scenarioKey); var locationTokens = locationKeys.reduce(function(accumulator, cardKey) { return accumulator.concat(createCards(store, CardType.LOCATION, cardKey, gameModeKey)); }, []); var objectiveKeys = ObjectiveCard.keysByScenario(scenarioKey); var objectiveTokens = objectiveKeys.reduce(function(accumulator, cardKey) { return accumulator.concat(createCards(store, CardType.OBJECTIVE, cardKey, gameModeKey)); }, []); var treacheryKeys = TreacheryCard.keysByScenario(scenarioKey); var treacheryTokens = treacheryKeys.reduce(function(accumulator, cardKey) { return accumulator.concat(createCards(store, CardType.TREACHERY, cardKey, gameModeKey)); }, []); return enemyTokens.concat(locationTokens.concat(objectiveTokens.concat(treacheryTokens))); } function questBuildFunction(store, scenarioKey) { var questKeys = QuestCard.keysByScenario(scenarioKey); return questKeys.map(function(cardKey) { var card = QuestCard.properties[cardKey]; return new CardInstance(store, card); }); } export default ( { PassageThroughMirkwoodDeckBuilder: PassageThroughMirkwoodDeckBuilder, TheHuntForGollumDeckBuilder: TheHuntForGollumDeckBuilder, DeckBuilders: DeckBuilders, ScenarioDeckBuilder: ScenarioDeckBuilder, });
/* * jQuery for Comment Form Enhancements * */ jQuery(document).ready(function () { // $j=jQuery.noConflict(); // $j(document).ready(function() { $('.showDisqus').on('click', function(){ // click event of the show comments button var disqus_shortname = ''; // Enter your disqus user name // ajax request to load the disqus javascript $.ajax({ type: "GET", url: "http://" + disqus_shortname + ".disqus.com/embed.js", dataType: "script", cache: true }); $(this).fadeOut(); // remove the show comments button }); // }); /* Checks if this is a link to reply directly to a comment */ function is_replytocom() { var field = 'replytocom'; var url = window.location.href; if(url.indexOf('?' + field + '=') != -1 || url.indexOf('&' + field + '=') != -1 ) return true; else return false; } var identifier = window.location.hash; if (identifier === "#respond") { jQuery('#respond').show(); jQuery('#share-comment-button-bottom').show(); jQuery('.comment-form-reply-title').hide(); if(is_replytocom()) { // If this is a link to reply directly to a comment jQuery('#commentform-top').hide(); jQuery('#commentform-bottom').hide(); jQuery('#share-comment-button').show(); } else { // Otherwise, load the normal comment reply form jQuery('#commentform-top').show(); jQuery('#commentform-top').append(jQuery('#respond')); jQuery('#commentform-bottom').hide(); } } else { // Set the default state (forms hidden, buttons showing) jQuery('#respond').hide(); jQuery('#share-comment-button').show(); jQuery('#share-comment-button-bottom').show(); jQuery('#commentform-top').hide(); jQuery('#commentform-bottom').hide(); } /* Share Comment Button (Top) */ jQuery( document ).on('click', '#share-comment-button', function (event) { jQuery('#commentform-top').show(); jQuery('#commentform-bottom').hide(); jQuery('#cancel-comment-reply-link').click(); jQuery('#commentform-top').append(jQuery('#respond')); jQuery('#respond').show(); jQuery('#share-comment-button').toggle('hide'); jQuery('#share-comment-button-bottom').show(); jQuery('.comment-form-reply-title').hide(); jQuery('#main-reply-title').show(); jQuery('#comment').focus(); if(is_replytocom()) jQuery('#reply-title').hide(); }); /* Share Comment Button (Bottom)*/ jQuery( document ).on('click', '#share-comment-button-bottom', function (event) { jQuery('#commentform-bottom').show(); jQuery('#commentform-top').hide(); jQuery('#cancel-comment-reply-link').click(); jQuery('#commentform-bottom').append(jQuery('#respond')); jQuery('#share-comment-button-bottom').toggle('hide'); jQuery('#respond').show(); jQuery('#share-comment-button').show(); jQuery('.comment-form-reply-title').hide(); jQuery('#main-reply-title').show(); jQuery('#comment').focus(); if(is_replytocom()) jQuery('#reply-title').hide(); }); jQuery( document ).on('click', '.comment-reply-link', function (event) { jQuery('#respond').show(); jQuery('#share-comment-button').show(); jQuery('#share-comment-button-bottom').show(); jQuery('.comment-form-reply-title').show(); jQuery('#main-reply-title').hide(); jQuery('#comment').focus(); jQuery('#commentform-top').hide(); jQuery('#commentform-bottom').hide(); if(is_replytocom()) jQuery('#reply-title').hide(); }); jQuery( document ).on('click', '#cancel-comment-reply-link', function (event) { jQuery('#respond').hide(); jQuery('#share-comment-button').show(); if(is_replytocom()) jQuery('#reply-title').hide(); }); });
$(document).ready(function() { $(".remove").on("click", function() { $("#archive").submit(); }) });
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'components/breadcrumbs'; const requireDemo = require.context('docs/src/pages/components/breadcrumbs', false, /\.(js|tsx)$/); const requireRaw = require.context( '!raw-loader!../../src/pages/components/breadcrumbs', false, /\.(js|md|tsx)$/, ); export default function Page({ demos, docs }) { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
/* * The MIT License (MIT) * * Copyright (c) 2013 Adobe System Incorporated * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ define( [ 'exports', 'config', 'jquery', 'hbs!templates/ui/preloader', 'helpers/tweenHelper', 'stageReference' ], function(preloader, config, $, template, tweenHelper, stageReference) { var _container; var _wrapper; var _wrapperStyle; var _blocks; var _leftBlockStyle; var _rightBlockStyle; var _line; var _lineStyle; var _yearMarks; var _yearMarkStyles; var _yearWrappers; var _yearWrapperStyles; var _years; var _callback; var _tweenObj = {percent: 0}; var _blockStyle; var _tearItem; var _isHiding = false; var SKIP_ANIMATION = false; var YEAR = (new Date()).getFullYear(); var _transform3DStyle = config.transform3DStyle; function init(){ _initVariables(); _initEvents(); _onResize(); $('#app').append(_container); } function _initVariables(){ _container = $(template(config.data.preloader)); _wrapper = _container.find('.wrapper'); _wrapperStyle = _wrapper[0].style; _blocks = _wrapper.find('.block'); _leftBlockStyle = _blocks.filter('.left')[0].style; _rightBlockStyle = _blocks.filter('.right')[0].style; _line = _blocks.find('.line'); _lineStyle = _line[0].style; _yearMarks = _container.find('.year-mask'); _yearWrappers = _yearMarks.find('.year-wrapper'); _years = _yearWrappers.find('.year'); } function _initEvents(){ stageReference.onResize.add(_onResize); } function _onResize(){ var stageWidth = stageReference.stageWidth; var stageHeight = stageReference.stageHeight; var distance = Math.sqrt(stageWidth * stageWidth + stageHeight * stageHeight); var angle = Math.atan2(stageWidth, stageHeight); _wrapper[0].style[_transform3DStyle] = 'rotateZ(' + angle + 'rad)'; _yearWrappers[0].style[_transform3DStyle] = _yearWrappers[1].style[_transform3DStyle] = 'rotateZ(' + (-angle) + 'rad)'; if(!_isHiding) _blockStyle = 'scale3d(' + (distance / stageWidth) + ',' + (distance / stageHeight) + ',1)'; _leftBlockStyle[_transform3DStyle] = _rightBlockStyle[_transform3DStyle] = _blockStyle; } function show(onStart, onLoaded) { _callback = onLoaded; onStart(); } function onLoading(percent){ tweenHelper.add(_tweenObj).to({percent: percent}, SKIP_ANIMATION ? 0 : 1500).easing( tweenHelper.Easing.Cubic.InOut).onUpdate(_onAnimate).start(); } function _onAnimate(){ var percent = _tweenObj.percent; _yearMarks[0].style[_transform3DStyle] = 'translate3d(0,' + ((1 - percent) * -50) + 'px,0) scale3d(' + (.7 + percent * .3) + ',' + (.7 + percent * .3) + ',0)'; _yearMarks[1].style[_transform3DStyle] = 'translate3d(0,' + ((1 - percent) * 50) + 'px,0) scale3d(' + (1.3 - percent * .3) + ',' + (1.3 - percent * .3) + ',0)'; _lineStyle.height = (percent * 100) + '%'; _years.html(percent * YEAR | 0); if(percent == 1) { _lineStyle.bottom = 'auto'; _lineStyle.top = 0; tweenHelper.add({}).to({}, SKIP_ANIMATION ? 0 :500).easing( tweenHelper.Easing.Cubic.InOut).onUpdate(function(t){ _lineStyle.height = ((1 - t) * 100) + '%'; }).start(); tweenHelper.add({}).delay(SKIP_ANIMATION ? 0 : 500).to({}, SKIP_ANIMATION ? 0 :1500).easing( tweenHelper.Easing.Cubic.InOut).onUpdate(_onHiding).start(); _callback(); } } function _onHiding(t) { _years[0].style[_transform3DStyle] = 'translate3d('+ (t * 100) + 'px,0,0)'; _years[1].style[_transform3DStyle] = 'translate3d('+ (t * -100) + 'px,0,0)'; _years[0].style.opacity = _years[1].style.opacity = 1 - t; _leftBlockStyle[_transform3DStyle] = _blockStyle + 'translate3d(' + (t * - 100) + '%,0,0)'; _rightBlockStyle[_transform3DStyle] = _blockStyle + 'translate3d(' + (t * 100) + '%,0,0)'; if(t == 1) { stageReference.onResize.remove(_onResize); hide(); } } function hide(){ _container.hide(); } preloader.init = init; preloader.show = show; preloader.onLoading = onLoading; preloader.hide = hide; return preloader; } );
var searchData= [ ['fircoefs_2eh',['FirCoefs.h',['../_fir_coefs_8h.html',1,'']]], ['flash_5fdemo_2ec',['flash_demo.c',['../flash__demo_8c.html',1,'']]], ['flash_5fdemo_2edox',['flash_demo.dox',['../flash__demo_8dox.html',1,'']]], ['flash_5fdemo_2eh',['flash_demo.h',['../flash__demo_8h.html',1,'']]], ['flash_5fdemo_5fram_2ec',['flash_demo_ram.c',['../flash__demo__ram_8c.html',1,'']]], ['flash_5fswap_2ec',['flash_swap.c',['../flash__swap_8c.html',1,'']]], ['flexcan_5fuart_2ec',['flexcan_uart.c',['../flexcan__uart_8c.html',1,'']]], ['flexcan_5fuart_2edox',['flexcan_uart.dox',['../flexcan__uart_8dox.html',1,'']]], ['freemaster_2eh',['freemaster.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster_8h.html',1,'']]], ['freemaster_5fappcmd_2ec',['freemaster_appcmd.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__appcmd_8c.html',1,'']]], ['freemaster_5fbdm_2ec',['freemaster_bdm.c',['../freemaster__bdm_8c.html',1,'']]], ['freemaster_5fcan_2ec',['freemaster_can.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__can_8c.html',1,'']]], ['freemaster_5fcfg_2eh',['freemaster_cfg.h',['../freemaster__demo_2demo__usbcdc_2freemaster__cfg_8h.html',1,'']]], ['freemaster_5fcfg_2eh',['freemaster_cfg.h',['../freemaster__demo_2demo__flexcan_2freemaster__cfg_8h.html',1,'']]], ['freemaster_5fcfg_2eh',['freemaster_cfg.h',['../freemaster__demo_2demo__lpuart_2freemaster__cfg_8h.html',1,'']]], ['freemaster_5fcfg_2eh',['freemaster_cfg.h',['../freemaster__demo_2demo__uart_2freemaster__cfg_8h.html',1,'']]], ['freemaster_5fdefcfg_2eh',['freemaster_defcfg.h',['../freemaster__defcfg_8h.html',1,'']]], ['freemaster_5fdemo_2edox',['freemaster_demo.dox',['../freemaster__demo_8dox.html',1,'']]], ['freemaster_5fdemo_5fguide_5fug_2emd',['freemaster_demo_guide_ug.md',['../freemaster__demo__guide__ug_8md.html',1,'']]], ['freemaster_5fdemo_5fintroduction_5fug_2emd',['freemaster_demo_introduction_ug.md',['../freemaster__demo__introduction__ug_8md.html',1,'']]], ['freemaster_5fexample_2ec',['freemaster_example.c',['../freemaster__example_8c.html',1,'']]], ['freemaster_5fexample_2eh',['freemaster_example.h',['../freemaster__example_8h.html',1,'']]], ['freemaster_5fkxx_2ec',['freemaster_Kxx.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster___kxx_8c.html',1,'']]], ['freemaster_5fkxx_2eh',['freemaster_Kxx.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster___kxx_8h.html',1,'']]], ['freemaster_5fprivate_2eh',['freemaster_private.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster__private_8h.html',1,'']]], ['freemaster_5fprotocol_2ec',['freemaster_protocol.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__protocol_8c.html',1,'']]], ['freemaster_5fprotocol_2eh',['freemaster_protocol.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster__protocol_8h.html',1,'']]], ['freemaster_5frec_2ec',['freemaster_rec.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__rec_8c.html',1,'']]], ['freemaster_5frec_2eh',['freemaster_rec.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster__rec_8h.html',1,'']]], ['freemaster_5fscope_2ec',['freemaster_scope.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__scope_8c.html',1,'']]], ['freemaster_5fserial_2ec',['freemaster_serial.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__serial_8c.html',1,'']]], ['freemaster_5fsfio_2ec',['freemaster_sfio.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__sfio_8c.html',1,'']]], ['freemaster_5ftsa_2ec',['freemaster_tsa.c',['../freemaster__demo_2src_2driver__v1__8_2freemaster__tsa_8c.html',1,'']]], ['freemaster_5ftsa_2eh',['freemaster_tsa.h',['../freemaster__demo_2src_2driver__v1__8_2freemaster__tsa_8h.html',1,'']]], ['fs_2ec',['fs.c',['../fs_8c.html',1,'']]], ['fs_2eh',['fs.h',['../fs_8h.html',1,'']]], ['fsdata_2ec',['fsdata.c',['../fsdata_8c.html',1,'']]], ['fsdata_2eh',['fsdata.h',['../fsdata_8h.html',1,'']]], ['fsl_5fdac_5firq_2ec',['fsl_dac_irq.c',['../fsl__dac__irq_8c.html',1,'']]], ['fsl_5fgpio_5firq_2ec',['fsl_gpio_irq.c',['../fsl__gpio__irq_8c.html',1,'']]], ['ftm_5fpdb_5fadc_2edox',['ftm_pdb_adc.dox',['../ftm__pdb__adc_8dox.html',1,'']]], ['ftm_5fpdb_5fadc_5fdemo_2ec',['ftm_pdb_adc_demo.c',['../ftm__pdb__adc__demo_8c.html',1,'']]], ['ftm_5fpwm_2ec',['ftm_pwm.c',['../ftm__pwm_8c.html',1,'']]], ['ftm_5fpwm_2edox',['ftm_pwm.dox',['../ftm__pwm_8dox.html',1,'']]], ['main_2ec',['main.c',['../freemaster__demo_2demo__usbcdc_2main_8c.html',1,'']]], ['main_2ec',['main.c',['../freemaster__demo_2demo__uart_2main_8c.html',1,'']]], ['main_2ec',['main.c',['../freemaster__demo_2demo__flexcan_2main_8c.html',1,'']]], ['main_2ec',['main.c',['../freemaster__demo_2demo__lpuart_2main_8c.html',1,'']]] ];
const resolveStyles = sinon.spy(require('resolve-styles.js')); const Enhancer = require('inject!enhancer.js')({ './resolve-styles.js': resolveStyles }); import React, {Component} from 'react'; describe('Enhancer', () => { it('sets up initial state', () => { class Composed extends Component { } const Enhanced = Enhancer(Composed); const instance = new Enhanced(); expect(instance.state).to.deep.equal({_radiumStyleState: {}}); }); it('merges with existing state', () => { class Composed extends Component { constructor() { super(); this.state = {foo: 'bar'}; } render() {} } const Enhanced = Enhancer(Composed); const instance = new Enhanced(); expect(instance.state).to.deep.equal( {foo: 'bar', _radiumStyleState: {}} ); }); it('receives the given props', () => { class Composed extends Component { constructor(props) { super(props); } render() {} } const Enhanced = Enhancer(Composed); const instance = new Enhanced({foo: 'bar'}); expect(instance.props).to.deep.equal({foo: 'bar'}); }); it('calls existing render function, then resolveStyles', () => { const renderMock = sinon.spy(); class Composed extends Component { render() { renderMock(); return null; } } const Enhanced = Enhancer(Composed); const instance = new Enhanced({}, {}); instance.render(); expect(renderMock).to.have.been.called; expect(resolveStyles).to.have.been.called; }); it('calls existing constructor only once', () => { const constructorMock = sinon.spy(); class Composed extends Component { constructor() { super(); constructorMock(); } render() {} } const Enhanced = Enhancer(Composed); new Enhanced(); // eslint-disable-line no-new expect(constructorMock).to.have.been.calledOnce; }); it('uses the existing displayName', () => { class Composed extends Component {} Composed.displayName = 'Composed'; const Enhanced = Enhancer(Composed); expect(Enhanced.displayName).to.equal(Composed.displayName); }); it('sets up classNames on for printStyles have a copy', () => { class Composed extends Component { render() {} } Composed.displayName = 'PrintStyleTest'; Composed.printStyles = { foo: { display: 'none' }, bar: { display: 'block' } }; const Enhanced = Enhancer(Composed); const enhanced = new Enhanced(); expect(enhanced.printStyleClass.foo).to.equal('Radium-PrintStyleTest-foo'); expect(enhanced.printStyleClass.bar).to.equal('Radium-PrintStyleTest-bar'); }); it('calls existing componentWillUnmount function', () => { const existingComponentWillUnmount = sinon.spy(); class Composed extends Component { componentWillUnmount() { existingComponentWillUnmount(); } render() {} } const Enhanced = Enhancer(Composed); const instance = new Enhanced(); instance.componentWillUnmount(); expect(existingComponentWillUnmount).to.have.been.called; }); it('removes mouse up listener on componentWillUnmount', () => { const removeMouseUpListener = sinon.spy(); class Composed extends Component { constructor() { super(); this._radiumMouseUpListener = { remove: removeMouseUpListener }; } render() {} } const Enhanced = Enhancer(Composed); const instance = new Enhanced(); instance.componentWillUnmount(); expect(removeMouseUpListener).to.have.been.called; }); it('removes media query listeners on componentWillUnmount', () => { const mediaQueryListenersByQuery = { '(min-width: 1000px)': { remove: sinon.spy() }, '(max-width: 600px)': { remove: sinon.spy() }, '(min-resolution: 2dppx)': { remove: sinon.spy() } }; class Composed extends Component { constructor() { super(); this._radiumMediaQueryListenersByQuery = mediaQueryListenersByQuery; } render() {} } const Enhanced = Enhancer(Composed); const instance = new Enhanced(); instance.componentWillUnmount(); Object.keys(mediaQueryListenersByQuery).forEach(key => { expect(mediaQueryListenersByQuery[key].remove).to.have.been.called; }); }); it('manually populates all static properties for IE <10', () => { class Composed extends Component { static staticMethod() { return { bar: 'foo' }; } render() {} } Composed.defaultProps = { foo: 'bar' }; const Enhanced = Enhancer(Composed); expect(Enhanced.defaultProps).to.deep.equal({ foo: 'bar' }); expect(Enhanced.staticMethod()).to.deep.equal({ bar: 'foo' }); }); it('copies methods across to top level prototype', () => { const Composed = React.createClass({ getStyles: function() { return [{ color: 'black' }]; }, render: function() { return ( <div style={this.getStyles()}> Hello World! </div> ); } }); const Enhanced = Enhancer(Composed); Object.keys(Composed.prototype).forEach(key => { expect(Enhanced.prototype.hasOwnProperty(key)).to.equal(true); }); }); });
/*! * API Documentation * http://help.bigstockphoto.com/hc/en-us/articles/200303245-API-Documentation * * Copyright 2014 Bigstock * http://www.bigstockphoto.com */ // Bigstock Account ID var account_id = '222306'; // Globals var selected_category, search_term, infinite_scroll, page, jsonp_happening; $("#bigstock-button").click(function(e) { // Open search modal $("#search-form").modal({ backdrop: 'static' }); if ($("#categories ul li").length == 0) { // Populate the categories $.getJSON("http://api.bigstockphoto.com/2/"+account_id+"/categories/?callback=?", function(data){ if(data && data.data) { $.each(data.data, function(i, v){ if(v.name == "Sexual") { return; } $("#categories ul").append("<li><a href='#'>"+v.name+"</a></li>"); }); } }); } // When the user clicks on a category $("#categories").on("click", "a", function(e){ selected_category = $(this).text(); // A category has been clicked, trigger a bigstock category search trigger_search({ category:true }); e.preventDefault(); }); // Infinite scroll infinite_scroll = setInterval(function(){ var offset = $("#results li:last").offset(); if(offset && offset.top < 1000 && !jsonp_happening && $("#results-holder").is(":visible")) { page++; $("html").trigger("bigstock_search", { q: search_term, category:selected_category, page:page }) } }, 100); }); $("#search-button").click(function(e){ // The search button has been clicked, trigger a bigstock keyword search trigger_search(); e.preventDefault(); }); function trigger_search(val){ page = 1; var results = $("#results"); results.html("") results.append("<li id=\"loading\"><span class=\"label\">Loading...</span></li>"); var val = val || {}; // Check if the user selected a category or did a keyword search if (val.category) { search_term = ""; } else { selected_category = ""; search_term = $(".search-query").val(); } // Start the search $("html").trigger("bigstock_search", { q: search_term, category:selected_category }); $("#categories").hide(); $("#results-holder").show('medium'); $("#category-link").show(); } $("html").on("bigstock_search", function(e, val){ if(!jsonp_happening) { jsonp_happening = true; var val = val || {}; val.page = val.page || 1; var results = $("#results"); // Setup the paramaters for the JSONP request var params = {}; if(val.category != "") params.category = val.category; params.q = val.q; params.page = val.page; $.getJSON("http://api.bigstockphoto.com/2/"+account_id+"/search/?callback=?", params, function(data){ results.find("#loading").remove(); results.find("#oops").remove(); if (data && data.data && data.data.images) { var template = $(".item-template"); $.each(data.data.images, function(i, v){ template.find("img").attr({src: v.small_thumb.url, alt: v.title}); template.find("a").attr("href", "#"+v.id); results.append(template.html()) }); } else { results.append("<li id=\"oops\"><div class=\"alert alert-error\">OOOPS! We found no results. Please try another search.</div></li>"); } jsonp_happening = false; }); } }) $("#results").on("click", "a", function(e){ // Remove the hash id from the begining of the href var bigstock_id = $(this).attr("href").substring(1); var bigstock_thumb = $(this).children().attr("src"); // When a user clicks on a thumbnail $.getJSON("http://api.bigstockphoto.com/2/"+account_id+"/image/"+bigstock_id+"/?callback=?", function(data) { if (data && data.data && data.data.image) { var detail_template = $(".detail-template"); detail_template.find("img").attr({ src: data.data.image.preview.url, alt: bigstock_id, rel: bigstock_thumb }); detail_template.find("h4").html(data.data.image.title); $(".detail-template").modal({backdrop:false}); e.preventDefault(); } }); }); $(".detail-template").on("click", ".btn-primary", function(e){ /* User clicks on Select this Image. */ var $template = $(this).closest(".detail-template"); var $image = $template.find("img"); var $heading = $template.find("h4"); // Extract the image attributes and add to the form var bigstock_id = $image.attr('alt'); var bigstock_thumb = $image.attr('rel'); var bigstock_title = $heading.text(); // Add the selected image to the form add_website_image(bigstock_id, bigstock_thumb, bigstock_title); // Close modal $('.detail-template').modal('hide'); e.preventDefault(); }); $("#category-link").click(function(e){ // When a user clicks "browse by category" $("#results-holder, #category-link").hide(); $("#categories").show('medium'); e.preventDefault(); }); function add_website_image(bigstock_id, bigstock_thumb, bigstock_title) { // The table keeps the index of the next row in a data object var row = $('#website-images-table').data('nextrow'); // Define the markup for the form inputs var id_hidden = '<input type="hidden" name="company_website_images[' + row + '][id]" value="0">'; var bigstock_id_hidden = '<input type="hidden" name="company_website_images[' + row + '][bigstock_id]" value="' + bigstock_id + '">'; var bigstock_thumb_hidden = '<input type="hidden" name="company_website_images[' + row + '][bigstock_thumb]" value="' + bigstock_thumb + '">'; var bigstock_title_hidden = '<input type="hidden" name="company_website_images[' + row + '][bigstock_title]" value="' + bigstock_title + '">'; var thumb_html = '<img src="' + bigstock_thumb + '" class="img-thumbnail">'; var delete_button = '<button type="button" class="btn btn-link btn-xs"><span class="text-danger"><span class="glyphicon glyphicon-remove-circle"></span> Remove</span></button>'; // Structure the markup var html = ''; html += '<tr>'; html += '<td class="col-sm-3 text-right">' + delete_button + id_hidden + bigstock_id_hidden + '</td>'; html += '<td class="col-sm-4 text-center">' + thumb_html + bigstock_thumb_hidden + '</td>'; html += '<td class="col-sm-7">' + bigstock_title + bigstock_title_hidden + '</td>'; html += '</tr>'; // Add the new row to the end of the table and ensure it is visible $('#website-images-table tbody').append(html); $('#website-images-table').removeClass('hidden'); // Increment the tables data object row counter $('#website-images-table').data('nextrow', (row + 1)); } $('#website-images-table tbody').on('click', 'button', function() { // Remove the corresponding table row $(this).closest('tr').remove(); // If the last row has been removed, hide the table if ($('#website-images-table tbody tr').length == 0) { $('#website-images-table').addClass('hidden'); } });
import Ember from 'ember'; import DS from 'ember-data'; export default Ember.Mixin.create({ defaultSerializer: 'cardstack-resource-metadata', resourceMetadata: Ember.inject.service(), cardstackRouting: Ember.inject.service(), _defaultBranch: Ember.computed.alias('cardstackRouting.defaultBranch'), shouldReloadRecord(store, snapshot) { let requestedBranch = this._branchFromSnapshot(snapshot); let haveBranch = this.get('resourceMetadata').read(snapshot.record).get('branch'); return requestedBranch !== haveBranch; }, _branchFromSnapshot(snapshot) { let { adapterOptions } = snapshot; if (adapterOptions && adapterOptions.branch != null) { return adapterOptions.branch; } else { return this.get('_defaultBranch'); } }, _setBranchFromMeta(snapshot) { if (!snapshot.adapterOptions) { snapshot.adapterOptions = {}; } if (!snapshot.adapterOptions.branch) { let meta = this.get('resourceMetadata').read(snapshot.record); if (!meta.branch) { throw new Error("tried to update a record but I don't know what branch it came from"); } snapshot.adapterOptions.branch = meta.branch; } }, createRecord(store, type, snapshot) { this._setBranchFromMeta(snapshot); return this._super(store, type, snapshot); }, updateRecord(store, type, snapshot) { this._setBranchFromMeta(snapshot); return this._super(store, type, snapshot); }, deleteRecord(store, type, snapshot) { this._setBranchFromMeta(snapshot); let id = snapshot.id; let options = { headers: {}}; let meta = this.get('resourceMetadata').read(snapshot.record); if (meta.get('version')) { options.headers['if-match'] = meta.get('version'); } return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE", options); }, findRecord(store, type, id, snapshot) { let branch = this._branchFromSnapshot(snapshot); return this._super(store, type, id, snapshot).then(response => { this.get('resourceMetadata').write({ type: type.modelName, id }, { branch }); return response; }); }, queryRecord(store, type, query) { let branch = query.branch != null ? query.branch : this.get('_defaultBranch'); let upstreamQuery = Ember.assign({}, query); upstreamQuery.page = { size: 1 }; if (branch === this.get('_defaultBranch')) { delete upstreamQuery.branch; } return this._super(store, type, upstreamQuery).then(response => { if (!response.data || !Array.isArray(response.data) || response.data.length < 1) { throw new DS.AdapterError([ { code: 404, title: 'Not Found', detail: 'branch-adapter queryRecord got less than one record back' } ]); } if (!query.disableResourceMetadata) { this.get('resourceMetadata').write({ type: type.modelName, id: response.data[0].id }, { branch }); } let returnValue = { data: response.data[0], }; if (response.meta){ returnValue.meta = response.meta; } return returnValue; }); }, // This will properly set the branch query param from the // adapterOptions for everything *except* query and // queryRecord. Those two don't pass a snapshot to buildURL and are // handled separately above. buildURL(modelName, id, snapshot, requestType, query) { let url = this._super(modelName, id, snapshot, requestType, query); if (snapshot && snapshot.adapterOptions) { let { branch } = snapshot.adapterOptions; if (branch != null && branch !== this.get('_defaultBranch')) { url += '?branch=' + encodeURIComponent(branch); } } return url; } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _helperPluginUtils() { const data = require("@babel/helper-plugin-utils"); _helperPluginUtils = function () { return data; }; return data; } function _core() { const data = require("@babel/core"); _core = function () { return data; }; return data; } var _default = (0, _helperPluginUtils().declare)(api => { api.assertVersion(7); return { visitor: { Scope({ scope }) { if (!scope.getBinding("Symbol")) { return; } scope.rename("Symbol"); }, UnaryExpression(path) { const { node, parent } = path; if (node.operator !== "typeof") return; if (path.parentPath.isBinaryExpression() && _core().types.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { const opposite = path.getOpposite(); if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") { return; } } const helper = this.addHelper("typeof"); const isUnderHelper = path.findParent(path => { return path.isVariableDeclarator() && path.node.id === helper || path.isFunctionDeclaration() && path.node.id && path.node.id.name === helper.name; }); if (isUnderHelper) { return; } const call = _core().types.callExpression(helper, [node.argument]); const arg = path.get("argument"); if (arg.isIdentifier() && !path.scope.hasBinding(arg.node.name, true)) { const unary = _core().types.unaryExpression("typeof", _core().types.cloneNode(node.argument)); path.replaceWith(_core().types.conditionalExpression(_core().types.binaryExpression("===", unary, _core().types.stringLiteral("undefined")), _core().types.stringLiteral("undefined"), call)); } else { path.replaceWith(call); } } } }; }); exports.default = _default;
/* Created by Bradley Harker and Elijah Wilson Design Lead - Elijah Wilson Progamming Lead - Bradley Harker */ function Dot() { this.x; this.y; this.color = color(255,255,255); this.draw = function() { noStroke(); fill(this.color); ellipse(this.x,this.y,10,10); } }
var util = require('util'); //Setup exception handlers var AbstractException = function (resp,msg,constr) { Error.captureStackTrace(this, constr || this); this.message = msg || 'Error'; resp.exception = {"error": {"error_type": this.name, "message": this.message, "stacktrace": this.stack} }; resp.send(null); }; var Exception = function (resp,msg) { Exception.super_.call(this, resp, msg, this.constructor); }; var LoginException = function (resp,msg) { LoginException.super_.call(this, resp, msg, this.constructor); }; var LogoffException = function (resp,msg) { LogoffException.super_.call(this, resp, msg, this.constructor); }; var ServerTimeoutException = function (resp,msg) { ServerTimeoutException.super_.call(this, resp, msg, this.constructor); }; var ServerErrorException = function (resp,msg) { ServerErrorException.super_.call(this, resp, msg, this.constructor); }; var ObjectConflictErrorException = function (resp,msg) { ObjectConflictErrorException.super_.call(this, resp, msg, this.constructor); }; // Setup the types for each exception util.inherits(AbstractException, Error); util.inherits(Exception, AbstractException); util.inherits(LoginException, AbstractException); util.inherits(LogoffException, AbstractException); util.inherits(ServerTimeoutException, AbstractException); util.inherits(ServerErrorException, AbstractException); util.inherits(ObjectConflictErrorException, AbstractException); // Default names AbstractException.prototype.name = 'AbstractException'; Exception.prototype.name = 'Exception'; LoginException.prototype.name = 'LoginException'; LogoffException.prototype.name = 'LogoffException'; ServerTimeoutException.prototype.name = 'ServerTimeoutException'; ServerErrorException.prototype.name = 'ServerErrorException'; ObjectConflictErrorException.prototype.name = 'ObjectConflictErrorException'; // Public exceptions module.exports.Exception = Exception; module.exports.LoginException = LoginException; module.exports.LogoffException = LogoffException; module.exports.ServerTimeoutException = ServerTimeoutException; module.exports.ServerErrorException = ServerErrorException; module.exports.ObjectConflictErrorException = ObjectConflictErrorException;
module.exports = func /** * Exported function * @param {number} * @param {number} * @returns {number} * @exports module-exports-func */ function func (one, two) {}
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame, assertTrue, assertFalse, assertEquals, assertDataProperty, assertAccessorProperty, fail, } = Assert; // Tested implementations: JSC, Nashorn, V8, SpiderMonkey // Nashorn, V8, JSC { let names = ["a", "b", ""]; let set = () => fail `Unexpected [[Put]]`; let get = () => 2; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { Object.defineProperty(this, "b", { set, get }); } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "b", {value: 2, writable: true, enumerable: true, configurable: true}); } // Nashorn, V8, JSC { let names = ["a", "b", ""]; let set = () => fail `Unexpected [[Put]]`; let get = () => 2; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { Object.defineProperty(this, "b", { set, get, configurable: true }); } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "b", {value: 2, writable: true, enumerable: true, configurable: true}); } // SpiderMonkey, Nashorn, V8, JSC { let names = ["a", "b", ""]; let set = () => fail `Unexpected [[Put]]`; let get = () => 2; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { Object.defineProperty(this, "b", { set, get, configurable: false }); } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertAccessorProperty(o, "b", {get, set, enumerable: true, configurable: false}); } // SpiderMonkey, Nashorn, V8, JSC { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { Object.seal(this); } if (name === "b") { return 2; // new value must be ignored! } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertFalse(Object.isExtensible(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: false}); assertDataProperty(o, "b", {value: 1, writable: true, enumerable: true, configurable: false}); } // SpiderMonkey, V8, Nashorn { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { delete this.b; Object.seal(this); } if (name === "b") { return 2; // new value must be ignored! } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a"], Object.getOwnPropertyNames(o)); assertFalse(Object.isExtensible(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: false}); assertFalse(o.hasOwnProperty("b")); } // SpiderMonkey { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { Object.freeze(this); } if (name === "b") { return 2; // new value must be ignored! } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertFalse(Object.isExtensible(o)); assertDataProperty(o, "a", {value: 0, writable: false, enumerable: true, configurable: false}); assertDataProperty(o, "b", {value: 1, writable: false, enumerable: true, configurable: false}); } // SpiderMonkey, V8, Nashorn { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { delete this.b; Object.freeze(this); } if (name === "b") { return 2; // new value must be ignored! } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a"], Object.getOwnPropertyNames(o)); assertFalse(Object.isExtensible(o)); assertDataProperty(o, "a", {value: 0, writable: false, enumerable: true, configurable: false}); assertFalse(o.hasOwnProperty("b")); } // Nashorn { let array = Object.defineProperty([100], "0", { enumerable: false }); let names = ["a", "0", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { this.b = array; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "b", {value: array, writable: true, enumerable: true, configurable: true}); } // JSC { let names = ["0", "1", "2", ""]; let o = JSON.parse('[0, 1, 2]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "0") { Array.prototype[1] = 33; delete this[1]; } if (name === "2") { delete Array.prototype[1]; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["0", "1", "2", "length"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "0", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "1", {value: 33, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "2", {value: 2, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "length", {value: 3, writable: true, enumerable: false, configurable: false}); } // V8 { let names = ["0", "1", "2", ""]; let o = JSON.parse('[0, 1, 2]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "0") { Object.defineProperty(this, "1", { configurable: false }); } if (name === "1") { return; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["0", "1", "2", "length"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "0", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "1", {value: 1, writable: true, enumerable: true, configurable: false}); assertDataProperty(o, "2", {value: 2, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "length", {value: 3, writable: true, enumerable: false, configurable: false}); } // JSC { let names = ["0", ""]; let o = JSON.parse('[0]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "0") { this.push(1); } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["0", "1", "length"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "0", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "1", {value: 1, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "length", {value: 2, writable: true, enumerable: false, configurable: false}); } // Nashorn, JSC, V8, SpiderMonkey { let names = ["0", "1", ""]; let o = JSON.parse('[0, 1]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "0") { Object.defineProperty(this, 1, {configurable: false}); } if (name === "1") { return 33; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["0", "1", "length"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "0", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "1", {value: 1, writable: true, enumerable: true, configurable: false}); assertDataProperty(o, "length", {value: 2, writable: true, enumerable: false, configurable: false}); } // JSC, V8 { let names = ["0", ""]; let o = JSON.parse('[0]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "0") { this.length = 0; } if (name === "0") { return; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["length"], Object.getOwnPropertyNames(o)); assertFalse(o.hasOwnProperty(0)); assertDataProperty(o, "length", {value: 0, writable: true, enumerable: false, configurable: false}); } // Nashorn { let names = ["0", "1", ""]; let o = JSON.parse('[0, 1]', function reviver(name, value) { assertSame(names.shift(), name); if (name === "1") { this.length = 0; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["1", "length"], Object.getOwnPropertyNames(o)); assertFalse(o.hasOwnProperty(0)); assertDataProperty(o, "1", {value: 1, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "length", {value: 2, writable: true, enumerable: false, configurable: false}); } // V8 { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { delete this.b; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertFalse(o.hasOwnProperty("b")); } // V8 { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { delete this.b; } if (name === "b") { return 2; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "b", {value: 2, writable: true, enumerable: true, configurable: true}); } // JSC { let names = ["a", "b", ""]; let o = JSON.parse('{"a": 0, "b": 1}', function reviver(name, value) { assertSame(names.shift(), name); if (name === "a") { delete this.b; this.__proto__ = { set b(_) { fail `Unexpected [[Put]]`; } }; } if (name === "b") { return 2; } return value; }); assertSame(0, names.length, `Unvisited names: ${names}`); assertEquals(["a", "b"], Object.getOwnPropertyNames(o)); assertDataProperty(o, "a", {value: 0, writable: true, enumerable: true, configurable: true}); assertDataProperty(o, "b", {value: 2, writable: true, enumerable: true, configurable: true}); }
ig.module( "game.entities.misc.corpse" ) .requires( "impact.entity" ) .defines(function () { EntityCorpse = ig.Entity.extend({ zIndex: 0, ttlTimer: null, init: function (x, y, settings) { this.parent(x, y, settings); this.addAnim("death", 0.25, settings.frames, true); this.ttlTimer = new ig.Timer(2.5); }, update: function () { this.parent(); var delta = this.ttlTimer.delta(); // Fade out during the last second of ttl if (delta >= -1 && delta <= 0) { this.currentAnim.alpha = (delta / -1); } if (delta >= 0) { this.kill(); } } }); });
import babel from 'rollup-plugin-babel'; import multiEntry, { entry } from 'rollup-plugin-multi-entry'; export default { entry, plugins: [babel(), multiEntry('test/**/*_test.js')], format: 'cjs', dest: 'build/test-bundle.js' };
import fs from 'fs' import fse, {outputFileSync, removeSync} from 'fs-extra' import _ from 'lodash' import matchBracket from 'match-bracket' import locater from 'locater' import {insertToFile, checkFileExists} from '../utils' import {logger} from '../logger' import {getConfig} from '../config_utils' /** * Gets the output path of the file that will be generated. * @param type {String} - the type of file to be generated. See extensionMap * for the supported values. * @param entityName {String} - the name of the file that will be generated * @param [moduleName] {String} - the name of the module under which the file will * be generated * @return String - the output path relative to the app root */ export function getOutputPath (customConfig, type, entityName, moduleName) { const {modulesPath} = getConfig(customConfig) const extensionMap = { component: '.js', container: 'Container.js', storybook: '.stories.js' } let extension = extensionMap[type] const outputFileName = `${entityName}${extension}` let modulePath if (type === 'storybook') { modulePath = `./${modulesPath}/${moduleName}/components/stories` } else { modulePath = `./${modulesPath}/${moduleName}/${type}s` } return `${modulePath}/${outputFileName}` } /** * getTestOutputPath gets the output path for the test file. It is similar to * getOutputPath function. * * @param type {String} - the type of file to be generated. See extensionMap * for the supported values. * @param entityName {String} - the name of the file that will be generated * @param [moduleName] {String} - the name of the module under which the file will * be generated * @return String - the output path relative to the app root */ export function getTestOutputPath (customConfig, type, entityName, moduleName) { const {modulesPath, snakeCaseFileNames} = getConfig(customConfig) const casedEntityName = snakeCaseFileNames ? _.snakeCase(entityName) : _.camelCase(entityName) let outputFileName = `${casedEntityName}.js` return `${modulesPath}/${moduleName}/${type}s/tests/${outputFileName}` } /** * Reads the content of a generic template for the file type * @param type {String} - type of the file. See getOutputPath's extensionMap for * all valid types * @param templateOptions {Object} - options to be passed to functions for * getting the template path. * @param config {Object} - global configuration for CLI. This may contain * custom template content * @return Buffer - the content of the template for the given type */ export function readTemplateContent (type, templateOptions, config) { // First, try to get custom template from config // If cannot find custom template, return the default if (checkForCustomTemplate(config, type, templateOptions)) { let templateConfig = getCustomTemplate(config, type, templateOptions) return templateConfig.text } } function getCustomTemplate (config, entityType, {testTemplate = false}) { const selector = {name: entityType} if (testTemplate) { selector.test = true } const templateConfig = _.find(config.templates, selector) return templateConfig } /** * Checks if there is a custom template defined in the config * for the given entity type * @param config {Object} - global configuration for CLI. * @param entityType {String} - type of the file * @param options {Object} - options to be passed to functions for * getting the template path. * @return Boolean */ function checkForCustomTemplate (config, entityType, options) { if (!config.templates) { return false } const template = getCustomTemplate(config, entityType, options) return !_.isEmpty(template) } /** * Gets the variables to be passed to the generic template to be evaluated by * a template engine. * @param type {String} - type of the template * @param fileName {String} - name of the file being generated * @return {Object} - key-values pairs of variable names and their values */ export function getTemplateVariables ( customConfig, type, moduleName, fileName, options = {} ) { const {snakeCaseFileNames} = customConfig if (type === 'component') { return { moduleName: snakeCaseFileNames ? _.snakeCase(moduleName) : _.camelCase(moduleName), componentName: _.upperFirst(_.camelCase(fileName)) } } else if (type === 'storybook') { return { moduleName: snakeCaseFileNames ? _.snakeCase(moduleName) : _.camelCase(moduleName), componentName: _.upperFirst(_.camelCase(fileName)), componentFileName: snakeCaseFileNames ? _.snakeCase(fileName) : _.camelCase(fileName) } } else if (type === 'container') { return { moduleName: snakeCaseFileNames ? _.snakeCase(moduleName) : _.camelCase(moduleName), componentName: _.upperFirst(_.camelCase(fileName)), componentFileName: snakeCaseFileNames ? _.snakeCase(fileName) : _.camelCase(fileName) } } return {} } /** * Gets the variables to be passed to the test template. * @param type {String} - type of the template * @param moduleName {String} - name of the module the test belongs * @param fileName {String} - name of the file which the test is for * @return {Object} - key-values pairs of variable names and their values */ export function getTestTemplateVariables ( customConfig, type, moduleName, fileName ) { const {snakeCaseFileNames} = customConfig if (type === 'component') { return { componentName: _.upperFirst(_.camelCase(fileName)), componentFileName: snakeCaseFileNames ? _.snakeCase(fileName) : _.camelCase(fileName), moduleName: snakeCaseFileNames ? _.snakeCase(moduleName) : _.camelCase(moduleName) } } else if (type === 'container') { return { containerFileName: snakeCaseFileNames ? _.snakeCase(fileName) : _.camelCase(fileName), moduleName: snakeCaseFileNames ? _.snakeCase(moduleName) : _.camelCase(moduleName) } } } /** * Updates a relevant index.js file by inserting an import statement at the top * portion of the file, and a statement inside the export block. * Uses locater, and matchBracket to pinpoint the position at which the * statements are to be inserted. * * @param {Object} * - indexFilePath: the path to the index file to be modified * - exportBeginning: the content of the line on which the export block * begins * - insertImport: the import statement to be inserted at the top portion * of the file * - insertExport: the statement to be inserted inside the export block * - commaDelimited: whether the items in the export blocks are separated * by commas. * e.g. export default { posts, users } // => commaDelimited is true * - omitExport: whether to add export-statement (defaults to true) */ export function updateIndexFile ({ indexFilePath, exportBeginning, insertImport, insertExport, commaDelimited, omitExport = false }) { if (!checkFileExists(indexFilePath)) { logger.missing(indexFilePath) return } function analyzeExportBlock () { let indexContent = fs.readFileSync(indexFilePath, {encoding: 'utf-8'}) let exportBeginningRegex = new RegExp(_.escapeRegExp(exportBeginning), 'g') let exportBeginningPos = locater.findOne(exportBeginningRegex, indexContent) let bracketCursor = exportBeginning.indexOf('{') + 1 // cursor at which the bracket appears on the line where export block starts let matchedBracketPos = matchBracket( indexContent, _.assign(exportBeginningPos, {cursor: bracketCursor}) ) return { beginningLine: exportBeginningPos.line, endLine: matchedBracketPos.line, isEmpty: exportBeginningPos.line === matchedBracketPos.line - 1 } } logger.update(indexFilePath) // Insert the import statement at the top portion of the file insertToFile(indexFilePath, insertImport, { or: [ {after: {regex: /import .*\n/g, last: true}, asNewLine: true}, {before: {line: 1}, asNewLine: true, _appendToModifier: '\n'} ] }) if (!omitExport) { // Insert within the export block and modify the block content as needed let info = analyzeExportBlock() if (!info.isEmpty && commaDelimited) { insertToFile(indexFilePath, ',', {after: {line: info.endLine - 1}}) } insertToFile(indexFilePath, insertExport, { before: {line: info.endLine}, asNewLine: true }) } } /** * Removes from the string the whole line on which the pattern appears. Useful * when removing import and export lines from index files * * @param string {String} - a string to be modified * @param pattern {String|RegExp} - pattern to be matched against the `string` */ export function removeWholeLine (string, pattern) { function nthIndexOf (str, part, n) { let len = str.length let i = -1 while (n-- && i++ < len) { i = str.indexOf(part, i) if (i < 0) break } return i } let position = locater.findOne(pattern, string) if (!position) { return string } let lineNumber = position.line let lineStartIndex = nthIndexOf(string, '\n', lineNumber - 1) + 1 let lineEndIndex = nthIndexOf(string, '\n', lineNumber) return ( string.substring(0, lineStartIndex) + string.substring(lineEndIndex + 1) ) } /** * Remove the import and export statement for an entity from the index file * specified by the path * * @param indexFilePath {String} - the path to the index.js file to be modified * @param entityName {String} - the name of the entity whose import and export * statements to be removed from the index file */ export function removeFromIndexFile ( indexFilePath, type, entityName, options = {} ) { console.log( `export {default as ${entityName}} from './${type}/${entityName}'` ) if (!checkFileExists(indexFilePath)) { logger.missing(indexFilePath) return } logger.update(indexFilePath) let regex = new RegExp(` ${entityName}.*\n`, 'g') let content = fs.readFileSync(indexFilePath, {encoding: 'utf-8'}) content = removeWholeLine( content, `export {default as ${entityName}} from './${type}s/${entityName}'` ) content = removeWholeLine(content, regex) outputFileSync(indexFilePath, content) } /** * Removes a file at the given path * @param path {String} - the path to the file to be removed */ export function removeFile (path) { logger.remove(path) removeSync(path) } /** * Compiles a template given content and variables. Reads and applies user * configurations. * @param content {String} - template content * @param variables {Object} - variable names and values to be passed to the * template and evaluated * @param config {Object} - config * @return {String} - compiled content */ export function compileTemplate (content, variables, config) { let compiled = _.template(content)(variables) let tab = _.repeat(' ', config.tabSize) const defaultTabSize = 2 // TODO: windows newline // customize tabSpace by replacing spaces followed by newline return compiled.replace(/(\n|\r\n)( +)/g, function ( match, lineBreak, defaultTab ) { let numTabs = defaultTab.length / defaultTabSize return lineBreak + _.repeat(tab, numTabs) }) } /** * A generic function for generating entities. Used by generators for each * types * * @param type {String} - type of the entity to be generated * @param moduleName {String} - name of the module that the entity belongs * applicable for client entities. Set to `null` if not applicable * @param entityName {String} - name of the entity to be generated * @param options {Object} - options passed by the CLI * @param config {Object} - global configuration of the CLI * @return {String} - path to the generated file */ export function _generate (type, moduleName, entityName, options, customConfig) { const config = getConfig(customConfig) let templateContent = readTemplateContent(type, options, config) let outputPath = getOutputPath(customConfig, type, entityName, moduleName) let templateVariables = getTemplateVariables( customConfig, type, moduleName, entityName, options ) let component = compileTemplate(templateContent, templateVariables, config) if (checkFileExists(outputPath)) { logger.exists(outputPath) return {exists: true, outputPath} } fse.outputFileSync(outputPath, component) logger.create(outputPath) return {exists: false, outputPath} } export function _generateTest ( type, customConfig, moduleName, entityName, config ) { let templateContent = readTemplateContent(type, {testTemplate: true}, config) let outputPath = getTestOutputPath(customConfig, type, entityName, moduleName) let templateVariables = getTestTemplateVariables( customConfig, type, moduleName, entityName ) let component = _.template(templateContent)(templateVariables) if (checkFileExists(outputPath)) { logger.exists(outputPath) return outputPath } fse.outputFileSync(outputPath, component) logger.create(outputPath) return outputPath } /** * Checks if the given string follows the format of moduleName:entityName * @return {Boolean} - true if validation passes, false otherwise */ export function checkForModuleName (str) { let re = /.*:.*/ return re.test(str) } /** * Checks if name is in the format of `moduleName:entityName`. Exits the process * if the validation fails * * @param name {String} - name to validate */ export function ensureModuleNameProvided (name) { if (!checkForModuleName(name)) { console.log( `Invalid name: ${name}. Did you remember to provide the module name?` ) console.log('Run ` generate --help` for more options.') process.exit(1) } } /** * Checks if module with the given name exists. Exits the process if the module * does not exist * * @param moduleName {String} - name of the module to check if exists */ export function ensureModuleExists (moduleName, customConfig = {}) { const config = getConfig(customConfig) if (!checkFileExists(`./${config.modulesPath}/${moduleName}`)) { console.log( `A module named ${moduleName} does not exist. Try to generate it first.` ) console.log('Run ` generate --help` for more options.') process.exit(1) } }
//= require_tree './zahlen'
/* jshint proto: true */ /* global CoreObject */ import Ember from 'ember'; import { extend } from './utils'; function detect(obj) { return obj.isViewClass || this._super(obj); } Ember.CoreView.reopenClass({ detect: detect }); Ember.View.reopenClass({ detect: detect }); var metaFor = Ember.meta; var finishPartial = Ember.Mixin.finishPartial; var IS_BINDING = Ember.IS_BINDING; var computed = Ember.computed; var get = Ember.get; CoreObject.create = function(props) { return new this(props); }; CoreObject.reopenClass = function(props) { extend(this, props); }; var isBindingCache = Object.create(null); function isBinding(key) { if (isBindingCache[key]) { return true; } if (IS_BINDING.test(key)) { isBindingCache[key] = 1; return true; } return false; } var MetalView = CoreObject.extend({ init: function(props) { this.isView = true; this.tagName = props.tagName || this.tagName /* FIXME: read off prototype */ || null; this.isVirtual = false; this.elementId = null; this._actions = this.actions; var meta = metaFor(this); // FIXME var proto = meta.proto; meta.proto = this; // Secret handshake to prevent observers firing during init var bindings = meta.bindings = meta.bindings || {}; var possibleDesc; var desc; var keys = Object.keys(props); var key; for (var i = 0, l = keys.length; i < l; i++) { key = keys[i]; if (isBinding(key)) { this[key] = bindings[key] = props[key]; } else { possibleDesc = this[key]; desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined; if (desc) { desc.set(this, key, props[key]); } else { this[key] = props[key]; } } } if (!this.isVirtual && !this.elementId) { this.elementId = Ember.guidFor(this); } finishPartial(this, meta); meta.proto = proto; } }); MetalView.prototype.__ember_meta__ = metaFor(MetalView.prototype); MetalView.prototype.__ember_meta__.proto = MetalView.prototype; Ember.defineProperty(MetalView.prototype, 'parentView', computed('_parentView', function() { var parent = this._parentView; if (parent && parent.isVirtual) { return get(parent, 'parentView'); } else { return parent; } })); function noop() {} extend(MetalView.prototype, { _childViews: [], $: function(sel) { var elem = this.element; return sel ? jQuery(sel, elem) : jQuery(elem); }, // TODO: remove this currentState: { appendChild: function(view, childView, options) { var buffer = view.buffer; var _childViews = view._childViews; childView = view.createChildView(childView, options); if (!_childViews.length) { _childViews = view._childViews = _childViews.slice(); } _childViews.push(childView); if (!childView._morph) { buffer.pushChildView(childView); } if (view.propertyDidChange !== noop) { view.propertyDidChange('childViews'); } return childView; }, invokeObserver: function(target, observer) { observer.call(target); }, appendAttr: Ember.View.proto()._states.inBuffer.appendAttr }, propertyDidChange: noop, destroy: function() { // TODO: EmberObject#destroy stuff? if (!this.removedFromDOM && this._renderer) { this._renderer.remove(this, true); } // remove from parent if found. Don't call removeFromParent, // as removeFromParent will try to remove the element from // the DOM again. var parent = this._parentView; if (parent) { parent.removeChild(this); } this._transitionTo('destroying', false); return this; }, destroyElement: function() { var state = this._state; if (state === 'destroying') { throw 'destroyElement'; // TODO } if (this._renderer) { this._renderer.remove(this, false); } return this; }, _transitionTo: function(state) { this._state = state; }, __defineNonEnumerable: function(property) { this[property.name] = property.descriptor.value; }, _wrapAsScheduled: Ember.View.proto()._wrapAsScheduled, applyAttributesToBuffer: Ember.View.proto().applyAttributesToBuffer, attributeBindings: [], appendAttr: Ember.View.proto().appendAttr, }); var EmberViewModule = Ember.__loader.require('ember-views/views/view'); EmberViewModule.ViewKeywordSupport.apply(MetalView.prototype); EmberViewModule.ViewStreamSupport.apply(MetalView.prototype); EmberViewModule.ViewChildViewsSupport.apply(MetalView.prototype); EmberViewModule.ViewContextSupport.apply(MetalView.prototype); EmberViewModule.TemplateRenderingSupport.apply(MetalView.prototype); EmberViewModule.ClassNamesSupport.apply(MetalView.prototype); var AttributeBindingsSupport = Ember.__loader.require('ember-views/mixins/attribute_bindings_support')['default']; AttributeBindingsSupport.apply(MetalView.prototype); var TargetActionSupport = Ember.__loader.require('ember-runtime/mixins/target_action_support')['default']; TargetActionSupport.apply(MetalView.prototype); var Evented = Ember.__loader.require('ember-runtime/mixins/evented')['default']; Evented.apply(MetalView.prototype); var ActionHandler = Ember.__loader.require('ember-runtime/mixins/action_handler')['default']; ActionHandler.apply(MetalView.prototype); Ember.Mixin.create({ trigger: Ember.CoreView.proto().trigger, has: Ember.CoreView.proto().has }).apply(MetalView.prototype); extend(MetalView, { classProps: ['classProps', 'isClass', 'isViewClass', 'isMethod', 'proto', 'create', 'extend', 'reopenClass'], isClass: true, isViewClass: true, isMethod: false, proto: function() { return MetalView.prototype; }, // create: function(props) { // return new this(props); // }, extend: function(props) { var ParentClass = this.__proto__; var originalExtend = ParentClass.extend; var Subclass = originalExtend.call(this, props); var classProps = this.classProps; var key; for (var i = 0, l = classProps.length; i < l; i++) { key = classProps[i]; Subclass[key] = this[key]; } // Subclass.prototype = Ember.create(this.prototype); // if (props) { extend(Subclass.prototype, props); } return Subclass; }, // reopenClass: function(props) { // extend(this, props); // } }); export default MetalView;
import React, { Component } from "react" import PropTypes from "prop-types" import { connect } from "react-redux" import IconMenu from "material-ui/IconMenu" import IconButton from "material-ui/IconButton" import FontIcon from "material-ui/FontIcon" import MenuItem from "material-ui/MenuItem" import { red500, green500 } from "material-ui/styles/colors" import { NOMAD_DRAIN_CLIENT, NOMAD_REMOVE_CLIENT } from "../../sagas/event" class ClientActionMenu extends Component { handleClick = key => { return () => { switch (key) { case "drain_on": this.props.dispatch({ type: NOMAD_DRAIN_CLIENT, payload: { id: this.props.node.ID, action: "enable" } }) break case "drain_off": this.props.dispatch({ type: NOMAD_DRAIN_CLIENT, payload: { id: this.props.node.ID, action: "disable" } }) break case "remove": this.props.dispatch({ type: NOMAD_REMOVE_CLIENT, payload: this.props.node.Name }) break } } } getDrainMenu() { if (this.props.node.Drain) { return ( <MenuItem primaryText="Disable Drain mode" rightIcon={ <FontIcon className="material-icons" color={green500}> check_box </FontIcon> } onTouchTap={this.handleClick("drain_off")} /> ) } return ( <MenuItem primaryText="Enable Drain mode" rightIcon={ <FontIcon className="material-icons" color={red500}> check_box </FontIcon> } onTouchTap={this.handleClick("drain_on")} /> ) } getForceRemoveMenu() { if (this.props.node.Status != "failed") { return null } return ( <MenuItem primaryText="Remove client" rightIcon={ <FontIcon className="material-icons" color={red500}> remove_circle </FontIcon> } onTouchTap={this.handleClick("remove")} /> ) } render() { const icon = ( <IconButton> <FontIcon className="material-icons" color="white"> more_vert </FontIcon> </IconButton> ) return ( <span> <IconMenu iconButtonElement={icon} style={{ background: green500, borderRadius: "50%" }} anchorOrigin={{ horizontal: "left", vertical: "top" }} targetOrigin={{ horizontal: "left", vertical: "top" }} > {this.getDrainMenu()} {this.getForceRemoveMenu()} </IconMenu> </span> ) } } ClientActionMenu.propTypes = { dispatch: PropTypes.func.isRequired } export default connect()(ClientActionMenu)
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _affix = require('./affix'); Object.defineProperty(exports, 'Affix', { enumerable: true, get: function get() { return _interopRequireDefault(_affix)['default']; } }); var _anchor = require('./anchor'); Object.defineProperty(exports, 'Anchor', { enumerable: true, get: function get() { return _interopRequireDefault(_anchor)['default']; } }); var _autoComplete = require('./auto-complete'); Object.defineProperty(exports, 'AutoComplete', { enumerable: true, get: function get() { return _interopRequireDefault(_autoComplete)['default']; } }); var _alert = require('./alert'); Object.defineProperty(exports, 'Alert', { enumerable: true, get: function get() { return _interopRequireDefault(_alert)['default']; } }); var _avatar = require('./avatar'); Object.defineProperty(exports, 'Avatar', { enumerable: true, get: function get() { return _interopRequireDefault(_avatar)['default']; } }); var _backTop = require('./back-top'); Object.defineProperty(exports, 'BackTop', { enumerable: true, get: function get() { return _interopRequireDefault(_backTop)['default']; } }); var _badge = require('./badge'); Object.defineProperty(exports, 'Badge', { enumerable: true, get: function get() { return _interopRequireDefault(_badge)['default']; } }); var _breadcrumb = require('./breadcrumb'); Object.defineProperty(exports, 'Breadcrumb', { enumerable: true, get: function get() { return _interopRequireDefault(_breadcrumb)['default']; } }); var _button = require('./button'); Object.defineProperty(exports, 'Button', { enumerable: true, get: function get() { return _interopRequireDefault(_button)['default']; } }); var _calendar = require('./calendar'); Object.defineProperty(exports, 'Calendar', { enumerable: true, get: function get() { return _interopRequireDefault(_calendar)['default']; } }); var _card = require('./card'); Object.defineProperty(exports, 'Card', { enumerable: true, get: function get() { return _interopRequireDefault(_card)['default']; } }); var _collapse = require('./collapse'); Object.defineProperty(exports, 'Collapse', { enumerable: true, get: function get() { return _interopRequireDefault(_collapse)['default']; } }); var _carousel = require('./carousel'); Object.defineProperty(exports, 'Carousel', { enumerable: true, get: function get() { return _interopRequireDefault(_carousel)['default']; } }); var _cascader = require('./cascader'); Object.defineProperty(exports, 'Cascader', { enumerable: true, get: function get() { return _interopRequireDefault(_cascader)['default']; } }); var _checkbox = require('./checkbox'); Object.defineProperty(exports, 'Checkbox', { enumerable: true, get: function get() { return _interopRequireDefault(_checkbox)['default']; } }); var _col = require('./col'); Object.defineProperty(exports, 'Col', { enumerable: true, get: function get() { return _interopRequireDefault(_col)['default']; } }); var _datePicker = require('./date-picker'); Object.defineProperty(exports, 'DatePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_datePicker)['default']; } }); var _dropdown = require('./dropdown'); Object.defineProperty(exports, 'Dropdown', { enumerable: true, get: function get() { return _interopRequireDefault(_dropdown)['default']; } }); var _form = require('./form'); Object.defineProperty(exports, 'Form', { enumerable: true, get: function get() { return _interopRequireDefault(_form)['default']; } }); var _icon = require('./icon'); Object.defineProperty(exports, 'Icon', { enumerable: true, get: function get() { return _interopRequireDefault(_icon)['default']; } }); var _input = require('./input'); Object.defineProperty(exports, 'Input', { enumerable: true, get: function get() { return _interopRequireDefault(_input)['default']; } }); var _inputNumber = require('./input-number'); Object.defineProperty(exports, 'InputNumber', { enumerable: true, get: function get() { return _interopRequireDefault(_inputNumber)['default']; } }); var _layout = require('./layout'); Object.defineProperty(exports, 'Layout', { enumerable: true, get: function get() { return _interopRequireDefault(_layout)['default']; } }); var _localeProvider = require('./locale-provider'); Object.defineProperty(exports, 'LocaleProvider', { enumerable: true, get: function get() { return _interopRequireDefault(_localeProvider)['default']; } }); var _message = require('./message'); Object.defineProperty(exports, 'message', { enumerable: true, get: function get() { return _interopRequireDefault(_message)['default']; } }); var _menu = require('./menu'); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_menu)['default']; } }); var _modal = require('./modal'); Object.defineProperty(exports, 'Modal', { enumerable: true, get: function get() { return _interopRequireDefault(_modal)['default']; } }); var _notification = require('./notification'); Object.defineProperty(exports, 'notification', { enumerable: true, get: function get() { return _interopRequireDefault(_notification)['default']; } }); var _pagination = require('./pagination'); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_pagination)['default']; } }); var _popconfirm = require('./popconfirm'); Object.defineProperty(exports, 'Popconfirm', { enumerable: true, get: function get() { return _interopRequireDefault(_popconfirm)['default']; } }); var _popover = require('./popover'); Object.defineProperty(exports, 'Popover', { enumerable: true, get: function get() { return _interopRequireDefault(_popover)['default']; } }); var _progress = require('./progress'); Object.defineProperty(exports, 'Progress', { enumerable: true, get: function get() { return _interopRequireDefault(_progress)['default']; } }); var _radio = require('./radio'); Object.defineProperty(exports, 'Radio', { enumerable: true, get: function get() { return _interopRequireDefault(_radio)['default']; } }); var _rate = require('./rate'); Object.defineProperty(exports, 'Rate', { enumerable: true, get: function get() { return _interopRequireDefault(_rate)['default']; } }); var _row = require('./row'); Object.defineProperty(exports, 'Row', { enumerable: true, get: function get() { return _interopRequireDefault(_row)['default']; } }); var _select = require('./select'); Object.defineProperty(exports, 'Select', { enumerable: true, get: function get() { return _interopRequireDefault(_select)['default']; } }); var _slider = require('./slider'); Object.defineProperty(exports, 'Slider', { enumerable: true, get: function get() { return _interopRequireDefault(_slider)['default']; } }); var _spin = require('./spin'); Object.defineProperty(exports, 'Spin', { enumerable: true, get: function get() { return _interopRequireDefault(_spin)['default']; } }); var _steps = require('./steps'); Object.defineProperty(exports, 'Steps', { enumerable: true, get: function get() { return _interopRequireDefault(_steps)['default']; } }); var _switch = require('./switch'); Object.defineProperty(exports, 'Switch', { enumerable: true, get: function get() { return _interopRequireDefault(_switch)['default']; } }); var _table = require('./table'); Object.defineProperty(exports, 'Table', { enumerable: true, get: function get() { return _interopRequireDefault(_table)['default']; } }); var _transfer = require('./transfer'); Object.defineProperty(exports, 'Transfer', { enumerable: true, get: function get() { return _interopRequireDefault(_transfer)['default']; } }); var _tree = require('./tree'); Object.defineProperty(exports, 'Tree', { enumerable: true, get: function get() { return _interopRequireDefault(_tree)['default']; } }); var _treeSelect = require('./tree-select'); Object.defineProperty(exports, 'TreeSelect', { enumerable: true, get: function get() { return _interopRequireDefault(_treeSelect)['default']; } }); var _tabs = require('./tabs'); Object.defineProperty(exports, 'Tabs', { enumerable: true, get: function get() { return _interopRequireDefault(_tabs)['default']; } }); var _tag = require('./tag'); Object.defineProperty(exports, 'Tag', { enumerable: true, get: function get() { return _interopRequireDefault(_tag)['default']; } }); var _timePicker = require('./time-picker'); Object.defineProperty(exports, 'TimePicker', { enumerable: true, get: function get() { return _interopRequireDefault(_timePicker)['default']; } }); var _timeline = require('./timeline'); Object.defineProperty(exports, 'Timeline', { enumerable: true, get: function get() { return _interopRequireDefault(_timeline)['default']; } }); var _tooltip = require('./tooltip'); Object.defineProperty(exports, 'Tooltip', { enumerable: true, get: function get() { return _interopRequireDefault(_tooltip)['default']; } }); var _mention = require('./mention'); Object.defineProperty(exports, 'Mention', { enumerable: true, get: function get() { return _interopRequireDefault(_mention)['default']; } }); var _upload = require('./upload'); Object.defineProperty(exports, 'Upload', { enumerable: true, get: function get() { return _interopRequireDefault(_upload)['default']; } }); var _version = require('./version'); Object.defineProperty(exports, 'version', { enumerable: true, get: function get() { return _interopRequireDefault(_version)['default']; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/// <reference path="../../scripts/typings/processing.d.ts" /> /* tslint:disable: no-unused-variable */ /* tslint:disable: comment-format */ var NOC_I_06_a; (function (NOC_I_06_a) { 'use strict'; var Walker = (function () { function Walker(p) { this.p = p; this.pos = new this.p.PVector(this.p.width / 2, this.p.height / 2); this.nOff = new this.p.PVector(this.p.random(0), this.p.random(10000)); } Walker.prototype.display = function () { this.p.strokeWeight(2); this.p.fill(51); this.p.stroke(0); this.p.ellipse(this.pos.x, this.pos.y, 48, 48); }; Walker.prototype.step = function () { this.pos.x = this.p.map(this.p.noise(this.nOff.x), 0, 1, 0, this.p.width); this.pos.y = this.p.map(this.p.noise(this.nOff.y), 0, 1, 0, this.p.height); this.nOff.add(0.01, 0.01, 0); }; return Walker; })(); NOC_I_06_a.sketch = function (p) { var walker; p.setup = function () { p.size(640, 360); walker = new Walker(p); p.background(255); }; p.draw = function () { walker.step(); walker.display(); }; }; })(NOC_I_06_a || (NOC_I_06_a = {})); var canvas = document.getElementById('canvas1'); var processingInstance = new Processing(canvas, NOC_I_06_a.sketch); //# sourceMappingURL=Sketch.js.map
var path = require('path'); var webpack = require('webpack'); module.exports = { context: __dirname, entry: { App: './elm/App', }, output: { path: path.resolve('../elvanto_sync/static/js/'), filename: '[name].js', }, resolve: { extensions: ['.js'], }, plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true, debug: false, }), ], module: { loaders: [ { test: /\.elm$/, exclude: [/elm-stuff/, /node_modules/], loader: 'elm-webpack-loader', }, ], }, watchOptions: { poll: 500, }, };
const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); var PACKAGE = require('./package.json'); const webpackConfig = { output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') }, devtool: 'source-map', module: { rules: [ { test: /\.js$/, enforce: 'pre', loader: 'standard-loader', options: { typeCheck: true, emitErrors: true } }, { test: /\.ts$/, loader: 'ts-loader' }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader", query: { name: '[name].[ext]', outputPath: 'images/' } }, { test: require.resolve('jquery'), use: [{ loader: 'expose-loader', options: '$' }] } ] }, resolve: { modules: [ path.resolve('./src'), path.resolve('./node_modules') ], extensions: ['.js', '.ts', '.json'] }, node: { __dirname: false } } module.exports = [ Object.assign( { target: 'electron-main', entry: { main: './src/core/main.ts' }, plugins: [ new ExtractTextPlugin('styles.css'), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }) ] }, webpackConfig), Object.assign( { target: 'electron-renderer', entry: { renderer: './src/core/renderer.ts' }, plugins: [ new ExtractTextPlugin('styles.css'), new HtmlWebpackPlugin({ title: PACKAGE.full_name + ' - ' + PACKAGE.version }) ] }, webpackConfig) ]
const fs = require('fs'); const path = require('path'); const solution = fs.readFileSync(path.join(__dirname, 'input'), 'utf-8') .split('\n') .filter(line => line.length > 0) .map(line => { return line.split('-'); }) .map(line => { const tmp = line[line.length - 1].split('['); const sector = parseInt(tmp[0]); const checksum = tmp[1].slice(0, -1); const codeString = line.slice(0, -1).join(''); let code = {}; for (var i = 0; i < codeString.length; i++) { code[codeString[i]] = code[codeString[i]] === undefined ? 1 : code[codeString[i]] + 1; } code = Object.keys(code) .sort((a,b) => { if ((code[a] - code[b]) == 0) { return a > b ? 1 : -1; } else { return -1 * (code[a] - code[b]); } }); code = code[0] + code[1] + code[2] + code[3] + code[4]; return { sector, checksum, code, codeString} }) .filter(line => line.checksum == line.code) .map(room => { const abc = "abcdefghijklmnopqrstuvwxyz"; const decryptedCode = room.codeString .split('') .map(char => { let v = abc.indexOf(char); return abc[(v + room.sector) % 26]; }) .join(''); return { decryptedCode, sector: room.sector } }) .filter(room => room.decryptedCode.match(/north|pole/i)); console.log(solution);
var config = require('../config'); var fs = require('fs') , path = require('path') , Sequelize = require('sequelize') , lodash = require('lodash') , db = {}; var sequelize = new Sequelize(config.values.dbname, config.values.dbuser, config.values.dbpasswd, { dialect: 'postgres' }); fs .readdirSync(__dirname) .filter(function (file) { return ((file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) == '.js')) }) .forEach(function (file) { var model = sequelize.import(path.join(__dirname, file)) db[model.name] = model }); Object.keys(db).forEach(function (modelName) { if (db[modelName].options.hasOwnProperty('associate')) { db[modelName].options.associate(db) } }); module.exports = lodash.extend({ sequelize: sequelize, Sequelize: Sequelize }, db);
define(['prototype/component'], function(Component) { 'use strict'; var Widget = function(callbacks){ if (callbacks) { if (typeof Object.observe == 'function') { Object.observe(this.model.data, function(changes){ changes.forEach(function(change){ if (change.type == 'update' && typeof callbacks.updates[change.name] == 'function'){ callbacks.updates[change.name].call(this, this.model.data[change.name]); } }, this); }.bind(this)); } if (typeof Array.observe == 'function') { Array.observe(this.model.data, function(changes){ changes.forEach(function(change){ if (change.type == 'splice' && change.addedCount > 0 && typeof callbacks.adds == 'function'){ callbacks.adds.call(this, change.object[change.index]); } if (change.type == 'splice' && change.removed.length > 0) { change.removed.forEach(function (item, i) { this.children[i].view.dom.detach(); }, this); } }, this); }.bind(this)); } } }; Widget.prototype = Object.create(Component.prototype); return Widget; });
version https://git-lfs.github.com/spec/v1 oid sha256:6d8304df9eb34bb2cc6aae217724051890887b1273ec6a52d987aca26985a3a0 size 657
var Type = require("@kaoscript/runtime").Type; module.exports = function() { var __ks_RegExp = {}; function foobar(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } else if(!Type.isString(x)) { throw new TypeError("'x' is not of type 'String'"); } } const regex = /foo/; let match = regex.exec("foobar"); if(Type.isValue(match)) { if(Type.isValue(match[0])) { foobar(match[0]); } } };
'use strict'; /** * @ngdoc function * @name pixwallApp.controller:MainCtrl * @description * # MainCtrl * Controller of the pixwallApp */ angular.module('pixwallApp') .controller('MainCtrl', function ($scope,$timeout,$route,$location,$routeParams) { $scope.mouse; $scope.presetColors=['#FFC95B','#62A2FF','#8668FF','#FFEE6F','#E88853','#FF5B5E','#D65FE8','#59E8E0','#62FF89','#AEE865']; $scope.selectedCategoryIndex = 0; $scope.categories=[{color: $scope.presetColors[0],name:""},{color: $scope.presetColors[1],name:""},{color: $scope.presetColors[2],name:""}]; $scope.currentLabel; var location = $location; $scope.mapName = "My new map"; $scope.shareURL=window.location.href; //FORMAT: /* [ {"area":{"category":"1","path":"M 10 10 L 20 20","color":"#62A2FF"}}, {"text":{"label":"Hipster land","position":{"x":12,"y":45}}, {"pin":{"position":{"x":12,"y":45}}} ] */ $scope.mapData=[]; var mapContainer,map; var camera, scene, renderer,zoomFactor = 1; var objects; var currentBubble,currentArea; var raycaster = new THREE.Raycaster(); var mouse2D = new THREE.Vector2(); var currentArea,currentColor; //INIT PARSE Parse.initialize("jWmKfNZKKvQBj3wqu6a5jV4hhrUlWBW6guUGfieT", "oCl7Zy22n7HyCtBooJhQ7aLNMihz6dJTpBcz7XiZ"); var MapData = Parse.Object.extend("MapData"); var parseMapData; //HACK TO NOT RELOAD PAGE ON URL CHANGE var lastRoute = $route.current; $scope.$on('$locationChangeSuccess', function(event) { if($route.current.$$route.controller === 'MainCtrl'){ // Will not load only if my view use the same controller $route.current = lastRoute; } }); //UPDATE MAP NAME ON PARSE $scope.$watch('mapName',function(){ if(parseMapData){ parseMapData.set("name",$scope.mapName); parseMapData.save(); } }); //UPDATE MAP NAME ON PARSE $scope.onChangeCategory = function(e){ console.log("save"); if(parseMapData){ parseMapData.remove("category"); parseMapData.save(null,{ success: function(mapData) { for(var i=0;i<$scope.categories.length;i++){ if($scope.categories[i].name!=''){ var category = {"index":i,"name":$scope.categories[i].name,"color":$scope.categories[i].color}; console.log(category); parseMapData.addUnique("category",category); } } parseMapData.save(null); } }); } }; $scope.onSubmitCategory = function (e){ //NEW CATEGORY var newCategory={color: $scope.presetColors[$scope.categories.length],name:$scope.newCategoryName}; $scope.categories.push(newCategory); //SELECT NEW CATEGORY: $scope.selectedCategoryIndex=$scope.categories.length-1; $scope.onChangeCategory(); } $scope.onSubmitNewMap = function(e){ //REMOVE ALL PREVIOUS STUFF var objectsToRemove = [] try {scene.traverse (function (object) { //console.log(object); if (object instanceof THREE.CSS3DObject) { //REMOVE EVERYTHING EXEPT MAP if (object.element.name == 'map' ){ }else { console.log("remove object:"+object.element.name); objectsToRemove.push(object); } } }); } catch(error){ console.log(error); } for(var i=objectsToRemove.length;i>=0;i--){ scene.remove(objectsToRemove[i]); } //CREATE NEW MAP parseMapData = new MapData(); parseMapData.save(null, { success: function(mapData) { //CHANGE URL LOCATION console.log('New object created with objectId: ' + mapData.id); location.path("/map/"+mapData.id); $scope.$apply(); $scope.shareURL=window.location.href; }, error: function(mapData, error) { console.log("Sorry buddy. Couldn't save your map " + error.message); } }); //renderer.deallocateObject( obj ); } ///IF WE HAVE A MAP ID //// console.log("PATH : "+$location.path()+" param: "+ $routeParams.mapId); console.log($routeParams); if($routeParams.mapId){ var query = new Parse.Query(MapData); query.get($routeParams.mapId, { success: function(mapData) { // The object was retrieved successfully. parseMapData = mapData; //console.log(parseMapData.get("area")); ////////////////////// /////////AREAS///////// /////////////////////// var areaMapData = parseMapData.get("area"); for(var i in areaMapData){ var newArea = createArea(areaMapData[i]["color"]); //newArea.setAttribute("path", ); newArea.firstChild.firstChild.setAttribute("d", areaMapData[i]["path"]); } ////////////////////// /////////PINS///////// /////////////////////// var pinMapData = parseMapData.get("pin"); for(var i in pinMapData){ var newPin = createPin(pinMapData[i]["position"].x,pinMapData[i]["position"].y); } ////////////////////// /////////LABELS///////// /////////////////////// var labelMapData = parseMapData.get("label"); for(var i in labelMapData){ var newLabel = createLabel(labelMapData[i]["position"].x,labelMapData[i]["position"].y,labelMapData[i]["text"]); } //////////// MAP NAME ////////// $scope.mapName = parseMapData.get("name")?parseMapData.get("name"):"New Map"; console.log(" MAP NAME ="+$scope.mapName); //CATEGORIES if(parseMapData.get("category")){ var categoriesMapData = parseMapData.get("category"); $scope.categories = []; for(var i in categoriesMapData){ $scope.categories.push({"name":categoriesMapData[i].name,"color":categoriesMapData[i].color}); } } $scope.$apply(); }, error: function(object, error) { // The object was not retrieved successfully. // error is a Parse.Error with an error code and message. } }); }else { parseMapData = new MapData(); parseMapData.save(null, { success: function(mapData) { //CHANGE URL LOCATION console.log('New object created with objectId: ' + mapData.id); location.path("/map/"+mapData.id); $scope.$apply(); $scope.shareURL=window.location.href; }, error: function(mapData, error) { console.log("Sorry buddy. Couldn't save your map " + error.message); } }); } function saveData(){ //SAVE MAP parseMapData.save(null, { success: function(mapData) { // Execute any logic that should take place after the object is saved. console.log('Save Map with objectId: ' + mapData.id); }, error: function(mapData, error) { console.log("Sorry buddy. Couldn't save your map " + error.message); } }); } init(); animate(); function init() { console.log("INIT"); //INIT 3D camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 15000 ); camera.position.z = 2000; scene = new THREE.Scene(); scene.autoUpdate = false; renderer = new THREE.CSS3DRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.domElement.style.position = 'absolute'; var i, j; var currentPathValues, currentPathPoints =[] ; //CREATE MAP mapContainer = document.getElementById( 'mapContainer' ); /*map = document.createElement( 'img' ); map.src="images/map4000px.jpg"; map.name="map"; map.style.position = "absolute"; var object = new THREE.CSS3DObject( map ); scene.add( object ); map.object=object; mapContainer.appendChild( renderer.domElement );*/ map = document.createElement( 'iframe' ); map.src="https://a.tiles.mapbox.com/v4/peutichat.1ebac5f0/page.html?access_token=pk.eyJ1IjoicGV1dGljaGF0IiwiYSI6ImctaW8xNEEifQ.p3JWkuUUcrfLHErAbw0mSQ#15/51.5128/-0.1255"; map.name="map"; map.style.position = "absolute"; map.width="4000"; map.height="3000"; map.style.pointerEvents ="none"; var object = new THREE.CSS3DObject( map ); scene.add( object ); map.object=object; mapContainer.appendChild( renderer.domElement ); //<iframe width='100%' height='500px' frameBorder='0' src='https://a.tiles.mapbox.com/v4/rma.d1ede389/attribution.html?access_token=pk.eyJ1Ijoicm1hIiwiYSI6IlBmeG5LajgifQ.Wy2W04j0Hn69yf0YeZD6UA'></iframe> //EVENTS window.addEventListener( 'resize', onWindowResize, false ); mapContainer.addEventListener( 'mousedown', onMouseDown, false ); mapContainer.addEventListener( 'ondblclick', onDbleClick, false ); //document.addEventListener("keydown", onKeyPressInput); window.addEventListener( 'mousemove', onMouseMove, false ); //ADD DELETE HERE function onDbleClick(e){ console.log("ondoubleClick"); //CALCULATE 2D POSITION FROM 3D PLANE var pos = calculate2DPosition(e); currentColor = $scope.categories[$scope.selectedCategoryIndex].color; //CREATE NEW PIN var newPin = createPin(pos.x,pos.y); var newPinData = {"position":pos}; newPin.data = newPinData; parseMapData.addUnique("pin",(newPinData)); }; function onMouseDown(e){ //CALCULATE 2D POSITION FROM 3D PLANE var pos = calculate2DPosition(e); currentColor = $scope.categories[$scope.selectedCategoryIndex].color; //RESET AREA: currentArea = null; //REINIT LABEL //$scope.currentLabel = null; window.addEventListener( 'mousemove', onMouseDownMove, false ); window.addEventListener( 'mouseup', onMouseUp, false ); }; function onMouseDownMove(e){ e.preventDefault(); console.log("on mouse move"); //CREATE AN AREA IF WE START TO MOVE if(currentArea==null){ currentArea = createArea(currentColor); var newAreaData = {"color":currentColor,"position":{"x":"0","y":"0"}}; currentArea.data = newAreaData; parseMapData.addUnique("area",(newAreaData)); }else { //CALCULATE 2D POSITION FROM 3D PLANE var pos = calculate2DPosition(e); var currentPathString = addAreaPoint(currentArea,pos); currentArea.data["path"] = currentPathString; } }; function onMouseUp(e){ var pos = calculate2DPosition(e); //CREATE PIN IF NO AREA if(currentArea!=null) saveData(); window.removeEventListener( 'mousemove', onMouseDownMove ); window.removeEventListener( 'mouseup', onMouseUp ); } function onMouseMove( e){ $scope.mouse = calculate2DPosition(e); } /* function onKeyPressInput(e){ if( $scope.currentLabel==null){ //DON'T DO THAT IF WE'RE ON A TEXT INPUT // if(e.target.tagName=="INPUT")return; $scope.currentLabel = createLabel($scope.mouse.x,$scope.mouse.y,String.fromCharCode(e.charcode)); //CREATE NEW PARSE LABEL DATA var newLabelData = {"position":$scope.mouse,"text":$scope.currentLabel.value}; parseMapData.addUnique("label",newLabelData); $scope.currentLabel.data = newLabelData; }else if(e.keyCode == "13"){ console.log("save TEXT : "+$scope.currentLabel.value); //SAVE DATA saveData(); //IF PRESS ENTER REMOVE FOCUS console.log('pressed enter'); if($scope.currentLabel)$scope.currentLabel.blur(); $scope.currentLabel = null; render(); }else{ console.log("save new field:"+$scope.currentLabel.value); $scope.currentLabel.data.text = $scope.currentLabel.value; saveData(); } } */ } $(window).on('wheel', function(e){ //console.log('wheeeeee'); var eo = e.originalEvent; //ZOOM/PINCH if (eo.ctrlKey) { eo.preventDefault(); eo.stopImmediatePropagation(); if(!currentBubble){ console.log(0.000001*eo.wheelDeltaY/120); console.log(camera.position.z); // perform desired zoom action here camera.position.z = camera.position.z*(1 -0.05*(eo.wheelDeltaY)/120); //console.log(camera.position.z); //MAX if(camera.position.z<10){ camera.position.z =10; } if(camera.position.z>4000){ camera.position.z =4000; } }else { //console.log(currentBubble); currentBubble.scale.x += eo.wheelDeltaY* 0.0002; currentBubble.scale.y += eo.wheelDeltaY* 0.0002; //currentBubble. if(currentBubble.scale.x<0.1){ currentBubble.scale.x = 0.1; currentBubble.scale.y = 0.1; } } }else { //RESET BUBBLE currentBubble=null; //REINIT LABEL // if($scope.currentLabel)$scope.currentLabel.blur(); // $scope.currentLabel = null; //PANNING if(Math.abs(eo.wheelDeltaY) < 10 && Math.abs(eo.wheelDeltaX) > 2){ e.preventDefault(); if(eo.wheelDeltaX < -100 && !scope.item.swipedLeft){ // swipe left camera.position.x += delta* 10*camera.position.z/1000; } if(eo.wheelDeltaX > 100 && scope.item.swipedLeft){ // swipe right } camera.position.x -= eo.wheelDeltaX* 1*camera.position.z/1000; camera.position.y += eo.wheelDeltaY* 1*camera.position.z/1000; }else { camera.position.x -= eo.wheelDeltaX* 1*camera.position.z/1000; camera.position.y += eo.wheelDeltaY* 1*camera.position.z/1000; } } }); function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } function animate() { requestAnimationFrame( animate ); render(); } function render() { // update the picking ray with the camera and mouse position raycaster.setFromCamera( mouse2D, camera ); // calculate objects intersecting the picking ray var intersects = raycaster.intersectObjects( scene.children ); scene.updateMatrixWorld(); scene.traverse( function ( object ) { if ( object instanceof THREE.LOD ) { object.update( camera ); } } ); renderer.render( scene, camera ); } ///////////// CREATE OBJECTS ///////////// function createLabel(x,y,text){ console.log("create label "+x+" "+y); var newLabel = document.createElement( 'input' ); newLabel.type="text"; newLabel.value = text; newLabel.name="label"; newLabel.className = 'textLabel'; var object = new THREE.CSS3DObject( newLabel ); scene.add( object ); //Render here so we can focus render(); newLabel.focus(); object.position.x = x; object.position.y = y; object.position.z = 100; return newLabel; } function createPin(x,y){ console.log("create Pin "+x+" "+y); var newPin = document.createElement( 'img' ); newPin.setAttribute("src", "images/redPointer.png"); newPin.setAttribute("width", 50); newPin.name="area"; var object = new THREE.CSS3DObject( newPin ); scene.add( object ); object.position.x = x; object.position.y = y+35; object.position.z = 10; return newPin; } function createArea(color){ //CREATE NEW AREA WITH FIRST PRESET COLOR var newArea = document.createElement( 'div' ); newArea.innerHTML='<svg width="'+map.width+'" height="'+map.height+'"><path fill="'+color+'" /></svg>'; newArea.className = 'area'; newArea.name="area"; //INIT ARRAY OF POINTS newArea.points = []; var object = new THREE.CSS3DObject( newArea ); scene.add( object ); object.position.x = 0; object.position.y = 0; object.position.z = 0.1; return newArea; } function createBubble(x,y,color){ console.log("create bubble "+x+" "+y); var newBubble = document.createElement( 'div' ); newBubble.innerHTML='<svg><circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" fill="'+color+'" /></svg>'; newBubble.className = 'bubble'; var object = new THREE.CSS3DObject( newBubble ); scene.add( object ); object.position.x = x; object.position.y = y; object.position.z = 1; currentBubble = object; } function addAreaPoint(area,point){ //console.log(pos); area.points.push(point); var simplifiedPoints = simplify(area.points, 4, false); return updateArea(area,simplifiedPoints); } function updateArea(area,points){ //RECALCULATE PATH FOR SVG var currentPathString = []; for(var i=0;i<points.length;i++){ var currentPoint = points[i]; //FIRST TIME WE MOVE THE PATH TO POSITION if(i==0){ currentPathString = "M "+parseInt(map.width/2+currentPoint.x)+" "+parseInt(map.height/2-currentPoint.y)+" "; } currentPathString+="L "+parseInt(map.width/2+currentPoint.x)+" "+parseInt(map.height/2-currentPoint.y)+" "; } //CLOSE PATH currentPathString += "Z"; currentArea.firstChild.firstChild.setAttribute("d", currentPathString); return currentPathString; } //UTILS function calculate2DPosition(e){ var vector = new THREE.Vector3(); vector.set( ( e.clientX / window.innerWidth ) * 2 - 1, - ( e.clientY / window.innerHeight ) * 2 + 1, 0.5 ); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = - camera.position.z / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance ) ); return pos; } function getPosition(element) { var xPosition = 0; var yPosition = 0; while (element) { xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft); yPosition += (element.offsetTop - element.scrollTop + element.clientTop); element = element.offsetParent; } return { x: xPosition, y: yPosition }; } //CONNECT USER /*$scope.currentUser = Parse.User.current(); $scope.signUp = function(form) { var user = new Parse.User(); user.set("email", form.email); user.set("username", form.username); user.set("password", form.password); user.signUp(null, { success: function(user) { $scope.currentUser = user; $scope.$apply(); // Notify AngularJS to sync currentUser }, error: function(user, error) { alert("Unable to sign up: " + error.code + " " + error.message); } }); }; $scope.logOut = function(form) { Parse.User.logOut(); $scope.currentUser = null; };*/ /////IMAGE UPLOAD STUFF /* var holder = document.getElementById('holder') holder.ondragover = function () { this.className = 'hover'; return false; }; holder.ondragend = function () { this.className = ''; return false; }; holder.ondrop = function (e) { e.preventDefault(); var file = e.dataTransfer.files[0], reader = new FileReader(); reader.onload = function (event) { console.log(event.target); holder.style.background = 'url(' + event.target.result + ') no-repeat center'; }; console.log(file); reader.readAsDataURL(file); return false; }; $scope.onChangeFile = function(){ console.log("change file"); var fileUploadControl = $("#profilePhotoFileUpload")[0]; console.log(fileUploadControl.files); if (fileUploadControl.files.length > 0) { var file = fileUploadControl.files[0]; //var name = "photo.jpg"; } var fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.onload = function(e) { $timeout(function() { $scope.fileDataURL = e.target.result; console.log($scope.fileDataURL); $scope.$apply(); }); } $scope.file = file; } */ }); angular.module('pixwallApp').directive('ngEnter', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if(event.which === 13) { scope.$apply(function (){ scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; });
import React, { Component } from 'react'; import { ActionHome, HardwareKeyboardArrowRight } from 'material-ui/svg-icons'; import { Subheader, IconButton } from 'material-ui'; import { Link } from 'react-router-dom'; import { compose, graphql } from 'react-apollo'; import { mutations, queries } from '../../helpers'; import Form from '../Form'; import { withRouter } from 'react-router'; import { alertOptions, MyFaCheck } from 'theme/alert'; import AlertContainer from 'react-alert'; class Index extends Component { constructor() { super(); this.handleAdd = this.handleAdd.bind(this); } showAlertSuccess = () => { this.msg.success('Saved!', { type: 'success', icon: <MyFaCheck />, onClose: () => { this.props.history.replace('/conference/info'); }, }); }; async handleAdd(values) { try { await this.props.INSERT_COORGANIZER({ variables: { address: '', id: this.props.coOrganizerId, name: values.coOrganizerName, email: values.coOrganizerEmail, website: values.coOrganizerWebsite, phone: values.coOrganizerPhone, }, refetchQueries: [ { query: queries.GET_CURRENT_CONFERENCE, }, ], }); this.showAlertSuccess(); } catch (error) { throw console.log(error); } } render() { return ( <div className="conference"> <Subheader className="subheader"> {localStorage.getItem('conferenceTitle')} </Subheader> <div className="page-breadcrumb d-flex"> <Link className="d-flex" to="/"> <IconButton> <ActionHome /> </IconButton> <span>Dashboard</span> </Link> <IconButton> <HardwareKeyboardArrowRight /> </IconButton> <Link to="/conference/info"> <span>Conference Information</span> </Link> <IconButton> <HardwareKeyboardArrowRight /> </IconButton> <span>Co-Organizer Management</span> </div> <div className="dashboard content d-flex justify-content-center"> <Form onSubmit={this.handleAdd} /> </div> <AlertContainer ref={a => (this.msg = a)} {...alertOptions} /> </div> ); } } export default compose( withRouter, graphql(mutations.INSERT_COORGANIZER, { name: 'INSERT_COORGANIZER', }), )(Index);
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var http = require('http'); var env = require('node-env-file'); var logging = require('winston'); var routes = require('./routes/index'); var users = require('./routes/users'); var twitter = require('./routes/twitter'); var app = express(); // Load env variables if (!process.env.TWITTER_CONSUMER_KEY) { var fs = require('fs'); var envfile = path.join(__dirname, '.env'); fs.exists(envfile, function(exists) { if (exists) { env(envfile); } }); } // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.use('/api/twitter', twitter); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); var ENV = process.env.ENV || 'development'; var PORT = process.env.PORT || 7000; var server = app.listen(PORT, function() { var host = server.address().address; var port = server.address().port; logging.info('[app.js] Server listening at http://%s:%s', host, port); });
/** * @file [Please Input File Description] * @author wangmin(wangmin02@baidu.com) */ define( function ( require ) { // require template //require( 'er/tpl!./stepEnterprise.tpl.html' ); require( 'tpl!./stepEnterprise.tpl.html' ); //var UIView = require( 'ef/UIView' ); var FormView = require( 'ecma/mvc/FormView' ); var sysInfo = require('ecma/system/constants'); var select = require('esui/Select'); var calendar = require('esui/Calendar'); var config = require('../../config'); var date = require('esui/lib/date'); var moment = require('moment'); var dialog = require('esui/Dialog'); var locator = require('er/locator'); /** * [Please Input View Description] * * @constructor */ function ValidationCreateStepEnterpriseStepEnterpriseView() { FormView.apply( this, arguments ); } ValidationCreateStepEnterpriseStepEnterpriseView.prototype = { template: 'TPL_validation_create_stepenterprise_stepenterprise', uiProperties: { uploader: { text: '选择文件', action: config.uploadUrl, name: 'filedata', accept: 'image/*' }, dateEnd: { } }, uiEvents: { uploader: { complete: function(e) { var previewUrl = e.target.fileInfo.url || e.target.fileInfo.previewUrl; this.model.set('previewUrl', previewUrl); // var previewLink = this.get('previewLink'); // previewLink.main.href = previewUrl; }, fail: function() { dialog.alert({ 'title' : '提示', 'content' : '上传失败' }); } }, dateEnd : { 'change': function () { var calendar = this.get('dateEnd'); var date = calendar.rawValue; this.checkDateEnd(calendar); this.model.set('dateEnd', moment(date).format('YYYY-MM-DD'), {silent:true}); } }, enterpriseType: { 'change': function () { var label = this.get('qualiLbl'); var typeMap = { 'MAINLAND' : '企业法人营业执照', 'HK_EP' : '香港商业登记证', 'MAC_EP' : '澳门商业登记证', 'TW_EP' : '台湾营业执照', 'FOREIGN_EP' : '国外同等效力主体资质' }; var type = this.get('enterpriseType').getValue(); label.setText(typeMap[type]); } }, linkIndustry: { 'click': function (e) { this.controllTrackerRedirect(e); } }, linkValidate: { 'click': function(e) { this.controllTrackerRedirect(e); } }, linkPreview: { 'click': function(e) { this.controllTrackerRedirect(e); } } }, controllTrackerRedirect: function (e) { var linkId = e.target.id; var linkMap = { 'linkIndustry' : '/validation/create/stepIndustry', 'linkValidate' : '/validation/create/stepValidate', 'linkPreview' : '/validation/check' }; var redirectUrl = linkMap[linkId]; if (this.getQuery()) { var query = this.getQuery(); locator.redirect(redirectUrl + '~' + query); } else { dialog.alert({ 'title': '系统提示', 'content': '请先完成企业资质信息填写。' }); } }, getQuery: function () { var query = this.model.get('url').getSearch(); return query; }, checkDateEnd: function (calendar) { var unsafeEnd = new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000); if (calendar.rawValue.getTime() <= unsafeEnd.getTime()) { dialog.alert({ 'title' : '温馨提示', 'content' : '失效日期距今不足一个月,请确认尽快更新有效期', 'skin' : 'alert' }); } } }; ValidationCreateStepEnterpriseStepEnterpriseView.prototype.enterDocument = function() { FormView.prototype.enterDocument.apply(this, arguments); var calendar = this.get('dateEnd'); var today = new Date(); //时间控件的开始日期 var begin = new Date(today.getTime() + 9 * 24 * 60 * 60 * 1000); //时间控件的结束默认选中日期 var defaultCreateTime = new Date(today.getTime() + 31 * 24 * 60 * 60 * 1000); var model = this.model; if (!model.get('id')) { //新建则填一个月后的时间 calendar.setRawValue(defaultCreateTime); model.set('dateEnd', moment(calendar.getRawValue()).format('YYYY-MM-DD')); } else { //编辑则填充用户之前填写的时间 calendar.setValue(model.get('defaultFormData').dateEnd); //给企业类型赋默认值 var etSlt = this.get('enterpriseType'); etSlt.setValue(model.get('defaultFormData').enterpriseType); var uploader = this.get('uploader'); //设置已上传文件 if (model.getDefaultData().previewUrl) { uploader.setRawValue({ previewUrl: model.getDefaultData().previewUrl }); } } //设置可选区间 calendar.setRange({ 'begin' : begin, 'end' : new Date(2046, 10, 4) }); }; require( 'er/util' ).inherits( ValidationCreateStepEnterpriseStepEnterpriseView, FormView ); return ValidationCreateStepEnterpriseStepEnterpriseView; } );
import Flight from 'flight'; const TodoList = Flight.eventType( function(todos) { this.todos = todos; } ); const TodoListRequest = Flight.eventType( function(state) { this.state = state; } ); const ActiveCount = Flight.eventType( function(activeCount) { this.activeCount = activeCount; } ); TodoList.Filter = Flight.eventOfType(TodoListRequest).alias('TodoList:Filter'); TodoList.Request = Flight.eventOfType(TodoListRequest).alias('TodoList:Request'); TodoList.Ready = Flight.eventOfType(TodoList).alias('TodoList:Ready'); TodoList.ActiveCount = Flight.eventOfType(ActiveCount).alias('TodoList:ActiveCount'); export default TodoList;
var superagent = require('superagent') , url = require('url'); module.exports = function (req, res) { // save last URL visited in case of any oauth redirects req.session.last_url_visited = url.format({ protocol: 'http', host: 'localhost:3000', pathname: req.path, query: req.query }); res.render('index'); };
/*! jQuery Validation Plugin - v1.14.0 - 6/30/2015 * http://jqueryvalidation.org/ * Copyright (c) 2015 Jörn Zaefferer; Licensed MIT */ !function(a){"function"==typeof define&&define.amd?define(["jquery","../jquery.validate.min"],a):a(jQuery)}(function(a){a.extend(a.validator.messages,{required:"必須填寫",remote:"請修正此欄位",email:"請輸入有效的電子郵件",url:"請輸入有效的網址",date:"請輸入有效的日期",dateISO:"請輸入有效的日期 (YYYY-MM-DD)",number:"請輸入正確的數值",digits:"只可輸入數字",creditcard:"請輸入有效的信用卡號碼",equalTo:"請重複輸入一次",extension:"請輸入有效的後綴",maxlength:a.validator.format("最多 {0} 個字"),minlength:a.validator.format("最少 {0} 個字"),rangelength:a.validator.format("請輸入長度為 {0} 至 {1} 之間的字串"),range:a.validator.format("請輸入 {0} 至 {1} 之間的數值"),max:a.validator.format("請輸入不大於 {0} 的數值"),min:a.validator.format("請輸入不小於 {0} 的數值")})});
import { moduleFor, test } from 'ember-qunit'; moduleFor('route:playlists/show', 'Unit | Route | playlists/show', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); test('it exists', function(assert) { let route = this.subject(); assert.ok(route); });
import m from "mithril"; import {ListingsModel} from '../models/listings.js'; import {ListingItem} from '../components/listingItem.js'; var UnApprovedListings = { oncreate:function(){ ListingsModel.GetUnApprovedListings() }, view:function(){ return ( <section> <div class="pa3 bg-white shadow-m2 tc"> <div> <h3>Unapproved Listings</h3> </div> </div> <section class="pv3 "> { ListingsModel.UnApprovedListings.map(function(listing, key){ return (<ListingItem listing={listing} key={key} />); }) } </section> </section> ) } } export default UnApprovedListings;
(function (context){ let Rocky = context.Rocky = context.Rocky || {}; Rocky.compile = require('./compiler-esnext'); Rocky.parse = require('./parser-esnext'); })(window);
class PrintManager { /** * * @param fileFullPath * - Full Path of File to be printed */ printFile(fileFullPath) { // Create Instance of open Window this.win = window.open(fileFullPath); // Running the print like this allows the close to happen after the print to handle asynchronous this.runPrint(() => { // Close Window this.win.close(); }); } runPrint(_closeWindow) { // Create Window that allows printing functionality this.win.print(); // Close the Window _closeWindow(); } } // Set Export Default export default PrintManager;
const db = require('./db'); const logger = require('../util/logger'); function getSingleSynonym(req, res, next) { logger.winston.info('synonym.getSingleSynonym'); db.get('select * from synonyms where synonym_id = ?', req.params.synonym_id, function(err, data) { if (err) { logger.winston.error(err); } else { res.status(200).json(data); } }); } function getBotSynonyms(req, res, next) { logger.winston.info('synonym.getBotSynonyms'); db.all('select * from synonyms where bot_id = ? order by synonym_id desc', req.params.bot_id, function(err, data) { if (err) { logger.winston.error(err); } else { res.status(200).json(data); } }); } function createBotSynonym(req, res, next) { logger.winston.info('synonym.createBotSynonym'); db.run('insert into synonyms(bot_id, synonym_reference, regex_pattern)' + 'values (?,?,?)', [req.body.bot_id, req.body.synonym_reference, req.body.regex_pattern], function(err) { if (err) { logger.winston.error("Error inserting a new record"); } else { db.get('SELECT last_insert_rowid()', function(err, data) { if (err) { res.status(500).json({ status: 'error', message: '' }); } else { res.status(200).json({ status: 'success', message: 'Inserted', synonym_id: data['last_insert_rowid()'] }); } }); } }); } function removeSynonym(req, res, next) { logger.winston.info('synonym.removeExpression'); db.run("delete from synonym_variants where synonym_id = ?", req.params.synonym_id); db.run('delete from synonyms where synonym_id = ?', req.params.synonym_id, function(err) { if (err) { logger.winston.error("Error removing the record"); } else { res.status(200).json({ status: 'success', message: 'Removed' }); } }); } module.exports = { getSingleSynonym, getBotSynonyms, createBotSynonym, removeSynonym};
import Console from "../../system/console.js" import { Port } from "../../system/port.js" Console.puts = function(str, no_newline) { Port.current_output.put_string(str + (no_newline ? "" : "\n")) }; Console.p = function() { [].slice.call(arguments).forEach(Port.current_output.put_string); }; export default Console;
module.exports = [ { room: 'Reimar Lüst Hall, 254', phone: '4100' }, { room: 'Reimar Lüst Hall, 247', phone: '4103' }, { room: 'Reimar Lüst Hall, 255', phone: '4111' }, { room: 'Reimar Lüst Hall, 222', phone: '4112' }, { room: 'Reimar Lüst Hall, 252', phone: '4116' }, { room: 'Reimar Lüst Hall, 202', phone: '4117' }, { room: 'Reimar Lüst Hall, 161', phone: '4119' }, { room: 'Reimar Lüst Hall, 147', phone: '4200' }, { room: 'Reimar Lüst Hall, 133', phone: '4201' }, { room: 'Reimar Lüst Hall, 149', phone: '4202' }, { room: 'Reimar Lüst Hall, 148', phone: '4204' }, { room: 'Reimar Lüst Hall, 104', phone: '4208' }, { room: 'Reimar Lüst Hall, 145', phone: '4210' }, { room: 'Reimar Lüst Hall, 118', phone: '4211' }, { room: 'Reimar Lüst Hall, 115a', phone: '4213' }, { room: 'Reimar Lüst Hall, 131', phone: '4214' }, { room: 'Reimar Lüst Hall, 117', phone: '4215' }, { room: 'Reimar Lüst Hall, 132', phone: '4216' }, { room: 'Reimar Lüst Hall, 114', phone: '4222' }, { room: 'Reimar Lüst Hall, 138', phone: '4225' }, { room: 'Reimar Lüst Hall, 101', phone: '4227' }, { room: 'Reimar Lüst Hall, 130', phone: '4231' }, { room: 'Reimar Lüst Hall, 129', phone: '4232' }, { room: 'Reimar Lüst Hall, 289', phone: '4310' }, { room: 'Reimar Lüst Hall, 288', phone: '4311' }, { room: 'Reimar Lüst Hall, 284', phone: '4312' }, { room: 'Reimar Lüst Hall, 291', phone: '4313' }, { room: 'Reimar Lüst Hall, 154', phone: '4317' }, { room: 'Reimar Lüst Hall, 153', phone: '4318' }, { room: 'Reimar Lüst Hall, 151', phone: '4320' }, { room: 'Reimar Lüst Hall, 181', phone: '4321' }, { room: 'Reimar Lüst Hall, 152', phone: '4322' }, { room: 'Reimar Lüst Hall, 127', phone: '4324' }, { room: 'Reimar Lüst Hall, 126', phone: '4325' }, { room: 'Reimar Lüst Hall, 125', phone: '4326' }, { room: 'Reimar Lüst Hall, 260', phone: '4330' }, { room: 'Reimar Lüst Hall, 263', phone: '4332' }, { room: 'Reimar Lüst Hall, 265', phone: '4338' }, { room: 'Reimar Lüst Hall, 281', phone: '4340' }, { room: 'Reimar Lüst Hall, 162', phone: '4341' }, { room: 'Reimar Lüst Hall, 283', phone: '4342' }, { room: 'Reimar Lüst Hall, 261', phone: '4343' }, { room: 'Reimar Lüst Hall, 264', phone: '4345' }, { room: 'Reimar Lüst Hall, 282', phone: '4346' }, { room: 'Reimar Lüst Hall, 236', phone: '4400' }, { room: 'Reimar Lüst Hall, 251', phone: '4401' }, { room: 'Reimar Lüst Hall, 250b', phone: '4404' }, { room: 'Reimar Lüst Hall, 250a', phone: '4405' }, { room: 'Reimar Lüst Hall, 257', phone: '4450' }, { room: 'Reimar Lüst Hall, 246', phone: '4455' }, { room: 'Reimar Lüst Hall, 258', phone: '4460' }, { room: 'Reimar Lüst Hall, 224', phone: '4500' }, { room: 'Reimar Lüst Hall, 156', phone: '4501' }, { room: 'Reimar Lüst Hall, 233', phone: '4503' }, { room: 'Reimar Lüst Hall, 206', phone: '4507' }, { room: 'Reimar Lüst Hall, 213', phone: '4508' }, { room: 'Reimar Lüst Hall, 225', phone: '4509' }, { room: 'Reimar Lüst Hall, 210', phone: '4511' }, { room: 'Reimar Lüst Hall, 204-205', phone: '4512' }, { room: 'Reimar Lüst Hall, 207', phone: '4515' }, { room: 'Reimar Lüst Hall, 232', phone: '4516' }, { room: 'Reimar Lüst Hall, 203', phone: '4518' }, { room: 'Reimar Lüst Hall, 109', phone: '4521' }, { room: 'Reimar Lüst Hall, 234', phone: '4522' }, { room: 'Reimar Lüst Hall, 107', phone: '4523' }, { room: 'Reimar Lüst Hall, 267', phone: '4529' }, { room: 'Reimar Lüst Hall, 212', phone: '4532' }, { room: 'Reimar Lüst Hall, 200', phone: '4537' }, { room: 'Reimar Lüst Hall, 204', phone: '4538' }, { room: 'Reimar Lüst Hall, 211', phone: '4541' }, { room: 'Reimar Lüst Hall, 161-162', phone: '4621' }, { room: 'Reimar Lüst Hall, 108', phone: '4526' }, { room: 'Reimar Lüst Hall, 214', phone: '3234' }, { room: 'Reimar Lüst Hall, 142', phone: '3481' }, { room: 'Reimar Lüst Hall, 179', phone: '3487' } ];
import expect from 'expect'; import React from 'react'; import { shallow } from 'enzyme'; import notfoundComponent from '../../../client/src/components/commons/notFound.component'; describe('<notfoundComponent />', () => { it('renders the correct elements', () => { const wrapper = mount( <notfoundComponent /> ); expect(wrapper.find('h1')).toExist(); expect(wrapper.find('p')).toExist(); expect(wrapper.find('Link')).toExist(); }); });
/** * Copyright (c) 2014 brian@bevey.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ (function (exports){ 'use strict'; exports.tcl = function (deviceId, markup, state, value, fragments) { var template = fragments.list, i = 0, tempMarkup = ''; if (value) { for (i in value) { if (value.hasOwnProperty(i)) { tempMarkup = tempMarkup + template.split('{{APP_ID}}').join(value[i].id); tempMarkup = tempMarkup.split('{{APP_IMG}}').join(value[i].cache); tempMarkup = tempMarkup.split('{{APP_NAME}}').join(value[i].name); } } } return markup.replace('{{TCL_DYNAMIC}}', tempMarkup); }; })(typeof exports === 'undefined' ? this.SB.spec.parsers : exports);
'use strict'; var hapi = require('hapi'); var minimist = require('minimist'); var _ = require('lodash'); var argv = minimist(process.argv.slice(2)); var server = new hapi.Server(); var connectionOptions = { port: argv['p'] || 3080 }; server.connection(connectionOptions); server.route({ method: '*', path: '/{path*}', handler: function(request, reply) { var body = JSON.stringify({ message: 'success', warning: null }); setTimeout(_.partial(reply, body), 1000); } }); server.start(function(err) { if (err) { console.error(err); } else { console.log(server.info.uri); } });
let dbus = require('dbus'); let bus = dbus.getBus('system'); let udev = require('udev'); let exec = require('child_process').exec; let monitor = udev.monitor(); let currentlyPlayingTrack = {}; let getUniqueTrackId = function (track) { return track.Title + '_' + track.Artist + '_' + track.Album; }; let getMacAddress = function () { return new Promise(function (fulfill, reject) { exec('hcitool con | grep SLAVE | grep -o -E "([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}"', function (err, stdout, stderr) { if (err) { reject(err); return; } fulfill(stdout.replace('\n', '')); }); }); }; let getBusInterface = function (macAddress) { return new Promise(function (fulfill, reject) { bus.getInterface('org.bluez', '/org/bluez/hci0/dev_' + macAddress.replace(/\:/g, '_') + '/player0', 'org.bluez.MediaPlayer1', (err, interface) => { if (err) { reject(err); return; } fulfill(interface); }); }); }; let setSocketListeners = function (interface) { let socket = require('socket.io-client')('http://localhost:3000'); setInterval(() => { interface.getProperties((err, data) => { if (err) { /* * For now we don't do anything with interface errors yet. If an error * occurs it's probably just not ready for getting the properties and it * will run a next time. */ return; } if (data.Track.Title && getUniqueTrackId(currentlyPlayingTrack) !== getUniqueTrackId(data.Track)) { currentlyPlayingTrack = data.Track; } let payload = { track: currentlyPlayingTrack, status: data.Status, position: data.Position }; socket.emit('broadcast', { eventName: 'mediaPlayerUpdate', payload: payload }); }); }, 500); socket.on('mediaEvent', (payload) => { switch (payload.type) { case 'playPause': if (payload.status === 'playing') { interface.Pause(); } else { interface.Play(); } break; case 'goToNext': interface.Next(); break; case 'goToPrevious': interface.Previous(); break; } }); }; let useDeviceForControls = function () { getMacAddress() .then(getBusInterface) .then(setSocketListeners) .catch((err) => { console.log('Error while setting the device for control use', err); }); } monitor.on('add', function (device) { if (device.SUBSYSTEM === 'bluetooth') { /* * For some reason hcitool does not receive the device as fast as udev does, for this reason * we currently use a timeout to ensure we can retrieve the MAC address. This is totally wonky * and error prone and should be fixed. * * TODO: find a better solution for checking the MAC address */ setTimeout(useDeviceForControls, 3000); } });
function login() { var div = document.getElementsByName("myusername")[0].value; var div2 =document.getElementsByName("mypassword")[0].value; var div3 =document.getElementById('menu_services_list'); var div4 =document.getElementById('error_login'); if(window.XMLHttpRequest) { xhr_object = new XMLHttpRequest(); //les autre navigateur } else if(window.ActiveXObject) { xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); //IE } else{ div.innerHTML = 'impossible , problèmes de navigateur'; } xhr_object.open("GET", "content/checklogin.php?user="+div+"&mdp="+div2 , false); xhr_object.send(null); if(xhr_object.readyState == 4) { if(xhr_object.responseText == "1") { div4.innerHTML = "<span style='color:red; font-size:12; font-weight:bold;'>Mot de passe ou identifiant incorrecte.</span>"; }else div3.innerHTML = xhr_object.responseText; } if(div3.innerHTML == "admin") window.location = "content/admin.php"; } function logout() { var div3 = document.getElementById('menu_services_list'); if(window.XMLHttpRequest) { xhr_object = new XMLHttpRequest(); //les autre navigateur x= new XMLHttpRequest(); } else if(window.ActiveXObject) { xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); //IE x= new ActiveXObject("Microsoft.XMLHTTP"); } else{ alert('impossible , problèmes de navigateur'); } xhr_object.open("GET", "content/logout.php" , false); xhr_object.send(null); window.location = "index.php"; }
'use strict'; const util = require('gulp-util'); module.exports = function (gulp) { gulp.task('default', ['clean'], function () { let taskList = []; taskList.push('copy:audio'); taskList.push('copy:fonts'); taskList.push('copy:images'); taskList.push('concat:internal'); taskList.push('concat:external'); taskList.push('concat:json'); taskList.push('sass'); taskList.push('assemble:all'); taskList.push('watch'); taskList.push('server'); gulp.start(taskList); }); }
/*! * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var arrify = require('arrify'); var common = require('@google-cloud/common'); var extend = require('extend'); var is = require('is'); /** * Get and set IAM policies for your Cloud Storage bucket. * * @see [Cloud Storage IAM Management](https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management) * @see [Granting, Changing, and Revoking Access](https://cloud.google.com/iam/docs/granting-changing-revoking-access) * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) * * @constructor Iam * @mixin * * @param {Bucket} bucket The parent instance. * @example * var storage = require('@google-cloud/storage')(); * var bucket = storage.bucket('my-bucket'); * // bucket.iam */ function Iam(bucket) { this.request_ = bucket.request.bind(bucket); this.resourceId_ = 'buckets/' + bucket.id; } /** * @typedef {array} GetPolicyResponse * @property {object} 0 The policy. * @property {object} 1 The full API response. */ /** * @callback GetPolicyCallback * @param {?Error} err Request error, if any. * @param {object} acl The policy. * @param {object} apiResponse The full API response. */ /** * Get the IAM policy. * * @param {GetPolicyCallback} [callback] Callback function. * @returns {Promise<GetPolicyResponse>} * * @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy} * * @example * var storage = require('@google-cloud/storage')(); * var bucket = storage.bucket('my-bucket'); * bucket.iam.getPolicy(function(err, policy, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * bucket.iam.getPolicy().then(function(data) { * var policy = data[0]; * var apiResponse = data[1]; * }); * * @example <caption>include:samples/iam.js</caption> * region_tag:view_bucket_iam_members * Example of retrieving a bucket's IAM policy: */ Iam.prototype.getPolicy = function(callback) { this.request_( { uri: '/iam', }, callback ); }; /** * @typedef {array} SetPolicyResponse * @property {object} 0 The policy. * @property {object} 1 The full API response. */ /** * @callback SetPolicyCallback * @param {?Error} err Request error, if any. * @param {object} acl The policy. * @param {object} apiResponse The full API response. */ /** * Set the IAM policy. * * @throws {Error} If no policy is provided. * * @param {object} policy The policy. * @param {array} policy.bindings Bindings associate members with roles. * @param {string} [policy.etag] Etags are used to perform a read-modify-write. * @param {SetPolicyCallback} callback Callback function. * @returns {Promise<SetPolicyResponse>} * * @see [Buckets: setIamPolicy API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy} * @see [IAM Roles](https://cloud.google.com/iam/docs/understanding-roles) * * @example * var storage = require('@google-cloud/storage')(); * var bucket = storage.bucket('my-bucket'); * * var myPolicy = { * bindings: [ * { * role: 'roles/storage.admin', * members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] * } * ] * }; * * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {}); * * //- * // If the callback is omitted, we'll return a Promise. * //- * bucket.iam.setPolicy(myPolicy).then(function(data) { * var policy = data[0]; * var apiResponse = data[1]; * }); * * @example <caption>include:samples/iam.js</caption> * region_tag:add_bucket_iam_member * Example of adding to a bucket's IAM policy: * * @example <caption>include:samples/iam.js</caption> * region_tag:remove_bucket_iam_member * Example of removing from a bucket's IAM policy: */ Iam.prototype.setPolicy = function(policy, callback) { if (!is.object(policy)) { throw new Error('A policy object is required.'); } this.request_( { method: 'PUT', uri: '/iam', json: extend( { resourceId: this.resourceId_, }, policy ), }, callback ); }; /** * @typedef {array} TestIamPermissionsResponse * @property {object[]} 0 A subset of permissions that the caller is allowed. * @property {object} 1 The full API response. */ /** * @callback TestIamPermissionsCallback * @param {?Error} err Request error, if any. * @param {object[]} acl A subset of permissions that the caller is allowed. * @param {object} apiResponse The full API response. */ /** * Test a set of permissions for a resource. * * @throws {Error} If permissions are not provided. * * @param {string|string[]} permissions - The permission(s) to test for. * @param {TestIamPermissionsCallback} [callback] Callback function. * @returns {Promise<TestIamPermissionsResponse>} * * @see [Buckets: testIamPermissions API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions} * * @example * var storage = require('@google-cloud/storage')(); * var bucket = storage.bucket('my-bucket'); * * //- * // Test a single permission. * //- * var test = 'storage.buckets.delete'; * * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) { * console.log(permissions); * // { * // "storage.buckets.delete": true * // } * }); * * //- * // Test several permissions at once. * //- * var tests = [ * 'storage.buckets.delete', * 'storage.buckets.get' * ]; * * bucket.iam.testPermissions(tests, function(err, permissions) { * console.log(permissions); * // { * // "storage.buckets.delete": false, * // "storage.buckets.get": true * // } * }); * * //- * // If the callback is omitted, we'll return a Promise. * //- * bucket.iam.testPermissions(test).then(function(data) { * var permissions = data[0]; * var apiResponse = data[1]; * }); */ Iam.prototype.testPermissions = function(permissions, callback) { if (!is.array(permissions) && !is.string(permissions)) { throw new Error('Permissions are required.'); } permissions = arrify(permissions); this.request_( { uri: '/iam/testPermissions', qs: { permissions: permissions, }, useQuerystring: true, }, function(err, resp) { if (err) { callback(err, null, resp); return; } var availablePermissions = arrify(resp.permissions); var permissionsHash = permissions.reduce(function(acc, permission) { acc[permission] = availablePermissions.indexOf(permission) > -1; return acc; }, {}); callback(null, permissionsHash, resp); } ); }; /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ common.util.promisifyAll(Iam); module.exports = Iam;
/** * create SET_COMMITS action * @param {String[]} commits - List of commit SHAs * @return {Object} - a SET_COMMITS action with an Immutable.List of SHAs */ export const setCommits = commits => ( { commits , type: 'SET_COMMITS' } )
var uuid = require('node-uuid'); var db=require("../core/db"); var self=require("./images"); var AWS=require("../core/S3-upload"); exports.getUserProfile=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var query="SELECT * from ImagePost i where i.user_id="+UserID+" order by currTime desc;"; console.log(query); db.executeSql(query,function(data,err){ if(err){ console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(data.rows) + "\n"); resp.end(); } }); }; exports.getUserFeed=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; db.executeSql("select * from ImagePost i where i.user_id="+UserID+" or exists( select 1 from Relationship r where r.follower="+UserID +" and r.follows=i.user_id) order by currTime desc;",function(data,err){ if(err){ console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(data.rows) + "\n"); resp.end(); } }); }; exports.getOtherUserProfile=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var OtherID= (req.body.OtherId).replace(/"/g,''); db.executeSql("select * from ImagePost i where i.user_id="+OtherID+" and exists( select 1 from Relationship r where r.follower="+UserID +" and r.follows=i.user_id) order by currTime desc;",function(data,err){ if(err){ console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(data.rows) + "\n"); resp.end(); } }) }; exports.likePost=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; console.log(UserID); var imgID= (req.body.post_id).replace(/"/g,''); console.log(imgID); var query="UPDATE ImagePost SET favorite_UserID = ltrim(favorite_UserID||':'||"+UserID+", ':'),favorite_count=favorite_count+1 where id="+Number(imgID); console.log(query); db.executeSql(query, function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.unlikePost=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; console.log(UserID); var imgID= (req.body.post_id).replace(/"/g,''); console.log("UPDATE ImagePost SET favorite_UserID=trim(both ':' from replace((':'||favorite_UserID||':'),':'||"+UserID+"||':',':')),favorite_count=favorite_count-1 where id="+Number(imgID)+" and (':'||favorite_UserID||':') LIKE '%'||"+UserID+"||'%'"); db.executeSql("UPDATE ImagePost SET favorite_UserID=trim(both ':' from replace((':'||favorite_UserID||':'),':'||"+UserID+"||':',':')),favorite_count=favorite_count-1 where id="+Number(imgID)+" and (':'||favorite_UserID||':') LIKE '%'||"+UserID+"||'%'", function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.uploadImage=function(myPath,req,resp){ var url=new AWS.AWSUpload(myPath, function(url,err){ if (err) { console.log(err); } else { console.log(url); var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; console.log(UserID); var lat=req.body.latitude.replace(/"/g,''); var lon=req.body.longitude.replace(/"/g,''); var description=(req.body.caption).replace(/"/g,'') var location="ST_GeomFromText('POINT("+lon+" "+lat+")',4326)"; var storyname=req.body.location.replace(/"/g,''); var query="INSERT INTO ImagePost(user_id,description,favorite_UserID,favorite_count,share_UserID,share_count,geoMapLocation,storyname,currTime,image) values ("+UserID+",'"+description+"','',0,'',0,"+location+",'"+storyname+"',CURRENT_TIMESTAMP,'"+url+"')"; console.log(query); db.executeSql(query, function(result,err) { if (err) { console.log(err); } else { console.log('row inserted ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }}); }; exports.searchByLocation=function(req,resp){ var radius=req.body.radius?req.body.radius:50;//in metres console.log(radius); var lat=req.body.latitude; var lon=req.body.longitude; var currGeom="ST_GeomFromText('POINT("+lon+" "+lat+")',4326)"; db.executeSql("select * from ImagePost i where ST_Distance("+currGeom+",geoMapLocation,true)<="+radius+" order by currTime desc;",function(data,err){ if(err){ console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(data.rows) + "\n"); resp.end(); } }) }; exports.followUser=function(req,resp){ var followerID= (req.body.user_id).replace(/"/g,''); var followerID= "'"+followerID.replace(/'/g,'')+"'"; var followsID= (req.body.OtherId).replace(/"/g,''); var followsID= "'"+followsID.replace(/'/g,'')+"'"; var query="WITH upsert AS(UPDATE Relationship SET friends='t' WHERE follower="+followsID+" AND follows="+followerID+" RETURNING friends) INSERT INTO Relationship (follower, follows, friends) SELECT "+followerID+","+followsID+",COALESCE(upsert.friends,foo.friends) from upsert RIGHT JOIN (select 'f'::boolean as friends) AS foo on true;" db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.unfollowUser=function(req,resp){ var followerID= (req.body.user_id).replace(/"/g,''); var followerID= "'"+followerID.replace(/'/g,'')+"'"; var followsID= (req.body.OtherId).replace(/"/g,''); var followsID= "'"+followsID.replace(/'/g,'')+"'"; var query="WITH upsert AS(delete from Relationship WHERE follower="+followerID+" AND follows="+followsID+" RETURNING *) UPDATE Relationship r SET friends='f' from upsert where upsert.friends='t'and r.follower=upsert.follows and r.follows=upsert.follower;" db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.sharePost=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); //var UserID= "'"+UserID.replace(/'/g,'')+"'"; var imgID= (req.body.post_id).replace(/"/g,''); var query="WITH upsert AS(UPDATE ImagePost SET share_UserID = ltrim(share_UserID||':'||'"+UserID+"', ':'),share_count=share_count+1 WHERE id="+imgID+" RETURNING *) INSERT INTO ImagePost (user_id,image,currTime,description,favorite_UserID,favorite_count,share_UserID,share_count,geoMapLocation) SELECT '"+UserID+"',image,CURRENT_TIMESTAMP,description,'',0,'',0,geoMapLocation from upsert;" console.log(query); db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.deletePost=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var imgID= (req.body.post_id).replace(/"/g,''); var query="delete from ImagePost where id="+imgID+" and user_id='"+UserID+"'"; console.log(query); db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { console.log('row updated ' + req.body.user_id); resp.writeHead(200,{"Content-Type":"application/json"}); resp.end(JSON.stringify({"status":"Done"})); }}); }; exports.blockPost=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var imgID= (req.body.post_id).replace(/"/g,''); var query="UPDATE Users SET blockedPosts=ltrim(blockedPosts||':'||"+imgID+", ':') WHERE user_id='"+UserID+"'"; db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { console.log('row inserted ' + req.body.user_id); self.getUserFeed(req,resp); }}); }; exports.collectedFeed=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var radius=req.body.radius?req.body.radius:50;//in metres var lat=req.body.latitude; var lon=req.body.longitude; var lastImgID=req.body.lastImgId?req.body.lastImgId:""; console.log("last"+lastImgID); var currGeom="ST_GeomFromText('POINT("+lon+" "+lat+")',4326)"; var query= "select B.id post_id,user_id,COALESCE(title,B.firstname||' '||lastname) title,COALESCE(storytype,'single') storytype,COALESCE(D.icon_url,B.icon_url) icon_url,COALESCE(ST_X(geomaplocation),location_long) location_long,COALESCE(ST_Y(geomaplocation),location_lat) location_lat,"+ "COALESCE(image_url,ARRAY[image]) image_url,favorite_count,share_count,(':'||favorite_UserID||':') LIKE '%'||"+UserID+"||'%' liked,description,title location_name,B.currTime "+ "from (SELECT storyname as title,avg(ST_X(geomaplocation)) AS location_long, avg(ST_Y(geomaplocation)) AS location_lat,(array_agg(image))[1] icon_url,array_agg(image) image_url, 'collected'::text storytype FROM "+ "(SELECT ROW_NUMBER() OVER (PARTITION BY storyname ORDER BY favorite_count desc) AS r,"+ "geomaplocation,image, storyname FROM "+ "ImagePost t where storyname IS NOT NULL and ST_Distance("+currGeom+",geoMapLocation,true)<="+radius+" ) x "+ "WHERE x.r <= 10 group by storyname) AS D FULL OUTER JOIN "+ "(select x.*,y.firstname,y.lastname,y.icon_url from ImagePost x,users y where x.user_id=y.user_id and storyname IS NULL and ST_Distance("+currGeom+",geoMapLocation,true)<="+radius; if(lastImgID.length>0) query=query+" and B.id<"+lastImgID; query=query+" order by currTime desc ) AS B ON D.title=B.storyname limit 10;"; console.log("query"+query); db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(result.rows) + "\n"); resp.end(); }}); }; exports.collectedFeed1=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var radius=req.body.radius?req.body.radius:1000000000; var lat=req.body.latitude; var lon=req.body.longitude; var latestTime=req.body.latestTime?req.body.latestTime.replace(/"/g,''):""; var currGeom="ST_GeomFromText('POINT("+lon+" "+lat+")',4326)"; var query= "select (S.combo).* from (SELECT CASE array_length((array_agg(image)),1) "+ "WHEN 1 THEN ((array_agg(id))[1],(array_agg(user_id))[1],(array_agg(firstname))[1]||' '||(array_agg(lastname))[1],'single',(array_agg(icon_url))[1],"+ "ST_X((array_agg(geomaplocation))[1]),ST_Y((array_agg(geomaplocation))[1]),"+ "(array_agg(image))[1],(array_agg(favorite_count))[1],(array_agg(share_count))[1],(':'||(array_agg(favorite_UserID))[1]||':') LIKE '%'||"+UserID+"||'%',"+ "(array_agg(description))[1],(array_agg(storyname))[1],(array_agg(currTime))[1])::feedType "+ "ELSE (null,null,storyname,'collected',(array_agg(image))[1],avg(ST_X(geomaplocation)),avg(ST_Y(geomaplocation)),"+ "array_agg(image),null,null,null,null,storyname,max(currTime))::feedType END AS combo FROM (SELECT ROW_NUMBER() OVER (PARTITION BY storyname ORDER BY favorite_count desc) AS r,"+ "id,u.user_id, currTime,description, favorite_userid, favorite_count, share_count,geomaplocation,image, storyname,firstname,lastname,icon_url "+ "FROM ImagePost t,Users u where t.user_id= u.user_id and ST_Distance("+currGeom+",geoMapLocation,true)<="+radius+" ) x "+ "WHERE x.r <= 10 group by storyname) S" if(latestTime.length>0) query=query+" where (S.combo).currTime::timestamp<'"+latestTime+"'::timestamp"; query=query+" order by(S.combo).currTime desc limit 10;"; console.log("query"+query); db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(result.rows) + "\n"); resp.end(); }}); }; exports.getStory=function(req,resp){ var UserID= (req.body.user_id).replace(/"/g,''); var UserID= "'"+UserID.replace(/'/g,'')+"'"; var radius=req.body.radius?req.body.radius:1000000000;//in metres var lat=req.body.latitude; var lon=req.body.longitude; var lastImgID=req.body.lastImgId?req.body.lastImgId:""; var story=(req.body.title).replace(/"/g,''); var currGeom="ST_GeomFromText('POINT("+lon+" "+lat+")',4326)"; var query= "select id post_id,x.user_id,firstname||' '||lastname title,'single' storytype,icon_url,ST_X(geomaplocation) location_long,ST_Y(geomaplocation) location_lat,"+ "array[image] image_url,favorite_count,share_count,(':'||favorite_UserID||':') LIKE '%'||"+UserID+"||'%' liked,description,storyname location_name,currTime::text "+ "from ImagePost x,users y where x.user_id=y.user_id and ST_Distance("+currGeom+",geoMapLocation,true)<="+radius+" and storyname='"+story+"'"; if(lastImgID.length>0) query=query+" and id<"+lastImgID; query=query+" order by currTime desc limit 10;"; console.log("query"+query); db.executeSql(query,function(result,err) { if (err) { console.log(err); } else { resp.writeHead(200,{"Content-Type":"application/json"}); resp.write(JSON.stringify(result.rows) + "\n"); resp.end(); }}); };
/*! jQuery UI - v1.10.3 - 2014-01-16 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.datepicker.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.tooltip.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.10.3", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.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 ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; }, 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; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.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() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use $.widget() extensions instead. 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 ) { var i, set = instance.plugins[ name ]; if ( !set || !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 ); } } } }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it 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; } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.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., width-unite-bgcgable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : 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 ); }; $.widget.extend = function( target ) { var input = 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 = 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 ( !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 || {} )._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 = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); 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._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 ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .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 ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { 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 ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "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 { // accept selectors, DOM elements 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 ); }, _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(); }); } }; }); })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.10.3", 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 ) { $(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; } // 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); }; $(document) .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) .bind("mouseup."+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // 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); } 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) { $(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); } 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); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, 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;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.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : 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] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? 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 ( !$.support.offsetFractions ) { 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; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); }( jQuery ) ); (function( $, undefined ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.10.3", 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" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._mouseInit(); }, _destroy: function() { this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; // 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; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth+"px", height: this.offsetHeight+"px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _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(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.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 }); //Generate the original position this.originalPosition = this.position = 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)); //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); } 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; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition(event); 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; } 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"; } 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 the original element is no longer in the DOM don't bother to continue (see #8269) if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) { return 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) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } 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; }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(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)); } if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } 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 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 //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.element.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.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 over, c, ce, o = this.options; 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; } over = c.css( "overflow" ) !== "hidden"; 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 ) , ( over ? 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, ( over ? 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.relative_container = c; }, _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; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; } 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() : 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.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod ) ) }; }, _generatePosition: function(event) { var containment, co, top, left, o = this.options, scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent, pageX = event.pageX, pageY = event.pageY; //Cache the scroll if (!this.offset.scroll) { this.offset.scroll = {top : scroll.scrollTop(), left : scroll.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 ( this.originalPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.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; } } 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() : 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.scrollParent.scrollLeft() : 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; }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call(this, type, [event, ui]); //The absolute position has to be recalculated after plugins if(type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } 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) { var inst = $(this).data("ui-draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, "ui-sortable"); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function(event, ui) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var inst = $(this).data("ui-draggable"), uiSortable = $.extend({}, ui, { item: inst.element }); $.each(inst.sortables, function() { if(this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if(this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if(inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function(event, ui) { var inst = $(this).data("ui-draggable"), that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if(this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function () { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if(innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if(!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if(this.instance.currentItem) { this.instance._mouseDrag(event); } } 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(this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if(this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function() { var t = $("body"), o = $(this).data("ui-draggable").options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function() { var o = $(this).data("ui-draggable").options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function() { var i = $(this).data("ui-draggable"); if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event ) { var i = $(this).data("ui-draggable"), o = i.options, scrolled = false; if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { if(!o.axis || o.axis !== "x") { if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if(!o.axis || o.axis !== "y") { if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].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() { var i = $(this).data("ui-draggable"), 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) { var ts, bs, ls, rs, l, r, t, b, i, first, inst = $(this).data("ui-draggable"), 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; r = l + inst.snapElements[i].width; t = inst.snapElements[i].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 - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.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 - inst.margins.top; } if(bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if(ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if(rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.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() { var min, o = this.data("ui-draggable").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) { var t = $(ui.helper), o = $(this).data("ui-draggable").options; if(t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function(event, ui) { var o = $(this).data("ui-draggable").options; if(o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); })(jQuery); (function( $, undefined ) { function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } $.widget("ui.droppable", { version: "1.10.3", 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 o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, _destroy: function() { var i = 0, drop = $.ui.ddmanager.droppables[this.options.scope]; for ( ; i < drop.length; i++ ) { if ( drop[i] === this ) { drop.splice(i, 1); } } 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); }; } $.Widget.prototype._setOption.apply(this, arguments); }, _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 = $.data(this, "ui-droppable"); 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) ) { 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(draggable, droppable, toleranceMode) { if (!droppable.offset) { return false; } var draggableLeft, draggableTop, x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, 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": draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left); draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top); return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, 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)) { 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), 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 $.data(this, "ui-droppable").options.scope === scope; }); if (parent.length) { parentInstance = $.data(parent[0], "ui-droppable"); 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 ); } } }; })(jQuery); (function( $, undefined ) { function num(v) { return parseInt(v, 10) || 0; } function isNumber(value) { return !isNaN(parseInt(value, 10)); } $.widget("ui.resizable", $.ui.mouse, { version: "1.10.3", 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 }, _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)) { //Create a wrapper element and set the wrapper to the new current internal element 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") }) ); //Overwrite the original this.element this.element = this.element.parent().data( "ui-resizable", this.element.data("ui-resizable") ); this.elementIsWrapper = true; //Move margins to the wrapper 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}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); // fix handlers offset 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>"); // Apply zIndex to all handles - see #7960 axis.css({ zIndex: o.zIndex }); //TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } //Insert into internal handles object and append to element 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.handles[i], this.element).show(); } //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... 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(); //Matching axis name 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); } //Axis, default = se that.axis = axis && axis[1] ? axis[1] : "se"; } }); //If we want to auto hide the elements 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(); } }); } //Initialize the mouse interaction 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, iniPos = this.element.position(), el = this.element; this.resizing = true; // bugfix for http://dev.jquery.com/ticket/1749 if ( (/absolute/).test( el.css("position") ) ) { el.css({ position: "absolute", top: el.css("top"), left: el.css("left") }); } else if (el.is(".ui-draggable")) { el.css({ position: "absolute", top: iniPos.top, left: iniPos.left }); } this._renderProxy(); curleft = num(this.helper.css("left")); curtop = num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio 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) { //Increase performance, avoid regex var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, prevTop = this.position.top, prevLeft = this.position.left, prevWidth = this.size.width, prevHeight = this.size.height, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; if (!trigger) { return false; } // Calculate the attrs that will be change data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); // plugins callbacks need to be called first this._propagate("resize", event); if (this.position.top !== prevTop) { props.top = this.position.top + "px"; } if (this.position.left !== prevLeft) { props.left = this.position.left + "px"; } if (this.size.width !== prevWidth) { props.width = this.size.width + "px"; } if (this.size.height !== prevHeight) { props.height = this.size.height + "px"; } el.css(props); if (!this._helper && this._proportionallyResizeElements.length) { this._proportionallyResize(); } // Call the user callback if the element was resized if ( ! $.isEmptyObject(props) ) { this._trigger("resize", event, this.ui()); } 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 && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 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; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { // We want to create an enclosing box whose aspect ration is the requested one // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension 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 (isNumber(data.left)) { this.position.left = data.left; } if (isNumber(data.top)) { this.position.top = data.top; } if (isNumber(data.height)) { this.size.height = data.height; } if (isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (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 = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = 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; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 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).data("ui-resizable"), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 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).data("ui-resizable"), 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 }; } // i'm a node, so compute top, left, right, bottom else { element = $(ce); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = 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 = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ); height = ($.ui.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).data("ui-resizable"), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement; 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; } 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; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left+that.position.left; that.offset.top = that.parentData.top+that.position.top; woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ); hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); isParent = that.containerElement.get(0) === that.element.parent().get(0); isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position")); if(isParent && isOffsetRelative) { woset -= that.parentData.left; } 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; } } 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; } } }, stop: function(){ var that = $(this).data("ui-resizable"), 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).data("ui-resizable"), 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).data("ui-resizable"), 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).data("ui-resizable"), 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).data("ui-resizable"); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).data("ui-resizable"); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).data("ui-resizable"), 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 = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = 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 { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); })(jQuery); (function( $, undefined ) { $.widget("ui.selectable", $.ui.mouse, { version: "1.10.3", 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"); 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"); 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); (function( $, undefined ) { /*jshint loopfunc: true */ function isOverAxis( x, reference, size ) { return ( x > reference ) && ( x < ( reference + size ) ); } function isFloating(item) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); } $.widget("ui.sortable", $.ui.mouse, { version: "1.10.3", 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 }, _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" || 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(); //We're ready to go this.ready = true; }, _destroy: function() { this.element .removeClass("ui-sortable ui-sortable-disabled"); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _setOption: function(key, value){ if ( key === "disabled" ) { this.options[ key ] = value; this.widget().toggleClass( "ui-sortable-disabled", !!value ); } else { // Don't call widget base _setOption for disable as it adds ui-state-disabled class $.Widget.prototype._setOption.apply(this, arguments); } }, _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 form 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 // beetween 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") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || 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 = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = 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.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]); for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each(function() { items.push(this); }); } 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, base, cur, nearBottom, floating, 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 || isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; base = this.positionAbs[posProperty] + this.offset.click[posProperty]; 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; } if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ nearBottom = true; cur += this.items[j][sizeProperty]; } if(Math.abs(cur - base) < dist) { dist = Math.abs(cur - base); 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]) { 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 for (i = this.containers.length - 1; i >= 0; i--){ if(!noPropagation) { delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); } if(this.containers[i].containerCache.over) { delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(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(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); 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 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.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 true; }, _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); (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.10.3" } }); var PROP_NAME = "datepicker", instActive; /* 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.dpDiv = 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) { 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 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, PROP_NAME, 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, PROP_NAME, 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], PROP_NAME, inst); } 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], PROP_NAME, 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, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, PROP_NAME); 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, PROP_NAME); 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, PROP_NAME); 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, PROP_NAME); } 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"); 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; } 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.zIndex($(input).zIndex()+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) instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a").mouseover(); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; 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, PROP_NAME))) { 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)))), digits = new RegExp("^\\d{1," + 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" + ((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 instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function 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", function(){ if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : 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 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.10.3"; })(jQuery); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.10.3", 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 ); } 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 ); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.10.3", 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 }, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); 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 = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", 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 { this.range = $([]); } }, _setupEvents: function() { var elements = this.handles.add( this.range ).filter( "a" ); this._off( elements ); this._on( elements, this._handleEvents ); this._hoverable( elements ); this._focusable( elements ); }, _destroy: function() { this.handles.remove(); 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, true ); } } } 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; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); 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 "min": case "max": this._animateOff = true; 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) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.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 ) { /*jshint maxcomplexity:25*/ 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()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / 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 ); }, click: function( event ) { event.preventDefault(); }, 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)); (function( $ ) { var increments = 0; function addDescribedBy( 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( " " ) ) ); } function removeDescribedBy( 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" ); } } $.widget( "ui.tooltip", { version: "1.10.3", 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 }, _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(); } }, _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, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = 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" ) ) .attr( "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 tooltip, events, delayedShow, 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. tooltip = this._find( target ); if ( tooltip.length ) { 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" ); } } tooltip = this._tooltip( target ); addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); 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 ); } }, 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 that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // 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 ( this.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 ( target.data( "ui-tooltip-title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } removeDescribedBy( target ); 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 ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var id = "ui-tooltip-" + increments++, tooltip = $( "<div>" ) .attr({ id: id, role: "tooltip" }) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); 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" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); element.removeData( "ui-tooltip-title" ); } }); } }); }( jQuery ) );
const redis = bot.utils.redis; const EventEmitter = require("events").EventEmitter; const resolver = require("../modules/audio/main.js"); const autoplay = require("../modules/audio/autoplay.js"); class Player extends EventEmitter { constructor(guild, data = {}) { super(); this.id = guild.id; this._guild = guild; if(data.channelID) this.setChannel(data.channelID); bot.players.set(this.id, this); handlePlayer(this); } get connection() { return bot.voiceConnections.get(this.id); } async connect(channelID) { if(this.connection) return false; await bot.voiceConnections.join(this.id, channelID); await this.setConnection(channelID); this.connection.on("error", err => this.emit("error", err)); this.connection.on("disconnect", () => this.destroy("disconnect")); this.connection.on("end", async () => { let queue = await this.getQueue(); let playerOptions = await this.getOptions(); if(playerOptions.repeat) { queue.push(await this.getCurrent()); await this.setQueue(queue); } if(!queue.length) this.destroy("no_queue"); else setTimeout(() => this.play(), 100); }); return true; } async addQueue(data) { if(!this.connection) return false; let current = await this.getCurrent(); let queue = await this.getQueue(); if(queue.length >= 1500) { let donator = await r.db("Oxyl").table("donators").get(this._guild.ownerID).run(); if(!donator) return __("modules.player.maxQueue", this._guild); } if(Array.isArray(data)) queue = queue.concat(data); else if(typeof data === "object") queue.push(data); if(queue.length >= 1500) { let donator = await r.db("Oxyl").table("donators").get(this._guild.ownerID).run(); if(!donator) { queue = queue.slice(0, (donator ? 10000 : 1500) - 1); await this.setQueue(queue); if(!donator) return __("modules.player.cutOffQueue", this._guild); } } await this.setQueue(queue); if(!current) setTimeout(() => this.play(), 100); return true; } async destroy(reason = "end") { let connection = this.connection; if(connection) { connection.removeAllListeners(); if(connection.playing) connection.stop(); if(bot.voiceConnections.has(this.id)) bot.voiceConnections.leave(this.id); } bot.players.delete(this.id); let keys = await redis.keys(`${redis.options.keyPrefix}player:*:${this.id}`); keys.forEach(key => redis.del(key.substring(redis.options.keyPrefix.length))); } async play(options) { let connection = this.connection; let current = await this.getCurrent(); if(!connection || (current && connection.playing)) return; let queue = await this.getQueue(); let song = queue[0]; if(!song && !current && !queue.length) { this.destroy("no_queue"); return; } else if(!song) { setTimeout(() => this.play(), 100); return; } else { queue.shift(); } if(!song.track) song = await resolver(song.uri); let playerOptions = await this.getOptions(); if(!playerOptions.repeat && playerOptions.autoplay && song.uri.startsWith("https://www.youtube.com/")) { queue.unshift(await autoplay(song.identifier)); } await this.setQueue(queue); connection.play(song.track, options); this.setCurrent(song); this.emit("playing", song); } voiceCheck(member) { if(!member.voiceState || !member.voiceState.channelID || !this.connection) return false; else return member.voiceState.channelID === this.connection.channelId; } async getOptions() { let options = await redis.get(`player:options:${this.id}`); return options ? JSON.parse(options) : { autoplay: false, repeat: false }; } async setOptions(options) { return await redis.set(`player:options:${this.id}`, JSON.stringify(options), "EX", 7200); } async getChannel() { let channel = await redis.get(`player:channel:${this.id}`); return channel ? this._guild.channels.get(channel) : undefined; } async setChannel(channelID) { return await redis.set(`player:channel:${this.id}`, channelID, "EX", 7200); } async getCurrent() { let current = await redis.get(`player:current:${this.id}`); return current ? JSON.parse(current) : undefined; } async setCurrent(song) { return await redis.set(`player:current:${this.id}`, JSON.stringify(song), "EX", 7200); } async getQueue() { let queue = await redis.get(`player:queue:${this.id}`); return queue ? JSON.parse(queue) : []; } async setQueue(queue) { return await redis.set(`player:queue:${this.id}`, JSON.stringify(queue), "EX", 7200); } async getConnection() { return await redis.get(`player:connection:${this.id}`); } async setConnection(channelID) { if(channelID === null) return await redis.del(`player:connection:${this.id}`); else return await redis.set(`player:connection:${this.id}`, channelID, "EX", 7200); } async getTime() { return await redis.get(`player:time:${this.id}`); } async setTime(time) { return await redis.set(`player:time:${this.id}`, time, "EX", 7200); } } module.exports = Player; module.exports.resumeQueues = async () => { let keys = await redis.keys(`${redis.options.keyPrefix}player:queue:*`); keys.forEach(async key => { let id = key.substring(key.indexOf("queue:") + 6); if(!bot.guilds.has(id)) return; let player = new Player(bot.guilds.get(id)); let connection = await player.getConnection(); if(!connection) { let keys2 = await redis.keys(`${redis.options.keyPrefix}player:*:${id}`); keys2.forEach(key2 => redis.del(key2.substring(redis.options.keyPrefix.length))); return; } let current = await player.getCurrent(); let options = await player.getOptions(); let queue = await player.getQueue(); let time = await player.getTime(); queue.unshift(current); await player.connect(connection); await player.setQueue(queue); await player.setOptions(options); await player.play({ startTime: time && !isNaN(time) ? time : 0 }); if(options.volume) player.connection.setVolume(options.volume); if(options.paused) { await new Promise(resolve => setTimeout(resolve, 1500)); player.connection.setPause(true); } }); }; function handlePlayer(player) { let createMessage = async message => { if(!player.connection) return; let channel = await player.getChannel(); if(!channel) return; let messageDisabled = await r.table("settings").get(["disable-music-messages", player.id]).run(); if(messageDisabled && messageDisabled.value) return; let listening = player._guild.channels.get(player.connection.channelId).voiceMembers .filter(member => !member.bot && !member.voiceState.selfDeaf).length; if(listening >= 1) channel.createMessage(typeof message === "object" ? { embed: message } : message); }; player.on("playing", async song => { let message = `${__("phrases.nowPlaying", this._guild)} **${song.title}**`; if(song.author && song.author !== "Unknown artist") message += ` by ${song.author}`; if(song.length && song.length < 900000000000000) { message += ` \`(${bot.utils.secondsToDuration(song.length / 1000)})\``; } createMessage(message); }); player.on("error", async err => { createMessage({ color: 0xF1C40F, description: err.stack || err.message, title: `⚠ ${__("phrases.recievedError", this._guild)}` }); }); }
/** * Created by Raul Rivero on 6/15/2015. */ angular.module('controllers').controller('RegisterController', function($scope, $state, $timeout, $ionicPopup, $ionicLoading, mainFactory) { $scope.modelGUI = {}; $scope.emptyPlayerId = false; $scope.emptyPin = false; $scope.emptyName = false; $scope.wrongPin = false; AdMob.hideBanner(); $scope.registerUser = function () { if (!$scope.modelGUI.name) { $scope.emptyName = true; return; } if (!$scope.modelGUI.username) { $scope.emptyPlayerId = true; return; } if (!$scope.modelGUI.pin) { $scope.emptyPin = true; return; } if ($scope.modelGUI.pin.toString().length < 4 || $scope.modelGUI.pin.toString().length > 8) { $scope.wrongPin = true; $timeout(hideErrorMessage, 5000); return; } $scope.modelGUI.age = $scope.modelGUI.age === undefined ? null : $scope.modelGUI.age; $scope.showLoadingMessage(); mainFactory.getUsers().success(function (data) { for (var i = 0; i < data.length; i++) { if (data[i].user_playerid === $scope.modelGUI.username) { $scope.modelGUI.username = ""; $scope.hideLoadingMessage(); showMessageError(); return; } } mainFactory.registerUser($scope.modelGUI).success(function () { //window.analytics.trackEvent('New user', 'Register User'); $scope.hideLoadingMessage(); showMessageSuccess(); }); }) .error(function () { $scope.hideLoadingMessage(); requestError("There is no internet connection! We're unable to contact our servers."); }); }; function requestError (msg) { var alertPopup = $ionicPopup.alert({ title: 'Request error!', template: msg }); alertPopup.then(function (res) { }); } function hideErrorMessage () { $scope.wrongPin = false; } $scope.showLoadingMessage = function() { $ionicLoading.show({ template: 'Registering new player...' }); }; $scope.hideLoadingMessage = function(){ $ionicLoading.hide(); }; function showMessageError () { var alertPopup = $ionicPopup.confirm({ title: 'Error', template: "Player ID <b>" + $scope.modelGUI.username + "</b> is taken by another user. Please select a different one." }); alertPopup.then(function (res) { }); } function showMessageSuccess () { var alertPopup = $ionicPopup.alert({ title: 'Confirmation', template: "New player <b>" + $scope.modelGUI.username + "</b> has been created succesfully!" }); alertPopup.then(function (res) { $state.go('home'); }); } });
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var prefix = require('gulp-autoprefixer'); var cp = require('child_process'); var messages = { jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build' }; /** * Build the Jekyll Site */ gulp.task('jekyll-build', function (done) { browserSync.notify(messages.jekyllBuild); return cp.spawn('jekyll.bat', ['build'], {stdio: 'inherit'}) .on('close', done); }); /** * Rebuild Jekyll & do page reload */ gulp.task('jekyll-rebuild', ['jekyll-build'], function () { browserSync.reload(); }); /** * Wait for jekyll-build, then launch the Server */ gulp.task('browser-sync', ['sass', 'jekyll-build'], function() { browserSync({ notify: false, server: { baseDir: '_site' } }); }); /** * Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds) */ gulp.task('sass', function () { return gulp.src('assets/css/styles.scss') .pipe(sass({ //outputStyle: 'compressed', includePaths: ['css'], onError: browserSync.notify })) .pipe(prefix(['last 2 versions', '> 1%', 'ie 8', 'ie 7', 'ie 9'], { cascade: true })) .pipe(gulp.dest('_site/assets/css')) .pipe(browserSync.reload({stream:true})) .pipe(gulp.dest('assets/css')); }); /** * Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds) */ gulp.task('img', function () { gulp.src('assets/img/**/**/*.{png,jpg,svg,gif}') .pipe(gulp.dest('_site/assets/img')); }); /** * Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds) */ gulp.task('js', function () { gulp.src('assets/js/**/**/*.{js}') .pipe(gulp.dest('_site/assets/js')); }); /** * Watch scss files for changes & recompile * Watch html/md files, run jekyll & reload BrowserSync */ gulp.task('watch', function () { gulp.watch('assets/js/**/**/*.{js}', ['js']); gulp.watch('assets/img/**/**/*.{png,jpg,svg}', ['img']); gulp.watch('assets/css/**/*.scss', ['sass']); gulp.watch(['index.html', '*/index.html', '_layouts/**/*.html', '_posts/**/*.md', '_includes/**/*', '_config.yml'], ['jekyll-rebuild']); }); /** * Default task, running just `gulp` will compile the sass, * compile the jekyll site, launch BrowserSync & watch files. */ gulp.task('default', ['browser-sync', 'watch']);
import React from 'react'; import PropTypes from 'prop-types'; import { Svg } from '../../Svg'; import makeIcon from './makeIcon'; const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( <Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}> <Svg.Path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm2.2 15.24c-.54.2-2.44 1.13-3.54.16-.33-.3-.5-.66-.5-1.1 0-.83.28-1.56.77-3.3.1-.33.2-.76.2-1.1 0-.58-.23-.73-.83-.73-.3 0-.62.1-.9.2l.15-.65c.65-.27 1.48-.6 2.18-.6 1.06 0 1.84.53 1.84 1.53 0 .3-.05.8-.16 1.15l-.6 2.15c-.1.44-.3 1.4 0 1.68s1.2.13 1.6-.06l-.14.67zm-1-8.57c-.68 0-1.24-.56-1.24-1.25 0-.7.56-1.25 1.25-1.25.7 0 1.3.56 1.3 1.25 0 .7-.55 1.25-1.24 1.25z" fill={fill} /> </Svg> )); Icon.propTypes = { size: PropTypes.number, fill: PropTypes.string, }; export default Icon;
import { searchJSON } from "../../search.js"; import { v2apibase } from "../../base.js"; import { endpoint } from "./endpoint.js"; export const _search = new URL( `/${endpoint}/_search`.replace(/\/{2,}/g, "/"), v2apibase ); // Minimal metadata const defaultShow = "id,name,area,status,beginLifespanVersion,geometry"; export const findByCaseNumber = async (n) => { const caseNumber = n; const findCaseNumberURL = (n) => `${_search}?and=@id:${n}&type=feed&page=0..1`; const url = findCaseNumberURL(caseNumber); return searchJSON({ url }); }; export const findID = async ({ name, area, ident }) => { const url = `${_search}?q=&and=name:${name}${ area ? `,area:${area}` : "" }&page=0..1&type=feed`; // type feed and 1 object => JSON const p = await fetch(url).then((r) => r.json()); if (p) { return p.id; } }; export const fetchByIDs = async (ids) => { const or = ids.map((id) => `id:${id}`).join(","); const url = `${_search}?or=${or}`; const { results } = await searchJSON({ url }); return results; }; export const fetchByNames = async ( names, { area, status = "official", show = defaultShow } = {} ) => { if (names === undefined || names.length < 1) { return []; } const or = names.map((name) => `name:${name}`).join(","); const url = `${_search}?or=${or}&and=status:${status}${ area ? `&and=area:${area}` : "" }&page=..&show=${show}`; const { results } = await searchJSON({ url }); return results; }; export const findPlacenamesLinkingToCase = async (n) => { const url = new URL( `${_search}?and=cases.@id:${n}&show=id,name,area,status,beginLifespanVersion,geometry&page=..` ); let { results, ...rest } = await searchJSON({ url }); results = results.sort((a, b) => a.name.localeCompare(b.name)); return { results, ...rest }; }; export const findPlacenamesUpdatedAfter = async ({ datetime, area, show = defaultShow + ",_meta.modified", }) => { const dt = new Date(datetime); const url = new URL( `${_search}?date-and=_meta.modified:${datetime}..&show=${show}&page=..&verbose=true` ); if (area) { url.searchParams.append("and", `area:${area}`); } return searchJSON({ url }); }; // export const findNamesinArea = async ({ area }) => { // const url = new URL( // `${_search}?and=area:${area}&and=status:official&show=name&sort=name:asc&page=..` // ); // let { results, ...rest } = await searchJSON({ url }); // results = results.sort((a, b) => a.name.localeCompare(b.name)); // return { results, ...rest }; // };
var APP_NAME = 'Start Template'; /** * Module dependencies. */ var express = require('express'), mongoStore = require('connect-mongo')(express), flash = require('connect-flash'), http = require('http'), path = require('path'), util = require('util'), bcrypt = require('bcrypt'), mongoose = require('mongoose'), colors = require('colors'), passport = require('passport'), LocalStrategy = require('passport-local') .Strategy, moment = require('moment'), sprintf = require('sprintf') .sprintf, async = require('async'), Grid = require('gridfs-stream'), events = require('events'), i18n = require('i18next'), _ = require('underscore'); Grid.mongo = mongoose.mongo; var app = express(); var mongodb_uri; // 页面资源相关-> 页面相关的js,插件相关的js,页面相关的css,插件相关的css var path_js_page, path_js_plugins, path_css_page, path_css_plugins; app.configure('development', function () { //配置开发环境相关的变量 app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); mongodb_uri = 'mongodb://localhost/dbname?poolSize=5'; path_js_page = '/pagejs'; path_css_page = 'pagecss'; path_js_plugins = 'plugins/js'; path_css_plugins = 'plugins/css'; }); app.configure('production', function () { //配置生产环境相关的变量 app.use(express.errorHandler()); mongodb_uri = 'mongodb://localhost/dbname?poolSize=10'; path_js_page = '/pagejs-min'; path_css_page = 'pagecss-min'; path_js_plugins = 'plugins'; path_css_plugins = 'plugins/css'; }); // 建立mongodb连接 mongoose.connect(mongodb_uri); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.on('open', function () { console.log(colors.yellow('Connected to Mongoose on ' + mongodb_uri)); }); //多语言引擎的配置 i18n.init({ useCookie: true, //使用cookie来保存语言 detectLngFromHeaders: true, //使用header里面的信息 supportedLngs: ['en', 'zh'], //设置支持英文和中文 fallbackLng: 'zh', // debug: true, resGetPath: __dirname + '/locales/__lng__/__ns__.json', ns: { namespaces: ['app', 'btn', 'msg'], //设定命名空间,用来区分不同用途的翻译信息。 defaultNs: 'app' }, resSetPath: __dirname + '/locales/__lng__/new.__ns__.json', saveMissing: true, ignoreRoutes: ['img', 'avatar_72', 'avatar_288', 'css', 'js', 'pagejs'], // sendMissingTo: 'all' }); // all environments app.set('port', process.env.PORT || 9990); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.compress()); //use compress app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('pony')); app.use(express.session({ secret: "()&*$#@QDFG^&%$^##W^&*TFGCXS$%$^&*(UOIHDS%$^$%&*%$WSDRFGU*&^R&%F*&T^RF))", store: new mongoStore({ mongoose_connection: db, }) })); app.use(i18n.handle); // have i18n befor app.router app.use(flash()); // use flash function app.use(app.router); // Remember Me middleware & i18n set language app.use(function (req, res, next) { if (req.method == 'POST' && req.url == '/login') { if (req.body.rememberme) { req.session.cookie.maxAge = 2592000000; // 30*24*60*60*1000 Rememeber 'me' for 30 days } else { req.session.cookie.expires = false; } } next(); }); //设置passport组件 passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (token, done) { if (!app.locals.login_users) { //lazy init login_users app.locals.login_users = {}; } if (app.locals.login_users[token]) { // console.log('deserializeUser from cache'); done(null, app.locals.login_users[token]) } else { User.findById(token) .populate('') .exec(function (err, user) { // console.log('deserializeUser from database'); if (user) { app.locals.login_users[token] = user; }; done(err, user); }); } }); app.use(passport.initialize()); //initialing passport midleware app.use(passport.session()); //enabling passport session support //设置passport组件——结束 app.use(express.static(path.join(__dirname, 'public'))); app.locals.APP_NAME = APP_NAME; // 注册helper函数 app.locals({ toISODate: function (date) { return util.isDate(date) ? moment(date) .format('YYYY-MM-DD') : date; }, toISOTime: function (date) { return util.isDate(date) ? moment(date) .format('HH:mm:ss') : date; }, toISODatetime: function (date) { return util.isDate(date) ? moment(date) .format('YYYY-MM-DD HH:mm:ss') : date; }, calcSize: function (size) { if (size < 1024) { return sprintf('%0.2f B', size); } else if (size >= 1024 && size < 1048576) { //1024 * 1024 return sprintf('%0.2f KB', size / 1024); } else if (size >= 1048576 && size < 1073741824) { //1024^3 return sprintf('%0.2f MB', size / 1048576); } else if (size >= 1073741824) { return springf('%0.2f GB', size / 1073741824); }; }, handle500: function (err, req, res) { res.status(500); res.render('500.jade', { title: '500: Internal Server Error', error: err }); }, handle404: function (err, req, res) { res.status(404); }, }) // 设置全局变量 app.locals({ gv_toolpath: path.join(__dirname, 'tools'), path_js_page: path_js_page, path_js_plugins: path_js_plugins, path_css_page: path_css_page, path_css_plugins: path_css_plugins, }) i18n.registerAppHelper(app) .serveClientScript(app) .serveDynamicResources(app) .serveMissingKeyRoute(app) .serveChangeKeyRoute(app) .serveRemoveKeyRoute(app); // web translate interface i18n.serveWebTranslate(app, { i18nextWTOptions: { languages: ['zh', 'en'], namespaces: ['app', 'btn', 'msg'], resGetPath: "locales/resources.json?lng=__lng__&ns=__ns__", resChangePath: 'locales/change/__lng__/__ns__', resRemovePath: 'locales/remove/__lng__/__ns__', fallbackLng: "zh", dynamicLoad: true }, authenticated: function (req, res) { //return req.user; return true; //for dev } }); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } // app.get('/', routes.index); // app.get('/users', user.list); // Handle 404 - last chance app.use(function (req, res) { //console.log('message in 404'); res.status(404); res.render('404.jade', { title: '404: File Not Found' }); }); // Handle 500 - last chance app.use(function (error, req, res, next) { // throw error; console.log(util.inspect(error, { depth: null })); res.status(500); res.render('500.jade', { title: '500: Internal Server Error', error: error }); }); var server = http.createServer(app) .listen(app.get('port'), function () { var env_msg = (app.get('env') == 'development') ? colors.green(app.get('env')) : colors.red(app.get('env')); console.log("Express server listening on port " + colors.green(app.get('port')) + ' in ' + env_msg + ' mode.'); }) .on('close', function () { console.log(colors.red('terminating server')); client.quit(); });
//! moment.js locale configuration //! locale : vietnamese (vi) //! author : Bang Nguyen : https://github.com/bangnk ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var vi = moment.defineLocale('vi', { months : 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'), monthsShort : 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), weekdays : 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), weekdaysShort : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), weekdaysMin : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM [năm] YYYY', LLL : 'D MMMM [năm] YYYY HH:mm', LLLL : 'dddd, D MMMM [năm] YYYY HH:mm', l : 'DD/M/YYYY', ll : 'D MMM YYYY', lll : 'D MMM YYYY HH:mm', llll : 'ddd, D MMM YYYY HH:mm' }, calendar : { sameDay: '[Hôm nay lúc] LT', nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : '%s tới', past : '%s trước', s : 'vài giây', m : 'một phút', mm : '%d phút', h : 'một giờ', hh : '%d giờ', d : 'một ngày', dd : '%d ngày', M : 'một tháng', MM : '%d tháng', y : 'một năm', yy : '%d năm' }, ordinalParse: /\d{1,2}/, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return vi; }));
'use strict'; const obj1 = {}; obj1.name = 'Marcus'; obj1.city = 'Roma'; obj1.born = 121; console.dir({ obj1 }); const obj2 = new Object(); obj2.name = 'Marcus'; obj2.city = 'Roma'; obj2.born = 121; console.dir({ obj2 }); const obj3 = { name: 'Marcus', city: 'Roma', born: 121 }; console.dir({ obj3 });
'use strict'; (function() { describe('Test test case', function() { it('1 should be equals to 1', function() { expect(1).toBe(1); }); }); // Articles Controller Spec /*describe('MEAN controllers', function() { describe('ArticlesController', function() { // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we use a newly-defined toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function() { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); beforeEach(function() { module('mean'); module('mean.system'); module('mean.articles'); }); // Initialize the controller and a mock scope var ArticlesController, scope, $httpBackend, $stateParams, $location; // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { scope = $rootScope.$new(); ArticlesController = $controller('ArticlesController', { $scope: scope }); $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; })); it('$scope.find() should create an array with at least one article object ' + 'fetched from XHR', function() { // test expected GET request $httpBackend.expectGET('api\/articles').respond([{ title: 'An SitePost about MEAN', content: 'MEAN rocks!' }]); // run controller scope.find(); $httpBackend.flush(); // test scope value expect(scope.articles).toEqualData([{ title: 'An SitePost about MEAN', content: 'MEAN rocks!' }]); }); it('$scope.findOne() should create an array with one article object fetched ' + 'from XHR using a articleId URL parameter', function() { // fixture URL parament $stateParams.articleId = '525a8422f6d0f87f0e407a33'; // fixture response object var testArticleData = function() { return { title: 'An SitePost about MEAN', content: 'MEAN rocks!' }; }; // test expected GET request with response object $httpBackend.expectGET(/api\/articles\/([0-9a-fA-F]{24})$/).respond(testArticleData()); // run controller scope.findOne(); $httpBackend.flush(); // test scope value expect(scope.article).toEqualData(testArticleData()); }); it('$scope.create() with valid form data should send a POST request ' + 'with the form input values and then ' + 'locate to new object URL', function() { // fixture expected POST data var postArticleData = function() { return { title: 'An SitePost about MEAN', content: 'MEAN rocks!' }; }; // fixture expected response data var responseArticleData = function() { return { _id: '525cf20451979dea2c000001', title: 'An SitePost about MEAN', content: 'MEAN rocks!' }; }; // fixture mock form input values scope.title = 'An SitePost about MEAN'; scope.content = 'MEAN rocks!'; // test post request is sent $httpBackend.expectPOST('api\/articles', postArticleData()).respond(responseArticleData()); // Run controller scope.create(true); $httpBackend.flush(); // test form input(s) are reset expect(scope.title).toEqual(''); expect(scope.content).toEqual(''); // test URL location to new object expect($location.path()).toBe('/articles/' + responseArticleData()._id); }); it('$scope.update(true) should update a valid article', inject(function(Articles) { // fixture rideshare var putArticleData = function() { return { _id: '525a8422f6d0f87f0e407a33', title: 'An SitePost about MEAN', to: 'MEAN is great!' }; }; // mock article object from form var article = new Articles(putArticleData()); // mock article in scope scope.article = article; // test PUT happens correctly $httpBackend.expectPUT(/api\/articles\/([0-9a-fA-F]{24})$/).respond(); // testing the body data is out for now until an idea for testing the dynamic updated array value is figured out //$httpBackend.expectPUT(/articles\/([0-9a-fA-F]{24})$/, putArticleData()).respond(); [> Error: Expected PUT /articles\/([0-9a-fA-F]{24})$/ with different data EXPECTED: {"_id":"525a8422f6d0f87f0e407a33","title":"An SitePost about MEAN","to":"MEAN is great!"} GOT: {"_id":"525a8422f6d0f87f0e407a33","title":"An SitePost about MEAN","to":"MEAN is great!","updated":[1383534772975]} <] // run controller scope.update(true); $httpBackend.flush(); // test URL location to new object expect($location.path()).toBe('/articles/' + putArticleData()._id); })); it('$scope.remove() should send a DELETE request with a valid articleId ' + 'and remove the article from the scope', inject(function(Articles) { // fixture rideshare var article = new Articles({ _id: '525a8422f6d0f87f0e407a33' }); // mock rideshares in scope scope.articles = []; scope.articles.push(article); // test expected rideshare DELETE request $httpBackend.expectDELETE(/api\/articles\/([0-9a-fA-F]{24})$/).respond(204); // run controller scope.remove(article); $httpBackend.flush(); // test after successful delete URL location articles list //expect($location.path()).toBe('/articles'); expect(scope.articles.length).toBe(0); })); }); });*/ }());
import {run} from "@cycle/core" import {makeDOMDriver} from "@cycle/dom" import {Model} from "stanga" import Counter from "./Counter" run(Counter, { DOM: makeDOMDriver("#app"), M: Model(0) // use initial value 0 })
import keyBy from 'lodash/keyBy'; import Immutable from 'seamless-immutable'; import Reservation from '../../../utils/fixtures/Reservation'; import Resource from '../../../utils/fixtures/Resource'; import Unit from '../../../utils/fixtures/Unit'; import User from '../../../utils/fixtures/User'; import reservationPageSelector from '../reservationPageSelector'; const defaultUnit = Unit.build(); const defaultReservation = Reservation.build(); const defaultResource = Resource.build({ unit: defaultUnit.id }); const defaultUser = User.build(); function getState(resources = [], units = [], user = defaultUser) { return { api: Immutable({ activeRequests: [], }), auth: Immutable({ userId: user.id, token: 'mock-token', }), data: Immutable({ resources: keyBy(resources, 'id'), units: keyBy(units, 'id'), users: { [user.id]: user }, }), ui: Immutable({ reservations: { selected: [ { begin: '2016-10-10T10:00:00+03:00', end: '2016-10-10T11:00:00+03:00', resource: defaultResource.id, }, ], toEdit: [defaultReservation], toShow: [defaultReservation], toShowEdited: [defaultReservation], }, }), recurringReservations: { reservations: [], }, }; } function getProps(id = 'some-id') { return { location: { search: `?date=2015-10-10&resource=${defaultResource.id}`, }, params: { id, }, }; } describe('pages/reservation/reservationPageSelector', () => { test('returns date', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.date).toBeDefined(); }); test('returns isAdmin', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.isAdmin).toBeDefined(); }); test('returns isStaff', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.isStaff).toBeDefined(); }); test('returns isFetchingResource', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.isFetchingResource).toBeDefined(); }); test('returns isMakingReservations', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.isMakingReservations).toBeDefined(); }); test('returns resource', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.resource).toBeDefined(); }); test('returns resourceId', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.resourceId).toBeDefined(); }); test('returns reservationToEdit', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.reservationToEdit).toBeDefined(); }); test('returns reservationCreated', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.reservationCreated).toBeDefined(); }); test('returns reservationEdited', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.reservationEdited).toBeDefined(); }); test('returns the unit corresponding to the resource.unit', () => { const state = getState([defaultResource], [defaultUnit]); const props = getProps(defaultResource.id); const selected = reservationPageSelector(state, props); expect(selected.unit).toEqual(defaultUnit); }); test('returns user', () => { const state = getState(); const props = getProps(); const selected = reservationPageSelector(state, props); expect(selected.user).toBeDefined(); }); });
if(!xtag.tags['cd-panelmenusubitem']) { xtag.register('cd-panelmenusubitem', { accessors: { id: { attribute: {} }, icon: { attribute: {} }, href: { attribute: {} } }, lifecycle: { created: function() { } } }); }
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Get the current URL. * * @param {function(string)} callback - called when the URL of the current tab * is found. */ function popOut() { chrome.tabs.executeScript({ file: 'background.js' }); } document.getElementById('clickme').addEventListener('click', popOut);
var base_datos = require('./db/db'); var es_ES= require('./idiomas/es_ES'); var en_US= require('./idiomas/en_US'); //############################################### var autenticado_con_cookies = function (req,res,role, funcion_exito) { //Aprobechamos para la comprobacion de idioma var idioma = req.cookies.idioma; if (idioma === undefined){ res.cookie('idioma','es_ES'); }; //------------- var dni = req.cookies.dni; var pass = req.cookies.pass; //var role = req.cookies.role; no lo cogemos en las cookies y lo comprobamos por parametro para poder forzar una comprobacion especifica if (role === ""){var rol = req.cookies.role;} //solo lo cogemos en las cookies si el otro no esta definido, para una autencticacion generica. else{rol=role}; //---------------------------- if (dni === undefined || pass === undefined){ res.redirect('/');} else { //------------------ var f_fracaso = function(){ res.redirect('/');} //------------------ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //Aprobechamos para la gestion de citas (para el badge con la informacion) var f_exito = function(){ switch (rol) { case "patient": base_datos.citas_futuras_paciente (dni,function(lista_citas){ req.cookies.citas = JSON.stringify(lista_citas.length); // se hace en req para que el cambio sea instantaneo funcion_exito(); }); break; case "doctor": base_datos.citas_futuras_doctor (dni,function(lista_citas){ req.cookies.citas = JSON.stringify(lista_citas.length); // se hace en req para que el cambio sea instantaneo funcion_exito(); }); break; default: funcion_exito(); break; } } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ base_datos.comprobar_dni_pass_role(dni,pass,rol,f_exito,f_fracaso); }; }; //############################################### var texto = function (req,res,text) { // para gestionar los idiomas var idioma = req.cookies.idioma; if (idioma === undefined){ idioma = 'es_ES'; }; switch (idioma) { case "es_ES": return es_ES.textos[text]; break; case "en_US": return en_US.textos[text]; break; default: return es_ES.textos[text]; break; } }; //############################################### var url_activa = function (req,res,url) { //para la barra de navegacion var parte1= req.url.substring(0,url.length); var parte2= req.url.substring(url.length); //de ahi en adelante if (parte1 == url){ //buscamos url en req.url para evitar tener que poner la fecha en /patient/meetings/day/month/year if ((parte2=="") || (parte2.substring(0,1)=="/")) {return "active"} else {return ""} }else { return ""} } //############################################### module.exports = { autenticado_con_cookies : autenticado_con_cookies, texto : texto, url_activa : url_activa }
// @flow import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './svg-icon.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
import moment from 'moment'; import { expect } from 'chai'; import isDayVisible from '../../src/utils/isDayVisible'; describe('#isDayVisible', () => { it('returns true if arg is in visible months', () => { const test = moment().add(3, 'months'); const currentMonth = moment().add(2, 'months'); expect(isDayVisible(test, currentMonth, 2)).to.equal(true); }); it('returns false if arg is before first month', () => { const test = moment().add(1, 'months'); const currentMonth = moment().add(2, 'months'); expect(isDayVisible(test, currentMonth, 2)).to.equal(false); }); it('returns false if arg is after last month', () => { const test = moment().add(4, 'months'); const currentMonth = moment().add(2, 'months'); expect(isDayVisible(test, currentMonth, 2)).to.equal(false); }); describe('enableOutsideDays', () => { it('returns true if arg is in partial week before visible months', () => { const test = moment('2019-04-30'); const currentMonth = moment('2019-05-01'); expect(isDayVisible(test, currentMonth, 1, false)).to.equal(false); expect(isDayVisible(test, currentMonth, 1, true)).to.equal(true); }); it('returns true if arg is in partial week after visible months', () => { const test = moment('2019-06-01'); const currentMonth = moment('2019-05-01'); expect(isDayVisible(test, currentMonth, 1, false)).to.equal(false); expect(isDayVisible(test, currentMonth, 1, true)).to.equal(true); }); it('returns false if arg is before partial week before visible months', () => { const test = moment('2019-04-27'); const currentMonth = moment('2019-05-01'); expect(isDayVisible(test, currentMonth, 1, true)).to.equal(false); }); it('returns false if arg is after partial week after visible months', () => { const test = moment('2019-06-03'); const currentMonth = moment('2019-05-01'); expect(isDayVisible(test, currentMonth, 1, true)).to.equal(false); }); }); // this test fails when run with the whole suite, // potentially due to cache pollution from other tests it.skip('works when the first day of the week that starts the month does not have a midnight', () => { const march29 = moment('2020-03-29').utcOffset(-1 /* 'Atlantic/Azores' */); const april2020 = moment('2020-04-02').utcOffset(-1 /* 'Atlantic/Azores' */); expect(isDayVisible(march29, april2020, 1, true)).to.equal(true); }); });
'use strict'; angular.module('core').controller('TimelineController', ['$scope', function($scope) { // Controller Logic // ... } ]);
var winston = require('winston'); winston.emitErrs = true; var logger = new winston.Logger({ transports: [ new winston.transports.File({ level: 'info', filename: './logs/server_logs.log', handleExceptions: true, json: true, maxsize: 5242880, // 5MB maxFiles: 5, colorize: false }), new winston.transports.Console({ level: 'debug', handleExceptions: true, json: false, colorize: true }) ], exitOnError: false }); module.exports = logger; module.exports.stream = { write: function(message, encoding) { logger.info(message); } };
/*! * ui-grid - v4.8.5 - 2020-09-14 * Copyright (c) 2020 ; License: MIT */ (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('nl', { aggregate: { label: 'items' }, groupPanel: { description: 'Sleep hier een kolomnaam heen om op te groeperen.' }, search: { placeholder: 'Zoeken...', showingItems: 'Getoonde items:', selectedItems: 'Geselecteerde items:', totalItems: 'Totaal aantal items:', size: 'Items per pagina:', first: 'Eerste pagina', next: 'Volgende pagina', previous: 'Vorige pagina', last: 'Laatste pagina' }, menu: { text: 'Kies kolommen:' }, sort: { ascending: 'Sorteer oplopend', descending: 'Sorteer aflopend', remove: 'Verwijder sortering' }, column: { hide: 'Verberg kolom' }, aggregation: { count: 'Aantal rijen: ', sum: 'Som: ', avg: 'Gemiddelde: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Zet links vast', pinRight: 'Zet rechts vast', unpin: 'Maak los' }, gridMenu: { columns: 'Kolommen:', importerTitle: 'Importeer bestand', exporterAllAsCsv: 'Exporteer alle data als csv', exporterVisibleAsCsv: 'Exporteer zichtbare data als csv', exporterSelectedAsCsv: 'Exporteer geselecteerde data als csv', exporterAllAsPdf: 'Exporteer alle data als pdf', exporterVisibleAsPdf: 'Exporteer zichtbare data als pdf', exporterSelectedAsPdf: 'Exporteer geselecteerde data als pdf', exporterAllAsExcel: 'Exporteer alle data als excel', exporterVisibleAsExcel: 'Exporteer zichtbare data als excel', exporterSelectedAsExcel: 'Exporteer alle data als excel', clearAllFilters: 'Alle filters wissen' }, importer: { noHeaders: 'Kolomnamen kunnen niet worden afgeleid. Heeft het bestand een header?', noObjects: 'Objecten kunnen niet worden afgeleid. Bevat het bestand data naast de headers?', invalidCsv: 'Het bestand kan niet verwerkt worden. Is het een valide csv bestand?', invalidJson: 'Het bestand kan niet verwerkt worden. Is het valide json?', jsonNotArray: 'Het json bestand moet een array bevatten. De actie wordt geannuleerd.' }, pagination: { sizes: 'items per pagina', totalItems: 'items', of: 'van de' }, grouping: { group: 'Groepeer', ungroup: 'Groepering opheffen', aggregate_count: 'Agg: Aantal', aggregate_sum: 'Agg: Som', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Gem', aggregate_remove: 'Agg: Verwijder' } }); return $delegate; }]); }]); })();
var Matter = require('../../CustomMain'); /** * A coordinate wrapping plugin for matter.js. * See the readme for usage and examples. * @module MatterWrap */ var MatterWrap = { // plugin meta name: 'matter-wrap', // PLUGIN_NAME version: '0.1.4', // PLUGIN_VERSION for: 'matter-js@^0.13.1', silent: true, // no console log please // installs the plugin where `base` is `Matter` // you should not need to call this directly. install: function(base) { base.after('Engine.update', function() { MatterWrap.Engine.update(this); }); }, Engine: { /** * Updates the engine by wrapping bodies and composites inside `engine.world`. * This is called automatically by the plugin. * @function MatterWrap.Engine.update * @param {Matter.Engine} engine The engine to update. * @returns {void} No return value. */ update: function(engine) { var world = engine.world, bodies = Matter.Composite.allBodies(world), composites = Matter.Composite.allComposites(world); for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i]; if (body.plugin.wrap) { MatterWrap.Body.wrap(body, body.plugin.wrap); } } for (i = 0; i < composites.length; i += 1) { var composite = composites[i]; if (composite.plugin.wrap) { MatterWrap.Composite.wrap(composite, composite.plugin.wrap); } } } }, Bounds: { /** * Returns a translation vector that wraps the `objectBounds` inside the `bounds`. * @function MatterWrap.Bounds.wrap * @param {Matter.Bounds} objectBounds The bounds of the object to wrap inside the bounds. * @param {Matter.Bounds} bounds The bounds to wrap the body inside. * @returns {?Matter.Vector} A translation vector (only if wrapping is required). */ wrap: function(objectBounds, bounds) { var x = null, y = null; if (typeof bounds.min.x !== 'undefined' && typeof bounds.max.x !== 'undefined') { if (objectBounds.min.x > bounds.max.x) { x = bounds.min.x - objectBounds.max.x; } else if (objectBounds.max.x < bounds.min.x) { x = bounds.max.x - objectBounds.min.x; } } if (typeof bounds.min.y !== 'undefined' && typeof bounds.max.y !== 'undefined') { if (objectBounds.min.y > bounds.max.y) { y = bounds.min.y - objectBounds.max.y; } else if (objectBounds.max.y < bounds.min.y) { y = bounds.max.y - objectBounds.min.y; } } if (x !== null || y !== null) { return { x: x || 0, y: y || 0 }; } } }, Body: { /** * Wraps the `body` position such that it always stays within the given bounds. * Upon crossing a boundary the body will appear on the opposite side of the bounds, * while maintaining its velocity. * This is called automatically by the plugin. * @function MatterWrap.Body.wrap * @param {Matter.Body} body The body to wrap. * @param {Matter.Bounds} bounds The bounds to wrap the body inside. * @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required). */ wrap: function(body, bounds) { var translation = MatterWrap.Bounds.wrap(body.bounds, bounds); if (translation) { Matter.Body.translate(body, translation); } return translation; } }, Composite: { /** * Returns the union of the bounds of all of the composite's bodies * (not accounting for constraints). * @function MatterWrap.Composite.bounds * @param {Matter.Composite} composite The composite. * @returns {Matter.Bounds} The composite bounds. */ bounds: function(composite) { var bodies = Matter.Composite.allBodies(composite), vertices = []; for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i]; vertices.push(body.bounds.min, body.bounds.max); } return Matter.Bounds.create(vertices); }, /** * Wraps the `composite` position such that it always stays within the given bounds. * Upon crossing a boundary the composite will appear on the opposite side of the bounds, * while maintaining its velocity. * This is called automatically by the plugin. * @function MatterWrap.Composite.wrap * @param {Matter.Composite} composite The composite to wrap. * @param {Matter.Bounds} bounds The bounds to wrap the composite inside. * @returns {?Matter.Vector} The translation vector that was applied (only if wrapping was required). */ wrap: function(composite, bounds) { var translation = MatterWrap.Bounds.wrap( MatterWrap.Composite.bounds(composite), bounds ); if (translation) { Matter.Composite.translate(composite, translation); } return translation; } } }; module.exports = MatterWrap; /** * @namespace Matter.Body * @see http://brm.io/matter-js/docs/classes/Body.html */ /** * This plugin adds a new property `body.plugin.wrap` to instances of `Matter.Body`. * This is a `Matter.Bounds` instance that specifies the wrapping region. * @property {Matter.Bounds} body.plugin.wrap * @memberof Matter.Body */ /** * This plugin adds a new property `composite.plugin.wrap` to instances of `Matter.Composite`. * This is a `Matter.Bounds` instance that specifies the wrapping region. * @property {Matter.Bounds} composite.plugin.wrap * @memberof Matter.Composite */
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function (config) { // Define changes to default configuration here. // For the complete reference: // http://docs.ckeditor.com/#!/api/CKEDITOR.config config.skin = 'office2013'; // The toolbar groups arrangement, optimized for a single toolbar row. config.toolbarGroups = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'forms' }, { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] }, { name: 'links' }, { name: 'insert' }, { name: 'styles' }, { name: 'colors' }, { name: 'tools' }, { name: 'others' }, // { name: 'about' } ]; // The default plugins included in the basic setup define some buttons that // we don't want too have in a basic editor. We remove them here. config.removeButtons = 'Cut,Copy,Paste,Undo,Redo,Anchor,Underline,Strike,Subscript,Superscript'; // Let's have it basic on dialogs as well. config.removeDialogTabs = 'link:advanced'; config.extraPlugins = 'table'; config.extraPlugins = 'tabletools'; config.extraPlugins = 'sourcedialog'; config.height = '350px'; config.allowedContent = true; };
import { F as FormatterBehavior } from './formatter-b2667231.js'; import { n as numberFormat } from './number-e0c71222.js'; import './index-ea38c5c1.js'; class NumberBehavior extends FormatterBehavior { static get formatter() { return numberFormat; } } export default NumberBehavior;
/** * Module dependencies. */ var citizen = require('citizen'); var config = require('config'); var request = require('request'); var SideComments = require('side-comments'); var StatefulView = require('stateful-view'); var t = require('t'); var o = require('dom'); var template = require('./template'); var log = require('debug')('democracyos:proposal-clause'); /** * Expose `ProposalClauses` */ module.exports = ProposalClauses; function ProposalClauses(law, reference) { StatefulView.call(this, template, { clauses: law.clauses }); this.law = law; this.reference = reference; this.loadComments(); } StatefulView(ProposalClauses); ProposalClauses.prototype.loadComments = function() { this .load() .ready(this.sideComments.bind(this)); }; ProposalClauses.prototype.load = function(clauseId) { var self = this; request .get('/api/law/:id/clause-comments'.replace(':id', this.law.id)) .end(function (err, res) { if (res.status !== 200) ; //log error self.comments = res.body; request .get('/api/law/:id/summary-comments'.replace(':id', self.law.id)) .end(function (err, res) { if (res.status !== 200) ; //log error self.comments = self.comments.concat(res.body); self.state('loaded'); }); }); return this; }; ProposalClauses.prototype.sideComments = function () { var self = this; var law = this.law; var className = '.commentable-container'; var userComment = citizen.id ? { id: citizen.id, avatarUrl: citizen.avatar, name: citizen.firstName + ' ' + citizen.lastName, isAdmin: citizen.staff } : null; var sections = this.getSections(law); var locals = { trans: t, locale: config.locale, reference: this.reference }; var sideComments = new SideComments(className, userComment, sections, locals); sideComments.on('commentPosted', self.onClauseCommentPosted.bind(self)); sideComments.on('commentUpdated', self.onClauseCommentUpdated.bind(self)); sideComments.on('commentDeleted', self.onClauseCommentDeleted.bind(self)); self.sideComments = sideComments; } ProposalClauses.prototype.getSections = function (law) { log('This topic has been generated with Quill'); var self = this; var sections = []; var summary = o(law.summary); var paragraphs = summary[0].childNodes; function byReference(index) { return function (comment) { return comment.reference == law.id + '-' + index; } } for (var i = 0; i < paragraphs.length; i++) { var section = {}; section.sectionId = law.id + '-' + i; section.comments = self.comments .filter(byReference(i)) .map(self.formatComment); sections.push(section); } return sections; } ProposalClauses.prototype.getClausesSections = function (law) { log('This law has been generated in the traditional way (with clauses)'); var self = this; var paragraphs = law.summary.split('\n'); var sections = []; function filterBySection(comment) { return comment.reference == law.id + '-' + i; } var i = 0; paragraphs.forEach(function (paragraph) { if (!paragraph) return; var section = {}; section.sectionId = law.id + '-' + i; section.comments = self.comments .filter(filterBySection) .map(self.formatComment); sections.push(section); i++; }) law.clauses.forEach(function (clause) { var section = {}; section.sectionId = clause.id; function filterBySection(comment) { return comment.reference == clause.id; } section.comments = self.comments.filter(filterBySection).map(self.formatComment); sections.push(section); }); return sections; } ProposalClauses.prototype.formatComment = function (comment) { comment.authorAvatarUrl = comment.author.avatar; comment.authorName = comment.author.fullName; comment.authorId = comment.author.id; comment.comment = comment.text; comment.sectionId = comment.reference; return comment; } ProposalClauses.prototype.onClauseCommentPosted = function(comment) { var self = this; var clauseComment = {}; clauseComment.reference = comment.sectionId; if (~comment.sectionId.indexOf('-')) { clauseComment.context = 'summary'; } else { clauseComment.context = 'clause'; } clauseComment.text = comment.comment; request .post( '/api/:context/:reference/comment' .replace(':context', 'law') .replace(':reference', comment.sectionId)) .send({ comment: clauseComment }) .end(function(err, res) { if (err) return log('Error when posting clause comment %s', err); var comment = self.formatComment(res.body); self.sideComments.insertComment(comment); }); }; ProposalClauses.prototype.onClauseCommentUpdated = function(comment) { var self = this; request .put( '/api/comment/' + comment.id) .send({ text: comment.comment, reference: comment.sectionId }) .end(function(err, res) { if (err) return log('Error when putting clause comment %s', err); var comment = self.formatComment(res.body); self.sideComments.replaceComment(comment); }); }; ProposalClauses.prototype.onClauseCommentDeleted = function(comment) { var self = this; request .del('/api/comment/:id' .replace(':id', comment.id)) .end(function(err, res) { if (err) return log('Fetch error: %s', err); if (!res.ok) err = res.error, log('Fetch error: %s', err); if (res.body && res.body.error) err = res.body.error, log('Fetch response error: %s', err); self.sideComments.removeComment(comment.sectionId, comment.id); }); }; /** * Check if the string is HTML * * @param {String} str * @return {Boolean} * @api private */ function isHTML(str) { // Faster than running regex, if str starts with `<` and ends with `>`, assume it's HTML if (str.charAt(0) === '<' && str.charAt(str.length - 1) === '>' && str.length >= 3) return true; // Run the regex var match = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/.exec(str); return !!(match && match[1]); }
'use strict'; var noteApp = angular.module('myApp.notes', ['ngRoute']); noteApp.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/notes', { templateUrl: 'notes/notes.html', controller: 'NotesController' }); }]); noteApp.controller('NotesController', function($scope, NotesBackend) { NotesBackend.fetchNotes(); $scope.notes = function() { return NotesBackend.getNotes(); }; $scope.hasNotes = function() { return this.notes().length > 0; }; $scope.findNote = function(noteId) { var notes = this.notes (); for (var i=0; i < notes.length; i++) { if (notes[i].id === noteId) { return notes[i]; } } }; $scope.cloneNote = function(note) { return JSON.parse(JSON.stringify(note)); }; $scope.loadNote = function(noteId) { $scope.note = JSON.parse(JSON.stringify(this.findNote(noteId))); }; $scope.commit = function() { if ($scope.note && $scope.note.id) { NotesBackend.updateNote($scope.note); } else { NotesBackend.postNote($scope.note); } }; $scope.clearNote = function() { $scope.note = {}; //document.getElementById('note_title').focus(); $scope.$broadcast('noteCleared'); }; $scope.deleteNote = function () { NotesBackend.deleteNote($scope.note); this.clearNote(); }; });
// secrets for API keys and such var secrets = require('./.gitignore/secrets.json') var FeatureCollection = {"type":"FeatureCollection","features":[]} var fs = require('fs') var geofilelocation = './maps/geo.json' //puts together feature information function weaver (id, latitude, longitude, temperature) { id = parseInt(id,16) return feature = { "type":"Feature", "geometry":{"type":"Point", "coordinates":[longitude, latitude]}, "properties":{"temperature": temperature}, "id": id} } var mqtt = require('mqtt') var client = mqtt.connect('mqtt://169.50.27.27') //manual topics //var topics = ['devices/1','devices/20','devices/100'] //populate list of topics var topics = [] for(var i = 0; i < 10; i++){topics[i] = "devices/".concat(i+1)} client.on('connect', function () { client.subscribe(topics) //client.publish('presence', 'Hello mqtt') }) console.log("Subattu topikkeihin: ", topics.toString()) console.log("Haetaan viestejä, odota pari minuuttia...") client.on('message', function (topic, message) { /* id, latitude, longitude, temperature */ /* JSON format */ var my_message = JSON.parse(message) //id to base10 console.log("Datapoint: ", my_message.id, "Temperature: ", my_message.temperature, " ºC") // build feature and push to collection var feature = weaver(my_message.id, my_message.latitude, my_message.longitude, my_message.temperature) FeatureCollection.features.push(feature) client.end() if (topics.length == FeatureCollection.features.length){ //export to json file if all topics are gathered console.log(FeatureCollection) var jsonfile = JSON.stringify(FeatureCollection) fs.writeFile(geofilelocation, jsonfile, 'utf8') } })
/** ***************************************** * Created by lifx * Created on 2017-08-16 16:21:35 ***************************************** */ 'use strict'; /** ************************************* * 定义数据模型 ************************************* */ const model = {}; /** ************************************* * 添加事件监听器 ************************************* */ export function on(name, handler) { // 校验事件类型 if (typeof name !== 'string') { throw new TypeError('Event name should be a string!'); } // 校验监听函数 if (typeof handler !== 'function') { throw new TypeError('Event handler should be a function!'); } // 添加事件监听 if (name in model) { model[name].push(handler); } else { model[name] = [handler]; } } /** ************************************* * 移除事件监听器 ************************************* */ export function off(name, handler) { // 校验事件类型 if (typeof name !== 'string') { throw new TypeError('Event name should be a string!'); } // 移除同类事件 if (arguments.length === 1) { return delete model[name]; } // 校验监听函数 if (typeof handler !== 'function') { throw new TypeError('Event handler should be a function!'); } // 移除监听函数 model[name] = model[name].filter(item => item !== handler); } /** ************************************* * 触发事件 ************************************* */ export function emit(name, ...args) { // 校验事件类型 if (typeof name !== 'string') { throw new TypeError('Event name should be a string!'); } // 执行事件队列 if (name in model) { model[name].forEach(handler => handler(...args)); } }
var Keys = { BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, PAUSE: 19, CAPS_LOCK: 20, ESCAPE: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT_ARROW: 37, UP_ARROW: 38, RIGHT_ARROW: 39, DOWN_ARROW: 40, INSERT: 45, DELETE: 46, KEY_0: 48, KEY_1: 49, KEY_2: 50, KEY_3: 51, KEY_4: 52, KEY_5: 53, KEY_6: 54, KEY_7: 55, KEY_8: 56, KEY_9: 57, KEY_A: 65, KEY_B: 66, KEY_C: 67, KEY_D: 68, KEY_E: 69, KEY_F: 70, KEY_G: 71, KEY_H: 72, KEY_I: 73, KEY_J: 74, KEY_K: 75, KEY_L: 76, KEY_M: 77, KEY_N: 78, KEY_O: 79, KEY_P: 80, KEY_Q: 81, KEY_R: 82, KEY_S: 83, KEY_T: 84, KEY_U: 85, KEY_V: 86, KEY_W: 87, KEY_X: 88, KEY_Y: 89, KEY_Z: 90, LEFT_META: 91, RIGHT_META: 92, SELECT: 93, NUMPAD_0: 96, NUMPAD_1: 97, NUMPAD_2: 98, NUMPAD_3: 99, NUMPAD_4: 100, NUMPAD_5: 101, NUMPAD_6: 102, NUMPAD_7: 103, NUMPAD_8: 104, NUMPAD_9: 105, MULTIPLY: 106, ADD: 107, SUBTRACT: 109, DECIMAL: 110, DIVIDE: 111, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, NUM_LOCK: 144, SCROLL_LOCK: 145, SEMICOLON: 186, EQUALS: 187, COMMA: 188, DASH: 189, PERIOD: 190, FORWARD_SLASH: 191, GRAVE_ACCENT: 192, OPEN_BRACKET: 219, BACK_SLASH: 220, CLOSE_BRACKET: 221, SINGLE_QUOTE: 222 };
'use strict'; describe('Controller: CreategroupCtrl', function () { // load the controller's module beforeEach(module('infoApp')); var CreategroupCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); CreategroupCtrl = $controller('CreategroupCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
import React from 'react' import PropTypes from 'prop-types' // external-global styles must be imported in your JS. import normalizeCss from 'normalize.css' import resetcss from 'styles/reset.less' import hljscss from 'styles/hljs.css' // import normalizeCss from 'normalize.css' import s from './Layout.css' import Header from './Header' import Footer from './Footer' import Content from './Content' class Layout extends React.Component { static propTypes = { children: PropTypes.node.isRequired, } render() { return ( <div id={s.layout}> <Header /> <Content content={this.props.children} /> <Footer /> </div> ) } } export default Layout
import React from 'react'; import { Provider } from 'react-redux'; import { renderToString } from 'react-dom/server'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; function renderFullPage(html, preloadedState) { return ` <!doctype html> <html> <head> <title>Dashboard Dashinator Style</title> <link rel="stylesheet" href="/application.css"> <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"> <link rel="stylesheet" href="//code.shutterstock.com/rickshaw/rickshaw.min.css"> <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script> </head> <body style='margin: 0px'> <div id="app">${html}</div> <script> window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')} </script> <script src="/bundle.js"></script> </body> </html> `; } const handleRender = currentStateFunc => (req, res) => { const currentState = currentStateFunc(); const store = configureStore(currentState); const html = renderToString( <Provider store={ store }> <App /> </Provider> ); const finalState = store.getState(); res.send(renderFullPage(html, finalState)); }; module.exports = handleRender;
/** * Created by DELL on 2017/7/13. */ var svg = dreamCharts.getSVG("#svg"); //定义需要的全局变量 var svg_width = svg.attr("width"),svg_height = svg.attr("height"); var wStart = svg_width*0.05,wEnd = svg_width*0.95,hStart = svg_height*0.05,hEnd = svg_height*0.95;//依次是直方图范围左上角顶点x坐标,直方图范围右下角顶点x坐标,直方图范围左上角顶点y坐标,直方图范围右下角顶点y坐标 var data = { "name": "AAA", "children": [ { "name": "BBB", "children": [ { "name": "CCC", "children": [ { "name": "DDD", "children": [ { "name": "EEE", "size": 1 }, { "name": "EEE", "size": 2 }, { "name": "EEE", "size": 13 }, { "name": "EEE", "size": 4 }, { "name": "EEE", "size": 5 } ] }, { "name": "DDD", "size": 6 }, { "name": "DDD", "children": [ { "name": "EEE", "size": 7 }, { "name": "EEE", "size": 8 }, { "name": "EEE", "size":9 }, { "name": "EEE", "size": 10 } ] }, { "name": "DDD", "size": 12 }, { "name": "DDD", "size": 13 }, { "name": "DDD", "children": [ { "name": "EEE", "size": 25 } ] } ] }, { "name": "CCC", "size": 15 }, { "name": "CCC", "size": 16 }, { "name": "CCC", "size": 17 }, { "name": "CCC", "size": 18 }, { "name": "CCC", "size": 19 } ] }, { "name": "BBB", "children": [ { "name": "CCC", "size": 22 }, { "name": "CCC", "size": 23 }, { "name": "CCC", "size":24 }, { "name": "CCC", "size": 25 }, { "name": "CCC", "size": 26 } ] }, { "name": "BBB", "size": 21 }, { "name": "BBB", "children": [ { "name": "CCC", "size": 22 }, { "name": "CCC", "size": 23 }, { "name": "CCC", "size":24 }, { "name": "CCC", "size": 25 } ] }, { "name": "BBB", "size": 27 } ] }; var pack = dreamCharts.pack.settings({ data:data, xOffsetText:-10, yOffsetText:60 }); pack.drawPack(wStart,wEnd,hStart,hEnd,"pack"); svg.selectAll(".pack5").attr({ fill:"red" });
var util = require('util'); var assert = require('assert'); var _ = require('lodash'); describe('Association Interface', function() { describe('Has Many Through Association with Custom Primary Keys', function() { ///////////////////////////////////////////////////// // TEST SETUP //////////////////////////////////////////////////// before(function(done) { // Check Stadium hasManytoMany Team through Venue assert.strictEqual(Associations.Stadiumcustom.attributes.teams.collection, 'teamcustom'); assert.strictEqual(Associations.Teamcustom.attributes.stadiums.collection, 'stadiumcustom'); assert.strictEqual(Associations.Venuecustom.attributes.stadium.model, 'stadiumcustom'); assert.strictEqual(Associations.Venuecustom.attributes.team.model, 'teamcustom'); var stadiumRecords = [ { address: 'a00-A', name: 'hasManyThrough find customPK' }, { address: 'b00-B', name: 'hasManyThrough find customPK' } ]; Associations.Stadiumcustom.createEach(stadiumRecords, function(err, stadiums) { assert.ifError(err); Associations.Stadiumcustom.find({ name: 'hasManyThrough find customPK' }) .sort('address asc') .exec(function(err, stadiums) { assert.ifError(err); // Create 8 teams, 4 for one stadium, 4 for the other var teams = []; for(var i=0; i<8; i++) { if(i < 4) teams.push({ location: 'team'+i, stadiums: stadiums[0].address }); if(i >= 4) teams.push({ location: 'team'+i, stadiums: stadiums[1].address }); } Associations.Teamcustom.createEach(teams, function(err, teams) { assert.ifError(err); done(); }); }); }); }); describe('.find', function() { ///////////////////////////////////////////////////// // TEST METHODS //////////////////////////////////////////////////// it('should return teams when the populate criteria is added', function(done) { Associations.Stadiumcustom.find({ name: 'hasManyThrough find customPK' }) .populate('teams') .exec(function(err, stadiums) { assert.ifError(err); assert(Array.isArray(stadiums)); assert.strictEqual(stadiums.length, 2, 'expected 2 stadiums, got these stadiums:'+require('util').inspect(stadiums, false, null)); assert(Array.isArray(stadiums[0].teams)); assert(Array.isArray(stadiums[1].teams)); assert.strictEqual(stadiums[0].teams.length, 4); assert.strictEqual(stadiums[1].teams.length, 4); done(); }); }); }); }); });
(function(root) { 'use strict'; root.app = root.app || {}; root.app.View = root.app.View || {}; root.app.Helper = root.app.Helper || {}; root.app.View.mapMapView = Backbone.View.extend({ initialize: function(options) { this.router = options.router; }, onMapClick: function() { this.trigger('click:map'); }, onZoomEnd: function() { this.trigger('zoom:map'); }, onMapRendered: function() { this.trigger('render:map', this.map); }, start: function() { this.render(); }, render: function() { L.mapbox.accessToken = root.app.Helper.globals.mapToken; this.map = L.mapbox.map('map', 'undp-caboverde.b3dd420c', { center: [20.5, 26], zoom: 3 }); this.map.zoomControl.setPosition('bottomleft'); this.map.on('click', this.onMapClick.bind(this)); this.map.on('zoomend', this.onZoomEnd.bind(this)); /* We could directly trigger the event but as the map could be * asynchronous, we prefer to let this structure */ this.onMapRendered(); }, /* Zoom to fit the passed markers */ zoomToFit: function(markers) { var latLngs = _.map(markers, function(m) { return m.options.originalLatLng || m.getLatLng(); }); /* We don't zoom if the markers have the same position */ if(_.uniq(latLngs).length > 1) { this.map.fitBounds(latLngs, { padding: L.point(30, 30) }); } }, /* Zoom to the passed marker */ zoomToMarker: function(marker) { this.map.setView(marker.options.originalLatLng || marker.getLatLng(), 16); }, /* Center the map to the latLng object or array of coordinates passed as * argument */ centerMap: function(latLng) { if(this.map) { this.map.panTo(latLng); } } }); })(this);
module.exports = [ {name: "bin/{{ project-name }}.js", data: require("./file/bin")}, {name: "lib/{{ project-name }}.js", data: ""}, {name: "test/lib/{{ project-name }}.test.js", data: require("./file/test")}, {name: "test/suite.js", data: require("./file/suite")}, {name: ".gitignore", data: require("./file/gitignore")}, {name: "LICENSE", data: require("../common/file/license")}, {name: "Makefile", data: require("./file/makefile")}, {name: "package.json", data: require("./file/package")}, {name: "README.md", data: require("./file/readme")} ];
/*! * jQuery blockUI plugin * Version 2.36 (16-NOV-2010) * @requires jQuery v1.2.3 or later * * Examples at: http://malsup.com/jquery/block/ * Copyright (c) 2007-2008 M. Alsup * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to Amir-Hossein Sobhi for some excellent contributions! */ ;(function($) { if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) { alert('blockUI requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery); return; } $.fn._fadeIn = $.fn.fadeIn; var noOp = function() {}; // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle // retarded userAgent strings on Vista) var mode = document.documentMode || 0; var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8); var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode; // global $ methods for blocking/unblocking the entire page $.blockUI = function(opts) { install(window, opts); }; $.unblockUI = function(opts) { remove(window, opts); }; // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) $.growlUI = function(title, message, timeout, onClose) { var $m = $('<div class="growlUI"></div>'); if (title) $m.append('<h1>'+title+'</h1>'); if (message) $m.append('<h2>'+message+'</h2>'); if (timeout == undefined) timeout = 3000; $.blockUI({ message: $m, fadeIn: 700, fadeOut: 1000, centerY: false, timeout: timeout, showOverlay: false, onUnblock: onClose, css: $.blockUI.defaults.growlCSS }); }; // plugin method for blocking element content $.fn.block = function(opts) { return this.unblock({ fadeOut: 0 }).each(function() { if ($.css(this,'position') == 'static') this.style.position = 'relative'; if ($.browser.msie) this.style.zoom = 1; // force 'hasLayout' install(this, opts); }); }; // plugin method for unblocking element content $.fn.unblock = function(opts) { return this.each(function() { remove(this, opts); }); }; $.blockUI.version = 2.35; // 2nd generation blocking at no extra cost! // override these in your code to change the default behavior and style $.blockUI.defaults = { // message displayed when blocking (use null for no message) message: '<h1>Please wait...</h1>', title: null, // title string; only used when theme == true draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) theme: false, // set to true to use with jQuery UI themes // styles for the message when blocking; if you wish to disable // these and use an external stylesheet then do this in your code: // $.blockUI.defaults.css = {}; css: { padding: 0, margin: 0, width: '30%', top: '40%', left: '35%', textAlign: 'center', color: '#000', border: '3px solid #aaa', backgroundColor:'#fff', cursor: 'wait' }, // minimal style set used when themes are used themedCSS: { width: '30%', top: '40%', left: '35%' }, // styles for the overlay overlayCSS: { backgroundColor: '#000', opacity: 0.6, cursor: 'wait' }, // styles applied when using $.growlUI growlCSS: { width: '350px', top: '10px', left: '', right: '10px', border: 'none', padding: '5px', opacity: 0.6, cursor: 'default', color: '#fff', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', 'border-radius': '10px' }, // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w // (hat tip to Jorge H. N. de Vasconcelos) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', // force usage of iframe in non-IE browsers (handy for blocking applets) forceIframe: false, // z-index for the blocking overlay baseZ: 1000, // set these to true to have the message automatically centered centerX: true, // <-- only effects element blocking (page block controlled via css above) centerY: true, // allow body element to be stetched in ie6; this makes blocking look better // on "short" pages. disable if you wish to prevent changes to the body height allowBodyStretch: true, // enable if you want key and mouse events to be disabled for content that is blocked bindEvents: true, // be default blockUI will supress tab navigation from leaving blocking content // (if bindEvents is true) constrainTabKey: true, // fadeIn time in millis; set to 0 to disable fadeIn on block fadeIn: 200, // fadeOut time in millis; set to 0 to disable fadeOut on unblock fadeOut: 400, // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock timeout: 0, // disable if you don't want to show the overlay showOverlay: true, // if true, focus will be placed in the first available input field when // page blocking focusInput: true, // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) applyPlatformOpacityRules: true, // callback method invoked when fadeIn has completed and blocking message is visible onBlock: null, // callback method invoked when unblocking has completed; the callback is // passed the element that has been unblocked (which is the window object for page // blocks) and the options that were passed to the unblock call: // onUnblock(element, options) onUnblock: null, // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 quirksmodeOffsetHack: 4, // class name of the message block blockMsgClass: 'blockMsg' }; // private data and functions follow... var pageBlock = null; var pageBlockEls = []; function install(el, opts) { var full = (el == window); var msg = opts && opts.message !== undefined ? opts.message : undefined; opts = $.extend({}, $.blockUI.defaults, opts || {}); opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); var css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); msg = msg === undefined ? opts.message : msg; // remove the current block (if there is one) if (full && pageBlock) remove(window, {fadeOut:0}); // if an existing element is being used as the blocking content then we capture // its current place in the DOM (and current display style) so we can restore // it when we unblock if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { var node = msg.jquery ? msg[0] : msg; var data = {}; $(el).data('blockUI.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; if (data.parent) data.parent.removeChild(node); } var z = opts.baseZ; // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; // layer1 is the iframe layer which is used to supress bleed through of underlying content // layer2 is the overlay layer which has opacity and a wait cursor (by default) // layer3 is the message content that is displayed while blocking var lyr1 = ($.browser.msie || opts.forceIframe) ? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>') : $('<div class="blockUI" style="display:none"></div>'); var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'); var lyr3, s; if (opts.theme && full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:fixed">' + '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>' + '<div class="ui-widget-content ui-dialog-content"></div>' + '</div>'; } else if (opts.theme) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+z+';display:none;position:absolute">' + '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>' + '<div class="ui-widget-content ui-dialog-content"></div>' + '</div>'; } else if (full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+z+';display:none;position:fixed"></div>'; } else { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+z+';display:none;position:absolute"></div>'; } lyr3 = $(s); // if we have a message, style it if (msg) { if (opts.theme) { lyr3.css(themedCSS); lyr3.addClass('ui-widget-content'); } else lyr3.css(css); } // style the overlay if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))) lyr2.css(opts.overlayCSS); lyr2.css('position', full ? 'fixed' : 'absolute'); // make iframe layer transparent in IE if ($.browser.msie || opts.forceIframe) lyr1.css('opacity',0.0); //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); $.each(layers, function() { this.appendTo($par); }); if (opts.theme && opts.draggable && $.fn.draggable) { lyr3.draggable({ handle: '.ui-dialog-titlebar', cancel: 'li' }); } // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0); if (ie6 || expr) { // give body 100% height if (full && opts.allowBodyStretch && $.boxModel) $('html,body').css('height','100%'); // fix ie6 issue when blocked element has a border width if ((ie6 || !$.boxModel) && !full) { var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); var fixT = t ? '(0 - '+t+')' : 0; var fixL = l ? '(0 - '+l+')' : 0; } // simulate fixed position $.each([lyr1,lyr2,lyr3], function(i,o) { var s = o[0].style; s.position = 'absolute'; if (i < 2) { full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"') : s.setExpression('height','this.parentNode.offsetHeight + "px"'); full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"') : s.setExpression('width','this.parentNode.offsetWidth + "px"'); if (fixL) s.setExpression('left', fixL); if (fixT) s.setExpression('top', fixT); } else if (opts.centerY) { if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); s.marginTop = 0; } else if (!opts.centerY && full) { var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0; var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; s.setExpression('top',expression); } }); } // show the message if (msg) { if (opts.theme) lyr3.find('.ui-widget-content').append(msg); else lyr3.append(msg); if (msg.jquery || msg.nodeType) $(msg).show(); } if (($.browser.msie || opts.forceIframe) && opts.showOverlay) lyr1.show(); // opacity is zero if (opts.fadeIn) { var cb = opts.onBlock ? opts.onBlock : noOp; var cb1 = (opts.showOverlay && !msg) ? cb : noOp; var cb2 = msg ? cb : noOp; if (opts.showOverlay) lyr2._fadeIn(opts.fadeIn, cb1); if (msg) lyr3._fadeIn(opts.fadeIn, cb2); } else { if (opts.showOverlay) lyr2.show(); if (msg) lyr3.show(); if (opts.onBlock) opts.onBlock(); } // bind key and mouse events bind(1, el, opts); if (full) { pageBlock = lyr3[0]; pageBlockEls = $(':input:enabled:visible',pageBlock); if (opts.focusInput) setTimeout(focus, 20); } else center(lyr3[0], opts.centerX, opts.centerY); if (opts.timeout) { // auto-unblock var to = setTimeout(function() { full ? $.unblockUI(opts) : $(el).unblock(opts); }, opts.timeout); $(el).data('blockUI.timeout', to); } }; // remove the block function remove(el, opts) { var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $('.blockUI', el); if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { els.fadeOut(opts.fadeOut); setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut); } else reset(els, data, opts, el); }; // move blocking element back into the DOM where it started function reset(els,data,opts,el) { els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; if (data.parent) data.parent.appendChild(data.el); $(el).removeData('blockUI.history'); } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); }; // bind/unbind the handler function bind(b, el, opts) { var full = el == window, $el = $(el); // don't bother unbinding if there is nothing to unbind if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) return; if (!full) $el.data('blockUI.isBlocked', b); // don't bind events when overlay is not in use or if bindEvents is false if (!opts.bindEvents || (b && !opts.showOverlay)) return; // bind anchors and inputs for mouse and key events var events = 'mousedown mouseup keydown keypress'; b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler); // former impl... // var $e = $('a,:input'); // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); }; // event handler to suppress keyboard/mouse events when blocking function handler(e) { // allow tab navigation (conditionally) if (e.keyCode && e.keyCode == 9) { if (pageBlock && e.data.constrainTabKey) { var els = pageBlockEls; var fwd = !e.shiftKey && e.target === els[els.length-1]; var back = e.shiftKey && e.target === els[0]; if (fwd || back) { setTimeout(function(){focus(back)},10); return false; } } } var opts = e.data; // allow events within the message content if ($(e.target).parents('div.' + opts.blockMsgClass).length > 0) return true; // allow events for content that is not being blocked return $(e.target).parents().children().filter('div.blockUI').length == 0; }; function focus(back) { if (!pageBlockEls) return; var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; if (e) e.focus(); }; function center(el, x, y) { var p = el.parentNode, s = el.style; var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); if (x) s.left = l > 0 ? (l+'px') : '0'; if (y) s.top = t > 0 ? (t+'px') : '0'; }; function sz(el, p) { return parseInt($.css(el,p))||0; }; })(jQuery);
/* * grunt-json-toc-generator * https://github.com/jediq/documento/grunt-json-toc-generator * * Copyright (c) 2015 Ricky Walker * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). json_toc_generator: { test: { src: ['test/fixtures/**/*.md', 'test/fixtures/**/*.markdown', 'test/fixtures/**/*.html'], dest: 'tmp/toc.json' } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'json_toc_generator:test', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
/** * Checks if the given form element's value equals the expected value. * * ``` * this.demoTest = function (browser) { * browser.assert.value("form.login input[type=text]", "username"); * }; * ``` * * @method value * @param {string|object} definition The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide#element-properties). * @param {string} expected The expected text. * @param {string} [msg] Optional log message to display in the output. If missing, one is displayed by default. * @api assertions * @deprecated */ const {setElementSelectorProps} = require('../../utils'); exports.assertion = function(definition, expected, msg) { this.options = { elementSelector: true }; // eslint-disable-next-line no-console console.warn('DEPRECATED: the assertion .value() has been deprecated and will be ' + 'removed from future versions. Use assert.valueEquals() instead.'); this.expected = function() { return this.negate ? `not equals '${expected}'` : `equals '${expected}'`; }; this.formatMessage = function() { const message = msg || `Testing if value of element %s ${this.negate ? 'doesn\'t equal %s' : 'equals %s'}`; return { message, args: [this.elementSelector, `'${expected}'`] }; }; this.actual = function(passed) { const value = this.getValue(); if (typeof value != 'string') { return 'Element does not have a value attribute'; } return this.getValue(); }; this.evaluate = function(value) { return value === expected; }; this.command = function(callback) { this.api.getValue(setElementSelectorProps(definition, { suppressNotFoundErrors: true }), callback); }; };
'use strict'; var ValidateFields = function (formValues) { var isValid = {}; isValid['all'] = true; var validator = { formValues: formValues, name: function (inputName) { var self = this; return ( self.checkMinLength(inputName, 4)); }, email: function (inputEmail) { var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; return filter.test(inputEmail); }, company: function (inputCompany) { var self = this; return ( self.checkMinLength(inputCompany, 3)); }, number: function (inputNumber) { inputNumber = inputNumber.replace(/\s/g, ''); var filter = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im; return filter.test(inputNumber); }, message: function (inputMessage) { var self = this; return ( self.checkMinLength(inputMessage, 5)); }, checkAlphaNumeric: function (str) { return true; }, checkMinLength: function (str, length) { return (str.length >= length); } }; for (var field in formValues) { if (formValues.hasOwnProperty(field)) { var validField = validator[field](formValues[field]); isValid[field] = (validField) ? 'success' : 'error'; if (!validField) { isValid['all'] = false; } } } return isValid; }; module.exports = ValidateFields;
import React from 'react' import ReactDOM from 'react-dom' // class Hello extends React.Component { // render(){ // return React.createElement('h1', null, 'Hello') // } // } class Clock extends React.Component { constructor(){ super(); this.state = { now: new Date().toLocaleTimeString() }; setInterval(() => { // this.state.now = new Date().toLocaleTimeString() this.setState({ now: new Date().toLocaleTimeString() }) }, 1000) } render(){ console.log('Rendering Clock') const now = this.state.now return <div>{now} <Hello name='from clock' /> </div>; } } class Hello extends React.Component { render() { // console.log(this.props) console.log('Rendering Hello') return <h1>Hello {this.props.name}</h1>; } } Hello.propTypes = { name: React.PropTypes.string.isRequired } class Controlled extends React.Component{ constructor(){ super(); this.state = { value : '123' } this.onChange = this.onChange.bind(this) } onChange(e) { this.setState({value: e.target.value}) } render(){ return <input value={this.state.value} onChange={this.onChange} /> } } class Uncontrolled extends React.Component{ constructor(){ super(); this.input = null; setInterval(() => console.log(this.input.value), 5000) } render(){ return <input defaultValue='123' ref={e => this.input = e} /> } } class App extends React.Component{ constructor(){ super(); this.state = { counter: 0 } this.onClick = this.onClick.bind(this); } onClick(){ console.log('I was clicked') this.setState({counter: this.state.counter + 1}) } render(){ console.log('Rendering App') return ( <div> <Hello name={'Maurice'} /> <button onClick={this.onClick}>Click me</button> {this.state.counter} <Clock/> <Controlled /> <Uncontrolled /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app') )
import Ember from 'ember'; import layout from '../templates/components/m3r-modal-buttons'; export default Ember.Component.extend({ modal: Ember.inject.service(), layout: layout, actions: { closeModal() { this.get('modal').close('close'); }, ok() { this.get('modal').close('ok'); } } });
/*! * DevExtreme (dx.messages.cs.js) * Version: 21.1.4 (build 21209-0924) * Build date: Wed Jul 28 2021 * * Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define((function(require) { factory(require("devextreme/localization")) })) } else if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } }(0, (function(localization) { localization.loadMessages({ cs: { Yes: "Ano", No: "Ne", Cancel: "Zru\u0161it", Clear: "Smazat", Done: "Hotovo", Loading: "Nahr\xe1v\xe1n\xed...", Select: "V\xfdb\u011br...", Search: "Hledat", Back: "Zp\u011bt", OK: "OK", "dxCollectionWidget-noDataText": "\u017d\xe1dn\xe1 data k zobrazen\xed", "dxDropDownEditor-selectLabel": "V\xfdb\u011br", "validation-required": "povinn\xe9", "validation-required-formatted": "{0} je povinn\xfdch", "validation-numeric": "Hodnota mus\xed b\xfdt \u010d\xedslo", "validation-numeric-formatted": "{0} mus\xed b\xfdt \u010d\xedslo", "validation-range": "Hodnota je mimo rozsah", "validation-range-formatted": "{0} je mimo rozsah", "validation-stringLength": "D\xe9lka textov\xe9ho \u0159etezce nen\xed spr\xe1vn\xe1", "validation-stringLength-formatted": "D\xe9lka textu {0} nen\xed spr\xe1vn\xe1", "validation-custom": "Neplatn\xe1 hodnota", "validation-custom-formatted": "{0} je neplatn\xfdch", "validation-async": "Neplatn\xe1 hodnota", "validation-async-formatted": "{0} je neplatn\xfdch", "validation-compare": "Hodnoty se neshoduj\xed", "validation-compare-formatted": "{0} se neshoduje", "validation-pattern": "Hodnota neodpov\xedd\xe1 vzoru", "validation-pattern-formatted": "{0} neodpov\xedd\xe1 vzoru", "validation-email": "Neplatn\xfd email", "validation-email-formatted": "{0} nen\xed platn\xfd", "validation-mask": "Hodnota nen\xed platn\xe1", "dxLookup-searchPlaceholder": "Minim\xe1ln\xed po\u010det znak\u016f: {0}", "dxList-pullingDownText": "St\xe1hn\u011bte dol\u016f pro obnoven\xed...", "dxList-pulledDownText": "Uvoln\u011bte pro obnoven\xed...", "dxList-refreshingText": "Obnovuji...", "dxList-pageLoadingText": "Nahr\xe1v\xe1m...", "dxList-nextButtonText": "V\xedce", "dxList-selectAll": "Vybrat v\u0161e", "dxListEditDecorator-delete": "Smazat", "dxListEditDecorator-more": "V\xedce", "dxScrollView-pullingDownText": "St\xe1hn\u011bte dol\u016f pro obnoven\xed...", "dxScrollView-pulledDownText": "Uvoln\u011bte pro obnoven\xed...", "dxScrollView-refreshingText": "Obnovuji...", "dxScrollView-reachBottomText": "Nahr\xe1v\xe1m...", "dxDateBox-simulatedDataPickerTitleTime": "Vyberte \u010das", "dxDateBox-simulatedDataPickerTitleDate": "Vyberte datum", "dxDateBox-simulatedDataPickerTitleDateTime": "Vyberte datum a \u010das", "dxDateBox-validation-datetime": "Hodnota mus\xed b\xfdt datum nebo \u010das", "dxFileUploader-selectFile": "Vyberte soubor", "dxFileUploader-dropFile": "nebo p\u0159eneste soubor sem", "dxFileUploader-bytes": "byt\u016f", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Nahr\xe1t", "dxFileUploader-uploaded": "Nahr\xe1no", "dxFileUploader-readyToUpload": "P\u0159ipraveno k nahr\xe1n\xed", "dxFileUploader-uploadAbortedMessage": "TODO", "dxFileUploader-uploadFailedMessage": "Nahr\xe1v\xe1n\xed selhalo", "dxFileUploader-invalidFileExtension": "", "dxFileUploader-invalidMaxFileSize": "", "dxFileUploader-invalidMinFileSize": "", "dxRangeSlider-ariaFrom": "Od", "dxRangeSlider-ariaTill": "Do", "dxSwitch-switchedOnText": "ZAP", "dxSwitch-switchedOffText": "VYP", "dxForm-optionalMark": "voliteln\xfd", "dxForm-requiredMessage": "{0} je vy\u017eadov\xe1no", "dxNumberBox-invalidValueMessage": "Hodnota mus\xed b\xfdt \u010d\xedslo", "dxNumberBox-noDataText": "\u017d\xe1dn\xe1 data", "dxDataGrid-columnChooserTitle": "V\xfdb\u011br sloupc\u016f", "dxDataGrid-columnChooserEmptyText": "P\u0159esu\u0148te sloupec zde pro skyt\xed", "dxDataGrid-groupContinuesMessage": "Pokra\u010dovat na dal\u0161\xed stran\u011b", "dxDataGrid-groupContinuedMessage": "Pokra\u010dov\xe1n\xed z p\u0159edchoz\xed strany", "dxDataGrid-groupHeaderText": "Slou\u010dit sloupce", "dxDataGrid-ungroupHeaderText": "Odd\u011blit", "dxDataGrid-ungroupAllText": "Odd\u011blit v\u0161e", "dxDataGrid-editingEditRow": "Upravit", "dxDataGrid-editingSaveRowChanges": "Ulo\u017eit", "dxDataGrid-editingCancelRowChanges": "Zru\u0161it", "dxDataGrid-editingDeleteRow": "Smazat", "dxDataGrid-editingUndeleteRow": "Obnovit", "dxDataGrid-editingConfirmDeleteMessage": "Opravdu chcete smazat tento z\xe1znam?", "dxDataGrid-validationCancelChanges": "Zru\u0161it zm\u011bny", "dxDataGrid-groupPanelEmptyText": "P\u0159eneste hlavi\u010dku sloupce zde pro slou\u010den\xed", "dxDataGrid-noDataText": "\u017d\xe1dn\xe1 data", "dxDataGrid-searchPanelPlaceholder": "Hled\xe1n\xed...", "dxDataGrid-filterRowShowAllText": "(V\u0161e)", "dxDataGrid-filterRowResetOperationText": "Reset", "dxDataGrid-filterRowOperationEquals": "Rovn\xe1 se", "dxDataGrid-filterRowOperationNotEquals": "Nerovn\xe1 se", "dxDataGrid-filterRowOperationLess": "Men\u0161\xed", "dxDataGrid-filterRowOperationLessOrEquals": "Men\u0161\xed nebo rovno", "dxDataGrid-filterRowOperationGreater": "V\u011bt\u0161\xed", "dxDataGrid-filterRowOperationGreaterOrEquals": "V\u011bt\u0161\xed nebo rovno", "dxDataGrid-filterRowOperationStartsWith": "Za\u010d\xedn\xe1 na", "dxDataGrid-filterRowOperationContains": "Obsahuje", "dxDataGrid-filterRowOperationNotContains": "Neobsahuje", "dxDataGrid-filterRowOperationEndsWith": "Kon\u010d\xed na", "dxDataGrid-filterRowOperationBetween": "Mezi", "dxDataGrid-filterRowOperationBetweenStartText": "Za\u010d\xedn\xe1", "dxDataGrid-filterRowOperationBetweenEndText": "Kon\u010d\xed", "dxDataGrid-applyFilterText": "Pou\u017e\xedt filtr", "dxDataGrid-trueText": "Plat\xed", "dxDataGrid-falseText": "Neplat\xed", "dxDataGrid-sortingAscendingText": "Srovnat vzestupn\u011b", "dxDataGrid-sortingDescendingText": "Srovnat sestupn\u011b", "dxDataGrid-sortingClearText": "Zru\u0161it rovn\xe1n\xed", "dxDataGrid-editingSaveAllChanges": "Ulo\u017eit zm\u011bny", "dxDataGrid-editingCancelAllChanges": "Zru\u0161it zm\u011bny", "dxDataGrid-editingAddRow": "P\u0159idat \u0159\xe1dek", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "Min {1} je {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "Max {1} je {0}", "dxDataGrid-summaryAvg": "Pr\u016fm.: {0}", "dxDataGrid-summaryAvgOtherColumn": "Pr\u016fm\u011br ze {1} je {0}", "dxDataGrid-summarySum": "Suma: {0}", "dxDataGrid-summarySumOtherColumn": "Suma {1} je {0}", "dxDataGrid-summaryCount": "Po\u010det: {0}", "dxDataGrid-columnFixingFix": "Uchytit", "dxDataGrid-columnFixingUnfix": "Uvolnit", "dxDataGrid-columnFixingLeftPosition": "Vlevo", "dxDataGrid-columnFixingRightPosition": "Vpravo", "dxDataGrid-exportTo": "Export", "dxDataGrid-exportToExcel": "Export do se\u0161itu Excel", "dxDataGrid-exporting": "Export...", "dxDataGrid-excelFormat": "soubor Excel", "dxDataGrid-selectedRows": "Vybran\xe9 \u0159\xe1dky", "dxDataGrid-exportSelectedRows": "Export vybran\xfdch \u0159\xe1dk\u016f", "dxDataGrid-exportAll": "Exportovat v\u0161echny z\xe1znamy", "dxDataGrid-headerFilterEmptyValue": "(pr\xe1zdn\xe9)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "Zru\u0161it", "dxDataGrid-ariaColumn": "Sloupec", "dxDataGrid-ariaValue": "Hodnota", "dxDataGrid-ariaFilterCell": "Filtrovat bu\u0148ku", "dxDataGrid-ariaCollapse": "Sbalit", "dxDataGrid-ariaExpand": "Rozbalit", "dxDataGrid-ariaDataGrid": "Datov\xe1 m\u0159\xed\u017eka", "dxDataGrid-ariaSearchInGrid": "Hledat v datov\xe9 m\u0159\xed\u017ece", "dxDataGrid-ariaSelectAll": "Vybrat v\u0161e", "dxDataGrid-ariaSelectRow": "Vybrat \u0159\xe1dek", "dxDataGrid-filterBuilderPopupTitle": "Tvorba Filtru", "dxDataGrid-filterPanelCreateFilter": "Vytvo\u0159it Filtr", "dxDataGrid-filterPanelClearFilter": "Smazat", "dxDataGrid-filterPanelFilterEnabledHint": "Povolit Filtr", "dxTreeList-ariaTreeList": "Tree list", "dxTreeList-editingAddRowToNode": "P\u0159idat", "dxPager-infoText": "Strana {0} ze {1} ({2} polo\u017eek)", "dxPager-pagesCountText": "ze", "dxPager-pageSizesAllText": "V\u0161e", "dxPivotGrid-grandTotal": "Celkem", "dxPivotGrid-total": "{0} Celkem", "dxPivotGrid-fieldChooserTitle": "V\xfdb\u011br pole", "dxPivotGrid-showFieldChooser": "Zobrazit v\xfdb\u011br pole", "dxPivotGrid-expandAll": "Rozbalit v\u0161e", "dxPivotGrid-collapseAll": "Sbalit v\u0161e", "dxPivotGrid-sortColumnBySummary": 'Srovnat "{0}" podle tohoto sloupce', "dxPivotGrid-sortRowBySummary": 'Srovnat "{0}" podle tohoto \u0159\xe1dku', "dxPivotGrid-removeAllSorting": "Odstranit ve\u0161ker\xe9 t\u0159\xedd\u011bn\xed", "dxPivotGrid-dataNotAvailable": "nedostupn\xe9", "dxPivotGrid-rowFields": "Pole \u0159\xe1dk\u016f", "dxPivotGrid-columnFields": "Pole sloupc\u016f", "dxPivotGrid-dataFields": "Pole dat", "dxPivotGrid-filterFields": "Filtrovat pole", "dxPivotGrid-allFields": "V\u0161echna pole", "dxPivotGrid-columnFieldArea": "Zde vlo\u017ete pole sloupc\u016f", "dxPivotGrid-dataFieldArea": "Zde vlo\u017ete pole dat", "dxPivotGrid-rowFieldArea": "Zde vlo\u017ete pole \u0159\xe1dk\u016f", "dxPivotGrid-filterFieldArea": "Zde vlo\u017ete filtr pole", "dxScheduler-editorLabelTitle": "P\u0159edm\u011bt", "dxScheduler-editorLabelStartDate": "Po\u010d\xe1te\u010dn\xed datum", "dxScheduler-editorLabelEndDate": "Koncov\xe9 datum", "dxScheduler-editorLabelDescription": "Popis", "dxScheduler-editorLabelRecurrence": "Opakovat", "dxScheduler-openAppointment": "Otev\u0159\xedt sch\u016fzku", "dxScheduler-recurrenceNever": "Nikdy", "dxScheduler-recurrenceMinutely": "Minutely", "dxScheduler-recurrenceHourly": "Hourly", "dxScheduler-recurrenceDaily": "Denn\u011b", "dxScheduler-recurrenceWeekly": "T\xfddn\u011b", "dxScheduler-recurrenceMonthly": "M\u011bs\xed\u010dn\u011b", "dxScheduler-recurrenceYearly": "Ro\u010dn\u011b", "dxScheduler-recurrenceRepeatEvery": "Ka\u017ed\xfd", "dxScheduler-recurrenceRepeatOn": "Repeat On", "dxScheduler-recurrenceEnd": "Konec opakov\xe1n\xed", "dxScheduler-recurrenceAfter": "Po", "dxScheduler-recurrenceOn": "Zap", "dxScheduler-recurrenceRepeatMinutely": "minute(s)", "dxScheduler-recurrenceRepeatHourly": "hour(s)", "dxScheduler-recurrenceRepeatDaily": "dn\xed", "dxScheduler-recurrenceRepeatWeekly": "t\xfddn\u016f", "dxScheduler-recurrenceRepeatMonthly": "m\u011bs\xedc\u016f", "dxScheduler-recurrenceRepeatYearly": "rok\u016f", "dxScheduler-switcherDay": "Den", "dxScheduler-switcherWeek": "T\xfdden", "dxScheduler-switcherWorkWeek": "Pracovn\xed t\xfdden", "dxScheduler-switcherMonth": "M\u011bs\xedc", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "\u010casov\xe1 osa den", "dxScheduler-switcherTimelineWeek": "\u010casov\xe1 osa t\xfdden", "dxScheduler-switcherTimelineWorkWeek": "\u010casov\xe1 osa pracovn\xed t\xfdden", "dxScheduler-switcherTimelineMonth": "\u010casov\xe1 osa m\u011bs\xedc", "dxScheduler-recurrenceRepeatOnDate": "na den", "dxScheduler-recurrenceRepeatCount": "v\xfdskyt\u016f", "dxScheduler-allDay": "Cel\xfd den", "dxScheduler-confirmRecurrenceEditMessage": "Chcete upravit pouze tuto sch\u016fzku nebo celou s\xe9rii?", "dxScheduler-confirmRecurrenceDeleteMessage": "Chcete smazat pouze tuto sch\u016fzku nebo celou s\xe9rii?", "dxScheduler-confirmRecurrenceEditSeries": "Upravit s\xe9rii", "dxScheduler-confirmRecurrenceDeleteSeries": "Smazat s\xe9rii", "dxScheduler-confirmRecurrenceEditOccurrence": "Upravit sch\u016fzku", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Smazat sch\u016fzku", "dxScheduler-noTimezoneTitle": "Bez \u010dasov\xe9 z\xf3ny", "dxScheduler-moreAppointments": "{0} nav\xedc", "dxCalendar-todayButtonText": "Dnes", "dxCalendar-ariaWidgetName": "Kalend\xe1\u0159", "dxColorView-ariaRed": "\u010cerven\xe1", "dxColorView-ariaGreen": "Zelen\xe1", "dxColorView-ariaBlue": "Modr\xe1", "dxColorView-ariaAlpha": "Pr\u016fhledn\xe1", "dxColorView-ariaHex": "K\xf3d barvy", "dxTagBox-selected": "{0} vybr\xe1no", "dxTagBox-allSelected": "V\u0161e vybr\xe1no ({0})", "dxTagBox-moreSelected": "{0} nav\xedc", "vizExport-printingButtonText": "Tisk", "vizExport-titleMenuText": "Export/import", "vizExport-exportButtonText": "{0} soubor\u016f", "dxFilterBuilder-and": "A", "dxFilterBuilder-or": "NEBO", "dxFilterBuilder-notAnd": "NAND", "dxFilterBuilder-notOr": "NOR", "dxFilterBuilder-addCondition": "P\u0159idat podm\xednku", "dxFilterBuilder-addGroup": "P\u0159idat skupinu", "dxFilterBuilder-enterValueText": "<vlo\u017ete hodnotu>", "dxFilterBuilder-filterOperationEquals": "Rovn\xe1 se", "dxFilterBuilder-filterOperationNotEquals": "Nerovn\xe1 se", "dxFilterBuilder-filterOperationLess": "Men\u0161\xed ne\u017e", "dxFilterBuilder-filterOperationLessOrEquals": "Men\u0161\xed nebo rovno ne\u017e", "dxFilterBuilder-filterOperationGreater": "V\u011bt\u0161\xed ne\u017e", "dxFilterBuilder-filterOperationGreaterOrEquals": "V\u011bt\u0161\xed nebo rovno ne\u017e", "dxFilterBuilder-filterOperationStartsWith": "Za\u010d\xedn\xe1 na", "dxFilterBuilder-filterOperationContains": "Obsahuje", "dxFilterBuilder-filterOperationNotContains": "Neobsahuje", "dxFilterBuilder-filterOperationEndsWith": "Kon\u010d\xed na", "dxFilterBuilder-filterOperationIsBlank": "Je pr\xe1zdn\xe9", "dxFilterBuilder-filterOperationIsNotBlank": "Nen\xed pr\xe1zdn\xe9", "dxFilterBuilder-filterOperationBetween": "Mezi", "dxFilterBuilder-filterOperationAnyOf": "Libovoln\xfd z", "dxFilterBuilder-filterOperationNoneOf": "\u017d\xe1dn\xfd z", "dxHtmlEditor-dialogColorCaption": "!TODO!", "dxHtmlEditor-dialogBackgroundCaption": "!TODO!", "dxHtmlEditor-dialogLinkCaption": "!TODO!", "dxHtmlEditor-dialogLinkUrlField": "!TODO!", "dxHtmlEditor-dialogLinkTextField": "!TODO!", "dxHtmlEditor-dialogLinkTargetField": "!TODO!", "dxHtmlEditor-dialogImageCaption": "!TODO!", "dxHtmlEditor-dialogImageUrlField": "!TODO!", "dxHtmlEditor-dialogImageAltField": "!TODO!", "dxHtmlEditor-dialogImageWidthField": "!TODO!", "dxHtmlEditor-dialogImageHeightField": "!TODO!", "dxHtmlEditor-dialogInsertTableRowsField": "!TODO", "dxHtmlEditor-dialogInsertTableColumnsField": "!TODO", "dxHtmlEditor-dialogInsertTableCaption": "!TODO", "dxHtmlEditor-heading": "!TODO!", "dxHtmlEditor-normalText": "!TODO!", "dxHtmlEditor-background": "TODO", "dxHtmlEditor-bold": "TODO", "dxHtmlEditor-color": "TODO", "dxHtmlEditor-font": "TODO", "dxHtmlEditor-italic": "TODO", "dxHtmlEditor-link": "TODO", "dxHtmlEditor-image": "TODO", "dxHtmlEditor-size": "TODO", "dxHtmlEditor-strike": "TODO", "dxHtmlEditor-subscript": "TODO", "dxHtmlEditor-superscript": "TODO", "dxHtmlEditor-underline": "TODO", "dxHtmlEditor-blockquote": "TODO", "dxHtmlEditor-header": "TODO", "dxHtmlEditor-increaseIndent": "TODO", "dxHtmlEditor-decreaseIndent": "TODO", "dxHtmlEditor-orderedList": "TODO", "dxHtmlEditor-bulletList": "TODO", "dxHtmlEditor-alignLeft": "TODO", "dxHtmlEditor-alignCenter": "TODO", "dxHtmlEditor-alignRight": "TODO", "dxHtmlEditor-alignJustify": "TODO", "dxHtmlEditor-codeBlock": "TODO", "dxHtmlEditor-variable": "TODO", "dxHtmlEditor-undo": "TODO", "dxHtmlEditor-redo": "TODO", "dxHtmlEditor-clear": "TODO", "dxHtmlEditor-insertTable": "TODO", "dxHtmlEditor-insertRowAbove": "TODO", "dxHtmlEditor-insertRowBelow": "TODO", "dxHtmlEditor-insertColumnLeft": "TODO", "dxHtmlEditor-insertColumnRight": "TODO", "dxHtmlEditor-deleteColumn": "TODO", "dxHtmlEditor-deleteRow": "TODO", "dxHtmlEditor-deleteTable": "TODO", "dxHtmlEditor-list": "TODO", "dxHtmlEditor-ordered": "TODO", "dxHtmlEditor-bullet": "TODO", "dxHtmlEditor-align": "TODO", "dxHtmlEditor-center": "TODO", "dxHtmlEditor-left": "TODO", "dxHtmlEditor-right": "TODO", "dxHtmlEditor-indent": "TODO", "dxHtmlEditor-justify": "TODO", "dxFileManager-newDirectoryName": "TODO", "dxFileManager-rootDirectoryName": "TODO", "dxFileManager-errorNoAccess": "TODO", "dxFileManager-errorDirectoryExistsFormat": "TODO", "dxFileManager-errorFileExistsFormat": "TODO", "dxFileManager-errorFileNotFoundFormat": "TODO", "dxFileManager-errorDirectoryNotFoundFormat": "TODO", "dxFileManager-errorWrongFileExtension": "TODO", "dxFileManager-errorMaxFileSizeExceeded": "TODO", "dxFileManager-errorInvalidSymbols": "TODO", "dxFileManager-errorDefault": "TODO", "dxFileManager-errorDirectoryOpenFailed": "TODO", "dxDiagram-categoryGeneral": "TODO", "dxDiagram-categoryFlowchart": "TODO", "dxDiagram-categoryOrgChart": "TODO", "dxDiagram-categoryContainers": "TODO", "dxDiagram-categoryCustom": "TODO", "dxDiagram-commandExportToSvg": "TODO", "dxDiagram-commandExportToPng": "TODO", "dxDiagram-commandExportToJpg": "TODO", "dxDiagram-commandUndo": "TODO", "dxDiagram-commandRedo": "TODO", "dxDiagram-commandFontName": "TODO", "dxDiagram-commandFontSize": "TODO", "dxDiagram-commandBold": "TODO", "dxDiagram-commandItalic": "TODO", "dxDiagram-commandUnderline": "TODO", "dxDiagram-commandTextColor": "TODO", "dxDiagram-commandLineColor": "TODO", "dxDiagram-commandLineWidth": "TODO", "dxDiagram-commandLineStyle": "TODO", "dxDiagram-commandLineStyleSolid": "TODO", "dxDiagram-commandLineStyleDotted": "TODO", "dxDiagram-commandLineStyleDashed": "TODO", "dxDiagram-commandFillColor": "TODO", "dxDiagram-commandAlignLeft": "TODO", "dxDiagram-commandAlignCenter": "TODO", "dxDiagram-commandAlignRight": "TODO", "dxDiagram-commandConnectorLineType": "TODO", "dxDiagram-commandConnectorLineStraight": "TODO", "dxDiagram-commandConnectorLineOrthogonal": "TODO", "dxDiagram-commandConnectorLineStart": "TODO", "dxDiagram-commandConnectorLineEnd": "TODO", "dxDiagram-commandConnectorLineNone": "TODO", "dxDiagram-commandConnectorLineArrow": "TODO", "dxDiagram-commandFullscreen": "TODO", "dxDiagram-commandUnits": "TODO", "dxDiagram-commandPageSize": "TODO", "dxDiagram-commandPageOrientation": "TODO", "dxDiagram-commandPageOrientationLandscape": "TODO", "dxDiagram-commandPageOrientationPortrait": "TODO", "dxDiagram-commandPageColor": "TODO", "dxDiagram-commandShowGrid": "TODO", "dxDiagram-commandSnapToGrid": "TODO", "dxDiagram-commandGridSize": "TODO", "dxDiagram-commandZoomLevel": "TODO", "dxDiagram-commandAutoZoom": "TODO", "dxDiagram-commandFitToContent": "TODO", "dxDiagram-commandFitToWidth": "TODO", "dxDiagram-commandAutoZoomByContent": "TODO", "dxDiagram-commandAutoZoomByWidth": "TODO", "dxDiagram-commandSimpleView": "TODO", "dxDiagram-commandCut": "TODO", "dxDiagram-commandCopy": "TODO", "dxDiagram-commandPaste": "TODO", "dxDiagram-commandSelectAll": "TODO", "dxDiagram-commandDelete": "TODO", "dxDiagram-commandBringToFront": "TODO", "dxDiagram-commandSendToBack": "TODO", "dxDiagram-commandLock": "TODO", "dxDiagram-commandUnlock": "TODO", "dxDiagram-commandInsertShapeImage": "TODO", "dxDiagram-commandEditShapeImage": "TODO", "dxDiagram-commandDeleteShapeImage": "TODO", "dxDiagram-commandLayoutLeftToRight": "TODO", "dxDiagram-commandLayoutRightToLeft": "TODO", "dxDiagram-commandLayoutTopToBottom": "TODO", "dxDiagram-commandLayoutBottomToTop": "TODO", "dxDiagram-unitIn": "TODO", "dxDiagram-unitCm": "TODO", "dxDiagram-unitPx": "TODO", "dxDiagram-dialogButtonOK": "TODO", "dxDiagram-dialogButtonCancel": "TODO", "dxDiagram-dialogInsertShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageSelectButton": "TODO", "dxDiagram-dialogEditShapeImageLabelText": "TODO", "dxDiagram-uiExport": "TODO", "dxDiagram-uiProperties": "TODO", "dxDiagram-uiSettings": "TODO", "dxDiagram-uiShowToolbox": "TODO", "dxDiagram-uiSearch": "TODO", "dxDiagram-uiStyle": "TODO", "dxDiagram-uiLayout": "TODO", "dxDiagram-uiLayoutTree": "TODO", "dxDiagram-uiLayoutLayered": "TODO", "dxDiagram-uiDiagram": "TODO", "dxDiagram-uiText": "TODO", "dxDiagram-uiObject": "TODO", "dxDiagram-uiConnector": "TODO", "dxDiagram-uiPage": "TODO", "dxDiagram-shapeText": "TODO", "dxDiagram-shapeRectangle": "TODO", "dxDiagram-shapeEllipse": "TODO", "dxDiagram-shapeCross": "TODO", "dxDiagram-shapeTriangle": "TODO", "dxDiagram-shapeDiamond": "TODO", "dxDiagram-shapeHeart": "TODO", "dxDiagram-shapePentagon": "TODO", "dxDiagram-shapeHexagon": "TODO", "dxDiagram-shapeOctagon": "TODO", "dxDiagram-shapeStar": "TODO", "dxDiagram-shapeArrowLeft": "TODO", "dxDiagram-shapeArrowUp": "TODO", "dxDiagram-shapeArrowRight": "TODO", "dxDiagram-shapeArrowDown": "TODO", "dxDiagram-shapeArrowUpDown": "TODO", "dxDiagram-shapeArrowLeftRight": "TODO", "dxDiagram-shapeProcess": "TODO", "dxDiagram-shapeDecision": "TODO", "dxDiagram-shapeTerminator": "TODO", "dxDiagram-shapePredefinedProcess": "TODO", "dxDiagram-shapeDocument": "TODO", "dxDiagram-shapeMultipleDocuments": "TODO", "dxDiagram-shapeManualInput": "TODO", "dxDiagram-shapePreparation": "TODO", "dxDiagram-shapeData": "TODO", "dxDiagram-shapeDatabase": "TODO", "dxDiagram-shapeHardDisk": "TODO", "dxDiagram-shapeInternalStorage": "TODO", "dxDiagram-shapePaperTape": "TODO", "dxDiagram-shapeManualOperation": "TODO", "dxDiagram-shapeDelay": "TODO", "dxDiagram-shapeStoredData": "TODO", "dxDiagram-shapeDisplay": "TODO", "dxDiagram-shapeMerge": "TODO", "dxDiagram-shapeConnector": "TODO", "dxDiagram-shapeOr": "TODO", "dxDiagram-shapeSummingJunction": "TODO", "dxDiagram-shapeContainerDefaultText": "TODO", "dxDiagram-shapeVerticalContainer": "TODO", "dxDiagram-shapeHorizontalContainer": "TODO", "dxDiagram-shapeCardDefaultText": "TODO", "dxDiagram-shapeCardWithImageOnLeft": "TODO", "dxDiagram-shapeCardWithImageOnTop": "TODO", "dxDiagram-shapeCardWithImageOnRight": "TODO", "dxGantt-dialogTitle": "TODO", "dxGantt-dialogStartTitle": "TODO", "dxGantt-dialogEndTitle": "TODO", "dxGantt-dialogProgressTitle": "TODO", "dxGantt-dialogResourcesTitle": "TODO", "dxGantt-dialogResourceManagerTitle": "TODO", "dxGantt-dialogTaskDetailsTitle": "TODO", "dxGantt-dialogEditResourceListHint": "TODO", "dxGantt-dialogEditNoResources": "TODO", "dxGantt-dialogButtonAdd": "TODO", "dxGantt-contextMenuNewTask": "TODO", "dxGantt-contextMenuNewSubtask": "TODO", "dxGantt-contextMenuDeleteTask": "TODO", "dxGantt-contextMenuDeleteDependency": "TODO", "dxGantt-dialogTaskDeleteConfirmation": "TODO", "dxGantt-dialogDependencyDeleteConfirmation": "TODO", "dxGantt-dialogResourcesDeleteConfirmation": "TODO", "dxGantt-dialogConstraintCriticalViolationMessage": "TODO", "dxGantt-dialogConstraintViolationMessage": "TODO", "dxGantt-dialogCancelOperationMessage": "TODO", "dxGantt-dialogDeleteDependencyMessage": "TODO", "dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO", "dxGantt-undo": "TODO", "dxGantt-redo": "TODO", "dxGantt-expandAll": "TODO", "dxGantt-collapseAll": "TODO", "dxGantt-addNewTask": "TODO", "dxGantt-deleteSelectedTask": "TODO", "dxGantt-zoomIn": "TODO", "dxGantt-zoomOut": "TODO", "dxGantt-fullScreen": "TODO", "dxGantt-quarter": "TODO" } }) }));
/* * 曲線エディタ * https://github.com/tckz/curveedit * * Copyright(c) 2011 tckz<at.tckz@gmail.com> * This software is licensed under the MIT license. * See COPYRIGHT.txt */ /** * 点モデル */ var Dot = function() { this.initialize.apply(this, arguments); } Dot.prototype = { /** * 図上のx,y座標 */ initialize: function(x, y, id) { this.x = x; this.y = y; /* * このドットから次のドットへ至る制御点の座標 */ this.cp1x = undefined; this.cp1y = undefined; this.cp2x = undefined; this.cp2y = undefined; this.id = id; this.next = undefined; this.previous = undefined; this.selected = false; this.notifier = new Notifier(this); }, toSerializable: function() { var ret = { cp1x: this.cp1x, cp1y: this.cp1y, cp2x: this.cp2x, cp2y: this.cp2y, x: this.x, y: this.y }; return ret; }, /** * ドットの座標を相対座標で変更。 * 制御点も同様に変更される。 */ setPositionRelative: function(rx, ry, rx1, ry1, rx2, ry2) { if (rx) { this.x = this.x + rx; } if (ry) { this.y = this.y + ry; } if (is_defined(this.cp1x) && rx1) { this.cp1x = this.cp1x + rx1; } if (is_defined(this.cp1y) && ry1) { this.cp1y = this.cp1y + ry1; } if (is_defined(this.cp2x) && rx2) { this.cp2x = this.cp2x + rx2; } if (is_defined(this.cp2y) && ry2) { this.cp2y = this.cp2y + ry2; } this.notifier.notify(); }, /** * 制御点座標を設定 */ setCPPosition: function(cp1x, cp1y, cp2x, cp2y) { if (is_defined(cp1x) && is_defined(cp1y)) { this.cp1x = cp1x; this.cp1y = cp1y; } if (is_defined(cp2x) && is_defined(cp2y)) { this.cp2x = cp2x; this.cp2y = cp2y; } this.notifier.notify(); }, setPosition: function(x, y) { this.x = x; this.y = y; this.notifier.notify(); } }; /** * エディタ:model */ var EditorModel = function() { this.initialize.apply(this, arguments); } EditorModel.prototype = { initialize: function() { this.dots = []; this.background_image = undefined; // どんどん増えるだけ。モデルの中で一意な番号を振る。 this.dot_count = 0; // ドットのインデックス番号を表示するか否か this.show_index = false; this.first = undefined; this.last = undefined; this.current_handle = undefined; this.notifier = new Notifier(this); }, getShowIndex: function() { return this.show_index; }, setShowIndex: function(flag) { this.show_index = flag ? true : false; }, toSerializable: function() { var ret = { dots: [], background_image: this.background_image }; for (var dot = this.first; is_defined(dot); dot = dot.next) { ret.dots.push(dot.toSerializable()); } return ret; }, fromSerializable: function(t) { this.background_image = this.background_image; var dots = t.dots; for (var i = 0; i < dots.length; i++) { var dot = this.newDot(dots[i].x, dots[i].y); dot.setCPPosition( dots[i].cp1x, dots[i].cp1y, dots[i].cp2x, dots[i].cp2y ); } }, setCurrentHandle: function(h) { this.current_handle = h; }, getCurrentHandle: function() { return this.current_handle; }, /** * 全dotsを指定された選択状態に。 */ setSelectedAll: function(flag) { for (var i = 0; i < this.dots.length; i++) { this.dots[i].selected = flag; } }, /** * 指定されたdotsだけを指定された選択状態に。 */ setSelected: function(dots, flag) { for (var i = 0; i < dots.length; i++) { var dot = this.findDotById(dots[i].id); dot.selected = flag; } }, /** * 選択状態のdotsを返す */ getSelected: function() { var ret = []; for (var i = 0; i < this.dots.length; i++) { var dot = this.dots[i]; if (dot.selected) { ret.push(dot); } } return ret; }, setBackgroundImage: function(url) { if (!is_defined(url) || !url.match(/^(https?:\/\/|[\.$,;=\?!\*~@_\(\)a-zA-Z0-9]+\/)[\.$,;:&=\?!\*~@#_\(\)a-zA-Z0-9\/]+$/)) { return {message: "Invalid URL."}; } this.background_image = url; this.notifier.notify(); return {success: true}; }, getBackgroundImage: function() { return this.background_image; }, previousDot: function(dot) { var prev = dot.previous; if (!is_defined(prev)) { prev = this.last; } return prev; }, nextDot: function(dot) { var next = dot.next; if (!is_defined(next)) { next = this.first; } return next; }, deleteDots: function(targets) { for (var i = 0; i < targets.length; i++){ var target = targets[i]; this.deleteDot(target); } this.notifier.notify(); }, /** * @param target 削除したいドットモデル */ deleteDot: function(target) { /* * 3点を割るとパスが閉じなくて面倒なので、削除不可に。 */ if (this.dots.length <= 3 || !target) { return; } for (var i = 0; i < this.dots.length; i++) { var dot = this.dots[i]; if (dot === target) { var prev = dot.previous; var next = dot.next; if (!prev) { this.first = next; } else { prev.next = next; } if (!next) { this.last = prev; } else { next.previous = prev; } this.dots.splice(i, 1); return; } } }, /** * 指定された座標に一番近いドットを返す */ findDotNearByPoint: function(x, y) { var ret = undefined; var nearest_dist = 99999; var loc = {x: x, y: y}; for (var i = 0; i < this.dots.length; i++) { var dot = this.dots[i]; var dist = this.calcDistance(dot, loc); if (dist < nearest_dist) { ret = dot; nearest_dist = dist; } } return ret; }, /** * p2-p1間の距離を計算する * p2省略時は原点 */ calcDistance: function(p1, p2) { if (!is_defined(p2)) { p2 = {x: 0, y: 0}; } var dist = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); return dist; }, findDotById: function(id) { for (var i = 0; i < this.dots.length; i++) { var dot = this.dots[i]; if (dot.id == id) { return dot; } } return undefined; }, /** * 現在のドット座標群の重心座標を計算して返す * ドットの数が0のときは、undefined */ calcCenterPosition: function() { var num = this.dots.length; if (num == 0) { return undefined; } var sum = {x: 0, y: 0}; for (var i = 0; i < num; i++) { var dot = this.dots[i]; sum.x = sum.x + dot.x; sum.y = sum.y + dot.y; } return {x: sum.x/num, y: sum.y/num}; }, getDot: function(i) { return this.dots[i]; }, /** * 現在のドットの数 */ getDotsCount: function() { return this.dots.length; }, /** * ドットp1からp2に向かうベクトル(に相当する)x.yを返す */ toVector: function(p1, p2) { return { x: p2.x - p1.x, y: p2.y - p1.y }; }, /** * (リスト登録済の)ドットに対しデフォルトの制御点を設定する * * ドットが3つ未満の状態は考えていない */ setDefaultCPPosition: function(dot) { var center = this.calcCenterPosition(); var prev = this.previousDot(dot); var next = this.nextDot(dot); // ドットの座標から重心へのベクトル var v = this.toVector(dot, center); // vをnormalize var v_size = this.calcDistance(v); v.x = v.x / v_size; v.y = v.y / v_size; var v_cp_size = v_size / 3.0; // ドットから見て前のドットに向かう制御点 var cp_prev = { x: v.y * v_cp_size + dot.x, y: (v.x * -1) * v_cp_size + dot.y }; // ドットから見て次のドットに向かう制御点 var cp_next = { x: -v.y * v_cp_size + dot.x, y: v.x * v_cp_size + dot.y }; // cp_prev -> prevと // cp_next -> nextが交差する場合は、制御点を逆にする。 if (this.isIntersect(cp_prev, prev, cp_next, next)) { var t = cp_prev; cp_prev = cp_next; cp_next = t; } prev.setCPPosition(undefined, undefined, cp_prev.x, cp_prev.y ); dot.setCPPosition(cp_next.x, cp_next.y); }, /** * 線分a1-a2とb1-b2が交差するかどうか */ isIntersect: function(a1, a2, b1, b2) { // てきとう・・・ var eps = 0.00000000000000000001; return (this.calcCrossProduct( this.toVector(a1, a2), this.toVector(a1, b1)) * this.calcCrossProduct( this.toVector(a1, a2), this.toVector(a1, b2)) < eps) && (this.calcCrossProduct( this.toVector(b1, b2), this.toVector(b1, a1)) * this.calcCrossProduct( this.toVector(b1, b2), this.toVector(b1, a2)) < eps); }, /** * ベクトルv1とv2の外積 * 平面上なのでスカラーに */ calcCrossProduct: function(v1, v2) { return v1.x * v2.y - v1.y * v2.x; }, /** * 平面上の座標を指定して新しい点モデルを返す * * neighborを指定した場合は、(リンクリスト上)指定ノードの次の位置にする。 * * @param neighbor 前のドット */ newDot: function(x, y, neighbor) { var dot = new Dot(x, y, "dot" + this.dot_count); this.dots.push(dot); if (this.dots.length == 1) { this.first = dot; this.last = dot; } else { this.last.next = dot; dot.previous = this.last; this.last = dot; } if (is_defined(neighbor)) { this.moveNextTo(dot, neighbor); } this.dot_count++; return dot; }, /** * 指定されたドットを指定された隣人の次のノードにする */ moveNextTo: function(dot, neighbor) { var org_neighbor_next = neighbor.next; if (org_neighbor_next === dot) { return; } var org_dot_prev = dot.previous; var org_dot_next = dot.next; if (!neighbor.next) { this.last = dot; } neighbor.next = dot; dot.previous = neighbor; dot.next = org_neighbor_next; if (!org_dot_prev) { this.first = org_dot_next; } else { org_dot_prev.next = org_dot_next; } if (!org_dot_next) { this.last = org_dot_prev; } else { org_dot_next.previous = org_dot_prev; } if (org_neighbor_next) { org_neighbor_next.previous = dot; } } };
/** * @overview A sevice that sends get, post, put, and delete requests to the server through http. Allows raw mongoDB queries to be passed to the server. The user creates a new instance of the endpoints service providing an endpoint url to reach and calls api methods on that instance. * @author Jon Paul Miles <milesjonpaul@gmail.com> * @version 1.0.0 * @license MIT * @example `var menus = new endpoints('menus'); * var replaceMenu = { * url: '/new-url', * classes: 'another-class', * target:'_self' * }; * //Pass in raw mongoDB queries * menus.update({url: '/about'}, replaceMenu).then(cb);` */ (function(){ /** * Sets up a rest endpoint for the given url so create, find, update, and delete can be performed on it. * @constructor * @param {string} endpoint The URL of the server endpoint to reach. `/api/` prefix is already assumed. * @return {nothing} */ function endpoints(endpoint) { this.endpoint = endpoint || ''; this.url = endpoint; } /** * Adds content in the server database for the endpoint passed into the constructor function. * @param {object} content the item to be added to the database * @return {promise} An object or array of items that were created */ endpoints.prototype.create = function(content) { return feathers.service(this.url).create(_.clone(content, true)); }; /** * Gets data matching the query. * @param {object} identifier Raw mongoDB query * @return {promise} An object or array of items matching the query */ endpoints.prototype.find = function(identifier) { return feathers.service(this.url).find({ query: identifier }); }; /** * Updates data in the server database identified with a mongoDB query with the replacement data passed in. * @param {object} identifier Raw mongoDB query * @param {object} replacement Whatever data you want to replace the found data with * @return {promise} Number of items that were updated */ endpoints.prototype.update = function(identifier, replacement) { var rp = _.clone(replacement, true); rp.createdAt = undefined; rp.updatedAt = undefined; return feathers.service(this.url).patch(null, rp, {query: identifier}); }; /** * Deletes data from the server database that matches the mongoDB query passed in. * @param {object} identifier Raw mongoDB query * @return {promise} http response object */ endpoints.prototype.delete = function(identifier) { let id = null; let query = {query: identifier}; if(identifier._id) { id = identifier._id; query = undefined; } return feathers.service(this.url).remove(id, query); }; /** * Returns one item from the server that has the mongoDB _id passed in. * @param {string} id The _id value of the object to retrieve * @return {promise} Object that has that id */ endpoints.prototype.findOne = function(id) { return feathers.service(this.url).get(id); }; /** * Updates one item in the database that has the _id passed in with the information in replacement. * @param {string} id The `_id` of the mongoDB object * @param {object} replacement The content to replace the found object with * @return {promise} Number of items replaced */ endpoints.prototype.updateOne = function(id, replacement) { var rp = _.clone(replacement, true); rp.createdAt = undefined; rp.updatedAt = undefined; return feathers.service(this.url).patch(id, rp); } /** * Deletes one item from the server database that has the _id that was passed in. * @param {string} id The _id of the mongoDB object to delete * @return {promise} http response object */ endpoints.prototype.deleteOne = id => { return feathers.service(this.url).remove(id); }; window.endpoints = endpoints })();
module.exports = { semi: true, tabWidth: 4, singleQuote: true, trailingComma: 'es5' };
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2754',"Tlece.Recruitment.Models.SelectionProcess Namespace","topic_000000000000094D.html"],['2772',"SelectionProcessIndexDataVm Class","topic_0000000000000955.html"],['2774',"Properties","topic_0000000000000955_props--.html"],['2791',"VideoId Property","topic_000000000000095C.html"]];
(function() { 'use strict'; angular .module('myApp') .config(config); config.$inject = [ // '$routeProvider', // '$locationProvider', // '$httpProvider' '$stateProvider', 'angularAuth0Provider', 'lockProvider', '$urlRouterProvider', 'jwtOptionsProvider', '$templateFactoryProvider' ]; function config( $stateProvider, angularAuth0Provider, lockProvider, $urlRouterProvider, jwtOptionsProvider, $templateFactoryProvider ) { $templateFactoryProvider.shouldUnsafelyUseHttp(true); // Configuration for angular-jwt jwtOptionsProvider.config({ tokenGetter: function () { return localStorage.getItem('id_token'); } }); $stateProvider // Index .state('index', { url: '/', templateUrl: 'components/index/index.component.html', controller: 'welcomeController', controllerAs: 'vm', }) // Auth .state('login', { url: '/login', templateUrl: 'components/auth/login.component.html', controller: 'LoginController', controllerAs: 'vm', }) // Bootstrap .state('bootstrap', { url: '/bootstrap', templateUrl: 'components/bootstrap/index.component.html', controller: 'bootstrapController', }) .state('bootstrapComponent', { url: '/bootstrap/:component', templateUrl: 'components/bootstrap/index.component.html', controller: 'bootstrapController', }) // Material .state('material', { url: '/material', templateUrl: 'components/material/index.component.html', controller: 'materialController' }) .state('materialComponent', { url: '/material/:component', templateUrl: 'components/material/index.component.html', controller: 'materialController' }) // Plugins .state('plugins', { url: '/plugins', templateUrl: 'components/plugins/index.component.html', controller: 'pluginsController' }) .state('pluginsPlugin', { url: '/plugins/:plugin', templateUrl: 'components/plugins/plugins.component.html', controller: 'pluginsController' }) // Templates .state('templates', { url: '/templates', templateUrl: 'components/templates/index.component.html', controller: 'templatesController' }) .state('templatesSub', { url: '/templates/:template', templateUrl: 'components/templates/index.component.html', controller: 'templatesController' }) angularAuth0Provider.init({ clientID: 'vQLN0V90OASSE2w0cNKJRk2YXFF1XXK1', domain: 'jackhummah.auth0.com' }); lockProvider.init({ clientID: 'vQLN0V90OASSE2w0cNKJRk2YXFF1XXK1', domain: 'jackhummah.auth0.com' }); $urlRouterProvider.otherwise('/'); } })();