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
define('controllers/panel',['require','jquery','backbone','utils/metrics','utils/browser','utils/video-player','utils/pubsub','controllers/panel-display'],function(require) { var $ = require('jquery'), Backbone = require('backbone'), Metrics = require('utils/metrics'), Browser = require('utils/browser'), VideoPlayer = require('utils/video-player'), PubSub = require('utils/pubsub'), PanelDisplay = require('controllers/panel-display') ; var PanelView = Backbone.View.extend({ events: { }, panelOn: false, minWidth: 320, minHeight: 180, leftLimit: 100, topLimit: 100, offset: 10, border: 5, initialize: function() { Browser.checkMobileTabletDevice(); this.logger = new eventsCore.util.Logger('PanelView'); this.panel1 = new PanelDisplay({el: '#panel1'}).render(); this.panel2 = new PanelDisplay({el: '#panel2'}).render(); //this.logger.info('initialize - panel1:%o panel2:%o', this.panel1, this.panel2); this.on('route:change', this.checkPage); this.listenTo(PubSub, 'video:playPanel', this.onPlayPanel); this.listenTo(PubSub, 'video:exitPanel', this.onExitPanel); this.listenTo(PubSub, 'video:resetHero', this.onResetHero); this.listenTo(PubSub, 'video:resetVod', this.onResetVod); this.listenTo(VideoPlayer, 'player:play', this.onPlayEvent); this.listenTo(VideoPlayer, 'player:panelOpen', this.onPanelOpenEvent); this.listenTo(VideoPlayer, 'player:panelClosed', this.onPanelClosedEvent); }, render: function() { return this; }, /** * checks state/position of each panel and updates initial mute status * executes on play and route change */ checkVolume: function() { this.logger.info('checkVolume - panel1:%o panel2:%o', this.panel1.state(), this.panel2.state()); if (this.panel1.state() != '' && this.panel2.state() == '') { this.panel1.mute(false); this.panel2.mute(true); } else if (this.panel2.state() != '' && this.panel1.state() == '') { this.panel2.mute(false); this.panel1.mute(true); } else if (this.panel1.state() == 'floatVideo' && this.panel2.state() == 'heroVideo') { this.panel2.mute(false); this.panel1.mute(true); } else if (this.panel1.state() == 'heroVideo' && this.panel2.state() == 'floatVideo') { this.panel1.mute(false); this.panel2.mute(true); } }, /** * close any open hero panel * - used for mobile internal ref to a different watch live channel */ onResetHero: function() { if(this.panel1.state() === 'heroVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'heroVideo') { this.panel2.onPanelExit(); } }, /** * close any open vod floated panel */ onResetVod: function() { if(this.panel1.state() === 'floatVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'floatVideo') { this.panel2.onPanelExit(); } }, /** * play video in a panel, check for channel existing in panel first and use existing if playing * @param data - panel video data * @param channel - this live video data * @param options - options to be passed to video player, consisting of: * floated - optional boolean indicating if should start in float mode * vod - indicates if playing a vod */ onPlayPanel: function(data, channel, options) { options = _.extend({ floated: false, vod: false }, options); this.logger.info('onPlayPanel - panel1:%o chan1:%o panel2:%o chan2:%o data:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId(), data); //if panel1 floating and opening the same channel, close to hero (to force back to hero when return to live channel page) // do not close if float is true, call is trying to open same channel in already open float panel if (this.panel1.channelId() == data[0].id) { // if panel has no state, reset it to play channel if(this.panel1.state() === '') { this.panel1.playPanel(data, channel, options); } else if (this.panel1.state() == 'floatVideo' && !options.floated) this.panel1.panelClose(data, false); else this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel already active'); } //if panel2 floating and opening the same channel, close to hero (to force back to hero when return to live channel page) // do not close if float is true, call i trying to open same channel in already open float panel else if (this.panel2.channelId() == data[0].id){ // if panel has no state, reset it to play channel if(this.panel2.state() === '') { this.panel2.playPanel(data, channel, options); } else if (this.panel2.state() == 'floatVideo' && !options.floated) this.panel2.panelClose(data, false); else this.logger.warn('onPlayPanel - ignoring call, attempted to open same channel to floating panel'); } //if panel1 in hero use it, (if not playing this channel) else if ((this.panel1.state() == 'heroVideo' || this.panel1.state() == '') && this.panel1.channelId() != data[0].id) { this.panel1.playPanel(data, channel, options); } //else use panel2 (if not playing this channel) else if (this.panel2.channelId() != data[0].id){ this.panel2.playPanel(data, channel, options); } }, /** * exit video playing in panel, whichever panel is open */ onExitPanel: function() { this.logger.info('onExitPanel - panel1:%o chan1:%o panel2:%o chan2:%o', this.panel1.state(), this.panel1.channelId(), this.panel2.state(), this.panel2.channelId()); // close whichever one is floated if(this.panel1.state() === 'floatVideo') { this.panel1.onPanelExit(); } else if(this.panel2.state() === 'floatVideo') { this.panel2.onPanelExit(); } }, /** * on play, initiates check for setting initial mute * @param data - event data with panel id */ onPlayEvent: function(data) { //this.logger.info('onPlayEvent - data:%o', data.id); if (data.id == 'panel1' || data.id == 'panel2') this.checkVolume(); }, /** * handle panel open event from video player * triggers panel to transition to float state * @param data - event data with panel id */ onPanelOpenEvent: function(data) { this.logger.info('onPanelOpenEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id); if(data.id == 'panel1') { if (this.panel2.state() == 'floatVideo') { this.panel2.panelClose(null, false); } this.panel1.panelOpen(); } else if(data.id == 'panel2') { if (this.panel1.state() == 'floatVideo') { this.panel1.panelClose(null, false); } this.panel2.panelOpen(); } }, /** * handle panel close event from video player * triggers panel to return to hero state * @param data - event data with panel id */ onPanelClosedEvent: function(data) { this.logger.info('onPanelClosedEvent - panel1:%o panel2:%o id:%o', this.panel1.state(), this.panel2.state(), data.id); if(data.id == 'panel1') { this.panel1.panelClose(data, true); if (this.panel2.state() == 'heroVideo') { this.panel2.panelClose(data, false); this.checkVolume(); } } else if(data.id == 'panel2') { this.panel2.panelClose(data, true); if (this.panel1.state() == 'heroVideo') { this.panel1.panelClose(data, false); this.checkVolume(); } } }, /** * initiate page check for closing hero on route change * also check volume on route change */ checkPage: function(){ var route = Backbone.history.getFragment(); this.panel1.checkPage(route); this.panel2.checkPage(route); this.checkVolume(); } }); return PanelView; }) ;
rlaj/tmc
source/dist/controllers/panel.js
JavaScript
mit
9,409
// Design Basic Game Solo Challenge // This is a solo challenge // Your mission description:To complete a line of the same figure, horizontal, diagonal or vertical // Overall mission: To win all the time :) // Goals: make a line of the same kind before computer does // Characters:You and the computer // Objects:tic tac toe // Functions:clear_board, refresh_board, turn // Pseudocode // Make a Tictactoe class // Initialize the instance // Paint the board // Take a turn UNTIL someones win // Check if some one won // Clear the board // // // // // Initial Code turns = 0 board_state = [[" "," "," "], [" "," "," "], [" "," "," "]]; var Tictactoe = { take_turn : function(user){ mark = prompt("It is your turn, where do you want to mark?"); horizontal = mark[1]; vertical = mark[0].toUpperCase(); if (vertical == "A"){ vertical = 0 } else if (vertical == "B"){ vertical = 1 } else { vertical = 2 } board_state[horizontal-1][vertical] = user console.log(board_state) }, print_board : function(){ line = "" console.log(" A B C") for (i in board_state){ new_line = "\n ═══╬═══╬═══\n" for (x in board_state[i]){ ln = parseInt(i); if (x == 0){line = (ln+1)+" "} if (x == 2) { if (i == 2){new_line = "\n"} line += " "+board_state[i][x]+new_line; } else { line += " "+board_state[i][x]+" ║" } } console.log(line); } } } alert ("Welcome to @cyberpolin's Tic Tac Toe\n So it is the turn of User 1, please select where you want to mark...") Tictactoe.print_board() while (turns < 9){ if (turns%2 == 0){ Tictactoe.take_turn("o"); } else { Tictactoe.take_turn("x"); } Tictactoe.print_board(); turns++; } // RELECTION // What was the most difficult part of this challenge? // Order my toughts to make the code works as i wannted, also as javascript is not a language thinked for terminal it was difficult to figure out how it was going to work. // What did you learn about creating objects and functions that interact with one another? // Is like in ruby, i think of them as just methods // Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work? // The only one i used was toUpperCase, ad they are like Ruby methods even tough Javascript have a different syntax. // How can you access and manipulate properties of objects? // like in Ruby object[property] = new_value, or the JS way object.property = new_value // TODO'S // Check if a place is marked already // Check if you have winned // Make it playable with computer // MAKE IT GRAPHICAL!!!!
cyberpolin/Phase-0
week-7/tictactoe-game/game.js
JavaScript
mit
2,853
// GridFS // Copyright(c) 2013 Siddharth Mahendraker <[email protected]> // MIT Licensed exports.GridFS = require('./lib/GridFS'); exports.GridStream = require('./lib/GridStream');
SergejKasper/smartkitchen
server/node_modules/gridfstore/node_modules/GridFS/index.js
JavaScript
mit
187
// @flow class A { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(function (z) { this.y; // error, function has wrong this }); } } class B { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(function (z) { this.y; // ok, function gets passed correct this }, this); } } class C { x = [1, 2, 3]; y = 4; foo() { this.x = this.x.map(z => { this.y; // ok, arrow binds surrounding context this }); } }
facebook/flow
tests/arraylib/callback_this.js
JavaScript
mit
534
import collectionClass from "./collections.class"; import collectionColor from "./collections.color"; function collectionBackgroundStyles(contentItem) { return ` .${collectionClass(contentItem)} { background-color: #${collectionColor(contentItem)}; } `; } export default collectionBackgroundStyles;
NewSpring/apollos-core
imports/util/collections/collections.backgroundStyles.js
JavaScript
mit
320
version https://git-lfs.github.com/spec/v1 oid sha256:71736be070607c3c30f4c139b063edf1b1ffa587cf725a0acc1e06c6d3af0e48 size 53235
yogeshsaroya/new-cdnjs
ajax/libs/ace/1.1.5/mode-objectivec.js
JavaScript
mit
130
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), CurrentModel = mongoose.model('Attendance'), Schedule = mongoose.model('Schedule'), Group = mongoose.model('Group'), _ = require('lodash'); exports.attendance = function(req, res, next, id) { CurrentModel.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.attendance = item; next(); }); }; exports.schedule = function(req, res, next, id) { Schedule.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.schedule = item; next(); }); }; exports.group = function(req, res, next, id) { Group.load(id, function(err, item) { if (err) return next(err); if (!item) return next(new Error('Failed to load item ' + id)); req.group = item; next(); }); }; exports.create = function(req, res) { var value = new CurrentModel(req.body); value.group = req.group; value.schedule = req.schedule; value.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: value }); } else { res.jsonp(value); } }); }; exports.update = function(req, res) { var item = req.attendance; item = _.extend(item, req.body); item.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: item }); } else { res.jsonp(item); } }); }; exports.destroy = function(req, res) { var item = req.attendance; item.remove(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, object: item }); } else { res.jsonp(item); } }); }; exports.show = function(req, res) { res.jsonp(req.attendance); }; exports.all = function(req, res) { CurrentModel.find({ group: req.group, schedule: req.schedule }).populate('participant', 'name email').exec(function(err, items) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(items); } }); };
wolf-mtwo/attendance
packages/custom/groups/server/controllers/attendances.js
JavaScript
mit
2,206
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m22 6.92-1.41-1.41-2.85 3.21C15.68 6.4 12.83 5 9.61 5 6.72 5 4.07 6.16 2 8l1.42 1.42C5.12 7.93 7.27 7 9.61 7c2.74 0 5.09 1.26 6.77 3.24l-2.88 3.24-4-4L2 16.99l1.5 1.5 6-6.01 4 4 4.05-4.55c.75 1.35 1.25 2.9 1.44 4.55H21c-.22-2.3-.95-4.39-2.04-6.14L22 6.92z" }), 'MultilineChartOutlined'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/MultilineChartOutlined.js
JavaScript
mit
733
import dateformat from 'dateformat'; import { map } from "underscore"; import { getAccountById } from 'routes/root/routes/Banking/routes/Accounts/modules/accounts'; import { getCreditCardById, getPrepaidCardById } from 'routes/root/routes/Banking/routes/Cards/modules/cards'; import { getLoanById } from 'routes/root/routes/Banking/routes/Loans/modules/loans'; export const getDebitAccount = (debitAccountType, debitAccountId) => { switch (debitAccountType) { case "isAccount": getAccountById(debitAccountId) break; case "isLoan": getLoanById(debitAccountId) break; case "isCreditCard": getCreditCardById(debitAccountId) break; case "isPrepaidCard": getPrepaidCardById(debitAccountId) break; } } const findDebitAccount = (debitAccountType, debitAccountId, state) => { let debitAccount = {}; switch (debitAccountType) { case "isAccount": debitAccount = state.accounts.accounts.filter((account) => account.id == debitAccountId)[0] break; case "isLoan": debitAccount = state.loans.loans.filter((loan) => loan.id == debitAccountId)[0] break; case "isCreditCard": debitAccount = state.cards.creditCards.filter((creditCard) => creditCard.id == debitAccountId)[0] break; case "isPrepaidCard": debitAccount = state.cards.prepaidCards.filter((prepaidCard) => prepaidCard.id == debitAccountId)[0] break; } return debitAccount; } export const getDebitAccountAvailableBalance = (debitAccountType, debitAccountId, state) => { const debitAccount = findDebitAccount(debitAccountType, debitAccountId, state); return getProductAvailableBalance(debitAccount, debitAccountType); } export const getProductAvailableBalance = (debitAccount, debitAccountType) => { let availableBalance = 0; switch (debitAccountType) { case "isAccount": availableBalance = debitAccount.ledgerBalance; break; case "isLoan": case "isCreditCard": case "isPrepaidCard": availableBalance = debitAccount.availableBalance; break; } return availableBalance; } export const getDebitAccountCurrency = (debitAccountType, debitAccountId, state) => { return findDebitAccount(debitAccountType, debitAccountId, state).currency; } export const isValidDate = (date) => { return new Date(date).setHours(0,0,0,0) >= new Date(dateformat()).setHours(0,0,0,0) } export const isValidInstallmentPaymentAmount = (product, amount, availableBalance) => { return amount > 0 && (parseFloat(amount) <= product.nextInstallmentAmount || parseFloat(amount) <= product.debt) && parseFloat(amount) <= availableBalance } export const isValidInstallmentPaymentForm = (transactionForm) => { return transactionForm.debitAccount.correct && transactionForm.amount.correct && transactionForm.date.correct } export const getPaymentType = (paymentMethod) => { let paymentType = ''; switch (paymentMethod) { case 'ΚΑΡΤΑ AGILE BANK': paymentType = 'isCreditCardAgile'; break; case 'ΚΑΡΤΑ ΑΛΛΗΣ ΤΡΑΠΕΖΗΣ': paymentType = 'isCreditCardThirdParty'; break; case 'ΔΑΝΕΙΟ AGILE BANK': paymentType = 'isLoan'; break; default: paymentType = 'thirdPartyPayment'; } return paymentType; } export const getCustomerName = (fullCustomerName) => { return (fullCustomerName.firstName + ' ' + fullCustomerName.lastName) .replace('ά', 'α') .replace('έ', 'ε') .replace('ί', 'ι') .replace('ή', 'η') .replace('ό', 'ο') .replace('ύ', 'υ') .replace('ώ', 'ω'); } export const getActualFullName = (fullName, currentFullName) => { const correctPattern = new RegExp("^[A-Za-zΑ-Ωα-ω ]+$"); return fullName = (correctPattern.test(fullName) || fullName == '' ? fullName : currentFullName).toUpperCase(); } export const isValidFullName = (fullName) => fullName.split(' ').length == 2 export const isValidDebitAmount = (amount, availableBalance) => { return amount > 0 && (parseFloat(amount)) <= availableBalance } export const isValidChargesBeneficiary = (beneficiary) => { return beneficiary == 'both' || beneficiary == 'sender' || beneficiary == 'beneficiary' } export const findPaymentCharges = (paymentMethods, paymentName) => { return map(paymentMethods, (paymentMethod) => paymentMethod.map(method => method)) .flatMap(paymentMethod => paymentMethod) .filter(payment => payment.name == paymentName)[0].charges } export const findTransferCharges = (beneficiary) => { let charges = 0; switch (beneficiary) { case 'both': charges = 3; break; case 'sender': charges = 6; break; case 'beneficiary': charges = 0; break; } return charges; } export const getImmediateText = (language) => { let immediateText = ''; switch (language) { case 'greek': immediateText = 'ΑΜΕΣΑ'; break; case 'english': immediateText = 'IMMEDIATE'; break; } return immediateText; } export const formatCardNumber = (cardNumber) => { return [...cardNumber].map(((num, key) => key % 4 == 0 && key != 0 ? ' ' + num : num )) }
GKotsovos/WebBanking-Front-End
src/routes/root/routes/Banking/routes/utils/commonUtils.js
JavaScript
mit
5,183
var assert = require('assert'); var num = require('../'); test('sub', function() { assert.equal(num.sub(0, 0), '0'); assert.equal(num.sub('0', '-0'), '0'); assert.equal(num.sub('1.0', '-1.0'), '2.0'); assert.equal(num('987654321987654321.12345678901').sub(100.012), '987654321987654221.11145678901'); assert.equal(num(100.012).sub(num('987654321987654321.12345678901')), '-987654321987654221.11145678901'); }); test('sub#constness', function() { var one = num(1.2); var two = num(-1.2); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); one.sub(two); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); two.sub(one); assert.equal(one, '1.2'); assert.equal(two, '-1.2'); });
Rebero/arbitrade
server/node_modules/num/test/sub.js
JavaScript
mit
745
/*! * vue-resource v1.5.3 * https://github.com/pagekit/vue-resource * Released under the MIT License. */ 'use strict'; /** * Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis) */ var RESOLVED = 0; var REJECTED = 1; var PENDING = 2; function Promise$1(executor) { this.state = PENDING; this.value = undefined; this.deferred = []; var promise = this; try { executor(function (x) { promise.resolve(x); }, function (r) { promise.reject(r); }); } catch (e) { promise.reject(e); } } Promise$1.reject = function (r) { return new Promise$1(function (resolve, reject) { reject(r); }); }; Promise$1.resolve = function (x) { return new Promise$1(function (resolve, reject) { resolve(x); }); }; Promise$1.all = function all(iterable) { return new Promise$1(function (resolve, reject) { var count = 0, result = []; if (iterable.length === 0) { resolve(result); } function resolver(i) { return function (x) { result[i] = x; count += 1; if (count === iterable.length) { resolve(result); } }; } for (var i = 0; i < iterable.length; i += 1) { Promise$1.resolve(iterable[i]).then(resolver(i), reject); } }); }; Promise$1.race = function race(iterable) { return new Promise$1(function (resolve, reject) { for (var i = 0; i < iterable.length; i += 1) { Promise$1.resolve(iterable[i]).then(resolve, reject); } }); }; var p = Promise$1.prototype; p.resolve = function resolve(x) { var promise = this; if (promise.state === PENDING) { if (x === promise) { throw new TypeError('Promise settled with itself.'); } var called = false; try { var then = x && x['then']; if (x !== null && typeof x === 'object' && typeof then === 'function') { then.call(x, function (x) { if (!called) { promise.resolve(x); } called = true; }, function (r) { if (!called) { promise.reject(r); } called = true; }); return; } } catch (e) { if (!called) { promise.reject(e); } return; } promise.state = RESOLVED; promise.value = x; promise.notify(); } }; p.reject = function reject(reason) { var promise = this; if (promise.state === PENDING) { if (reason === promise) { throw new TypeError('Promise settled with itself.'); } promise.state = REJECTED; promise.value = reason; promise.notify(); } }; p.notify = function notify() { var promise = this; nextTick(function () { if (promise.state !== PENDING) { while (promise.deferred.length) { var deferred = promise.deferred.shift(), onResolved = deferred[0], onRejected = deferred[1], resolve = deferred[2], reject = deferred[3]; try { if (promise.state === RESOLVED) { if (typeof onResolved === 'function') { resolve(onResolved.call(undefined, promise.value)); } else { resolve(promise.value); } } else if (promise.state === REJECTED) { if (typeof onRejected === 'function') { resolve(onRejected.call(undefined, promise.value)); } else { reject(promise.value); } } } catch (e) { reject(e); } } } }); }; p.then = function then(onResolved, onRejected) { var promise = this; return new Promise$1(function (resolve, reject) { promise.deferred.push([onResolved, onRejected, resolve, reject]); promise.notify(); }); }; p["catch"] = function (onRejected) { return this.then(undefined, onRejected); }; /** * Promise adapter. */ if (typeof Promise === 'undefined') { window.Promise = Promise$1; } function PromiseObj(executor, context) { if (executor instanceof Promise) { this.promise = executor; } else { this.promise = new Promise(executor.bind(context)); } this.context = context; } PromiseObj.all = function (iterable, context) { return new PromiseObj(Promise.all(iterable), context); }; PromiseObj.resolve = function (value, context) { return new PromiseObj(Promise.resolve(value), context); }; PromiseObj.reject = function (reason, context) { return new PromiseObj(Promise.reject(reason), context); }; PromiseObj.race = function (iterable, context) { return new PromiseObj(Promise.race(iterable), context); }; var p$1 = PromiseObj.prototype; p$1.bind = function (context) { this.context = context; return this; }; p$1.then = function (fulfilled, rejected) { if (fulfilled && fulfilled.bind && this.context) { fulfilled = fulfilled.bind(this.context); } if (rejected && rejected.bind && this.context) { rejected = rejected.bind(this.context); } return new PromiseObj(this.promise.then(fulfilled, rejected), this.context); }; p$1["catch"] = function (rejected) { if (rejected && rejected.bind && this.context) { rejected = rejected.bind(this.context); } return new PromiseObj(this.promise["catch"](rejected), this.context); }; p$1["finally"] = function (callback) { return this.then(function (value) { callback.call(this); return value; }, function (reason) { callback.call(this); return Promise.reject(reason); }); }; /** * Utility functions. */ var _ref = {}, hasOwnProperty = _ref.hasOwnProperty, slice = [].slice, debug = false, ntick; var inBrowser = typeof window !== 'undefined'; function Util (_ref2) { var config = _ref2.config, nextTick = _ref2.nextTick; ntick = nextTick; debug = config.debug || !config.silent; } function warn(msg) { if (typeof console !== 'undefined' && debug) { console.warn('[VueResource warn]: ' + msg); } } function error(msg) { if (typeof console !== 'undefined') { console.error(msg); } } function nextTick(cb, ctx) { return ntick(cb, ctx); } function trim(str) { return str ? str.replace(/^\s*|\s*$/g, '') : ''; } function trimEnd(str, chars) { if (str && chars === undefined) { return str.replace(/\s+$/, ''); } if (!str || !chars) { return str; } return str.replace(new RegExp("[" + chars + "]+$"), ''); } function toLower(str) { return str ? str.toLowerCase() : ''; } function toUpper(str) { return str ? str.toUpperCase() : ''; } var isArray = Array.isArray; function isString(val) { return typeof val === 'string'; } function isFunction(val) { return typeof val === 'function'; } function isObject(obj) { return obj !== null && typeof obj === 'object'; } function isPlainObject(obj) { return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype; } function isBlob(obj) { return typeof Blob !== 'undefined' && obj instanceof Blob; } function isFormData(obj) { return typeof FormData !== 'undefined' && obj instanceof FormData; } function when(value, fulfilled, rejected) { var promise = PromiseObj.resolve(value); if (arguments.length < 2) { return promise; } return promise.then(fulfilled, rejected); } function options(fn, obj, opts) { opts = opts || {}; if (isFunction(opts)) { opts = opts.call(obj); } return merge(fn.bind({ $vm: obj, $options: opts }), fn, { $options: opts }); } function each(obj, iterator) { var i, key; if (isArray(obj)) { for (i = 0; i < obj.length; i++) { iterator.call(obj[i], obj[i], i); } } else if (isObject(obj)) { for (key in obj) { if (hasOwnProperty.call(obj, key)) { iterator.call(obj[key], obj[key], key); } } } return obj; } var assign = Object.assign || _assign; function merge(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { _merge(target, source, true); }); return target; } function defaults(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { for (var key in source) { if (target[key] === undefined) { target[key] = source[key]; } } }); return target; } function _assign(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { _merge(target, source); }); return target; } function _merge(target, source, deep) { for (var key in source) { if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) { target[key] = {}; } if (isArray(source[key]) && !isArray(target[key])) { target[key] = []; } _merge(target[key], source[key], deep); } else if (source[key] !== undefined) { target[key] = source[key]; } } } /** * Root Prefix Transform. */ function root (options$$1, next) { var url = next(options$$1); if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) { url = trimEnd(options$$1.root, '/') + '/' + url; } return url; } /** * Query Parameter Transform. */ function query (options$$1, next) { var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1); each(options$$1.params, function (value, key) { if (urlParams.indexOf(key) === -1) { query[key] = value; } }); query = Url.params(query); if (query) { url += (url.indexOf('?') == -1 ? '?' : '&') + query; } return url; } /** * URL Template v2.0.6 (https://github.com/bramstein/url-template) */ function expand(url, params, variables) { var tmpl = parse(url), expanded = tmpl.expand(params); if (variables) { variables.push.apply(variables, tmpl.vars); } return expanded; } function parse(template) { var operators = ['+', '#', '.', '/', ';', '?', '&'], variables = []; return { vars: variables, expand: function expand(context) { return template.replace(/\{([^{}]+)\}|([^{}]+)/g, function (_, expression, literal) { if (expression) { var operator = null, values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function (variable) { var tmp = /([^:*]*)(?::(\d+)|(\*))?/.exec(variable); values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3])); variables.push(tmp[1]); }); if (operator && operator !== '+') { var separator = ','; if (operator === '?') { separator = '&'; } else if (operator !== '#') { separator = operator; } return (values.length !== 0 ? operator : '') + values.join(separator); } else { return values.join(','); } } else { return encodeReserved(literal); } }); } }; } function getValues(context, operator, key, modifier) { var value = context[key], result = []; if (isDefined(value) && value !== '') { if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { value = value.toString(); if (modifier && modifier !== '*') { value = value.substring(0, parseInt(modifier, 10)); } result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null)); } else { if (modifier === '*') { if (Array.isArray(value)) { value.filter(isDefined).forEach(function (value) { result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null)); }); } else { Object.keys(value).forEach(function (k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } }); } } else { var tmp = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function (value) { tmp.push(encodeValue(operator, value)); }); } else { Object.keys(value).forEach(function (k) { if (isDefined(value[k])) { tmp.push(encodeURIComponent(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { result.push(encodeURIComponent(key) + '=' + tmp.join(',')); } else if (tmp.length !== 0) { result.push(tmp.join(',')); } } } } else { if (operator === ';') { result.push(encodeURIComponent(key)); } else if (value === '' && (operator === '&' || operator === '?')) { result.push(encodeURIComponent(key) + '='); } else if (value === '') { result.push(''); } } return result; } function isDefined(value) { return value !== undefined && value !== null; } function isKeyOperator(operator) { return operator === ';' || operator === '&' || operator === '?'; } function encodeValue(operator, value, key) { value = operator === '+' || operator === '#' ? encodeReserved(value) : encodeURIComponent(value); if (key) { return encodeURIComponent(key) + '=' + value; } else { return value; } } function encodeReserved(str) { return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part); } return part; }).join(''); } /** * URL Template (RFC 6570) Transform. */ function template (options) { var variables = [], url = expand(options.url, options.params, variables); variables.forEach(function (key) { delete options.params[key]; }); return url; } /** * Service for URL templating. */ function Url(url, params) { var self = this || {}, options$$1 = url, transform; if (isString(url)) { options$$1 = { url: url, params: params }; } options$$1 = merge({}, Url.options, self.$options, options$$1); Url.transforms.forEach(function (handler) { if (isString(handler)) { handler = Url.transform[handler]; } if (isFunction(handler)) { transform = factory(handler, transform, self.$vm); } }); return transform(options$$1); } /** * Url options. */ Url.options = { url: '', root: null, params: {} }; /** * Url transforms. */ Url.transform = { template: template, query: query, root: root }; Url.transforms = ['template', 'query', 'root']; /** * Encodes a Url parameter string. * * @param {Object} obj */ Url.params = function (obj) { var params = [], escape = encodeURIComponent; params.add = function (key, value) { if (isFunction(value)) { value = value(); } if (value === null) { value = ''; } this.push(escape(key) + '=' + escape(value)); }; serialize(params, obj); return params.join('&').replace(/%20/g, '+'); }; /** * Parse a URL and return its components. * * @param {String} url */ Url.parse = function (url) { var el = document.createElement('a'); if (document.documentMode) { el.href = url; url = el.href; } el.href = url; return { href: el.href, protocol: el.protocol ? el.protocol.replace(/:$/, '') : '', port: el.port, host: el.host, hostname: el.hostname, pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname, search: el.search ? el.search.replace(/^\?/, '') : '', hash: el.hash ? el.hash.replace(/^#/, '') : '' }; }; function factory(handler, next, vm) { return function (options$$1) { return handler.call(vm, options$$1, next); }; } function serialize(params, obj, scope) { var array = isArray(obj), plain = isPlainObject(obj), hash; each(obj, function (value, key) { hash = isObject(value) || isArray(value); if (scope) { key = scope + '[' + (plain || hash ? key : '') + ']'; } if (!scope && array) { params.add(value.name, value.value); } else if (hash) { serialize(params, value, key); } else { params.add(key, value); } }); } /** * XDomain client (Internet Explorer). */ function xdrClient (request) { return new PromiseObj(function (resolve) { var xdr = new XDomainRequest(), handler = function handler(_ref) { var type = _ref.type; var status = 0; if (type === 'load') { status = 200; } else if (type === 'error') { status = 500; } resolve(request.respondWith(xdr.responseText, { status: status })); }; request.abort = function () { return xdr.abort(); }; xdr.open(request.method, request.getUrl()); if (request.timeout) { xdr.timeout = request.timeout; } xdr.onload = handler; xdr.onabort = handler; xdr.onerror = handler; xdr.ontimeout = handler; xdr.onprogress = function () {}; xdr.send(request.getBody()); }); } /** * CORS Interceptor. */ var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest(); function cors (request) { if (inBrowser) { var orgUrl = Url.parse(location.href); var reqUrl = Url.parse(request.getUrl()); if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) { request.crossOrigin = true; request.emulateHTTP = false; if (!SUPPORTS_CORS) { request.client = xdrClient; } } } } /** * Form data Interceptor. */ function form (request) { if (isFormData(request.body)) { request.headers["delete"]('Content-Type'); } else if (isObject(request.body) && request.emulateJSON) { request.body = Url.params(request.body); request.headers.set('Content-Type', 'application/x-www-form-urlencoded'); } } /** * JSON Interceptor. */ function json (request) { var type = request.headers.get('Content-Type') || ''; if (isObject(request.body) && type.indexOf('application/json') === 0) { request.body = JSON.stringify(request.body); } return function (response) { return response.bodyText ? when(response.text(), function (text) { var type = response.headers.get('Content-Type') || ''; if (type.indexOf('application/json') === 0 || isJson(text)) { try { response.body = JSON.parse(text); } catch (e) { response.body = null; } } else { response.body = text; } return response; }) : response; }; } function isJson(str) { var start = str.match(/^\s*(\[|\{)/); var end = { '[': /]\s*$/, '{': /}\s*$/ }; return start && end[start[1]].test(str); } /** * JSONP client (Browser). */ function jsonpClient (request) { return new PromiseObj(function (resolve) { var name = request.jsonp || 'callback', callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2), body = null, handler, script; handler = function handler(_ref) { var type = _ref.type; var status = 0; if (type === 'load' && body !== null) { status = 200; } else if (type === 'error') { status = 500; } if (status && window[callback]) { delete window[callback]; document.body.removeChild(script); } resolve(request.respondWith(body, { status: status })); }; window[callback] = function (result) { body = JSON.stringify(result); }; request.abort = function () { handler({ type: 'abort' }); }; request.params[name] = callback; if (request.timeout) { setTimeout(request.abort, request.timeout); } script = document.createElement('script'); script.src = request.getUrl(); script.type = 'text/javascript'; script.async = true; script.onload = handler; script.onerror = handler; document.body.appendChild(script); }); } /** * JSONP Interceptor. */ function jsonp (request) { if (request.method == 'JSONP') { request.client = jsonpClient; } } /** * Before Interceptor. */ function before (request) { if (isFunction(request.before)) { request.before.call(this, request); } } /** * HTTP method override Interceptor. */ function method (request) { if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) { request.headers.set('X-HTTP-Method-Override', request.method); request.method = 'POST'; } } /** * Header Interceptor. */ function header (request) { var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)]); each(headers, function (value, name) { if (!request.headers.has(name)) { request.headers.set(name, value); } }); } /** * XMLHttp client (Browser). */ function xhrClient (request) { return new PromiseObj(function (resolve) { var xhr = new XMLHttpRequest(), handler = function handler(event) { var response = request.respondWith('response' in xhr ? xhr.response : xhr.responseText, { status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText) }); each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) { response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1)); }); resolve(response); }; request.abort = function () { return xhr.abort(); }; xhr.open(request.method, request.getUrl(), true); if (request.timeout) { xhr.timeout = request.timeout; } if (request.responseType && 'responseType' in xhr) { xhr.responseType = request.responseType; } if (request.withCredentials || request.credentials) { xhr.withCredentials = true; } if (!request.crossOrigin) { request.headers.set('X-Requested-With', 'XMLHttpRequest'); } // deprecated use downloadProgress if (isFunction(request.progress) && request.method === 'GET') { xhr.addEventListener('progress', request.progress); } if (isFunction(request.downloadProgress)) { xhr.addEventListener('progress', request.downloadProgress); } // deprecated use uploadProgress if (isFunction(request.progress) && /^(POST|PUT)$/i.test(request.method)) { xhr.upload.addEventListener('progress', request.progress); } if (isFunction(request.uploadProgress) && xhr.upload) { xhr.upload.addEventListener('progress', request.uploadProgress); } request.headers.forEach(function (value, name) { xhr.setRequestHeader(name, value); }); xhr.onload = handler; xhr.onabort = handler; xhr.onerror = handler; xhr.ontimeout = handler; xhr.send(request.getBody()); }); } /** * Http client (Node). */ function nodeClient (request) { var client = require('got'); return new PromiseObj(function (resolve) { var url = request.getUrl(); var body = request.getBody(); var method = request.method; var headers = {}, handler; request.headers.forEach(function (value, name) { headers[name] = value; }); client(url, { body: body, method: method, headers: headers }).then(handler = function handler(resp) { var response = request.respondWith(resp.body, { status: resp.statusCode, statusText: trim(resp.statusMessage) }); each(resp.headers, function (value, name) { response.headers.set(name, value); }); resolve(response); }, function (error$$1) { return handler(error$$1.response); }); }); } /** * Base client. */ function Client (context) { var reqHandlers = [sendRequest], resHandlers = []; if (!isObject(context)) { context = null; } function Client(request) { while (reqHandlers.length) { var handler = reqHandlers.pop(); if (isFunction(handler)) { var _ret = function () { var response = void 0, next = void 0; response = handler.call(context, request, function (val) { return next = val; }) || next; if (isObject(response)) { return { v: new PromiseObj(function (resolve, reject) { resHandlers.forEach(function (handler) { response = when(response, function (response) { return handler.call(context, response) || response; }, reject); }); when(response, resolve, reject); }, context) }; } if (isFunction(response)) { resHandlers.unshift(response); } }(); if (typeof _ret === "object") return _ret.v; } else { warn("Invalid interceptor of type " + typeof handler + ", must be a function"); } } } Client.use = function (handler) { reqHandlers.push(handler); }; return Client; } function sendRequest(request) { var client = request.client || (inBrowser ? xhrClient : nodeClient); return client(request); } /** * HTTP Headers. */ var Headers = /*#__PURE__*/function () { function Headers(headers) { var _this = this; this.map = {}; each(headers, function (value, name) { return _this.append(name, value); }); } var _proto = Headers.prototype; _proto.has = function has(name) { return getName(this.map, name) !== null; }; _proto.get = function get(name) { var list = this.map[getName(this.map, name)]; return list ? list.join() : null; }; _proto.getAll = function getAll(name) { return this.map[getName(this.map, name)] || []; }; _proto.set = function set(name, value) { this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)]; }; _proto.append = function append(name, value) { var list = this.map[getName(this.map, name)]; if (list) { list.push(trim(value)); } else { this.set(name, value); } }; _proto["delete"] = function _delete(name) { delete this.map[getName(this.map, name)]; }; _proto.deleteAll = function deleteAll() { this.map = {}; }; _proto.forEach = function forEach(callback, thisArg) { var _this2 = this; each(this.map, function (list, name) { each(list, function (value) { return callback.call(thisArg, value, name, _this2); }); }); }; return Headers; }(); function getName(map, name) { return Object.keys(map).reduce(function (prev, curr) { return toLower(name) === toLower(curr) ? curr : prev; }, null); } function normalizeName(name) { if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name'); } return trim(name); } /** * HTTP Response. */ var Response = /*#__PURE__*/function () { function Response(body, _ref) { var url = _ref.url, headers = _ref.headers, status = _ref.status, statusText = _ref.statusText; this.url = url; this.ok = status >= 200 && status < 300; this.status = status || 0; this.statusText = statusText || ''; this.headers = new Headers(headers); this.body = body; if (isString(body)) { this.bodyText = body; } else if (isBlob(body)) { this.bodyBlob = body; if (isBlobText(body)) { this.bodyText = blobText(body); } } } var _proto = Response.prototype; _proto.blob = function blob() { return when(this.bodyBlob); }; _proto.text = function text() { return when(this.bodyText); }; _proto.json = function json() { return when(this.text(), function (text) { return JSON.parse(text); }); }; return Response; }(); Object.defineProperty(Response.prototype, 'data', { get: function get() { return this.body; }, set: function set(body) { this.body = body; } }); function blobText(body) { return new PromiseObj(function (resolve) { var reader = new FileReader(); reader.readAsText(body); reader.onload = function () { resolve(reader.result); }; }); } function isBlobText(body) { return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1; } /** * HTTP Request. */ var Request = /*#__PURE__*/function () { function Request(options$$1) { this.body = null; this.params = {}; assign(this, options$$1, { method: toUpper(options$$1.method || 'GET') }); if (!(this.headers instanceof Headers)) { this.headers = new Headers(this.headers); } } var _proto = Request.prototype; _proto.getUrl = function getUrl() { return Url(this); }; _proto.getBody = function getBody() { return this.body; }; _proto.respondWith = function respondWith(body, options$$1) { return new Response(body, assign(options$$1 || {}, { url: this.getUrl() })); }; return Request; }(); /** * Service for sending network requests. */ var COMMON_HEADERS = { 'Accept': 'application/json, text/plain, */*' }; var JSON_CONTENT_TYPE = { 'Content-Type': 'application/json;charset=utf-8' }; function Http(options$$1) { var self = this || {}, client = Client(self.$vm); defaults(options$$1 || {}, self.$options, Http.options); Http.interceptors.forEach(function (handler) { if (isString(handler)) { handler = Http.interceptor[handler]; } if (isFunction(handler)) { client.use(handler); } }); return client(new Request(options$$1)).then(function (response) { return response.ok ? response : PromiseObj.reject(response); }, function (response) { if (response instanceof Error) { error(response); } return PromiseObj.reject(response); }); } Http.options = {}; Http.headers = { put: JSON_CONTENT_TYPE, post: JSON_CONTENT_TYPE, patch: JSON_CONTENT_TYPE, "delete": JSON_CONTENT_TYPE, common: COMMON_HEADERS, custom: {} }; Http.interceptor = { before: before, method: method, jsonp: jsonp, json: json, form: form, header: header, cors: cors }; Http.interceptors = ['before', 'method', 'jsonp', 'json', 'form', 'header', 'cors']; ['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) { Http[method$$1] = function (url, options$$1) { return this(assign(options$$1 || {}, { url: url, method: method$$1 })); }; }); ['post', 'put', 'patch'].forEach(function (method$$1) { Http[method$$1] = function (url, body, options$$1) { return this(assign(options$$1 || {}, { url: url, method: method$$1, body: body })); }; }); /** * Service for interacting with RESTful services. */ function Resource(url, params, actions, options$$1) { var self = this || {}, resource = {}; actions = assign({}, Resource.actions, actions); each(actions, function (action, name) { action = merge({ url: url, params: assign({}, params) }, options$$1, action); resource[name] = function () { return (self.$http || Http)(opts(action, arguments)); }; }); return resource; } function opts(action, args) { var options$$1 = assign({}, action), params = {}, body; switch (args.length) { case 2: params = args[0]; body = args[1]; break; case 1: if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) { body = args[0]; } else { params = args[0]; } break; case 0: break; default: throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments'; } options$$1.body = body; options$$1.params = assign({}, options$$1.params, params); return options$$1; } Resource.actions = { get: { method: 'GET' }, save: { method: 'POST' }, query: { method: 'GET' }, update: { method: 'PUT' }, remove: { method: 'DELETE' }, "delete": { method: 'DELETE' } }; /** * Install plugin. */ function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.url = Url; Vue.http = Http; Vue.resource = Resource; Vue.Promise = PromiseObj; Object.defineProperties(Vue.prototype, { $url: { get: function get() { return options(Vue.url, this, this.$options.url); } }, $http: { get: function get() { return options(Vue.http, this, this.$options.http); } }, $resource: { get: function get() { return Vue.resource.bind(this); } }, $promise: { get: function get() { var _this = this; return function (executor) { return new Vue.Promise(executor, _this); }; } } }); } if (typeof window !== 'undefined' && window.Vue && !window.Vue.resource) { window.Vue.use(plugin); } module.exports = plugin;
vuejs/vue-resource
dist/vue-resource.common.js
JavaScript
mit
33,000
console.log('argv[0]: '+process.argv[0]); console.log('argv[1]: '+process.argv[1]);
AdonRain/neowheel
1_hello/hello_2/hello_2_2.js
JavaScript
mit
86
'use strict'; var Crawler = require('../lib/crawler'); var expect = require('chai').expect; var jsdom = require('jsdom'); var httpbinHost = 'localhost:8000'; describe('Errors', function() { describe('timeout', function() { var c = new Crawler({ timeout : 1500, retryTimeout : 1000, retries : 2, jquery : false }); it('should return a timeout error after ~5sec', function(done) { // override default mocha test timeout of 2000ms this.timeout(10000); c.queue({ uri : 'http://'+httpbinHost+'/delay/15', callback : function(error, response) //noinspection BadExpressionStatementJS,BadExpressionStatementJS { expect(error).not.to.be.null; expect(error.code).to.equal("ETIMEDOUT"); //expect(response).to.be.undefined; done(); } }); }); it('should retry after a first timeout', function(done) { // override default mocha test timeout of 2000ms this.timeout(15000); c.queue({ uri : 'http://'+httpbinHost+'/delay/1', callback : function(error, response) { expect(error).to.be.null; expect(response.body).to.be.ok; done(); } }); }); }); describe('error status code', function() { var c = new Crawler({ jQuery : false }); it('should not return an error on status code 400 (Bad Request)', function(done) { c.queue({ uri: 'http://' + httpbinHost + '/status/400', callback: function(error, response, $){ expect(error).to.be.null; expect(response.statusCode).to.equal(400); done(); } }); }); it('should not return an error on status code 401 (Unauthorized)', function(done) { c.queue({ uri: 'http://' + httpbinHost + '/status/401', callback: function(error, response, $){ expect(error).to.be.null; expect(response.statusCode).to.equal(401); done(); } }); }); it('should not return an error on status code 403 (Forbidden)', function(done) { c.queue({ uri: 'http://' + httpbinHost + '/status/403', callback: function(error, response, $){ expect(error).to.be.null; expect(response.statusCode).to.equal(403); done(); } }); }); it('should not return an error on a 404', function(done) { c.queue({ uri : 'http://'+httpbinHost+'/status/404', callback : function(error, response) { expect(error).to.be.null; expect(response.statusCode).to.equal(404); done(); } }); }); it('should not return an error on a 500', function(done) { c.queue({ uri : 'http://'+httpbinHost+'/status/500', callback : function(error, response) { expect(error).to.be.null; expect(response.statusCode).to.equal(500); done(); } }); }); it('should not failed on empty response', function(done) { c.queue({ uri : 'http://'+httpbinHost+'/status/204', callback : function(error) { expect(error).to.be.null; done(); } }); }); it('should not failed on a malformed html if jquery is false', function(done) { c.queue({ html : '<html><p>hello <div>dude</p></html>', callback : function(error, response) { expect(error).to.be.null; expect(response).not.to.be.null; done(); } }); }); it('should not return an error on a malformed html if jQuery is jsdom', function(done) { c.queue({ html : '<html><p>hello <div>dude</p></html>', jQuery : jsdom, callback : function(error, response) { expect(error).to.be.null; expect(response).not.to.be.undefined; done(); } }); }); }); });
shedar/node-webcrawler
tests/errorHandling.test.js
JavaScript
mit
4,772
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 3H3C2 3 1 4 1 5v14c0 1.1.9 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zM5 17l3.5-4.5 2.5 3.01L14.5 11l4.5 6H5z" }), 'PhotoSizeSelectActual'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/PhotoSizeSelectActual.js
JavaScript
mit
582
const PlotCard = require('../../plotcard.js'); class RiseOfTheKraken extends PlotCard { setupCardAbilities() { this.interrupt({ when: { onUnopposedWin: event => event.challenge.winner === this.controller }, handler: () => { this.game.addMessage('{0} uses {1} to gain an additional power from winning an unopposed challenge', this.controller, this); this.game.addPower(this.controller, 1); } }); } } RiseOfTheKraken.code = '02012'; module.exports = RiseOfTheKraken;
cryogen/gameteki
server/game/cards/02.1-TtB/RiseOfTheKraken.js
JavaScript
mit
588
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8 17c-.55 0-1-.45-1-1v-5c0-.55.45-1 1-1s1 .45 1 1v5c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v8c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1z" }), 'AssessmentRounded');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/AssessmentRounded.js
JavaScript
mit
471
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M12 4c4.41 0 8 3.59 8 8s-3.59 8-8 8-8-3.59-8-8 3.59-8 8-8m.06 9.34v2.14c-.92.02-1.84-.31-2.54-1.01-1.12-1.12-1.3-2.8-.59-4.13l-1.1-1.1c-1.28 1.94-1.07 4.59.64 6.29.97.98 2.25 1.47 3.53 1.47h.06v2l2.83-2.83-2.83-2.83zm3.48-4.88c-.99-.99-2.3-1.46-3.6-1.45V5L9.11 7.83l2.83 2.83V8.51H12c.9 0 1.79.34 2.48 1.02 1.12 1.12 1.3 2.8.59 4.13l1.1 1.1c1.28-1.94 1.07-4.59-.63-6.3z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M12 4c4.41 0 8 3.59 8 8s-3.59 8-8 8-8-3.59-8-8 3.59-8 8-8m0-2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm.06 11.34v2.14c-.92.02-1.84-.31-2.54-1.01-1.12-1.12-1.3-2.8-.59-4.13l-1.1-1.1c-1.28 1.94-1.07 4.59.64 6.29.97.98 2.25 1.47 3.53 1.47h.06v2l2.83-2.83-2.83-2.83zm3.48-4.88c-.99-.99-2.3-1.46-3.6-1.45V5L9.11 7.83l2.83 2.83V8.51H12c.9 0 1.79.34 2.48 1.02 1.12 1.12 1.3 2.8.59 4.13l1.1 1.1c1.28-1.94 1.07-4.59-.63-6.3z" }, "1")], 'ChangeCircleTwoTone');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/ChangeCircleTwoTone.js
JavaScript
mit
1,065
module.exports={A:{A:{"2":"K C G E B A WB"},B:{"2":"D u Y I M H"},C:{"1":"6 7","2":"0 1 2 3 UB z F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t y SB RB","132":"v","578":"5 g"},D:{"1":"0 1 2 3 5 6 7 t y v g GB BB DB VB EB","2":"F J K C G E B A D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s"},E:{"1":"MB","2":"F J K C G E B FB AB HB IB JB KB LB","322":"A"},F:{"1":"L h i j k l m n o p q r s t","2":"8 9 E A D I M H N O P Q R S T U V W X w Z a b c d e f NB OB PB QB TB x"},G:{"2":"4 G AB CB XB YB ZB aB bB cB dB eB","322":"A"},H:{"2":"fB"},I:{"1":"v","2":"4 z F gB hB iB jB kB lB"},J:{"2":"C B"},K:{"1":"L","2":"8 9 B A D x"},L:{"1":"BB"},M:{"132":"g"},N:{"2":"B A"},O:{"2":"mB"},P:{"1":"J","2":"F"},Q:{"2":"nB"},R:{"2":"oB"}},B:5,C:"Resource Hints: preload"};
mattstryfe/theWeatherHub
node_modules/caniuse-lite/data/features/link-rel-preload.js
JavaScript
mit
835
SVG.G = SVG.invent({ // Initialize node create: 'g' // Inherit from , inherit: SVG.Container // Add class methods , extend: { // Move over x-axis x: function(x) { return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true) } // Move over y-axis , y: function(y) { return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true) } // Move by center over x-axis , cx: function(x) { return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2) } // Move by center over y-axis , cy: function(y) { return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2) } , gbox: function() { var bbox = this.bbox() , trans = this.transform() bbox.x += trans.x bbox.x2 += trans.x bbox.cx += trans.x bbox.y += trans.y bbox.y2 += trans.y bbox.cy += trans.y return bbox } } // Add parent method , construct: { // Create a group element group: function() { return this.put(new SVG.G) } } })
albohlabs/svg.js
src/group.js
JavaScript
mit
1,102
'use strict'; module.exports = function generate_format(it, $keyword) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); if (it.opts.format === false) { if ($breakOnError) { out += ' if (true) { '; } return out; } var $isData = it.opts.v5 && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); if ($isData) { var $format = 'format' + $lvl; out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { '; if (it.async) { out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; } out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' ('; if ($unknownFormats === true || $allowUnknown) { out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; if ($allowUnknown) { out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; } out += ') || '; } out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? '; if (it.async) { out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; } else { out += ' ' + ($format) + '(' + ($data) + ') '; } out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; } else { var $format = it.formats[$schema]; if (!$format) { if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) { throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); } else { if (!$allowUnknown) { console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information'); } if ($breakOnError) { out += ' if (true) { '; } return out; } } var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; if ($isObject) { var $async = $format.async === true; $format = $format.validate; } if ($async) { if (!it.async) throw new Error('async format in sync schema'); var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { '; } else { out += ' if (! '; var $formatRef = 'formats' + it.util.getProperty($schema); if ($isObject) $formatRef += '.validate'; if (typeof $format == 'function') { out += ' ' + ($formatRef) + '(' + ($data) + ') '; } else { out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; } out += ') { '; } } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match format "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; }
Moccine/global-service-plus.com
web/libariries/bootstrap/node_modules/ajv/lib/dotjs/format.js
JavaScript
mit
5,423
require( [ 'gui/Button' ], function (Button) { return; var button = new Button({ main: $('#ui-button') }); button.render(); } );
musicode/gui
demo/Popup.js
JavaScript
mit
189
var GUID = (function () { function _GUID() { return UUIDcreatePart(4) + UUIDcreatePart(2) + UUIDcreatePart(2) + UUIDcreatePart(2) + UUIDcreatePart(6); }; function UUIDcreatePart(length) { var uuidpart = ""; for (var i = 0; i < length; i++) { var uuidchar = parseInt((Math.random() * 256), 10).toString(16); if (uuidchar.length == 1) { uuidchar = "0" + uuidchar; } uuidpart += uuidchar; } return uuidpart; } return { newGuid: _GUID }; })(); var dataSource = (function () { var tablesStorageKey = "60AE0285-40EE-4A2D-BA5F-F75D601593DD"; var globalData = []; var tables = [ { Id: 5, Name: "Contact", Schema: [ { k: "name", t: 1 }, { k: "companyname", t: 1 }, { k: "position", t: 1 } ], Created: "2016-08-12T07:32:46.69" }, { Id: 6, Name: "Profile", Schema: [ { k: "Name", t: 1 }, { k: "Age", t: 2 }, { k: "Gender", t: 4 }, { k: "Rating", t: 3 }, { k: "Created", t: 5 } ], Created: "2016-09-28T21:53:40.19" } ]; function _loadData(){ globalData = JSON.parse(localStorage[tablesStorageKey] || "[]"); } function _save() { localStorage[tablesStorageKey] = JSON.stringify(globalData); } function _getSchema(tableId) { for (var t = 0; t < tables.length; t++) if (tableId === tables[t].Id) return tables[t].Schema; } function _find(data) { var skip = data.start; var take = data.length; return { draw: data.draw, recordsTotal: globalData.length, recordsFiltered: globalData.length, data: globalData.slice(skip, take + skip) }; } function _insert(data) { var id = GUID.newGuid(); globalData.push([id, data.Name, data.Age, data.Gender, data.Rating, data.Created]); _save() return { IsOk: true, id: id }; } function _update(data) { for (var t = 0; t < globalData.length; t++) if (data._id === globalData[t][0]) { globalData[t] = [data._id, data.Name, data.Age, data.Gender, data.Rating, data.Created]; _save() return { IsOk: true }; } return { IsOk: false }; } function _delete(id) { for (var t = 0; t < globalData.length; t++) if (id === globalData[t][0]) { globalData = globalData.filter(item => item !== globalData[t]); _save(); return { IsOk: true }; } return { IsOk: false }; } _loadData(); return { getSchema: _getSchema, find: _find, insert: _insert, update: _update, delete: _delete }; })();
storyclm/storyCLM.js
presentation/js/dataSource.js
JavaScript
mit
3,648
(function() { 'use strict'; angular .module('app.core') .constant('STATIC_URL', '/static/js/'); })();
gopar/OhMyCommand
apps/static/js/core/constants.js
JavaScript
mit
127
$(document).ready(function(){ //Grabs url path var url = window.location.pathname; //Grabs current file name from URL var url = url.substring(url.lastIndexOf('/')+1); // now grab every link from the navigation $('#navigation a').each(function(){ //Grab the current elements href tag value var link = $(this).attr("href"); //Test if the url value and element value matches if(url === link){ //Adds class to the current item $(this).parent('li').addClass('active'); } }); });
sasd13/symfony
web/bundles/mywebsiteweb/js/active.js
JavaScript
mit
480
var fixDate = function(date) { return date.Format('2006-01-02 15:04:05'); }; var entries = executeCommand('getEntries', {}); dbotCommands = []; userCommands = []; for (var i = 0; i < entries.length; i++) { if (typeof entries[i].Contents == 'string' && entries[i].Contents.indexOf('!') === 0 && entries[i].Contents.indexOf('!listExecutedCommands') !== 0) { if (entries[i].Metadata.User) { if (args.source === 'All' || args.source === 'Manual') { userCommands.push({ 'Time': fixDate(entries[i].Metadata.Created), 'Entry ID': entries[i].ID, 'User': entries[i].Metadata.User, 'Command': entries[i].Contents }); } } else { if (args.source === 'All' || args.source === 'Playbook') { dbotCommands.push({ 'Time': fixDate(entries[i].Metadata.Created), 'Entry ID': entries[i].ID, 'Playbook (Task)': entries[i].Metadata.EntryTask.PlaybookName + " (" + entries[i].Metadata.EntryTask.TaskName + ")", 'Command': entries[i].Contents }); } } } } var md = ''; if (dbotCommands.length > 0) { md += tableToMarkdown('DBot Executed Commands', dbotCommands, ['Time', 'Entry ID', 'Playbook (Task)', 'Command']) + '\n'; } if (userCommands.length > 0) { md += tableToMarkdown('User Executed Commands', userCommands, ['Time', 'Entry ID', 'User', 'Command']) + '\n'; } if (md === '') { md = 'No commands found\n'; } return {ContentsFormat: formats.markdown, Type: entryTypes.note, Contents: md};
demisto/content
Packs/CommonScripts/Scripts/ListExecutedCommands/ListExecutedCommands.js
JavaScript
mit
1,692
'use strict'; var canUseDOM = require('./canUseDOM'); var one = function() { }; var on = function() { }; var off = function() { }; if (canUseDOM) { var bind = window.addEventListener ? 'addEventListener' : 'attachEvent'; var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent'; var prefix = bind !== 'addEventListener' ? 'on' : ''; one = function(node, eventNames, eventListener) { var typeArray = eventNames.split(' '); var recursiveFunction = function(e) { e.target.removeEventListener(e.type, recursiveFunction); return eventListener(e); }; for (var i = typeArray.length - 1; i >= 0; i--) { this.on(node, typeArray[i], recursiveFunction); } }; /** * Bind `node` event `eventName` to `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Obejct} * @api public */ on = function(node, eventName, eventListener, capture) { node[bind](prefix + eventName, eventListener, capture || false); return { off: function() { node[unbind](prefix + eventName, eventListener, capture || false); } }; } /** * Unbind `node` event `eventName`'s callback `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Function} * @api public */ off = function(node, eventName, eventListener, capture) { node[unbind](prefix + eventName, eventListener, capture || false); return eventListener; }; } module.exports = { one: one, on: on, off: off };
minwe/amazeui-react
src/utils/Events.js
JavaScript
mit
1,693
'use strict'; describe('angular', function() { var element; afterEach(function(){ dealoc(element); }); describe('case', function() { it('should change case', function() { expect(lowercase('ABC90')).toEqual('abc90'); expect(manualLowercase('ABC90')).toEqual('abc90'); expect(uppercase('abc90')).toEqual('ABC90'); expect(manualUppercase('abc90')).toEqual('ABC90'); }); }); describe("copy", function() { it("should return same object", function () { var obj = {}; var arr = []; expect(copy({}, obj)).toBe(obj); expect(copy([], arr)).toBe(arr); }); it("should copy Date", function() { var date = new Date(123); expect(copy(date) instanceof Date).toBeTruthy(); expect(copy(date).getTime()).toEqual(123); expect(copy(date) === date).toBeFalsy(); }); it("should deeply copy an array into an existing array", function() { var src = [1, {name:"value"}]; var dst = [{key:"v"}]; expect(copy(src, dst)).toBe(dst); expect(dst).toEqual([1, {name:"value"}]); expect(dst[1]).toEqual({name:"value"}); expect(dst[1]).not.toBe(src[1]); }); it("should deeply copy an array into a new array", function() { var src = [1, {name:"value"}]; var dst = copy(src); expect(src).toEqual([1, {name:"value"}]); expect(dst).toEqual(src); expect(dst).not.toBe(src); expect(dst[1]).not.toBe(src[1]); }); it('should copy empty array', function() { var src = []; var dst = [{key: "v"}]; expect(copy(src, dst)).toEqual([]); expect(dst).toEqual([]); }); it("should deeply copy an object into an existing object", function() { var src = {a:{name:"value"}}; var dst = {b:{key:"v"}}; expect(copy(src, dst)).toBe(dst); expect(dst).toEqual({a:{name:"value"}}); expect(dst.a).toEqual(src.a); expect(dst.a).not.toBe(src.a); }); it("should deeply copy an object into an existing object", function() { var src = {a:{name:"value"}}; var dst = copy(src, dst); expect(src).toEqual({a:{name:"value"}}); expect(dst).toEqual(src); expect(dst).not.toBe(src); expect(dst.a).toEqual(src.a); expect(dst.a).not.toBe(src.a); }); it("should copy primitives", function() { expect(copy(null)).toEqual(null); expect(copy('')).toBe(''); expect(copy('lala')).toBe('lala'); expect(copy(123)).toEqual(123); expect(copy([{key:null}])).toEqual([{key:null}]); }); it('should throw an exception if a Scope is being copied', inject(function($rootScope) { expect(function() { copy($rootScope.$new()); }). toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported."); })); it('should throw an exception if a Window is being copied', function() { expect(function() { copy(window); }). toThrow("[ng:cpws] Can't copy! Making copies of Window or Scope instances is not supported."); }); it('should throw an exception when source and destination are equivalent', function() { var src, dst; src = dst = {key: 'value'}; expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical."); src = dst = [2, 4]; expect(function() { copy(src, dst); }).toThrow("[ng:cpi] Can't copy! Source and destination are identical."); }); it('should not copy the private $$hashKey', function() { var src,dst; src = {}; hashKey(src); dst = copy(src); expect(hashKey(dst)).not.toEqual(hashKey(src)); }); it('should retain the previous $$hashKey', function() { var src,dst,h; src = {}; dst = {}; // force creation of a hashkey h = hashKey(dst); hashKey(src); dst = copy(src,dst); // make sure we don't copy the key expect(hashKey(dst)).not.toEqual(hashKey(src)); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); }); describe("extend", function() { it('should not copy the private $$hashKey', function() { var src,dst; src = {}; dst = {}; hashKey(src); dst = extend(dst,src); expect(hashKey(dst)).not.toEqual(hashKey(src)); }); it('should retain the previous $$hashKey', function() { var src,dst,h; src = {}; dst = {}; h = hashKey(dst); hashKey(src); dst = extend(dst,src); // make sure we don't copy the key expect(hashKey(dst)).not.toEqual(hashKey(src)); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); it('should work when extending with itself', function() { var src,dst,h; dst = src = {}; h = hashKey(dst); dst = extend(dst,src); // make sure we retain the old key expect(hashKey(dst)).toEqual(h); }); }); describe('shallow copy', function() { it('should make a copy', function() { var original = {key:{}}; var copy = shallowCopy(original); expect(copy).toEqual(original); expect(copy.key).toBe(original.key); }); it('should not copy $$ properties nor prototype properties', function() { var original = {$$some: true, $$: true}; var clone = {}; expect(shallowCopy(original, clone)).toBe(clone); expect(clone.$$some).toBeUndefined(); expect(clone.$$).toBeUndefined(); }); }); describe('elementHTML', function() { it('should dump element', function() { expect(startingTag('<div attr="123">something<span></span></div>')). toEqual('<div attr="123">'); }); }); describe('equals', function() { it('should return true if same object', function() { var o = {}; expect(equals(o, o)).toEqual(true); expect(equals(o, {})).toEqual(true); expect(equals(1, '1')).toEqual(false); expect(equals(1, '2')).toEqual(false); }); it('should recurse into object', function() { expect(equals({}, {})).toEqual(true); expect(equals({name:'misko'}, {name:'misko'})).toEqual(true); expect(equals({name:'misko', age:1}, {name:'misko'})).toEqual(false); expect(equals({name:'misko'}, {name:'misko', age:1})).toEqual(false); expect(equals({name:'misko'}, {name:'adam'})).toEqual(false); expect(equals(['misko'], ['misko'])).toEqual(true); expect(equals(['misko'], ['adam'])).toEqual(false); expect(equals(['misko'], ['misko', 'adam'])).toEqual(false); }); it('should ignore undefined member variables during comparison', function() { var obj1 = {name: 'misko'}, obj2 = {name: 'misko', undefinedvar: undefined}; expect(equals(obj1, obj2)).toBe(true); expect(equals(obj2, obj1)).toBe(true); }); it('should ignore $ member variables', function() { expect(equals({name:'misko', $id:1}, {name:'misko', $id:2})).toEqual(true); expect(equals({name:'misko'}, {name:'misko', $id:2})).toEqual(true); expect(equals({name:'misko', $id:1}, {name:'misko'})).toEqual(true); }); it('should ignore functions', function() { expect(equals({func: function() {}}, {bar: function() {}})).toEqual(true); }); it('should work well with nulls', function() { expect(equals(null, '123')).toBe(false); expect(equals('123', null)).toBe(false); var obj = {foo:'bar'}; expect(equals(null, obj)).toBe(false); expect(equals(obj, null)).toBe(false); expect(equals(null, null)).toBe(true); }); it('should work well with undefined', function() { expect(equals(undefined, '123')).toBe(false); expect(equals('123', undefined)).toBe(false); var obj = {foo:'bar'}; expect(equals(undefined, obj)).toBe(false); expect(equals(obj, undefined)).toBe(false); expect(equals(undefined, undefined)).toBe(true); }); it('should treat two NaNs as equal', function() { expect(equals(NaN, NaN)).toBe(true); }); it('should compare Scope instances only by identity', inject(function($rootScope) { var scope1 = $rootScope.$new(), scope2 = $rootScope.$new(); expect(equals(scope1, scope1)).toBe(true); expect(equals(scope1, scope2)).toBe(false); expect(equals($rootScope, scope1)).toBe(false); expect(equals(undefined, scope1)).toBe(false); })); it('should compare Window instances only by identity', function() { expect(equals(window, window)).toBe(true); expect(equals(window, window.parent)).toBe(false); expect(equals(window, undefined)).toBe(false); }); it('should compare dates', function() { expect(equals(new Date(0), new Date(0))).toBe(true); expect(equals(new Date(0), new Date(1))).toBe(false); expect(equals(new Date(0), 0)).toBe(false); expect(equals(0, new Date(0))).toBe(false); }); it('should correctly test for keys that are present on Object.prototype', function() { // MS IE8 just doesn't work for this kind of thing, since "for ... in" doesn't return // things like hasOwnProperty even if it is explicitly defined on the actual object! if (msie<=8) return; expect(equals({}, {hasOwnProperty: 1})).toBe(false); expect(equals({}, {toString: null})).toBe(false); }); }); describe('size', function() { it('should return the number of items in an array', function() { expect(size([])).toBe(0); expect(size(['a', 'b', 'c'])).toBe(3); }); it('should return the number of properties of an object', function() { expect(size({})).toBe(0); expect(size({a:1, b:'a', c:noop})).toBe(3); }); it('should return the number of own properties of an object', function() { var obj = inherit({protoProp: 'c', protoFn: noop}, {a:1, b:'a', c:noop}); expect(size(obj)).toBe(5); expect(size(obj, true)).toBe(3); }); it('should return the string length', function() { expect(size('')).toBe(0); expect(size('abc')).toBe(3); }); it('should not rely on length property of an object to determine its size', function() { expect(size({length:99})).toBe(1); }); }); describe('parseKeyValue', function() { it('should parse a string into key-value pairs', function() { expect(parseKeyValue('')).toEqual({}); expect(parseKeyValue('simple=pair')).toEqual({simple: 'pair'}); expect(parseKeyValue('first=1&second=2')).toEqual({first: '1', second: '2'}); expect(parseKeyValue('escaped%20key=escaped%20value')). toEqual({'escaped key': 'escaped value'}); expect(parseKeyValue('emptyKey=')).toEqual({emptyKey: ''}); expect(parseKeyValue('flag1&key=value&flag2')). toEqual({flag1: true, key: 'value', flag2: true}); }); it('should ignore key values that are not valid URI components', function() { expect(function() { parseKeyValue('%'); }).not.toThrow(); expect(parseKeyValue('%')).toEqual({}); expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined }); expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' }); }); it('should parse a string into key-value pairs with duplicates grouped in an array', function() { expect(parseKeyValue('')).toEqual({}); expect(parseKeyValue('duplicate=pair')).toEqual({duplicate: 'pair'}); expect(parseKeyValue('first=1&first=2')).toEqual({first: ['1','2']}); expect(parseKeyValue('escaped%20key=escaped%20value&&escaped%20key=escaped%20value2')). toEqual({'escaped key': ['escaped value','escaped value2']}); expect(parseKeyValue('flag1&key=value&flag1')). toEqual({flag1: [true,true], key: 'value'}); expect(parseKeyValue('flag1&flag1=value&flag1=value2&flag1')). toEqual({flag1: [true,'value','value2',true]}); }); }); describe('toKeyValue', function() { it('should serialize key-value pairs into string', function() { expect(toKeyValue({})).toEqual(''); expect(toKeyValue({simple: 'pair'})).toEqual('simple=pair'); expect(toKeyValue({first: '1', second: '2'})).toEqual('first=1&second=2'); expect(toKeyValue({'escaped key': 'escaped value'})). toEqual('escaped%20key=escaped%20value'); expect(toKeyValue({emptyKey: ''})).toEqual('emptyKey='); }); it('should serialize true values into flags', function() { expect(toKeyValue({flag1: true, key: 'value', flag2: true})).toEqual('flag1&key=value&flag2'); }); it('should serialize duplicates into duplicate param strings', function() { expect(toKeyValue({key: [323,'value',true]})).toEqual('key=323&key=value&key'); expect(toKeyValue({key: [323,'value',true, 1234]})). toEqual('key=323&key=value&key&key=1234'); }); }); describe('forEach', function() { it('should iterate over *own* object properties', function() { function MyObj() { this.bar = 'barVal'; this.baz = 'bazVal'; } MyObj.prototype.foo = 'fooVal'; var obj = new MyObj(), log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['bar:barVal', 'baz:bazVal']); }); it('should handle JQLite and jQuery objects like arrays', function() { var jqObject = jqLite("<p><span>s1</span><span>s2</span></p>").find("span"), log = []; forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:s1', '1:s2']); }); it('should handle NodeList objects like arrays', function() { var nodeList = jqLite("<p><span>a</span><span>b</span><span>c</span></p>")[0].childNodes, log = []; forEach(nodeList, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:a', '1:b', '2:c']); }); it('should handle HTMLCollection objects like arrays', function() { document.body.innerHTML = "<p>" + "<a name='x'>a</a>" + "<a name='y'>b</a>" + "<a name='x'>c</a>" + "</p>"; var htmlCollection = document.getElementsByName('x'), log = []; forEach(htmlCollection, function(value, key) { log.push(key + ':' + value.innerHTML)}); expect(log).toEqual(['0:a', '1:c']); }); it('should handle arguments objects like arrays', function() { var args, log = []; (function(){ args = arguments}('a', 'b', 'c')); forEach(args, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['0:a', '1:b', '2:c']); }); it('should handle objects with length property as objects', function() { var obj = { 'foo' : 'bar', 'length': 2 }, log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['foo:bar', 'length:2']); }); it('should handle objects of custom types with length property as objects', function() { function CustomType() { this.length = 2; this.foo = 'bar' } var obj = new CustomType(), log = []; forEach(obj, function(value, key) { log.push(key + ':' + value)}); expect(log).toEqual(['length:2', 'foo:bar']); }); }); describe('sortedKeys', function() { it('should collect keys from object', function() { expect(sortedKeys({c:0, b:0, a:0})).toEqual(['a', 'b', 'c']); }); }); describe('encodeUriSegment', function() { it('should correctly encode uri segment and not encode chars defined as pchar set in rfc3986', function() { //don't encode alphanum expect(encodeUriSegment('asdf1234asdf')). toEqual('asdf1234asdf'); //don't encode unreserved' expect(encodeUriSegment("-_.!~*'() -_.!~*'()")). toEqual("-_.!~*'()%20-_.!~*'()"); //don't encode the rest of pchar' expect(encodeUriSegment(':@&=+$, :@&=+$,')). toEqual(':@&=+$,%20:@&=+$,'); //encode '/', ';' and ' '' expect(encodeUriSegment('/; /;')). toEqual('%2F%3B%20%2F%3B'); }); }); describe('encodeUriQuery', function() { it('should correctly encode uri query and not encode chars defined as pchar set in rfc3986', function() { //don't encode alphanum expect(encodeUriQuery('asdf1234asdf')). toEqual('asdf1234asdf'); //don't encode unreserved expect(encodeUriQuery("-_.!~*'() -_.!~*'()")). toEqual("-_.!~*'()+-_.!~*'()"); //don't encode the rest of pchar expect(encodeUriQuery(':@$, :@$,')). toEqual(':@$,+:@$,'); //encode '&', ';', '=', '+', and '#' expect(encodeUriQuery('&;=+# &;=+#')). toEqual('%26%3B%3D%2B%23+%26%3B%3D%2B%23'); //encode ' ' as '+' expect(encodeUriQuery(' ')). toEqual('++'); //encode ' ' as '%20' when a flag is used expect(encodeUriQuery(' ', true)). toEqual('%20%20'); //do not encode `null` as '+' when flag is used expect(encodeUriQuery('null', true)). toEqual('null'); //do not encode `null` with no flag expect(encodeUriQuery('null')). toEqual('null'); }); }); describe('angularInit', function() { var bootstrapSpy; var element; beforeEach(function() { element = { getElementById: function (id) { return element.getElementById[id] || []; }, querySelectorAll: function(arg) { return element.querySelectorAll[arg] || []; }, getAttribute: function(name) { return element[name]; } }; bootstrapSpy = jasmine.createSpy('bootstrapSpy'); }); it('should do nothing when not found', function() { angularInit(element, bootstrapSpy); expect(bootstrapSpy).not.toHaveBeenCalled(); }); it('should look for ngApp directive as attr', function() { var appElement = jqLite('<div ng-app="ABC"></div>')[0]; element.querySelectorAll['[ng-app]'] = [appElement]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive in id', function() { var appElement = jqLite('<div id="ng-app" data-ng-app="ABC"></div>')[0]; jqLite(document.body).append(appElement); angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive in className', function() { var appElement = jqLite('<div data-ng-app="ABC"></div>')[0]; element.querySelectorAll['.ng\\:app'] = [appElement]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should look for ngApp directive using querySelectorAll', function() { var appElement = jqLite('<div x-ng-app="ABC"></div>')[0]; element.querySelectorAll['[ng\\:app]'] = [ appElement ]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should bootstrap using class name', function() { var appElement = jqLite('<div class="ng-app: ABC;"></div>')[0]; angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, ['ABC']); }); it('should bootstrap anonymously', function() { var appElement = jqLite('<div x-ng-app></div>')[0]; element.querySelectorAll['[x-ng-app]'] = [ appElement ]; angularInit(element, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should bootstrap anonymously using class only', function() { var appElement = jqLite('<div class="ng-app"></div>')[0]; angularInit(jqLite('<div></div>').append(appElement)[0], bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should bootstrap if the annotation is on the root element', function() { var appElement = jqLite('<div class="ng-app"></div>')[0]; angularInit(appElement, bootstrapSpy); expect(bootstrapSpy).toHaveBeenCalledOnceWith(appElement, []); }); it('should complain if app module cannot be found', function() { var appElement = jqLite('<div ng-app="doesntexist"></div>')[0]; expect(function() { angularInit(appElement, bootstrap); }).toThrowMatching( /\[\$injector:modulerr] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./ ); }); }); describe('angular service', function() { it('should override services', function() { module(function($provide){ $provide.value('fake', 'old'); $provide.value('fake', 'new'); }); inject(function(fake) { expect(fake).toEqual('new'); }); }); it('should inject dependencies specified by $inject and ignore function argument name', function() { expect(angular.injector([function($provide){ $provide.factory('svc1', function() { return 'svc1'; }); $provide.factory('svc2', ['svc1', function(s) { return 'svc2-' + s; }]); }]).get('svc2')).toEqual('svc2-svc1'); }); }); describe('isDate', function() { it('should return true for Date object', function() { expect(isDate(new Date())).toBe(true); }); it('should return false for non Date objects', function() { expect(isDate([])).toBe(false); expect(isDate('')).toBe(false); expect(isDate(23)).toBe(false); expect(isDate({})).toBe(false); }); }); describe('compile', function() { it('should link to existing node and create scope', inject(function($rootScope, $compile) { var template = angular.element('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope); $rootScope.$digest(); expect(template.text()).toEqual('hello world'); expect($rootScope.greeting).toEqual('hello world'); })); it('should link to existing node and given scope', inject(function($rootScope, $compile) { var template = angular.element('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope); $rootScope.$digest(); expect(template.text()).toEqual('hello world'); })); it('should link to new node and given scope', inject(function($rootScope, $compile) { var template = jqLite('<div>{{greeting = "hello world"}}</div>'); var compile = $compile(template); var templateClone = template.clone(); element = compile($rootScope, function(clone){ templateClone = clone; }); $rootScope.$digest(); expect(template.text()).toEqual('{{greeting = "hello world"}}'); expect(element.text()).toEqual('hello world'); expect(element).toEqual(templateClone); expect($rootScope.greeting).toEqual('hello world'); })); it('should link to cloned node and create scope', inject(function($rootScope, $compile) { var template = jqLite('<div>{{greeting = "hello world"}}</div>'); element = $compile(template)($rootScope, noop); $rootScope.$digest(); expect(template.text()).toEqual('{{greeting = "hello world"}}'); expect(element.text()).toEqual('hello world'); expect($rootScope.greeting).toEqual('hello world'); })); }); describe('nodeName_', function() { it('should correctly detect node name with "namespace" when xmlns is defined', function() { var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' + '<ngtest:foo ngtest:attr="bar"></ngtest:foo>' + '</div>')[0]; expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO'); expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar'); }); if (!msie || msie >= 9) { it('should correctly detect node name with "namespace" when xmlns is NOT defined', function() { var div = jqLite('<div xmlns:ngtest="http://angularjs.org/">' + '<ngtest:foo ngtest:attr="bar"></ng-test>' + '</div>')[0]; expect(nodeName_(div.childNodes[0])).toBe('NGTEST:FOO'); expect(div.childNodes[0].getAttribute('ngtest:attr')).toBe('bar'); }); } }); describe('nextUid()', function() { it('should return new id per call', function() { var seen = {}; var count = 100; while(count--) { var current = nextUid(); expect(current.match(/[\d\w]+/)).toBeTruthy(); expect(seen[current]).toBeFalsy(); seen[current] = true; } }); }); describe('version', function() { it('version should have full/major/minor/dot/codeName properties', function() { expect(version).toBeDefined(); expect(version.full).toBe('"NG_VERSION_FULL"'); expect(version.major).toBe("NG_VERSION_MAJOR"); expect(version.minor).toBe("NG_VERSION_MINOR"); expect(version.dot).toBe("NG_VERSION_DOT"); expect(version.codeName).toBe('"NG_VERSION_CODENAME"'); }); }); describe('bootstrap', function() { it('should bootstrap app', function(){ var element = jqLite('<div>{{1+2}}</div>'); var injector = angular.bootstrap(element); expect(injector).toBeDefined(); expect(element.injector()).toBe(injector); dealoc(element); }); it("should complain if app module can't be found", function() { var element = jqLite('<div>{{1+2}}</div>'); expect(function() { angular.bootstrap(element, ['doesntexist']); }).toThrowMatching( /\[\$injector:modulerr\] Failed to instantiate module doesntexist due to:\n.*\[\$injector:nomod\] Module 'doesntexist' is not available! You either misspelled the module name or forgot to load it\./); expect(element.html()).toBe('{{1+2}}'); dealoc(element); }); describe('deferred bootstrap', function() { var originalName = window.name, element; beforeEach(function() { window.name = ''; element = jqLite('<div>{{1+2}}</div>'); }); afterEach(function() { dealoc(element); window.name = originalName; }); it('should wait for extra modules', function() { window.name = 'NG_DEFER_BOOTSTRAP!'; angular.bootstrap(element); expect(element.html()).toBe('{{1+2}}'); angular.resumeBootstrap(); expect(element.html()).toBe('3'); expect(window.name).toEqual(''); }); it('should load extra modules', function() { element = jqLite('<div>{{1+2}}</div>'); window.name = 'NG_DEFER_BOOTSTRAP!'; var bootstrapping = jasmine.createSpy('bootstrapping'); angular.bootstrap(element, [bootstrapping]); expect(bootstrapping).not.toHaveBeenCalled(); expect(element.injector()).toBeUndefined(); angular.module('addedModule', []).value('foo', 'bar'); angular.resumeBootstrap(['addedModule']); expect(bootstrapping).toHaveBeenCalledOnce(); expect(element.injector().get('foo')).toEqual('bar'); }); it('should not defer bootstrap without window.name cue', function() { angular.bootstrap(element, []); angular.module('addedModule', []).value('foo', 'bar'); expect(function() { element.injector().get('foo'); }).toThrow('[$injector:unpr] Unknown provider: fooProvider <- foo'); expect(element.injector().get('$http')).toBeDefined(); }); it('should restore the original window.name after bootstrap', function() { window.name = 'NG_DEFER_BOOTSTRAP!my custom name'; angular.bootstrap(element); expect(element.html()).toBe('{{1+2}}'); angular.resumeBootstrap(); expect(element.html()).toBe('3'); expect(window.name).toEqual('my custom name'); }); }); }); describe('startingElementHtml', function(){ it('should show starting element tag only', function(){ expect(startingTag('<ng-abc x="2A"><div>text</div></ng-abc>')). toBe('<ng-abc x="2A">'); }); }); describe('startingTag', function() { it('should allow passing in Nodes instead of Elements', function() { var txtNode = document.createTextNode('some text'); expect(startingTag(txtNode)).toBe('some text'); }); }); describe('snake_case', function(){ it('should convert to snake_case', function() { expect(snake_case('ABC')).toEqual('a_b_c'); expect(snake_case('alanBobCharles')).toEqual('alan_bob_charles'); }); }); describe('fromJson', function() { it('should delegate to JSON.parse', function() { var spy = spyOn(JSON, 'parse').andCallThrough(); expect(fromJson('{}')).toEqual({}); expect(spy).toHaveBeenCalled(); }); }); describe('toJson', function() { it('should delegate to JSON.stringify', function() { var spy = spyOn(JSON, 'stringify').andCallThrough(); expect(toJson({})).toEqual('{}'); expect(spy).toHaveBeenCalled(); }); it('should format objects pretty', function() { expect(toJson({a: 1, b: 2}, true)). toBeOneOf('{\n "a": 1,\n "b": 2\n}', '{\n "a":1,\n "b":2\n}'); expect(toJson({a: {b: 2}}, true)). toBeOneOf('{\n "a": {\n "b": 2\n }\n}', '{\n "a":{\n "b":2\n }\n}'); }); it('should not serialize properties starting with $', function() { expect(toJson({$few: 'v', $$some:'value'}, false)).toEqual('{}'); }); it('should not serialize $window object', function() { expect(toJson(window)).toEqual('"$WINDOW"'); }); it('should not serialize $document object', function() { expect(toJson(document)).toEqual('"$DOCUMENT"'); }); it('should not serialize scope instances', inject(function($rootScope) { expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}'); })); }); });
rpanjwani/angular.js
test/AngularSpec.js
JavaScript
mit
30,438
/** * Logger configuration * * Configure the log level for your app, as well as the transport * (Underneath the covers, Sails uses Winston for logging, which * allows for some pretty neat custom transports/adapters for log messages) * * For more information on the Sails logger, check out: * http://sailsjs.org/#documentation */ module.exports = { // Valid `level` configs: // i.e. the minimum log level to capture with sails.log.*() // // 'error' : Display calls to `.error()` // 'warn' : Display calls from `.error()` to `.warn()` // 'debug' : Display calls from `.error()`, `.warn()` to `.debug()` // 'info' : Display calls from `.error()`, `.warn()`, `.debug()` to `.info()` // 'verbose': Display calls from `.error()`, `.warn()`, `.debug()`, `.info()` to `.verbose()` // log: { level: 'info' } };
emagnier/spinnaker
config/log.js
JavaScript
mit
866
var partialsTemp = [ "login", "profile" ]; exports.partialRender = function (req, res) { var pageIndex = req.params[0]; if (partialsTemp.indexOf("" + pageIndex) > -1) { res.render("partials/" + pageIndex, {}); } else { res.render("common/404", {}); } };
ManGroup/jsEasy
controllers/partials.js
JavaScript
mit
296
/* * The MIT License * * Copyright 2015 Eduardo Weiland. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ define(['knockout', 'grammar', 'productionrule', 'utils'], function(ko, Grammar, ProductionRule, utils) { 'use strict'; /** * Encontra todos os símbolos não-terminais inalcançáveis dentro de uma gramática. * * @param {Grammar} grammar Gramática para ser verificada. * @return {string[]} Lista de símbolos inalcançáveis. */ function findUnreachableSymbols(grammar) { var unreachable = [], nt = grammar.nonTerminalSymbols(), s = grammar.productionStartSymbol(); for (var i = 0, l = nt.length; i < l; ++i) { // Ignora símbolo de início de produção if (nt[i] === s) { continue; } var found = false; for (var j = 0, k = nt.length; j < k && !found; ++j) { if (i === j) { // Ignora produções do próprio símbolo continue; } var prods = grammar.getProductions(nt[j]); for (var x = 0, y = prods.length; x < y; ++x) { if (prods[x].indexOf(nt[i]) !== -1) { found = true; break; } } } if (!found) { unreachable.push(nt[i]); } } return unreachable; } function findSterileSymbols(grammar) { var steriles = [], rules = grammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var found = false, left = rules[i].leftSide(), right = rules[i].rightSide(); for (var j = 0, k = right.length; j < k && !found; ++j) { if (right[j].indexOf(left) === -1) { found = true; break; } } if (!found) { steriles.push(left); } } return steriles; } /** * Substitui símbolos não terminais no começo de todas as produções pelas suas produções. * * @param {Grammar} grammar Gramática para ser modificada. * @return {ProductionRule[]} Regras de produção modificadas. */ function replaceStartingSymbols(grammar) { var rules = grammar.productionRules(); var nt = grammar.nonTerminalSymbols(); var s = grammar.productionStartSymbol(); for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); if (left === s) { // Ignora produção inicial continue; } var prods = rules[i].rightSide(); // Não usa cache do length porque o array é modificado internamente for (var j = 0; j < prods.length; ++j) { if ( (prods[j][0] === left) || (nt.indexOf(prods[j][0]) === -1) ) { // Produção começa com o próprio símbolo não-terminal (recursivo) ou // não começa com nenhum símbolo não-terminal, ignora as substituições continue; } var otherProds = grammar.getProductions(prods[j][0]); var rest = prods[j].substr(1); for (var k = 0, m = otherProds.length; k < m; ++k) { otherProds[k] = otherProds[k] + rest; } // Remove a produção que começa com não-terminal e adiciona as novas produções no lugar prods.splice.apply(prods, [j--, 1].concat(otherProds)); } } return rules; } return { /** * Remove símbolos inúteis de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem os simbolos inúteis. */ removeUselessSymbols: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var sterile = findSterileSymbols(newGrammar), unreachable = findUnreachableSymbols(newGrammar), useless = utils.arrayUnion(sterile, unreachable), nt = newGrammar.nonTerminalSymbols(); // Remove os símbolos inalcançáveis... newGrammar.nonTerminalSymbols(utils.arrayRemove(nt, utils.arrayUnion(sterile, unreachable))); newGrammar.removeSymbolRules(useless); // .. e as produções em que eles aparecem var rules = newGrammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var right = rules[i].rightSide(); for (var j = 0, m = useless.length; j < m; ++j) { for (var k = 0; k < right.length; ++k) { if (right[k].indexOf(useless[j]) !== -1) { right.splice(k--, 1); } } } rules[i].rightSide(utils.arrayUnique(right)); } newGrammar.productionRules(rules); return newGrammar; }, /** * Remove produções vazias de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem as produções vazias. */ removeEmptyProductions: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var newStart; var rules = newGrammar.productionRules(); for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); var right = rules[i].rightSide(); var emptyIndex = right.indexOf(ProductionRule.EPSILON); if (emptyIndex === -1) { // Essa regra não possui produção vazia, ignora e testa a próxima continue; } if (left === newGrammar.productionStartSymbol()) { // Início de produção pode gerar sentença vazia, então trata o caso especial newStart = new ProductionRule(newGrammar, { leftSide: left + "'", rightSide: [left, ProductionRule.EPSILON] }); } // Encontra todas as outras regras que produzem esse símbolo e adiciona uma nova // produção sem esse símbolo for (var j = 0; j < l; ++j) { var rightOther = rules[j].rightSide(); for (var k = 0, m = rightOther.length; k < m; ++k) { if (rightOther[k].indexOf(left) !== -1) { rightOther.push(rightOther[k].replace(new RegExp(left, 'g'), '')); } } rules[j].rightSide(utils.arrayUnique(rightOther)); } right.splice(emptyIndex, 1); rules[i].rightSide(utils.arrayUnique(right)); } if (newStart) { rules.unshift(newStart); newGrammar.productionStartSymbol(newStart.leftSide()); newGrammar.nonTerminalSymbols([newStart.leftSide()].concat(newGrammar.nonTerminalSymbols())); } newGrammar.productionRules(rules); return newGrammar; }, /** * Fatora uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática fatorada. */ factor: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var rules = replaceStartingSymbols(newGrammar); var newRules = []; for (var i = 0; i < rules.length; ++i) { var left = rules[i].leftSide(); var right = rules[i].rightSide(); var newRight = []; var firstSymbolGrouped = {}; // Percorre todos as produções verificando quais precisam ser fatoradas for (var j = 0, l = right.length; j < l; ++j) { if (right[j].length === 1) { // Produções com apenas um símbolo são deixadas como estão newRight.push(right[j]); } else { // Agrupa todas as produções que começam com o mesmo símbolo terminal var firstSymbol = right[j][0]; if (!firstSymbolGrouped[firstSymbol]) { firstSymbolGrouped[firstSymbol] = []; } firstSymbolGrouped[firstSymbol].push(right[j].substr(1)); } } // Adiciona a produção na mesma ordem que estava antes, antes das novas produções serem adicionadas newRules.push(rules[i]); for (var j in firstSymbolGrouped) { if (firstSymbolGrouped[j].length > 1) { // Mais de uma produção começando com o mesmo símbolo terminal var newSymbol = newGrammar.createNonTerminalSymbol(left); newRight.push(j + newSymbol); newRules.push(new ProductionRule(newGrammar, { leftSide: newSymbol, rightSide: firstSymbolGrouped[j] })); } else { // Senão, é apenas uma produção (índice 0), mantém ela no mesmo lugar newRight.push(j + firstSymbolGrouped[j][0]); } } // Atualiza as produções para o símbolo existente rules[i].rightSide(utils.arrayUnique(newRight)); } newGrammar.productionRules(newRules); return newGrammar; }, /** * Remove recursão à esquerda de uma gramática. * * @param {Grammar} grammar Gramática de entrada. * @return {Grammar} Uma nova gramática sem recursão à esquerda. */ removeLeftRecursion: function(grammar) { var newGrammar = new Grammar(ko.toJS(grammar)); var rules = newGrammar.productionRules(); var newRules = []; for (var i = 0, l = rules.length; i < l; ++i) { var left = rules[i].leftSide(); var prods = rules[i].rightSide(); var recursives = []; // Adiciona a produção na mesma ordem que estava antes, antes das nova produção ser adicionada newRules.push(rules[i]); // Não usa cache do length porque o array é modificado internamente for (var j = 0; j < prods.length; ++j) { if (prods[j][0] === left && prods[j].length > 1) { // Encontrou produção recursiva, cria uma nova regra var newSymbol = newGrammar.createNonTerminalSymbol(left); recursives.push(newSymbol); newRules.push(new ProductionRule(newGrammar, { leftSide: newSymbol, rightSide: [prods[j].substr(1) + newSymbol, ProductionRule.EPSILON] })); // Remove essa produção prods.splice(j--, 1); } } var newProds = []; if (recursives.length === 0) { newProds = prods.slice(); } else { for (var j = 0; j < prods.length; ++j) { for (var k = 0; k < recursives.length; ++k) { newProds.push(prods[j] + recursives[k]); } } } rules[i].rightSide(newProds); } newGrammar.productionRules(newRules); return newGrammar; } }; });
eduardoweiland/transformacoes-glc
app/js/transformations.js
JavaScript
mit
13,493
/** * Uploader implementation - with the Connection object in ExtJS 4 * */ Ext.define('MyApp.ux.panel.upload.uploader.ExtJsUploader', { extend : 'MyApp.ux.panel.upload.uploader.AbstractXhrUploader', requires : [ 'MyApp.ux.panel.upload.data.Connection' ], config : { /** * @cfg {String} [method='PUT'] * * The HTTP method to be used. */ method : 'PUT', /** * @cfg {Ext.data.Connection} * * If set, this connection object will be used when uploading files. */ connection : null }, /** * @property * @private * * The connection object. */ conn : null, /** * @private * * Initializes and returns the connection object. * * @return {MyApp.ux.panel.upload.data.Connection} */ initConnection : function() { var conn, url = this.url; console.log('[ExtJsUploader initConnection params', this.params); if (this.connection instanceof Ext.data.Connection) { console.log('[ExtJsUploader] instanceof Connection'); conn = this.connection; } else { console.log('[ExtJsUploader] !! instanceof Connection'); if (this.params) { url = Ext.urlAppend(url, Ext.urlEncode(this.params)); } conn = Ext.create('MyApp.ux.panel.upload.data.Connection', { disableCaching : true, method : this.method, url : url, timeout : this.timeout, defaultHeaders : { 'Content-Type' : this.contentType, 'X-Requested-With' : 'XMLHttpRequest' } }); } return conn; }, /** * @protected */ initHeaders : function(item) { console.log('[ExtJsUploader] initHeaders', item); var headers = this.callParent(arguments); headers['Content-Type'] = item.getType(); return headers; }, /** * Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#uploadItem} * * @param {MyApp.ux.panel.upload.Item} * item */ uploadItem : function(item) { console.log('ExtJsUploader uploadItem', item); var file = item.getFileApiObject(); if (!file) { return; } item.setUploading(); // tony this.params = { folder : item.getRemoteFolder() }; this.conn = this.initConnection(); /* * Passing the File object directly as the "rawData" option. Specs: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-send()-method * http://dev.w3.org/2006/webapi/FileAPI/#blob */ console.log('ExtJsUploader conn', this.conn); this.conn.request({ scope : this, headers : this.initHeaders(item), rawData : file, timeout : MyApp.Const.JAVASCRIPT_MAX_NUMBER, // tony success : Ext.Function.bind(this.onUploadSuccess, this, [ item ], true), failure : Ext.Function.bind(this.onUploadFailure, this, [ item ], true), progress : Ext.Function.bind(this.onUploadProgress, this, [ item ], true) }); }, /** * Implements {@link MyApp.ux.panel.upload.uploader.AbstractUploader#abortUpload} */ abortUpload : function() { if (this.conn) { /* * If we don't suspend the events, the connection abortion will cause a failure event. */ this.suspendEvents(); console.log('abort conn', conn); this.conn.abort(); this.resumeEvents(); } } });
cwtuan/ExtJSTutorial-HiCloud
src/main/webapp/app/ux/panel/upload/uploader/ExtJsUploader.js
JavaScript
mit
3,140
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1H9.17C7.08 2 5.22 3.53 5.02 5.61 4.79 7.99 6.66 10 9 10zm11.65 7.65-2.79-2.79c-.32-.32-.86-.1-.86.35V17H6c-.55 0-1 .45-1 1s.45 1 1 1h11v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.19.2-.51.01-.7z" }), 'FormatTextdirectionLToRRounded'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/FormatTextdirectionLToRRounded.js
JavaScript
mit
769
var jazz = require("../lib/jazz"); var fs = require("fs"); var data = fs.readFileSync(__dirname + "/foreach_object.jazz", "utf8"); var template = jazz.compile(data); template.eval({"doc": { "title": "First", "content": "Some content" }}, function(data) { console.log(data); });
shinetech/jazz
examples/foreach_object.js
JavaScript
mit
288
/********************************************************************** map_GoogleV2.js $Comment: provides JavaScript for Google Api V2 calls $Source :map_GoogleV2.js,v $ $InitialAuthor: guenter richter $ $InitialDate: 2011/01/03 $ $Author: guenter richter $ $Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter Richter $ Copyright (c) Guenter Richter $Log:map_GoogleV2.js,v $ **********************************************************************/ /** * @fileoverview This is the interface to the Google maps API v2 * * @author Guenter Richter [email protected] * @version 0.9 */ /* ...................................................................* * global vars * * ...................................................................*/ /* ...................................................................* * Google directions * * ...................................................................*/ function __directions_handleErrors(){ var result = $("#directions-result")[0]; if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) result.innerHTML = ("Indirizzo sconosciuto. Forse è troppo nuovo o sbagliato.\n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) result.innerHTML = ("Richiesta non riuscita.\n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) result.innerHTML = ("Inserire indirizzi! \n Codice errore: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_BAD_KEY) result.innerHTML = ("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) result.innerHTML = ("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code); else result.innerHTML = ("Errore sconosciuto!"); } function _map_setDirections(map,fromAddress, toAddress, toHidden, locale) { var result = $("#directions-result")[0]; result.innerHTML = ""; gdir.loadFromWaypoints([fromAddress,toHidden], { "locale": locale, "preserveViewport":true }); } function _map_setDestinationWaypoint(marker){ if ( marker ){ var form = $("#directionsform")[0]; if ( form ){ form.to.value = marker.data.name; if ( marker.getLatLng ){ form.toHidden.value = marker.getLatLng(); } else if( marker.getVertex ){ form.toHidden.value = marker.getVertex(0); } } } } /** * Is called 'onload' to start creating the map */ function _map_loadMap(target){ var __map = null; // if google maps API v2 is loaded if ( GMap2 ){ // check if browser can handle Google Maps if ( !GBrowserIsCompatible()) { alert("sorry - your browser cannot handle Google Maps !"); return null; } __map = new GMap2(target); if ( __map ){ // configure user map interface __map.addControl(new GMapTypeControl()); // map.addControl(new GMenuMapTypeControl()); __map.addControl(new GLargeMapControl3D()); __map.addControl(new GScaleControl()); __map.addMapType(G_PHYSICAL_MAP); __map.addMapType(G_SATELLITE_3D_MAP); __map.enableDoubleClickZoom(); __map.enableScrollWheelZoom(); } } return __map; } /** * Is called to set up directions query */ function _map_addDirections(map,target){ if (map){ gdir = new GDirections(map,target); GEvent.addListener(gdir, "error", __directions_handleErrors); } } /** * Is called to set up traffic information layer */ function _map_addTrafficLayer(map,target){ /* tbd */ } /** * Is called to set event handler */ function _map_addEventListner(map,szEvent,callback,mapUp){ if (map){ GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) ); } } /** * Is called 'onunload' to clear objects */ function _map_unloadMap(map){ if (map){ GUnload(); } } // set map center and zoom // function _map_setMapExtension(map,bBox){ if (map){ var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) }; var mapZoom = map.getBoundsZoomLevel(new GLatLngBounds( new GLatLng(bBox[2],bBox[0]), new GLatLng(bBox[3],bBox[1]) ) ); map.setCenter(new GLatLng(mapCenter.lat, mapCenter.lon), mapZoom); } } // get map zoom // function _map_getZoom(map){ if (map){ return map.getZoom(); } return 0; } // get map center // function _map_getCenter(map){ if (map){ return map.getCenter(); } return null; } // set map zoom // function _map_setZoom(map,nZoom){ if (map){ map.setZoom(nZoom); } } // set map center // function _map_setCenter(map,center){ if (map){ map.setCenter(center); } } // set map center and zoom // function _map_setCenterAndZoom(map,center,nZoom){ if (map){ map.setCenter(center,nZoom); } } // create custom tooltip // function _map_createMyTooltip(marker, text, padding){ var tooltip = new Tooltip(marker, text, padding); marker.tooltip = tooltip; map.addOverlay(tooltip); } function _map_createMyTooltipListener(element, tooltip){ GEvent.addDomListener(element,'mouseover',GEvent.callback(tooltip, Tooltip.prototype.show)); GEvent.addDomListener(element,'mouseout',GEvent.callback(tooltip, Tooltip.prototype.hide)); } // ----------------------------- // EOF // -----------------------------
emergenzeHack/terremotocentro
maptune/js/maptune/maptune.GoogleV2.js
JavaScript
mit
5,620
import InputValidator from "../../common/js/InputValidator.js"; import ObjectUtilities from "../../common/js/ObjectUtilities.js"; import Action from "./Action.js"; import DefaultFilters from "./DefaultFilters.js"; import InitialState from "./InitialState.js"; var Reducer = {}; Reducer.root = function(state, action) { LOGGER.debug("root() type = " + action.type); if (typeof state === 'undefined') { return new InitialState(); } var newFilters, newFilteredTableRow; switch (action.type) { case Action.REMOVE_FILTERS: newFilteredTableRow = []; newFilteredTableRow = newFilteredTableRow.concat(state.tableRows); return Object.assign( {}, state, { filteredTableRows: newFilteredTableRow, }); case Action.SET_DEFAULT_FILTERS: newFilters = DefaultFilters.create(); return Object.assign( {}, state, { filters: newFilters, }); case Action.SET_FILTERS: LOGGER.debug("Reducer filters = "); Object.getOwnPropertyNames(action.filters).forEach(function(propertyName) { LOGGER.debug(propertyName + ": " + action.filters[propertyName]); }); newFilters = Object.assign( {}, state.filters); newFilters = ObjectUtilities.merge(newFilters, action.filters); newFilteredTableRow = Reducer.filterTableRow(state.tableRows, newFilters); Reducer.saveToLocalStorage(newFilters); return Object.assign( {}, state, { filters: newFilters, filteredTableRows: newFilteredTableRow, }); case Action.TOGGLE_FILTER_SHOWN: return Object.assign( {}, state, { isFilterShown: !state.isFilterShown, }); default: LOGGER.warn("Reducer.root: Unhandled action type: " + action.type); return state; } }; Reducer.filterTableRow = function(tableRows, filters) { InputValidator.validateNotNull("tableRows", tableRows); InputValidator.validateNotNull("filters", filters); var answer = []; tableRows.forEach(function(data) { if (Reducer.passes(data, filters)) { answer.push(data); } }); return answer; }; Reducer.passes = function(data, filters) { InputValidator.validateNotNull("data", data); InputValidator.validateNotNull("filters", filters); var answer = true; var propertyNames = Object.getOwnPropertyNames(filters); for (var i = 0; i < propertyNames.length; i++) { var propertyName = propertyNames[i]; var filter = filters[propertyName]; if (!filter.passes(data)) { answer = false; break; } } return answer; }; Reducer.saveToLocalStorage = function(filters) { InputValidator.validateNotNull("filters", filters); var filterObjects = []; Object.getOwnPropertyNames(filters).forEach(function(columnKey) { var filter = filters[columnKey]; filterObjects.push(filter.toObject()); }); localStorage.filters = JSON.stringify(filterObjects); }; export default Reducer;
jmthompson2015/lotr-card-game
src/accessory/player-card-table/Reducer.js
JavaScript
mit
3,186
ig.module( 'plusplus.config-user' ) .defines(function() { /** * User configuration of Impact++. * <span class="alert alert-info"><strong>Tip:</strong> it is recommended to modify this configuration file!</span> * @example * // in order to add your own custom configuration to Impact++ * // edit the file defining ig.CONFIG_USER, 'plusplus/config-user.js' * // ig.CONFIG_USER is never modified by Impact++ (it is strictly for your use) * // ig.CONFIG_USER is automatically merged over Impact++'s config * @static * @readonly * @memberof ig * @namespace ig.CONFIG_USER * @author Collin Hover - collinhover.com **/ ig.CONFIG_USER = { // no need to do force entity extended checks, we won't mess it up // because we know to have our entities extend ig.EntityExtended FORCE_ENTITY_EXTENDED: false, // auto sort AUTO_SORT_LAYERS: true, // fullscreen! GAME_WIDTH_PCT: 1, GAME_HEIGHT_PCT: 1, // dynamic scaling based on dimensions in view (resolution independence) GAME_WIDTH_VIEW: 352, GAME_HEIGHT_VIEW: 208, // clamped scaling is still dynamic, but within a range // so we can't get too big or too small SCALE_MIN: 1, SCALE_MAX: 4, // camera flexibility and smoothness CAMERA: { // keep the camera within the level // (whenever possible) //KEEP_INSIDE_LEVEL: true, KEEP_CENTERED: false, LERP: 0.025, // trap helps with motion sickness BOUNDS_TRAP_AS_PCT: true, BOUNDS_TRAP_PCT_MINX: -0.2, BOUNDS_TRAP_PCT_MINY: -0.3, BOUNDS_TRAP_PCT_MAXX: 0.2, BOUNDS_TRAP_PCT_MAXY: 0.3 }, // font and text settings FONT: { MAIN_NAME: "font_helloplusplus_white_16.png", ALT_NAME: "font_helloplusplus_white_8.png", CHAT_NAME: "font_helloplusplus_black_8.png", // we can have the font be scaled relative to system SCALE_OF_SYSTEM_SCALE: 0.5, // and force a min / max SCALE_MIN: 1, SCALE_MAX: 2 }, // text bubble settings TEXT_BUBBLE: { // match the visual style PIXEL_PERFECT: true }, UI: { // sometimes, we want to keep things at a static scale // for example, UI is a possible target SCALE: 3, IGNORE_SYSTEM_SCALE: true }, /* // to try dynamic clamped UI scaling // uncomment below and delete the UI settings above UI: { SCALE_MIN: 2, SCALE_MAX: 4 } */ // UI should persist across all levels UI_LAYER_CLEAR_ON_LOAD: false, CHARACTER: { // add some depth using offset SIZE_OFFSET_X: 8, SIZE_OFFSET_Y: 4 } }; });
collinhover/impactplusplus
examples/supercollider/lib/plusplus/config-user.js
JavaScript
mit
3,308
'use strict' const path = require('path') const hbs = require('express-hbs') module.exports = function (app, express) { hbs.registerHelper('asset', require('./helpers/asset')) app.engine('hbs', hbs.express4({ partialsDir: path.resolve('app/client/views/partials'), layoutsDir: path.resolve('app/client/views/layouts'), beautify: app.locals.isProduction })) app.set('view engine', 'hbs') app.set('views', path.resolve('app/client/views')) app.use(express.static(path.resolve('app/public'))) return app }
finkhq/fink-www
app/server/views/index.js
JavaScript
mit
535
// Polyfills if ( Number.EPSILON === undefined ) { Number.EPSILON = Math.pow( 2, - 52 ); } if ( Number.isInteger === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger = function ( value ) { return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value; }; } // if ( Math.sign === undefined ) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign Math.sign = function ( x ) { return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; }; } if ( 'name' in Function.prototype === false ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name Object.defineProperty( Function.prototype, 'name', { get: function () { return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ]; } } ); } if ( Object.assign === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign Object.assign = function ( target ) { 'use strict'; if ( target === undefined || target === null ) { throw new TypeError( 'Cannot convert undefined or null to object' ); } const output = Object( target ); for ( let index = 1; index < arguments.length; index ++ ) { const source = arguments[ index ]; if ( source !== undefined && source !== null ) { for ( const nextKey in source ) { if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { output[ nextKey ] = source[ nextKey ]; } } } } return output; }; }
fraguada/three.js
src/polyfills.js
JavaScript
mit
1,691
import supertest from 'supertest'; import { publicChannelName, privateChannelName } from './channel.js'; import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js'; import { username, email, adminUsername, adminPassword } from './user.js'; export const request = supertest('http://localhost:3000'); const prefix = '/api/v1/'; export function wait(cb, time) { return () => setTimeout(cb, time); } export const apiUsername = `api${ username }`; export const apiEmail = `api${ email }`; export const apiPublicChannelName = `api${ publicChannelName }`; export const apiPrivateChannelName = `api${ privateChannelName }`; export const apiRoleNameUsers = `api${ roleNameUsers }`; export const apiRoleNameSubscriptions = `api${ roleNameSubscriptions }`; export const apiRoleScopeUsers = `${ roleScopeUsers }`; export const apiRoleScopeSubscriptions = `${ roleScopeSubscriptions }`; export const apiRoleDescription = `api${ roleDescription }`; export const reservedWords = [ 'admin', 'administrator', 'system', 'user', ]; export const targetUser = {}; export const channel = {}; export const group = {}; export const message = {}; export const directMessage = {}; export const integration = {}; export const credentials = { 'X-Auth-Token': undefined, 'X-User-Id': undefined, }; export const login = { user: adminUsername, password: adminPassword, }; export function api(path) { return prefix + path; } export function methodCall(methodName) { return api(`method.call/${ methodName }`); } export function log(res) { console.log(res.req.path); console.log({ body: res.body, headers: res.headers, }); } export function getCredentials(done = function() {}) { request.post(api('login')) .send(login) .expect('Content-Type', 'application/json') .expect(200) .expect((res) => { credentials['X-Auth-Token'] = res.body.data.authToken; credentials['X-User-Id'] = res.body.data.userId; }) .end(done); }
VoiSmart/Rocket.Chat
tests/data/api-data.js
JavaScript
mit
1,993
'use strict'; // https://github.com/betsol/gulp-require-tasks // Require the module. const gulpRequireTasks = require('gulp-require-tasks'); const gulp = require('gulp'); const env = require('../index'); // Call it when necessary. gulpRequireTasks({ // Pass any options to it. Please see below. path: env.inConfigs('gulp', 'tasks')// This is default }); gulp.task('default', ['scripts:build', 'json-copy:build']);
ilivebox/microsb
node/configs/gulp/gulpfile.js
JavaScript
mit
421
/* @flow */ "use strict"; var _inherits = require("babel-runtime/helpers/inherits")["default"]; var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"]; var _getIterator = require("babel-runtime/core-js/get-iterator")["default"]; var _Object$assign = require("babel-runtime/core-js/object/assign")["default"]; var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"]; exports.__esModule = true; var _repeating = require("repeating"); var _repeating2 = _interopRequireDefault(_repeating); var _buffer = require("./buffer"); var _buffer2 = _interopRequireDefault(_buffer); var _node = require("./node"); var _node2 = _interopRequireDefault(_node); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var Printer = (function (_Buffer) { _inherits(Printer, _Buffer); function Printer() { _classCallCheck(this, Printer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Buffer.call.apply(_Buffer, [this].concat(args)); this.insideAux = false; this.printAuxAfterOnNextUserNode = false; } Printer.prototype.print = function print(node, parent) { var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (!node) return; if (parent && parent._compact) { node._compact = true; } var oldInAux = this.insideAux; this.insideAux = !node.loc; var oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } var printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name)); } if (node.loc) this.printAuxAfterComment(); this.printAuxBeforeComment(oldInAux); var needsParens = _node2["default"].needsParens(node, parent); if (needsParens) this.push("("); this.printLeadingComments(node, parent); this.catchUp(node); this._printNewline(true, node, parent, opts); if (opts.before) opts.before(); this.map.mark(node, "start"); this._print(node, parent); this.printTrailingComments(node, parent); if (needsParens) this.push(")"); // end this.map.mark(node, "end"); if (opts.after) opts.after(); this.format.concise = oldConcise; this.insideAux = oldInAux; this._printNewline(false, node, parent, opts); }; Printer.prototype.printAuxBeforeComment = function printAuxBeforeComment(wasInAux) { var comment = this.format.auxiliaryCommentBefore; if (!wasInAux && this.insideAux) { this.printAuxAfterOnNextUserNode = true; if (comment) this.printComment({ type: "CommentBlock", value: comment }); } }; Printer.prototype.printAuxAfterComment = function printAuxAfterComment() { if (this.printAuxAfterOnNextUserNode) { this.printAuxAfterOnNextUserNode = false; var comment = this.format.auxiliaryCommentAfter; if (comment) this.printComment({ type: "CommentBlock", value: comment }); } }; Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { var extra = node.extra; if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { return extra.raw; } }; Printer.prototype._print = function _print(node, parent) { var extra = this.getPossibleRaw(node); if (extra) { this.push(""); this._push(extra); } else { var printMethod = this[node.type]; printMethod.call(this, node, parent); } }; Printer.prototype.printJoin = function printJoin(nodes /*: ?Array*/, parent /*: Object*/) { // istanbul ignore next var _this = this; var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (!nodes || !nodes.length) return; var len = nodes.length; var node = undefined, i = undefined; if (opts.indent) this.indent(); var printOpts = { statement: opts.statement, addNewlines: opts.addNewlines, after: function after() { if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < len - 1) { _this.push(opts.separator); } } }; for (i = 0; i < nodes.length; i++) { node = nodes[i]; this.print(node, parent, printOpts); } if (opts.indent) this.dedent(); }; Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { var indent = !!node.leadingComments; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); }; Printer.prototype.printBlock = function printBlock(parent) { var node = parent.body; if (t.isEmptyStatement(node)) { this.semicolon(); } else { this.push(" "); this.print(node, parent); } }; Printer.prototype.generateComment = function generateComment(comment) { var val = comment.value; if (comment.type === "CommentLine") { val = "//" + val; } else { val = "/*" + val + "*/"; } return val; }; Printer.prototype.printTrailingComments = function printTrailingComments(node, parent) { this.printComments(this.getComments("trailingComments", node, parent)); }; Printer.prototype.printLeadingComments = function printLeadingComments(node, parent) { this.printComments(this.getComments("leadingComments", node, parent)); }; Printer.prototype.printInnerComments = function printInnerComments(node) { var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; if (!node.innerComments) return; if (indent) this.indent(); this.printComments(node.innerComments); if (indent) this.dedent(); }; Printer.prototype.printSequence = function printSequence(nodes, parent) { var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; opts.statement = true; return this.printJoin(nodes, parent, opts); }; Printer.prototype.printList = function printList(items, parent) { var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (opts.separator == null) { opts.separator = ","; if (!this.format.compact) opts.separator += " "; } return this.printJoin(items, parent, opts); }; Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { if (!opts.statement && !_node2["default"].isUserWhitespacable(node, parent)) { return; } var lines = 0; if (node.start != null && !node._ignoreUserWhitespace && this.tokens.length) { // user node if (leading) { lines = this.whitespace.getNewlinesBefore(node); } else { lines = this.whitespace.getNewlinesAfter(node); } } else { // generated node if (!leading) lines++; // always include at least a single line after if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; var needs = _node2["default"].needsWhitespaceAfter; if (leading) needs = _node2["default"].needsWhitespaceBefore; if (needs(node, parent)) lines++; // generated nodes can't add starting file whitespace if (!this.buf) lines = 0; } this.newline(lines); }; Printer.prototype.getComments = function getComments(key, node) { return node && node[key] || []; }; Printer.prototype.shouldPrintComment = function shouldPrintComment(comment) { if (this.format.shouldPrintComment) { return this.format.shouldPrintComment(comment.value); } else { if (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0) { return true; } else { return this.format.comments; } } }; Printer.prototype.printComment = function printComment(comment) { if (!this.shouldPrintComment(comment)) return; if (comment.ignore) return; comment.ignore = true; if (comment.start != null) { if (this.printedCommentStarts[comment.start]) return; this.printedCommentStarts[comment.start] = true; } this.catchUp(comment); // whitespace before this.newline(this.whitespace.getNewlinesBefore(comment)); var column = this.position.column; var val = this.generateComment(comment); if (column && !this.isLast(["\n", " ", "[", "{"])) { this._push(" "); column++; } // if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { var offset = comment.loc && comment.loc.start.column; if (offset) { var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } var indent = Math.max(this.indentSize(), column); val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent)); } if (column === 0) { val = this.getIndent() + val; } // force a newline for line comments when retainLines is set in case the next printed node // doesn't catch up if ((this.format.compact || this.format.retainLines) && comment.type === "CommentLine") { val += "\n"; } // this._push(val); // whitespace after this.newline(this.whitespace.getNewlinesAfter(comment)); }; Printer.prototype.printComments = function printComments(comments /*:: ?: Array<Object>*/) { if (!comments || !comments.length) return; for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var comment = _ref; this.printComment(comment); } }; return Printer; })(_buffer2["default"]); exports["default"] = Printer; var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; for (var _i2 = 0; _i2 < _arr.length; _i2++) { var generator = _arr[_i2]; _Object$assign(Printer.prototype, generator); } module.exports = exports["default"];
Shashank92/promises-demo
node_modules/gulp-babel/node_modules/babel-core/node_modules/babel-generator/lib/printer.js
JavaScript
mit
10,786
/** * Gulp tasks for wrapping Browserify modules. */ const browserify = require("browserify"); const gulp = require("gulp"); const sourcemaps = require("gulp-sourcemaps"); const uglify = require("gulp-uglify"); const path = require("path"); const through2 = require("through2"); const buffer = require("vinyl-buffer"); const source = require("vinyl-source-stream"); const asyncUtil = require("../../util/async-util"); const clientPackages = require("../../util/client-packages"); const display = require("../../util/display"); const uc = require("../../util/unite-config"); gulp.task("build-bundle-app", async () => { const uniteConfig = await uc.getUniteConfig(); const buildConfiguration = uc.getBuildConfiguration(uniteConfig, false); if (buildConfiguration.bundle) { display.info("Running", "Browserify for App"); const bApp = browserify({ debug: buildConfiguration.sourcemaps, entries: `./${path.join(uniteConfig.dirs.www.dist, "entryPoint.js")}` }); const vendorPackages = await clientPackages.getBundleVendorPackages(uniteConfig); let hasStyleLoader = false; Object.keys(vendorPackages).forEach((key) => { bApp.exclude(key); const idx = key.indexOf("systemjs"); if (idx >= 0 && !hasStyleLoader) { hasStyleLoader = key === "systemjs-plugin-css"; } }); bApp.transform("envify", { NODE_ENV: buildConfiguration.minify ? "production" : "development", global: true }); bApp.transform("browserify-css", { autoInject: hasStyleLoader }); bApp.transform("stringify", { appliesTo: { includeExtensions: uniteConfig.viewExtensions.map(ext => `.${ext}`) } }); bApp.transform("babelify", { global: true, presets: ["@babel/preset-env"] }); return asyncUtil.stream(bApp.bundle().on("error", (err) => { display.error(err); }) .pipe(source("app-bundle.js")) .pipe(buffer()) .pipe(buildConfiguration.minify ? uglify() .on("error", (err) => { display.error(err.toString()); }) : through2.obj()) .pipe(buildConfiguration.sourcemaps ? sourcemaps.init({ loadMaps: true }) : through2.obj()) .pipe(buildConfiguration.sourcemaps ? sourcemaps.mapSources((sourcePath) => sourcePath.replace(/dist\//, "./")) : through2.obj()) .pipe(buildConfiguration.sourcemaps ? sourcemaps.write({ includeContent: true }) : through2.obj()) .pipe(gulp.dest(uniteConfig.dirs.www.dist))); } }); // Generated by UniteJS
unitejs/engine
assets/gulp/dist/tasks/bundler/browserify/build-bundle-app.js
JavaScript
mit
2,848
// Commom Plugins (function($) { 'use strict'; // Scroll to Top Button. if (typeof theme.PluginScrollToTop !== 'undefined') { theme.PluginScrollToTop.initialize(); } // Tooltips if ($.isFunction($.fn['tooltip'])) { $('[data-tooltip]:not(.manual), [data-plugin-tooltip]:not(.manual)').tooltip(); } // Popover if ($.isFunction($.fn['popover'])) { $(function() { $('[data-plugin-popover]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.popover(opts); }); }); } // Validations if (typeof theme.PluginValidation !== 'undefined') { theme.PluginValidation.initialize(); } // Match Height if ($.isFunction($.fn['matchHeight'])) { $('.match-height').matchHeight(); // Featured Boxes $('.featured-boxes .featured-box').matchHeight(); // Featured Box Full $('.featured-box-full').matchHeight(); } }).apply(this, [jQuery]); // Animate (function($) { 'use strict'; if ($.isFunction($.fn['themePluginAnimate'])) { $(function() { $('[data-plugin-animate], [data-appear-animation]').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginAnimate(opts); }); }); } }).apply(this, [jQuery]); // Carousel (function($) { 'use strict'; if ($.isFunction($.fn['themePluginCarousel'])) { $(function() { $('[data-plugin-carousel]:not(.manual), .owl-carousel:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginCarousel(opts); }); }); } }).apply(this, [jQuery]); // Chart.Circular (function($) { 'use strict'; if ($.isFunction($.fn['themePluginChartCircular'])) { $(function() { $('[data-plugin-chart-circular]:not(.manual), .circular-bar-chart:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginChartCircular(opts); }); }); } }).apply(this, [jQuery]); // Counter (function($) { 'use strict'; if ($.isFunction($.fn['themePluginCounter'])) { $(function() { $('[data-plugin-counter]:not(.manual), .counters [data-to]').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginCounter(opts); }); }); } }).apply(this, [jQuery]); // Lazy Load (function($) { 'use strict'; if ($.isFunction($.fn['themePluginLazyLoad'])) { $(function() { $('[data-plugin-lazyload]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginLazyLoad(opts); }); }); } }).apply(this, [jQuery]); // Lightbox (function($) { 'use strict'; if ($.isFunction($.fn['themePluginLightbox'])) { $(function() { $('[data-plugin-lightbox]:not(.manual), .lightbox:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginLightbox(opts); }); }); } }).apply(this, [jQuery]); // Masonry (function($) { 'use strict'; if ($.isFunction($.fn['themePluginMasonry'])) { $(function() { $('[data-plugin-masonry]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginMasonry(opts); }); }); } }).apply(this, [jQuery]); // Match Height (function($) { 'use strict'; if ($.isFunction($.fn['themePluginMatchHeight'])) { $(function() { $('[data-plugin-match-height]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginMatchHeight(opts); }); }); } }).apply(this, [jQuery]); // Parallax (function($) { 'use strict'; if ($.isFunction($.fn['themePluginParallax'])) { $(function() { $('[data-plugin-parallax]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginParallax(opts); }); }); } }).apply(this, [jQuery]); // Progress Bar (function($) { 'use strict'; if ($.isFunction($.fn['themePluginProgressBar'])) { $(function() { $('[data-plugin-progress-bar]:not(.manual), [data-appear-progress-animation]').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginProgressBar(opts); }); }); } }).apply(this, [jQuery]); // Revolution Slider (function($) { 'use strict'; if ($.isFunction($.fn['themePluginRevolutionSlider'])) { $(function() { $('[data-plugin-revolution-slider]:not(.manual), .slider-container .slider:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginRevolutionSlider(opts); }); }); } }).apply(this, [jQuery]); // Sort (function($) { 'use strict'; if ($.isFunction($.fn['themePluginSort'])) { $(function() { $('[data-plugin-sort]:not(.manual), .sort-source:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginSort(opts); }); }); } }).apply(this, [jQuery]); // Sticky (function($) { 'use strict'; if ($.isFunction($.fn['themePluginSticky'])) { $(function() { $('[data-plugin-sticky]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginSticky(opts); }); }); } }).apply(this, [jQuery]); // Toggle (function($) { 'use strict'; if ($.isFunction($.fn['themePluginToggle'])) { $(function() { $('[data-plugin-toggle]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginToggle(opts); }); }); } }).apply(this, [jQuery]); // Tweets (function($) { 'use strict'; if ($.isFunction($.fn['themePluginTweets'])) { $(function() { $('[data-plugin-tweets]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginTweets(opts); }); }); } }).apply(this, [jQuery]); // Video Background (function($) { 'use strict'; if ($.isFunction($.fn['themePluginVideoBackground'])) { $(function() { $('[data-plugin-video-background]:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginVideoBackground(opts); }); }); } }).apply(this, [jQuery]); // Word Rotate (function($) { 'use strict'; if ($.isFunction($.fn['themePluginWordRotate'])) { $(function() { $('[data-plugin-word-rotate]:not(.manual), .word-rotate:not(.manual)').each(function() { var $this = $(this), opts; var pluginOptions = $this.data('plugin-options'); if (pluginOptions) opts = pluginOptions; $this.themePluginWordRotate(opts); }); }); } }).apply(this, [jQuery]); // Commom Partials (function($) { 'use strict'; // Sticky Header if (typeof theme.StickyHeader !== 'undefined') { theme.StickyHeader.initialize(); } // Nav Menu if (typeof theme.Nav !== 'undefined') { theme.Nav.initialize(); } // Search if (typeof theme.Search !== 'undefined') { theme.Search.initialize(); } // Newsletter if (typeof theme.Newsletter !== 'undefined') { theme.Newsletter.initialize(); } // Account if (typeof theme.Account !== 'undefined') { theme.Account.initialize(); } }).apply(this, [jQuery]);
SupasitC/Pricetrolley
src/javascripts/theme.init.js
JavaScript
mit
8,635
'use strict'; const BitcrusherProps = { bits: { type: 'number', bounds: [1, 16], defaultValue: 4 }, normfreq: { type: 'number', bounds: [0, 1], step: 0.1, defaultValue: 0.1 }, bufferSize: { type: 'number', bounds: [256, 16384], defaultValue: 4096 }, bypass: { type: 'number', bounds: [0, 1], defaultValue: 0 } }; export default BitcrusherProps;
civa86/web-synth
lib/src/properties/BitcrusherProps.js
JavaScript
mit
483
define({ "_widgetLabel": "Tra cứu Địa lý", "description": "Duyệt đến hoặc Kéo <a href='./widgets/GeoLookup/data/sample.csv' tooltip='Download an example sheet' target='_blank'> trang tính </a> tại đây để mô phỏng và thêm các dữ liệu bản đồ vào trang tính đó.", "selectCSV": "Chọn một CSV", "loadingCSV": "Đang tải CSV", "savingCSV": "Xuất CSV", "clearResults": "Xóa", "downloadResults": "Tải xuống", "plotOnly": "Chỉ các Điểm Vẽ bản đồ", "plottingRows": "Hàng vẽ bản đồ", "projectionChoice": "CSV trong", "projectionLat": "Vĩ độ/Kinh độ", "projectionMap": "Phép chiếu Bản đồ", "messages": "Thông báo", "error": { "fetchingCSV": "Đã xảy ra lỗi khi truy xuất các mục từ kho lưu trữ CSV: ${0}", "fileIssue": "Không xử lý được tệp.", "notCSVFile": "Hiện chỉ hỗ trợ các tệp được ngăn cách bằng dấu phẩy (.csv).", "invalidCoord": "Trường vị trí không hợp lệ. Vui lòng kiểm tra tệp .csv.", "tooManyRecords": "Rất tiếc, hiện không được có quá ${0} bản ghi.", "CSVNoRecords": "Tệp không chứa bất kỳ hồ sơ nào.", "CSVEmptyFile": "Không có nội dung trong tệp." }, "results": { "csvLoaded": "Đã tải ${0} bản ghi từ tệp CSV", "recordsPlotted": "Đã định vị ${0}/${1} bản ghi trên bản đồ", "recordsEnriched": "Đã xử lý ${0}/${1}, đã bổ sung ${2} so với ${3}", "recordsError": "${0} bản ghi có lỗi", "recordsErrorList": "Hàng ${0} có sự cố", "label": "Kết quả CSV" } });
cmccullough2/cmv-wab-widgets
wab/2.3/widgets/GeoLookup/nls/vi/strings.js
JavaScript
mit
1,683
var chai = require("chai") var should = chai.should(); chai.use(require("chai-http")); var request = chai.request(require("./server")) var db = require("mongojs")("test") describe("CRUD Handler", () => { before(done => { done() }) beforeEach(done => { db.dropDatabase(done); }) after(done => { db.dropDatabase(done) }) it("should save a document", (done) => { var data = { name: "test" } request.post("/test") .send(data) .end((err, res) => { should.not.exist(err) res.should.have.status(201); res.body.should.be.an("object") res.body.should.have.keys(['error', 'data']) res.body.error.should.not.be.ok; res.body.data.name.should.be.eql("test") res.body.data.should.have.property("_id"); done() }) }) it("should list all documents", (done ) => { var list = [ {name: 'test21'}, {name: 'test22'} ] db.collection("test").insert(list, (err, result) => { request.get("/test") .end((err, res) => { should.not.exist(err) res.should.have.status(200) res.body.should.be.an("object") res.body.should.have.keys(['error', 'data']) res.body.error.should.not.be.ok; res.body.data.should.have.keys(['count', 'list']) res.body.data.count.should.be.eql(2) res.body.data.list.length.should.be.eql(2) done() }) }) }) it("should get a single document", done => { var doc = { name: 'test3' } db.collection('test').insert(doc, (err, result ) => { request.get("/test/" + result._id) .end((err, res) => { should.not.exist(err) res.should.have.status(200) res.body.should.be.an("object") res.body.should.have.keys(['error', 'data']) res.body.error.should.not.be.ok; res.body.data.should.have.keys(['_id', 'name']) res.body.data.name.should.be.eql(doc.name); done() }) }) }) it("should update an existing document", done => { var doc = { name: 'test3' } db.collection('test').insert(doc, (err, result ) => { result.name = "test3_updated"; request.put("/test/" + result._id) .send(result) .end((err, res) => { should.not.exist(err) res.should.have.status(202) res.body.should.be.an("object") res.body.should.have.keys(['error', 'data']) res.body.error.should.not.be.ok; db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => { should.not.exist(err) result1.name.should.be.eql(result.name); done() }) }) }) }) it("should remove a document", done => { var doc = { name: 'test3' } db.collection('test').insert(doc, (err, result ) => { request.delete("/test/" + result._id) .end((err, res) => { should.not.exist(err) res.should.have.status(202) res.body.should.be.an("object") res.body.should.have.keys(['error', 'data']) res.body.error.should.not.be.ok; db.collection('test').findOne({_id: db.ObjectId(result._id)}, (err, result1) => { should.not.exist(err) should.not.exist(result1); done() }) }) }) }) })
AkashBabu/server-helper
test/crudHandler/test.js
JavaScript
mit
4,155
"use strict"; devdiv.directive('devDiv', [function () { return { restrict: 'E', link: function (scope, iElement, iAttrs) { iElement.addClass("dev-div"); iElement.addClass("row"); } }; }]) devdiv.controller('NameCtrl', function ($scope, $watch) { });
abdurrahmanekr/devdiv
src/directive/devdiv.js
JavaScript
mit
267
(function() { 'use strict'; /* Filters */ var md5 = function (s) { if (!s) return ''; function L(k, d) { return (k << d) | (k >>> (32 - d)); } function K(G, k) { var I, d, F, H, x; F = (G & 2147483648); H = (k & 2147483648); I = (G & 1073741824); d = (k & 1073741824); x = (G & 1073741823) + (k & 1073741823); if (I & d) { return (x ^ 2147483648 ^ F ^ H); } if (I | d) { if (x & 1073741824) { return (x ^ 3221225472 ^ F ^ H); } else { return (x ^ 1073741824 ^ F ^ H); } } else { return (x ^ F ^ H); } } function r(d, F, k) { return (d & F) | ((~d) & k); } function q(d, F, k) { return (d & k) | (F & (~k)); } function p(d, F, k) { return (d ^ F ^ k); } function n(d, F, k) { return (F ^ (d | (~k))); } function u(G, F, aa, Z, k, H, I) { G = K(G, K(K(r(F, aa, Z), k), I)); return K(L(G, H), F); } function f(G, F, aa, Z, k, H, I) { G = K(G, K(K(q(F, aa, Z), k), I)); return K(L(G, H), F); } function D(G, F, aa, Z, k, H, I) { G = K(G, K(K(p(F, aa, Z), k), I)); return K(L(G, H), F); } function t(G, F, aa, Z, k, H, I) { G = K(G, K(K(n(F, aa, Z), k), I)); return K(L(G, H), F); } function e(G) { var Z; var F = G.length; var x = F + 8; var k = (x - (x % 64)) / 64; var I = (k + 1) * 16; var aa = Array(I - 1); var d = 0; var H = 0; while (H < F) { Z = (H - (H % 4)) / 4; d = (H % 4) * 8; aa[Z] = (aa[Z] | (G.charCodeAt(H) << d)); H++; } Z = (H - (H % 4)) / 4; d = (H % 4) * 8; aa[Z] = aa[Z] | (128 << d); aa[I - 2] = F << 3; aa[I - 1] = F >>> 29; return aa; } function B(x) { var k = "", F = "", G, d; for (d = 0; d <= 3; d++) { G = (x >>> (d * 8)) & 255; F = "0" + G.toString(16); k = k + F.substr(F.length - 2, 2); } return k; } function J(k) { k = k.replace(/rn/g, "n"); var d = ""; for (var F = 0; F < k.length; F++) { var x = k.charCodeAt(F); if (x < 128) { d += String.fromCharCode(x); } else { if ((x > 127) && (x < 2048)) { d += String.fromCharCode((x >> 6) | 192); d += String.fromCharCode((x & 63) | 128); } else { d += String.fromCharCode((x >> 12) | 224); d += String.fromCharCode(((x >> 6) & 63) | 128); d += String.fromCharCode((x & 63) | 128); } } } return d; } var C = []; var P, h, E, v, g, Y, X, W, V; var S = 7, Q = 12, N = 17, M = 22; var A = 5, z = 9, y = 14, w = 20; var o = 4, m = 11, l = 16, j = 23; var U = 6, T = 10, R = 15, O = 21; s = J(s); C = e(s); Y = 1732584193; X = 4023233417; W = 2562383102; V = 271733878; for (P = 0; P < C.length; P += 16) { h = Y; E = X; v = W; g = V; Y = u(Y, X, W, V, C[P + 0], S, 3614090360); V = u(V, Y, X, W, C[P + 1], Q, 3905402710); W = u(W, V, Y, X, C[P + 2], N, 606105819); X = u(X, W, V, Y, C[P + 3], M, 3250441966); Y = u(Y, X, W, V, C[P + 4], S, 4118548399); V = u(V, Y, X, W, C[P + 5], Q, 1200080426); W = u(W, V, Y, X, C[P + 6], N, 2821735955); X = u(X, W, V, Y, C[P + 7], M, 4249261313); Y = u(Y, X, W, V, C[P + 8], S, 1770035416); V = u(V, Y, X, W, C[P + 9], Q, 2336552879); W = u(W, V, Y, X, C[P + 10], N, 4294925233); X = u(X, W, V, Y, C[P + 11], M, 2304563134); Y = u(Y, X, W, V, C[P + 12], S, 1804603682); V = u(V, Y, X, W, C[P + 13], Q, 4254626195); W = u(W, V, Y, X, C[P + 14], N, 2792965006); X = u(X, W, V, Y, C[P + 15], M, 1236535329); Y = f(Y, X, W, V, C[P + 1], A, 4129170786); V = f(V, Y, X, W, C[P + 6], z, 3225465664); W = f(W, V, Y, X, C[P + 11], y, 643717713); X = f(X, W, V, Y, C[P + 0], w, 3921069994); Y = f(Y, X, W, V, C[P + 5], A, 3593408605); V = f(V, Y, X, W, C[P + 10], z, 38016083); W = f(W, V, Y, X, C[P + 15], y, 3634488961); X = f(X, W, V, Y, C[P + 4], w, 3889429448); Y = f(Y, X, W, V, C[P + 9], A, 568446438); V = f(V, Y, X, W, C[P + 14], z, 3275163606); W = f(W, V, Y, X, C[P + 3], y, 4107603335); X = f(X, W, V, Y, C[P + 8], w, 1163531501); Y = f(Y, X, W, V, C[P + 13], A, 2850285829); V = f(V, Y, X, W, C[P + 2], z, 4243563512); W = f(W, V, Y, X, C[P + 7], y, 1735328473); X = f(X, W, V, Y, C[P + 12], w, 2368359562); Y = D(Y, X, W, V, C[P + 5], o, 4294588738); V = D(V, Y, X, W, C[P + 8], m, 2272392833); W = D(W, V, Y, X, C[P + 11], l, 1839030562); X = D(X, W, V, Y, C[P + 14], j, 4259657740); Y = D(Y, X, W, V, C[P + 1], o, 2763975236); V = D(V, Y, X, W, C[P + 4], m, 1272893353); W = D(W, V, Y, X, C[P + 7], l, 4139469664); X = D(X, W, V, Y, C[P + 10], j, 3200236656); Y = D(Y, X, W, V, C[P + 13], o, 681279174); V = D(V, Y, X, W, C[P + 0], m, 3936430074); W = D(W, V, Y, X, C[P + 3], l, 3572445317); X = D(X, W, V, Y, C[P + 6], j, 76029189); Y = D(Y, X, W, V, C[P + 9], o, 3654602809); V = D(V, Y, X, W, C[P + 12], m, 3873151461); W = D(W, V, Y, X, C[P + 15], l, 530742520); X = D(X, W, V, Y, C[P + 2], j, 3299628645); Y = t(Y, X, W, V, C[P + 0], U, 4096336452); V = t(V, Y, X, W, C[P + 7], T, 1126891415); W = t(W, V, Y, X, C[P + 14], R, 2878612391); X = t(X, W, V, Y, C[P + 5], O, 4237533241); Y = t(Y, X, W, V, C[P + 12], U, 1700485571); V = t(V, Y, X, W, C[P + 3], T, 2399980690); W = t(W, V, Y, X, C[P + 10], R, 4293915773); X = t(X, W, V, Y, C[P + 1], O, 2240044497); Y = t(Y, X, W, V, C[P + 8], U, 1873313359); V = t(V, Y, X, W, C[P + 15], T, 4264355552); W = t(W, V, Y, X, C[P + 6], R, 2734768916); X = t(X, W, V, Y, C[P + 13], O, 1309151649); Y = t(Y, X, W, V, C[P + 4], U, 4149444226); V = t(V, Y, X, W, C[P + 11], T, 3174756917); W = t(W, V, Y, X, C[P + 2], R, 718787259); X = t(X, W, V, Y, C[P + 9], O, 3951481745); Y = K(Y, h); X = K(X, E); W = K(W, v); V = K(V, g); } var i = B(Y) + B(X) + B(W) + B(V); return i.toLowerCase(); }; angular.module('talis.filters.md5', []). filter("md5", function(){ return md5; }); }).call(this);
chariotsolutions/reactive-quizzo-code-sample
public/moderator/bower_components/md5-angular-filter/js/md5.filter.js
JavaScript
mit
6,722
/*globals describe, before, beforeEach, afterEach, it */ /*jshint expr:true*/ var testUtils = require('../../utils'), should = require('should'), // Stuff we are testing dbAPI = require('../../../server/api/db'), ModelTag = require('../../../server/models/tag'), ModelPost = require('../../../server/models/post'); describe('DB API', function () { // Keep the DB clean before(testUtils.teardown); afterEach(testUtils.teardown); beforeEach(testUtils.setup('users:roles', 'posts', 'perms:db', 'perms:init')); should.exist(dbAPI); it('delete all content (owner)', function (done) { return dbAPI.deleteAllContent(testUtils.context.owner).then(function (result) { should.exist(result.db); result.db.should.be.instanceof(Array); result.db.should.be.empty; }).then(function () { return ModelTag.Tag.findAll(testUtils.context.owner).then(function (results) { should.exist(results); results.length.should.equal(0); }); }).then(function () { return ModelPost.Post.findAll(testUtils.context.owner).then(function (results) { should.exist(results); results.length.should.equal(0); done(); }); }).catch(done); }); it('delete all content (admin)', function (done) { return dbAPI.deleteAllContent(testUtils.context.admin).then(function (result) { should.exist(result.db); result.db.should.be.instanceof(Array); result.db.should.be.empty; }).then(function () { return ModelTag.Tag.findAll(testUtils.context.admin).then(function (results) { should.exist(results); results.length.should.equal(0); }); }).then(function () { return ModelPost.Post.findAll(testUtils.context.admin).then(function (results) { should.exist(results); results.length.should.equal(0); done(); }); }).catch(done); }); it('delete all content is denied (editor & author)', function (done) { return dbAPI.deleteAllContent(testUtils.context.editor).then(function () { done(new Error('Delete all content is not denied for editor.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.deleteAllContent(testUtils.context.author); }).then(function () { done(new Error('Delete all content is not denied for author.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.deleteAllContent(); }).then(function () { done(new Error('Delete all content is not denied without authentication.')); }).catch(function (error) { error.type.should.eql('NoPermissionError'); done(); }).catch(done); }); it('export content is denied (editor & author)', function (done) { return dbAPI.exportContent(testUtils.context.editor).then(function () { done(new Error('Export content is not denied for editor.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.exportContent(testUtils.context.author); }).then(function () { done(new Error('Export content is not denied for author.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.exportContent(); }).then(function () { done(new Error('Export content is not denied without authentication.')); }).catch(function (error) { error.type.should.eql('NoPermissionError'); done(); }).catch(done); }); it('import content is denied (editor & author)', function (done) { return dbAPI.importContent(testUtils.context.editor).then(function () { done(new Error('Import content is not denied for editor.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.importContent(testUtils.context.author); }).then(function () { done(new Error('Import content is not denied for author.')); }, function (error) { error.type.should.eql('NoPermissionError'); return dbAPI.importContent(); }).then(function () { done(new Error('Import content is not denied without authentication.')); }).catch(function (error) { error.type.should.eql('NoPermissionError'); done(); }).catch(done); }); });
dbanda/dalitsobanda.com
ghostgithub/core/test/integration/api/api_db_spec.js
JavaScript
mit
4,779
(function (subdivision) { 'use strict'; var count = 0; var builders; var defaultBuilder; function buildInternal(type, addin, options, meta) { var builder = subdivision.getBuilder(type); if (builder.preBuildTarget) { addin = buildInternal(builder.preBuildTarget, addin, options, meta); } return builder.build(addin, options, meta); } function buildInternalAsync(type, addin, options, meta) { try { var builder = subdivision.getBuilder(type); var promise = Promise.resolve(addin); if (builder.preBuildTarget) { promise = buildInternalAsync(builder.preBuildTarget, addin, options, meta); } return promise.then(function (addin) { return builder.build(addin, options, meta); }); } catch (ex) { return Promise.reject(ex); } } subdivision.Builder = function (options) { var builder = subdivision.Addin.$internalConstructor('builder', count++, options); if (!_.isFunction(builder.build)) { throw new Error('Builder options must contain the "build" function ' + JSON.stringify(options)); } builder.target = builder.target === undefined ? '' : builder.target; return builder; }; subdivision.systemPaths.builders = subdivision.registry.joinPath(subdivision.systemPaths.prefix, 'builders'); subdivision.defaultManifest.paths.push({ path: subdivision.systemPaths.builders, addins: [ { ///Update docs if this changes id: 'subdivision.defaultBuilder', type: 'subdivision.builder', target: null, order: subdivision.registry.$defaultOrder, build: function (addin) { return _.cloneDeep(addin); } } ] }); /** * Adds a new builder created from the options to the list of known builders. * If a builder that builds the given type already exists then * the new builder is added based on the forced option. If force is truthy it is added anyway otherwise does nothing * Returns true if a builder was added and false otherwise * */ subdivision.addBuilder = function (options, force) { var builder = new subdivision.Builder(options); if (builder.target === null) { if (!defaultBuilder || force) { defaultBuilder = builder; return true; } else { return false; } } if (!builders.hasOwnProperty(builder.target) || force) { builders[builder.target] = builder; return true; } else { return false; } }; /** * Gets a builder for the appropriate type, if no builder of the given type is found returns the default builder (builder with type === null) * @param type */ subdivision.getBuilder = function (type) { if (type === null && defaultBuilder) { return defaultBuilder; } else { if (builders.hasOwnProperty(type)) { return builders[type]; } if (defaultBuilder) { return defaultBuilder; } } throw new Error('No builder of type "' + type + '" was defined and no default builder was registered'); }; /** * Returns all the addins in the path after applying the appropriate builder on each * @param path - The path to build * @param options - Custom options to be passed to the addin builder * @param searchCriteria - The search criteria for the underscore filter function * @param skipSort - If truthy the topological sort is skipped * @returns {Array} = The built addins */ subdivision.build = function (path, options, searchCriteria, skipSort) { var addins = subdivision.getAddins(path, searchCriteria, skipSort); if (addins.length === 0) { return addins; } return _.map(addins, function (addin) { return buildInternal(addin.type, addin, options, { path: path }); }); }; /** * Returns all the addins in the path after applying the appropriate builder on each * @param path - The path to build * @param options - Custom options to be passed to the addin builder * @param searchCriteria - The search criteria for the underscore filter function * @param skipSort - If truthy the topological sort is skipped * @returns {Array} = A promise that resolves with an array of the built addins */ subdivision.build.async = function (path, options, searchCriteria, skipSort) { var addins = subdivision.getAddins(path, searchCriteria, skipSort); if (addins.length === 0) { return Promise.resolve(addins); } var promises = _.map(addins, function (addin) { //TODO: Optimization that tries to guess the builder from previous builder return buildInternalAsync(addin.type, addin, options, { path: path }); }); return Promise.all(promises); }; /** * Builds a single addin based on its type * @param addin The addin to build * @param options The options to pass to the builder */ subdivision.buildAddin = function (addin, options) { return buildInternal(addin.type, addin, options, { path: null }); }; /** * The async version of buildAddin * @param addin The addin to build * @param options The options to pass to the builder * @returns A promise that when resolved returns the built addin */ subdivision.buildAddin.async = function (addin, options) { return buildInternalAsync(addin.type, addin, options, { path: null }); }; /** * Builds a tree out of the given path. Each addin will have child elements at path+addin.id added * to its items property (default $items). * @param path * @param options - Custom options to be passed to the addin builder */ subdivision.buildTree = function (path, options) { var addins = subdivision.getAddins(path); if (addins.length === 0) { return addins; } return _.map(addins, function (addin) { //TODO: Optimization that tries to guess the builder from previous builder var result = buildInternal(addin.type, addin, options, { path: path }); var itemsProperty = addin.itemsProperty || '$items'; result[itemsProperty] = subdivision.buildTree(subdivision.registry.joinPath(path, addin.id), options); return result; }); }; /** * Regenerates all the builders from the system builders path */ subdivision.$generateBuilders = function () { subdivision.$clearBuilders(); var addins = subdivision.getAddins(subdivision.systemPaths.builders, {target: null}); if (addins.length > 0) { defaultBuilder = new subdivision.Builder(addins[0]); } addins = subdivision.getAddins(subdivision.systemPaths.builders); _.forEach(addins, function (addin) { subdivision.addBuilder(addin); }); }; subdivision.$clearBuilders = function () { builders = {}; defaultBuilder = null; }; subdivision.$clearBuilders(); Object.defineProperty(subdivision, 'builders', { enumerable: true, configurable: false, get: function () { return _.clone(builders); } }); })(subdivision);
BorisKozo/extensibility.js
app/lib/builder.js
JavaScript
mit
7,868
/*! * reveal.js * http://lab.hakim.se/reveal-js * MIT licensed * * Copyright (C) 2016 Hakim El Hattab, http://hakim.se */ (function( root, factory ) { if( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define( function() { root.Reveal = factory(); return root.Reveal; } ); } else if( typeof exports === 'object' ) { // Node. Does not work with strict CommonJS. module.exports = factory(); } else { // Browser globals. root.Reveal = factory(); } }( this, function() { 'use strict'; var Reveal; // The reveal.js version var VERSION = '3.3.0'; var SLIDES_SELECTOR = '.slides section', HORIZONTAL_SLIDES_SELECTOR = '.slides>section', VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section', HOME_SLIDE_SELECTOR = '.slides>section:first-of-type', UA = navigator.userAgent, // Configuration defaults, can be overridden at initialization time config = { // The "normal" size of the presentation, aspect ratio will be preserved // when the presentation is scaled to fit different resolutions width: 960, height: 700, // Factor of the display size that should remain empty around the content margin: 0.1, // Bounds for smallest/largest possible scale to apply to content minScale: 0.2, maxScale: 1.5, // Display controls in the bottom right corner controls: true, // Display a presentation progress bar progress: true, // Display the page number of the current slide slideNumber: false, // Push each slide change to the browser history history: false, // Enable keyboard shortcuts for navigation keyboard: true, // Optional function that blocks keyboard events when retuning false keyboardCondition: null, // Enable the slide overview mode overview: true, // Vertical centering of slides center: true, // Enables touch navigation on devices with touch input touch: true, // Loop the presentation loop: false, // Change the presentation direction to be RTL rtl: false, // Randomizes the order of slides each time the presentation loads shuffle: false, // Turns fragments on and off globally fragments: true, // Flags if the presentation is running in an embedded mode, // i.e. contained within a limited portion of the screen embedded: false, // Flags if we should show a help overlay when the questionmark // key is pressed help: true, // Flags if it should be possible to pause the presentation (blackout) pause: true, // Flags if speaker notes should be visible to all viewers showNotes: false, // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides autoSlide: 0, // Stop auto-sliding after user input autoSlideStoppable: true, // Use this method for navigation when auto-sliding (defaults to navigateNext) autoSlideMethod: null, // Enable slide navigation via mouse wheel mouseWheel: false, // Apply a 3D roll to links on hover rollingLinks: false, // Hides the address bar on mobile devices hideAddressBar: true, // Opens links in an iframe preview overlay previewLinks: false, // Exposes the reveal.js API through window.postMessage postMessage: true, // Dispatches all reveal.js events to the parent window through postMessage postMessageEvents: false, // Focuses body when page changes visiblity to ensure keyboard shortcuts work focusBodyOnPageVisibilityChange: true, // Transition style transition: 'fade', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom // Parallax background image parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg" // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px" // Amount of pixels to move the parallax background per slide step parallaxBackgroundHorizontal: null, parallaxBackgroundVertical: null, // Number of slides away from the current that are visible viewDistance: 3, // Script dependencies to load dependencies: [] }, // Flags if reveal.js is loaded (has dispatched the 'ready' event) loaded = false, // Flags if the overview mode is currently active overview = false, // Holds the dimensions of our overview slides, including margins overviewSlideWidth = null, overviewSlideHeight = null, // The horizontal and vertical index of the currently active slide indexh, indexv, // The previous and current slide HTML elements previousSlide, currentSlide, previousBackground, // Slides may hold a data-state attribute which we pick up and apply // as a class to the body. This list contains the combined state of // all current slides. state = [], // The current scale of the presentation (see width/height config) scale = 1, // CSS transform that is currently applied to the slides container, // split into two groups slidesTransform = { layout: '', overview: '' }, // Cached references to DOM elements dom = {}, // Features supported by the browser, see #checkCapabilities() features = {}, // Client is a mobile device, see #checkCapabilities() isMobileDevice, // Client is a desktop Chrome, see #checkCapabilities() isChrome, // Throttles mouse wheel navigation lastMouseWheelStep = 0, // Delays updates to the URL due to a Chrome thumbnailer bug writeURLTimeout = 0, // Flags if the interaction event listeners are bound eventsAreBound = false, // The current auto-slide duration autoSlide = 0, // Auto slide properties autoSlidePlayer, autoSlideTimeout = 0, autoSlideStartTime = -1, autoSlidePaused = false, // Holds information about the currently ongoing touch input touch = { startX: 0, startY: 0, startSpan: 0, startCount: 0, captured: false, threshold: 40 }, // Holds information about the keyboard shortcuts keyboardShortcuts = { 'N , SPACE': 'Next slide', 'P': 'Previous slide', '&#8592; , H': 'Navigate left', '&#8594; , L': 'Navigate right', '&#8593; , K': 'Navigate up', '&#8595; , J': 'Navigate down', 'Home': 'First slide', 'End': 'Last slide', 'B , .': 'Pause', 'F': 'Fullscreen', 'ESC, O': 'Slide overview' }; /** * Starts up the presentation if the client is capable. */ function initialize( options ) { checkCapabilities(); if( !features.transforms2d && !features.transforms3d ) { document.body.setAttribute( 'class', 'no-transforms' ); // Since JS won't be running any further, we load all lazy // loading elements upfront var images = toArray( document.getElementsByTagName( 'img' ) ), iframes = toArray( document.getElementsByTagName( 'iframe' ) ); var lazyLoadable = images.concat( iframes ); for( var i = 0, len = lazyLoadable.length; i < len; i++ ) { var element = lazyLoadable[i]; if( element.getAttribute( 'data-src' ) ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } } // If the browser doesn't support core features we won't be // using JavaScript to control the presentation return; } // Cache references to key DOM elements dom.wrapper = document.querySelector( '.reveal' ); dom.slides = document.querySelector( '.reveal .slides' ); // Force a layout when the whole page, incl fonts, has loaded window.addEventListener( 'load', layout, false ); var query = Reveal.getQueryHash(); // Do not accept new dependencies via query config to avoid // the potential of malicious script injection if( typeof query['dependencies'] !== 'undefined' ) delete query['dependencies']; // Copy options over to our config object extend( config, options ); extend( config, query ); // Hide the address bar in mobile browsers hideAddressBar(); // Loads the dependencies and continues to #start() once done load(); } /** * Inspect the client to see what it's capable of, this * should only happens once per runtime. */ function checkCapabilities() { isMobileDevice = /(iphone|ipod|ipad|android)/gi.test( UA ); isChrome = /chrome/i.test( UA ) && !/edge/i.test( UA ); var testElement = document.createElement( 'div' ); features.transforms3d = 'WebkitPerspective' in testElement.style || 'MozPerspective' in testElement.style || 'msPerspective' in testElement.style || 'OPerspective' in testElement.style || 'perspective' in testElement.style; features.transforms2d = 'WebkitTransform' in testElement.style || 'MozTransform' in testElement.style || 'msTransform' in testElement.style || 'OTransform' in testElement.style || 'transform' in testElement.style; features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function'; features.canvas = !!document.createElement( 'canvas' ).getContext; // Transitions in the overview are disabled in desktop and // Safari due to lag features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test( UA ); // Flags if we should use zoom instead of transform to scale // up slides. Zoom produces crisper results but has a lot of // xbrowser quirks so we only use it in whitelsited browsers. features.zoom = 'zoom' in testElement.style && !isMobileDevice && ( isChrome || /Version\/[\d\.]+.*Safari/.test( UA ) ); } /** * Loads the dependencies of reveal.js. Dependencies are * defined via the configuration option 'dependencies' * and will be loaded prior to starting/binding reveal.js. * Some dependencies may have an 'async' flag, if so they * will load after reveal.js has been started up. */ function load() { var scripts = [], scriptsAsync = [], scriptsToPreload = 0; // Called once synchronous scripts finish loading function proceed() { if( scriptsAsync.length ) { // Load asynchronous scripts head.js.apply( null, scriptsAsync ); } start(); } function loadScript( s ) { head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], function() { // Extension may contain callback functions if( typeof s.callback === 'function' ) { s.callback.apply( this ); } if( --scriptsToPreload === 0 ) { proceed(); } }); } for( var i = 0, len = config.dependencies.length; i < len; i++ ) { var s = config.dependencies[i]; // Load if there's no condition or the condition is truthy if( !s.condition || s.condition() ) { if( s.async ) { scriptsAsync.push( s.src ); } else { scripts.push( s.src ); } loadScript( s ); } } if( scripts.length ) { scriptsToPreload = scripts.length; // Load synchronous scripts head.js.apply( null, scripts ); } else { proceed(); } } /** * Starts up reveal.js by binding input events and navigating * to the current URL deeplink if there is one. */ function start() { // Make sure we've got all the DOM elements we need setupDOM(); // Listen to messages posted to this window setupPostMessage(); // Prevent the slides from being scrolled out of view setupScrollPrevention(); // Resets all vertical slides so that only the first is visible resetVerticalSlides(); // Updates the presentation to match the current configuration values configure(); // Read the initial hash readURL(); // Update all backgrounds updateBackground( true ); // Notify listeners that the presentation is ready but use a 1ms // timeout to ensure it's not fired synchronously after #initialize() setTimeout( function() { // Enable transitions now that we're loaded dom.slides.classList.remove( 'no-transition' ); loaded = true; dispatchEvent( 'ready', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); }, 1 ); // Special setup and config is required when printing to PDF if( isPrintingPDF() ) { removeEventListeners(); // The document needs to have loaded for the PDF layout // measurements to be accurate if( document.readyState === 'complete' ) { setupPDF(); } else { window.addEventListener( 'load', setupPDF ); } } } /** * Finds and stores references to DOM elements which are * required by the presentation. If a required element is * not found, it is created. */ function setupDOM() { // Prevent transitions while we're loading dom.slides.classList.add( 'no-transition' ); // Background element dom.background = createSingletonNode( dom.wrapper, 'div', 'backgrounds', null ); // Progress bar dom.progress = createSingletonNode( dom.wrapper, 'div', 'progress', '<span></span>' ); dom.progressbar = dom.progress.querySelector( 'span' ); // Arrow controls createSingletonNode( dom.wrapper, 'aside', 'controls', '<button class="navigate-left" aria-label="previous slide"></button>' + '<button class="navigate-right" aria-label="next slide"></button>' + '<button class="navigate-up" aria-label="above slide"></button>' + '<button class="navigate-down" aria-label="below slide"></button>' ); // Slide number dom.slideNumber = createSingletonNode( dom.wrapper, 'div', 'slide-number', '' ); // Element containing notes that are visible to the audience dom.speakerNotes = createSingletonNode( dom.wrapper, 'div', 'speaker-notes', null ); dom.speakerNotes.setAttribute( 'data-prevent-swipe', '' ); // Overlay graphic which is displayed during the paused mode createSingletonNode( dom.wrapper, 'div', 'pause-overlay', null ); // Cache references to elements dom.controls = document.querySelector( '.reveal .controls' ); dom.theme = document.querySelector( '#theme' ); dom.wrapper.setAttribute( 'role', 'application' ); // There can be multiple instances of controls throughout the page dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) ); dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) ); dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) ); dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) ); dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) ); dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) ); dom.statusDiv = createStatusDiv(); } /** * Creates a hidden div with role aria-live to announce the * current slide content. Hide the div off-screen to make it * available only to Assistive Technologies. */ function createStatusDiv() { var statusDiv = document.getElementById( 'aria-status-div' ); if( !statusDiv ) { statusDiv = document.createElement( 'div' ); statusDiv.style.position = 'absolute'; statusDiv.style.height = '1px'; statusDiv.style.width = '1px'; statusDiv.style.overflow ='hidden'; statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )'; statusDiv.setAttribute( 'id', 'aria-status-div' ); statusDiv.setAttribute( 'aria-live', 'polite' ); statusDiv.setAttribute( 'aria-atomic','true' ); dom.wrapper.appendChild( statusDiv ); } return statusDiv; } /** * Configures the presentation for printing to a static * PDF. */ function setupPDF() { var slideSize = getComputedSlideSize( window.innerWidth, window.innerHeight ); // Dimensions of the PDF pages var pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ), pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) ); // Dimensions of slides within the pages var slideWidth = slideSize.width, slideHeight = slideSize.height; // Let the browser know what page size we want to print injectStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0;}' ); // Limit the size of certain elements to the dimensions of the slide injectStyleSheet( '.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' ); document.body.classList.add( 'print-pdf' ); document.body.style.width = pageWidth + 'px'; document.body.style.height = pageHeight + 'px'; // Add each slide's index as attributes on itself, we need these // indices to generate slide numbers below toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); } ); } } ); // Slide and slide background layout toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) === false ) { // Center the slide inside of the page, giving the slide some margin var left = ( pageWidth - slideWidth ) / 2, top = ( pageHeight - slideHeight ) / 2; var contentHeight = getAbsoluteHeight( slide ); var numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 ); // Center slides vertically if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) { top = Math.max( ( pageHeight - contentHeight ) / 2, 0 ); } // Position the slide inside of the page slide.style.left = left + 'px'; slide.style.top = top + 'px'; slide.style.width = slideWidth + 'px'; // TODO Backgrounds need to be multiplied when the slide // stretches over multiple pages var background = slide.querySelector( '.slide-background' ); if( background ) { background.style.width = pageWidth + 'px'; background.style.height = ( pageHeight * numberOfPages ) + 'px'; background.style.top = -top + 'px'; background.style.left = -left + 'px'; } // Inject notes if `showNotes` is enabled if( config.showNotes ) { var notes = getSlideNotes( slide ); if( notes ) { var notesSpacing = 8; var notesElement = document.createElement( 'div' ); notesElement.classList.add( 'speaker-notes' ); notesElement.classList.add( 'speaker-notes-pdf' ); notesElement.innerHTML = notes; notesElement.style.left = ( notesSpacing - left ) + 'px'; notesElement.style.bottom = ( notesSpacing - top ) + 'px'; notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px'; slide.appendChild( notesElement ); } } // Inject slide numbers if `slideNumbers` are enabled if( config.slideNumber ) { var slideNumberH = parseInt( slide.getAttribute( 'data-index-h' ), 10 ) + 1, slideNumberV = parseInt( slide.getAttribute( 'data-index-v' ), 10 ) + 1; var numberElement = document.createElement( 'div' ); numberElement.classList.add( 'slide-number' ); numberElement.classList.add( 'slide-number-pdf' ); numberElement.innerHTML = formatSlideNumber( slideNumberH, '.', slideNumberV ); background.appendChild( numberElement ); } } } ); // Show all fragments toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' .fragment' ) ).forEach( function( fragment ) { fragment.classList.add( 'visible' ); } ); } /** * This is an unfortunate necessity. Some actions – such as * an input field being focused in an iframe or using the * keyboard to expand text selection beyond the bounds of * a slide – can trigger our content to be pushed out of view. * This scrolling can not be prevented by hiding overflow in * CSS (we already do) so we have to resort to repeatedly * checking if the slides have been offset :( */ function setupScrollPrevention() { setInterval( function() { if( dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0 ) { dom.wrapper.scrollTop = 0; dom.wrapper.scrollLeft = 0; } }, 1000 ); } /** * Creates an HTML element and returns a reference to it. * If the element already exists the existing instance will * be returned. */ function createSingletonNode( container, tagname, classname, innerHTML ) { // Find all nodes matching the description var nodes = container.querySelectorAll( '.' + classname ); // Check all matches to find one which is a direct child of // the specified container for( var i = 0; i < nodes.length; i++ ) { var testNode = nodes[i]; if( testNode.parentNode === container ) { return testNode; } } // If no node was found, create it now var node = document.createElement( tagname ); node.classList.add( classname ); if( typeof innerHTML === 'string' ) { node.innerHTML = innerHTML; } container.appendChild( node ); return node; } /** * Creates the slide background elements and appends them * to the background container. One element is created per * slide no matter if the given slide has visible background. */ function createBackgrounds() { var printMode = isPrintingPDF(); // Clear prior backgrounds dom.background.innerHTML = ''; dom.background.classList.add( 'no-transition' ); // Iterate over all horizontal slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( slideh ) { var backgroundStack; if( printMode ) { backgroundStack = createBackground( slideh, slideh ); } else { backgroundStack = createBackground( slideh, dom.background ); } // Iterate over all vertical slides toArray( slideh.querySelectorAll( 'section' ) ).forEach( function( slidev ) { if( printMode ) { createBackground( slidev, slidev ); } else { createBackground( slidev, backgroundStack ); } backgroundStack.classList.add( 'stack' ); } ); } ); // Add parallax background if specified if( config.parallaxBackgroundImage ) { dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")'; dom.background.style.backgroundSize = config.parallaxBackgroundSize; // Make sure the below properties are set on the element - these properties are // needed for proper transitions to be set on the element via CSS. To remove // annoying background slide-in effect when the presentation starts, apply // these properties after short time delay setTimeout( function() { dom.wrapper.classList.add( 'has-parallax-background' ); }, 1 ); } else { dom.background.style.backgroundImage = ''; dom.wrapper.classList.remove( 'has-parallax-background' ); } } /** * Creates a background for the given slide. * * @param {HTMLElement} slide * @param {HTMLElement} container The element that the background * should be appended to */ function createBackground( slide, container ) { var data = { background: slide.getAttribute( 'data-background' ), backgroundSize: slide.getAttribute( 'data-background-size' ), backgroundImage: slide.getAttribute( 'data-background-image' ), backgroundVideo: slide.getAttribute( 'data-background-video' ), backgroundIframe: slide.getAttribute( 'data-background-iframe' ), backgroundColor: slide.getAttribute( 'data-background-color' ), backgroundRepeat: slide.getAttribute( 'data-background-repeat' ), backgroundPosition: slide.getAttribute( 'data-background-position' ), backgroundTransition: slide.getAttribute( 'data-background-transition' ) }; var element = document.createElement( 'div' ); // Carry over custom classes from the slide to the background element.className = 'slide-background ' + slide.className.replace( /present|past|future/, '' ); if( data.background ) { // Auto-wrap image urls in url(...) if( /^(http|file|\/\/)/gi.test( data.background ) || /\.(svg|png|jpg|jpeg|gif|bmp)$/gi.test( data.background ) ) { slide.setAttribute( 'data-background-image', data.background ); } else { element.style.background = data.background; } } // Create a hash for this combination of background settings. // This is used to determine when two slide backgrounds are // the same. if( data.background || data.backgroundColor || data.backgroundImage || data.backgroundVideo || data.backgroundIframe ) { element.setAttribute( 'data-background-hash', data.background + data.backgroundSize + data.backgroundImage + data.backgroundVideo + data.backgroundIframe + data.backgroundColor + data.backgroundRepeat + data.backgroundPosition + data.backgroundTransition ); } // Additional and optional background properties if( data.backgroundSize ) element.style.backgroundSize = data.backgroundSize; if( data.backgroundColor ) element.style.backgroundColor = data.backgroundColor; if( data.backgroundRepeat ) element.style.backgroundRepeat = data.backgroundRepeat; if( data.backgroundPosition ) element.style.backgroundPosition = data.backgroundPosition; if( data.backgroundTransition ) element.setAttribute( 'data-background-transition', data.backgroundTransition ); container.appendChild( element ); // If backgrounds are being recreated, clear old classes slide.classList.remove( 'has-dark-background' ); slide.classList.remove( 'has-light-background' ); // If this slide has a background color, add a class that // signals if it is light or dark. If the slide has no background // color, no class will be set var computedBackgroundColor = window.getComputedStyle( element ).backgroundColor; if( computedBackgroundColor ) { var rgb = colorToRgb( computedBackgroundColor ); // Ignore fully transparent backgrounds. Some browsers return // rgba(0,0,0,0) when reading the computed background color of // an element with no background if( rgb && rgb.a !== 0 ) { if( colorBrightness( computedBackgroundColor ) < 128 ) { slide.classList.add( 'has-dark-background' ); } else { slide.classList.add( 'has-light-background' ); } } } return element; } /** * Registers a listener to postMessage events, this makes it * possible to call all reveal.js API methods from another * window. For example: * * revealWindow.postMessage( JSON.stringify({ * method: 'slide', * args: [ 2 ] * }), '*' ); */ function setupPostMessage() { if( config.postMessage ) { window.addEventListener( 'message', function ( event ) { var data = event.data; // Make sure we're dealing with JSON if( typeof data === 'string' && data.charAt( 0 ) === '{' && data.charAt( data.length - 1 ) === '}' ) { data = JSON.parse( data ); // Check if the requested method can be found if( data.method && typeof Reveal[data.method] === 'function' ) { Reveal[data.method].apply( Reveal, data.args ); } } }, false ); } } /** * Applies the configuration settings from the config * object. May be called multiple times. */ function configure( options ) { var numberOfSlides = dom.wrapper.querySelectorAll( SLIDES_SELECTOR ).length; dom.wrapper.classList.remove( config.transition ); // New config options may be passed when this method // is invoked through the API after initialization if( typeof options === 'object' ) extend( config, options ); // Force linear transition based on browser capabilities if( features.transforms3d === false ) config.transition = 'linear'; dom.wrapper.classList.add( config.transition ); dom.wrapper.setAttribute( 'data-transition-speed', config.transitionSpeed ); dom.wrapper.setAttribute( 'data-background-transition', config.backgroundTransition ); dom.controls.style.display = config.controls ? 'block' : 'none'; dom.progress.style.display = config.progress ? 'block' : 'none'; dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none'; if( config.shuffle ) { shuffle(); } if( config.rtl ) { dom.wrapper.classList.add( 'rtl' ); } else { dom.wrapper.classList.remove( 'rtl' ); } if( config.center ) { dom.wrapper.classList.add( 'center' ); } else { dom.wrapper.classList.remove( 'center' ); } // Exit the paused mode if it was configured off if( config.pause === false ) { resume(); } if( config.showNotes ) { dom.speakerNotes.classList.add( 'visible' ); } else { dom.speakerNotes.classList.remove( 'visible' ); } if( config.mouseWheel ) { document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.addEventListener( 'mousewheel', onDocumentMouseScroll, false ); } else { document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false ); } // Rolling 3D links if( config.rollingLinks ) { enableRollingLinks(); } else { disableRollingLinks(); } // Iframe link previews if( config.previewLinks ) { enablePreviewLinks(); } else { disablePreviewLinks(); enablePreviewLinks( '[data-preview-link]' ); } // Remove existing auto-slide controls if( autoSlidePlayer ) { autoSlidePlayer.destroy(); autoSlidePlayer = null; } // Generate auto-slide controls if needed if( numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame ) { autoSlidePlayer = new Playback( dom.wrapper, function() { return Math.min( Math.max( ( Date.now() - autoSlideStartTime ) / autoSlide, 0 ), 1 ); } ); autoSlidePlayer.on( 'click', onAutoSlidePlayerClick ); autoSlidePaused = false; } // When fragments are turned off they should be visible if( config.fragments === false ) { toArray( dom.slides.querySelectorAll( '.fragment' ) ).forEach( function( element ) { element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); } ); } sync(); } /** * Binds all event listeners. */ function addEventListeners() { eventsAreBound = true; window.addEventListener( 'hashchange', onWindowHashChange, false ); window.addEventListener( 'resize', onWindowResize, false ); if( config.touch ) { dom.wrapper.addEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.addEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.addEventListener( 'touchend', onTouchEnd, false ); // Support pointer-style touch interaction as well if( window.navigator.pointerEnabled ) { // IE 11 uses un-prefixed version of pointer events dom.wrapper.addEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.addEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.addEventListener( 'pointerup', onPointerUp, false ); } else if( window.navigator.msPointerEnabled ) { // IE 10 uses prefixed version of pointer events dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false ); } } if( config.keyboard ) { document.addEventListener( 'keydown', onDocumentKeyDown, false ); document.addEventListener( 'keypress', onDocumentKeyPress, false ); } if( config.progress && dom.progress ) { dom.progress.addEventListener( 'click', onProgressClicked, false ); } if( config.focusBodyOnPageVisibilityChange ) { var visibilityChange; if( 'hidden' in document ) { visibilityChange = 'visibilitychange'; } else if( 'msHidden' in document ) { visibilityChange = 'msvisibilitychange'; } else if( 'webkitHidden' in document ) { visibilityChange = 'webkitvisibilitychange'; } if( visibilityChange ) { document.addEventListener( visibilityChange, onPageVisibilityChange, false ); } } // Listen to both touch and click events, in case the device // supports both var pointerEvents = [ 'touchstart', 'click' ]; // Only support touch for Android, fixes double navigations in // stock browser if( UA.match( /android/gi ) ) { pointerEvents = [ 'touchstart' ]; } pointerEvents.forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Unbinds all event listeners. */ function removeEventListeners() { eventsAreBound = false; document.removeEventListener( 'keydown', onDocumentKeyDown, false ); document.removeEventListener( 'keypress', onDocumentKeyPress, false ); window.removeEventListener( 'hashchange', onWindowHashChange, false ); window.removeEventListener( 'resize', onWindowResize, false ); dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false ); dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false ); dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false ); // IE11 if( window.navigator.pointerEnabled ) { dom.wrapper.removeEventListener( 'pointerdown', onPointerDown, false ); dom.wrapper.removeEventListener( 'pointermove', onPointerMove, false ); dom.wrapper.removeEventListener( 'pointerup', onPointerUp, false ); } // IE10 else if( window.navigator.msPointerEnabled ) { dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false ); dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false ); dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false ); } if ( config.progress && dom.progress ) { dom.progress.removeEventListener( 'click', onProgressClicked, false ); } [ 'touchstart', 'click' ].forEach( function( eventName ) { dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } ); dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } ); dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } ); dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } ); dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } ); dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } ); } ); } /** * Extend object a with the properties of object b. * If there's a conflict, object b takes precedence. */ function extend( a, b ) { for( var i in b ) { a[ i ] = b[ i ]; } } /** * Converts the target object to an array. */ function toArray( o ) { return Array.prototype.slice.call( o ); } /** * Utility for deserializing a value. */ function deserialize( value ) { if( typeof value === 'string' ) { if( value === 'null' ) return null; else if( value === 'true' ) return true; else if( value === 'false' ) return false; else if( value.match( /^\d+$/ ) ) return parseFloat( value ); } return value; } /** * Measures the distance in pixels between point a * and point b. * * @param {Object} a point with x/y properties * @param {Object} b point with x/y properties */ function distanceBetween( a, b ) { var dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt( dx*dx + dy*dy ); } /** * Applies a CSS transform to the target element. */ function transformElement( element, transform ) { element.style.WebkitTransform = transform; element.style.MozTransform = transform; element.style.msTransform = transform; element.style.transform = transform; } /** * Applies CSS transforms to the slides container. The container * is transformed from two separate sources: layout and the overview * mode. */ function transformSlides( transforms ) { // Pick up new transforms from arguments if( typeof transforms.layout === 'string' ) slidesTransform.layout = transforms.layout; if( typeof transforms.overview === 'string' ) slidesTransform.overview = transforms.overview; // Apply the transforms to the slides container if( slidesTransform.layout ) { transformElement( dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview ); } else { transformElement( dom.slides, slidesTransform.overview ); } } /** * Injects the given CSS styles into the DOM. */ function injectStyleSheet( value ) { var tag = document.createElement( 'style' ); tag.type = 'text/css'; if( tag.styleSheet ) { tag.styleSheet.cssText = value; } else { tag.appendChild( document.createTextNode( value ) ); } document.getElementsByTagName( 'head' )[0].appendChild( tag ); } /** * Converts various color input formats to an {r:0,g:0,b:0} object. * * @param {String} color The string representation of a color, * the following formats are supported: * - #000 * - #000000 * - rgb(0,0,0) */ function colorToRgb( color ) { var hex3 = color.match( /^#([0-9a-f]{3})$/i ); if( hex3 && hex3[1] ) { hex3 = hex3[1]; return { r: parseInt( hex3.charAt( 0 ), 16 ) * 0x11, g: parseInt( hex3.charAt( 1 ), 16 ) * 0x11, b: parseInt( hex3.charAt( 2 ), 16 ) * 0x11 }; } var hex6 = color.match( /^#([0-9a-f]{6})$/i ); if( hex6 && hex6[1] ) { hex6 = hex6[1]; return { r: parseInt( hex6.substr( 0, 2 ), 16 ), g: parseInt( hex6.substr( 2, 2 ), 16 ), b: parseInt( hex6.substr( 4, 2 ), 16 ) }; } var rgb = color.match( /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i ); if( rgb ) { return { r: parseInt( rgb[1], 10 ), g: parseInt( rgb[2], 10 ), b: parseInt( rgb[3], 10 ) }; } var rgba = color.match( /^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i ); if( rgba ) { return { r: parseInt( rgba[1], 10 ), g: parseInt( rgba[2], 10 ), b: parseInt( rgba[3], 10 ), a: parseFloat( rgba[4] ) }; } return null; } /** * Calculates brightness on a scale of 0-255. * * @param color See colorStringToRgb for supported formats. */ function colorBrightness( color ) { if( typeof color === 'string' ) color = colorToRgb( color ); if( color ) { return ( color.r * 299 + color.g * 587 + color.b * 114 ) / 1000; } return null; } /** * Retrieves the height of the given element by looking * at the position and height of its immediate children. */ function getAbsoluteHeight( element ) { var height = 0; if( element ) { var absoluteChildren = 0; toArray( element.childNodes ).forEach( function( child ) { if( typeof child.offsetTop === 'number' && child.style ) { // Count # of abs children if( window.getComputedStyle( child ).position === 'absolute' ) { absoluteChildren += 1; } height = Math.max( height, child.offsetTop + child.offsetHeight ); } } ); // If there are no absolute children, use offsetHeight if( absoluteChildren === 0 ) { height = element.offsetHeight; } } return height; } /** * Returns the remaining height within the parent of the * target element. * * remaining height = [ configured parent height ] - [ current parent height ] */ function getRemainingHeight( element, height ) { height = height || 0; if( element ) { var newHeight, oldHeight = element.style.height; // Change the .stretch element height to 0 in order find the height of all // the other elements element.style.height = '0px'; newHeight = height - element.parentNode.offsetHeight; // Restore the old height, just in case element.style.height = oldHeight + 'px'; return newHeight; } return height; } /** * Checks if this instance is being used to print a PDF. */ function isPrintingPDF() { return ( /print-pdf/gi ).test( window.location.search ); } /** * Hides the address bar if we're on a mobile device. */ function hideAddressBar() { if( config.hideAddressBar && isMobileDevice ) { // Events that should trigger the address bar to hide window.addEventListener( 'load', removeAddressBar, false ); window.addEventListener( 'orientationchange', removeAddressBar, false ); } } /** * Causes the address bar to hide on mobile devices, * more vertical space ftw. */ function removeAddressBar() { setTimeout( function() { window.scrollTo( 0, 1 ); }, 10 ); } /** * Dispatches an event of the specified type from the * reveal DOM element. */ function dispatchEvent( type, args ) { var event = document.createEvent( 'HTMLEvents', 1, 2 ); event.initEvent( type, true, true ); extend( event, args ); dom.wrapper.dispatchEvent( event ); // If we're in an iframe, post each reveal.js event to the // parent window. Used by the notes plugin if( config.postMessageEvents && window.parent !== window.self ) { window.parent.postMessage( JSON.stringify({ namespace: 'reveal', eventName: type, state: getState() }), '*' ); } } /** * Wrap all links in 3D goodness. */ function enableRollingLinks() { if( features.transforms3d && !( 'msPerspective' in document.body.style ) ) { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) { var span = document.createElement('span'); span.setAttribute('data-title', anchor.text); span.innerHTML = anchor.innerHTML; anchor.classList.add( 'roll' ); anchor.innerHTML = ''; anchor.appendChild(span); } } } } /** * Unwrap all 3D links. */ function disableRollingLinks() { var anchors = dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ' a.roll' ); for( var i = 0, len = anchors.length; i < len; i++ ) { var anchor = anchors[i]; var span = anchor.querySelector( 'span' ); if( span ) { anchor.classList.remove( 'roll' ); anchor.innerHTML = span.innerHTML; } } } /** * Bind preview frame links. */ function enablePreviewLinks( selector ) { var anchors = toArray( document.querySelectorAll( selector ? selector : 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.addEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Unbind preview frame links. */ function disablePreviewLinks() { var anchors = toArray( document.querySelectorAll( 'a' ) ); anchors.forEach( function( element ) { if( /^(http|www)/gi.test( element.getAttribute( 'href' ) ) ) { element.removeEventListener( 'click', onPreviewLinkClicked, false ); } } ); } /** * Opens a preview window for the target URL. */ function showPreview( url ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-preview' ); dom.wrapper.appendChild( dom.overlay ); dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '<a class="external" href="'+ url +'" target="_blank"><span class="icon"></span></a>', '</header>', '<div class="spinner"></div>', '<div class="viewport">', '<iframe src="'+ url +'"></iframe>', '</div>' ].join(''); dom.overlay.querySelector( 'iframe' ).addEventListener( 'load', function( event ) { dom.overlay.classList.add( 'loaded' ); }, false ); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); dom.overlay.querySelector( '.external' ).addEventListener( 'click', function( event ) { closeOverlay(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } /** * Opens a overlay window with help material. */ function showHelp() { if( config.help ) { closeOverlay(); dom.overlay = document.createElement( 'div' ); dom.overlay.classList.add( 'overlay' ); dom.overlay.classList.add( 'overlay-help' ); dom.wrapper.appendChild( dom.overlay ); var html = '<p class="title">Keyboard Shortcuts</p><br/>'; html += '<table><th>KEY</th><th>ACTION</th>'; for( var key in keyboardShortcuts ) { html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[ key ] + '</td></tr>'; } html += '</table>'; dom.overlay.innerHTML = [ '<header>', '<a class="close" href="#"><span class="icon"></span></a>', '</header>', '<div class="viewport">', '<div class="viewport-inner">'+ html +'</div>', '</div>' ].join(''); dom.overlay.querySelector( '.close' ).addEventListener( 'click', function( event ) { closeOverlay(); event.preventDefault(); }, false ); setTimeout( function() { dom.overlay.classList.add( 'visible' ); }, 1 ); } } /** * Closes any currently open overlay. */ function closeOverlay() { if( dom.overlay ) { dom.overlay.parentNode.removeChild( dom.overlay ); dom.overlay = null; } } /** * Applies JavaScript-controlled layout rules to the * presentation. */ function layout() { if( dom.wrapper && !isPrintingPDF() ) { var size = getComputedSlideSize(); var slidePadding = 20; // TODO Dig this out of DOM // Layout the contents of the slides layoutSlideContents( config.width, config.height, slidePadding ); dom.slides.style.width = size.width + 'px'; dom.slides.style.height = size.height + 'px'; // Determine scale of content to fit within available space scale = Math.min( size.presentationWidth / size.width, size.presentationHeight / size.height ); // Respect max/min scale settings scale = Math.max( scale, config.minScale ); scale = Math.min( scale, config.maxScale ); // Don't apply any scaling styles if scale is 1 if( scale === 1 ) { dom.slides.style.zoom = ''; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } else { // Prefer zoom for scaling up so that content remains crisp. // Don't use zoom to scale down since that can lead to shifts // in text layout/line breaks. if( scale > 1 && features.zoom ) { dom.slides.style.zoom = scale; dom.slides.style.left = ''; dom.slides.style.top = ''; dom.slides.style.bottom = ''; dom.slides.style.right = ''; transformSlides( { layout: '' } ); } // Apply scale transform as a fallback else { dom.slides.style.zoom = ''; dom.slides.style.left = '50%'; dom.slides.style.top = '50%'; dom.slides.style.bottom = 'auto'; dom.slides.style.right = 'auto'; transformSlides( { layout: 'translate(-50%, -50%) scale('+ scale +')' } ); } } // Select all slides, vertical and horizontal var slides = toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ); for( var i = 0, len = slides.length; i < len; i++ ) { var slide = slides[ i ]; // Don't bother updating invisible slides if( slide.style.display === 'none' ) { continue; } if( config.center || slide.classList.contains( 'center' ) ) { // Vertical stacks are not centred since their section // children will be if( slide.classList.contains( 'stack' ) ) { slide.style.top = 0; } else { slide.style.top = Math.max( ( ( size.height - getAbsoluteHeight( slide ) ) / 2 ) - slidePadding, 0 ) + 'px'; } } else { slide.style.top = ''; } } updateProgress(); updateParallax(); } } /** * Applies layout logic to the contents of all slides in * the presentation. */ function layoutSlideContents( width, height, padding ) { // Handle sizing of elements with the 'stretch' class toArray( dom.slides.querySelectorAll( 'section > .stretch' ) ).forEach( function( element ) { // Determine how much vertical space we can use var remainingHeight = getRemainingHeight( element, height ); // Consider the aspect ratio of media elements if( /(img|video)/gi.test( element.nodeName ) ) { var nw = element.naturalWidth || element.videoWidth, nh = element.naturalHeight || element.videoHeight; var es = Math.min( width / nw, remainingHeight / nh ); element.style.width = ( nw * es ) + 'px'; element.style.height = ( nh * es ) + 'px'; } else { element.style.width = width + 'px'; element.style.height = remainingHeight + 'px'; } } ); } /** * Calculates the computed pixel size of our slides. These * values are based on the width and height configuration * options. */ function getComputedSlideSize( presentationWidth, presentationHeight ) { var size = { // Slide size width: config.width, height: config.height, // Presentation size presentationWidth: presentationWidth || dom.wrapper.offsetWidth, presentationHeight: presentationHeight || dom.wrapper.offsetHeight }; // Reduce available space by margin size.presentationWidth -= ( size.presentationWidth * config.margin ); size.presentationHeight -= ( size.presentationHeight * config.margin ); // Slide width may be a percentage of available width if( typeof size.width === 'string' && /%$/.test( size.width ) ) { size.width = parseInt( size.width, 10 ) / 100 * size.presentationWidth; } // Slide height may be a percentage of available height if( typeof size.height === 'string' && /%$/.test( size.height ) ) { size.height = parseInt( size.height, 10 ) / 100 * size.presentationHeight; } return size; } /** * Stores the vertical index of a stack so that the same * vertical slide can be selected when navigating to and * from the stack. * * @param {HTMLElement} stack The vertical stack element * @param {int} v Index to memorize */ function setPreviousVerticalIndex( stack, v ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) { stack.setAttribute( 'data-previous-indexv', v || 0 ); } } /** * Retrieves the vertical index which was stored using * #setPreviousVerticalIndex() or 0 if no previous index * exists. * * @param {HTMLElement} stack The vertical stack element */ function getPreviousVerticalIndex( stack ) { if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) { // Prefer manually defined start-indexv var attributeName = stack.hasAttribute( 'data-start-indexv' ) ? 'data-start-indexv' : 'data-previous-indexv'; return parseInt( stack.getAttribute( attributeName ) || 0, 10 ); } return 0; } /** * Displays the overview of slides (quick nav) by scaling * down and arranging all slide elements. */ function activateOverview() { // Only proceed if enabled in config if( config.overview && !isOverview() ) { overview = true; dom.wrapper.classList.add( 'overview' ); dom.wrapper.classList.remove( 'overview-deactivating' ); if( features.overviewTransitions ) { setTimeout( function() { dom.wrapper.classList.add( 'overview-animated' ); }, 1 ); } // Don't auto-slide while in overview mode cancelAutoSlide(); // Move the backgrounds element into the slide container to // that the same scaling is applied dom.slides.appendChild( dom.background ); // Clicking on an overview slide navigates to it toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { if( !slide.classList.contains( 'stack' ) ) { slide.addEventListener( 'click', onOverviewSlideClicked, true ); } } ); // Calculate slide sizes var margin = 70; var slideSize = getComputedSlideSize(); overviewSlideWidth = slideSize.width + margin; overviewSlideHeight = slideSize.height + margin; // Reverse in RTL mode if( config.rtl ) { overviewSlideWidth = -overviewSlideWidth; } updateSlidesVisibility(); layoutOverview(); updateOverview(); layout(); // Notify observers of the overview showing dispatchEvent( 'overviewshown', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Uses CSS transforms to position all slides in a grid for * display inside of the overview mode. */ function layoutOverview() { // Layout slides toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).forEach( function( hslide, h ) { hslide.setAttribute( 'data-index-h', h ); transformElement( hslide, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' ); if( hslide.classList.contains( 'stack' ) ) { toArray( hslide.querySelectorAll( 'section' ) ).forEach( function( vslide, v ) { vslide.setAttribute( 'data-index-h', h ); vslide.setAttribute( 'data-index-v', v ); transformElement( vslide, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' ); } ); } } ); // Layout slide backgrounds toArray( dom.background.childNodes ).forEach( function( hbackground, h ) { transformElement( hbackground, 'translate3d(' + ( h * overviewSlideWidth ) + 'px, 0, 0)' ); toArray( hbackground.querySelectorAll( '.slide-background' ) ).forEach( function( vbackground, v ) { transformElement( vbackground, 'translate3d(0, ' + ( v * overviewSlideHeight ) + 'px, 0)' ); } ); } ); } /** * Moves the overview viewport to the current slides. * Called each time the current slide changes. */ function updateOverview() { transformSlides( { overview: [ 'translateX('+ ( -indexh * overviewSlideWidth ) +'px)', 'translateY('+ ( -indexv * overviewSlideHeight ) +'px)', 'translateZ('+ ( window.innerWidth < 400 ? -1000 : -2500 ) +'px)' ].join( ' ' ) } ); } /** * Exits the slide overview and enters the currently * active slide. */ function deactivateOverview() { // Only proceed if enabled in config if( config.overview ) { overview = false; dom.wrapper.classList.remove( 'overview' ); dom.wrapper.classList.remove( 'overview-animated' ); // Temporarily add a class so that transitions can do different things // depending on whether they are exiting/entering overview, or just // moving from slide to slide dom.wrapper.classList.add( 'overview-deactivating' ); setTimeout( function () { dom.wrapper.classList.remove( 'overview-deactivating' ); }, 1 ); // Move the background element back out dom.wrapper.appendChild( dom.background ); // Clean up changes made to slides toArray( dom.wrapper.querySelectorAll( SLIDES_SELECTOR ) ).forEach( function( slide ) { transformElement( slide, '' ); slide.removeEventListener( 'click', onOverviewSlideClicked, true ); } ); // Clean up changes made to backgrounds toArray( dom.background.querySelectorAll( '.slide-background' ) ).forEach( function( background ) { transformElement( background, '' ); } ); transformSlides( { overview: '' } ); slide( indexh, indexv ); layout(); cueAutoSlide(); // Notify observers of the overview hiding dispatchEvent( 'overviewhidden', { 'indexh': indexh, 'indexv': indexv, 'currentSlide': currentSlide } ); } } /** * Toggles the slide overview mode on and off. * * @param {Boolean} override Optional flag which overrides the * toggle logic and forcibly sets the desired state. True means * overview is open, false means it's closed. */ function toggleOverview( override ) { if( typeof override === 'boolean' ) { override ? activateOverview() : deactivateOverview(); } else { isOverview() ? deactivateOverview() : activateOverview(); } } /** * Checks if the overview is currently active. * * @return {Boolean} true if the overview is active, * false otherwise */ function isOverview() { return overview; } /** * Checks if the current or specified slide is vertical * (nested within another slide). * * @param {HTMLElement} slide [optional] The slide to check * orientation of */ function isVerticalSlide( slide ) { // Prefer slide argument, otherwise use current slide slide = slide ? slide : currentSlide; return slide && slide.parentNode && !!slide.parentNode.nodeName.match( /section/i ); } /** * Handling the fullscreen functionality via the fullscreen API * * @see http://fullscreen.spec.whatwg.org/ * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode */ function enterFullscreen() { var element = document.body; // Check which implementation is available var requestMethod = element.requestFullScreen || element.webkitRequestFullscreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen; if( requestMethod ) { requestMethod.apply( element ); } } /** * Enters the paused mode which fades everything on screen to * black. */ function pause() { if( config.pause ) { var wasPaused = dom.wrapper.classList.contains( 'paused' ); cancelAutoSlide(); dom.wrapper.classList.add( 'paused' ); if( wasPaused === false ) { dispatchEvent( 'paused' ); } } } /** * Exits from the paused mode. */ function resume() { var wasPaused = dom.wrapper.classList.contains( 'paused' ); dom.wrapper.classList.remove( 'paused' ); cueAutoSlide(); if( wasPaused ) { dispatchEvent( 'resumed' ); } } /** * Toggles the paused mode on and off. */ function togglePause( override ) { if( typeof override === 'boolean' ) { override ? pause() : resume(); } else { isPaused() ? resume() : pause(); } } /** * Checks if we are currently in the paused mode. */ function isPaused() { return dom.wrapper.classList.contains( 'paused' ); } /** * Toggles the auto slide mode on and off. * * @param {Boolean} override Optional flag which sets the desired state. * True means autoplay starts, false means it stops. */ function toggleAutoSlide( override ) { if( typeof override === 'boolean' ) { override ? resumeAutoSlide() : pauseAutoSlide(); } else { autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide(); } } /** * Checks if the auto slide mode is currently on. */ function isAutoSliding() { return !!( autoSlide && !autoSlidePaused ); } /** * Steps from the current point in the presentation to the * slide which matches the specified horizontal and vertical * indices. * * @param {int} h Horizontal index of the target slide * @param {int} v Vertical index of the target slide * @param {int} f Optional index of a fragment within the * target slide to activate * @param {int} o Optional origin for use in multimaster environments */ function slide( h, v, f, o ) { // Remember where we were at before previousSlide = currentSlide; // Query all horizontal slides in the deck var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ); // If no vertical index is specified and the upcoming slide is a // stack, resume at its previous vertical index if( v === undefined && !isOverview() ) { v = getPreviousVerticalIndex( horizontalSlides[ h ] ); } // If we were on a vertical stack, remember what vertical index // it was on so we can resume at the same position when returning if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) { setPreviousVerticalIndex( previousSlide.parentNode, indexv ); } // Remember the state before this slide var stateBefore = state.concat(); // Reset the state array state.length = 0; var indexhBefore = indexh || 0, indexvBefore = indexv || 0; // Activate and transition to the new slide indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h ); indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v ); // Update the visibility of slides now that the indices have changed updateSlidesVisibility(); layout(); // Apply the new state stateLoop: for( var i = 0, len = state.length; i < len; i++ ) { // Check if this state existed on the previous slide. If it // did, we will avoid adding it repeatedly for( var j = 0; j < stateBefore.length; j++ ) { if( stateBefore[j] === state[i] ) { stateBefore.splice( j, 1 ); continue stateLoop; } } document.documentElement.classList.add( state[i] ); // Dispatch custom event matching the state's name dispatchEvent( state[i] ); } // Clean up the remains of the previous state while( stateBefore.length ) { document.documentElement.classList.remove( stateBefore.pop() ); } // Update the overview if it's currently active if( isOverview() ) { updateOverview(); } // Find the current horizontal slide and any possible vertical slides // within it var currentHorizontalSlide = horizontalSlides[ indexh ], currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' ); // Store references to the previous and current slides currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide; // Show fragment, if specified if( typeof f !== 'undefined' ) { navigateFragment( f ); } // Dispatch an event if the slide changed var slideChanged = ( indexh !== indexhBefore || indexv !== indexvBefore ); if( slideChanged ) { dispatchEvent( 'slidechanged', { 'indexh': indexh, 'indexv': indexv, 'previousSlide': previousSlide, 'currentSlide': currentSlide, 'origin': o } ); } else { // Ensure that the previous slide is never the same as the current previousSlide = null; } // Solves an edge case where the previous slide maintains the // 'present' class when navigating between adjacent vertical // stacks if( previousSlide ) { previousSlide.classList.remove( 'present' ); previousSlide.setAttribute( 'aria-hidden', 'true' ); // Reset all slides upon navigate to home // Issue: #285 if ( dom.wrapper.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) { // Launch async task setTimeout( function () { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i; for( i in slides ) { if( slides[i] ) { // Reset stack setPreviousVerticalIndex( slides[i], 0 ); } } }, 0 ); } } // Handle embedded content if( slideChanged || !previousSlide ) { stopEmbeddedContent( previousSlide ); startEmbeddedContent( currentSlide ); } // Announce the current slide contents, for screen readers dom.statusDiv.textContent = currentSlide.textContent; updateControls(); updateProgress(); updateBackground(); updateParallax(); updateSlideNumber(); updateNotes(); // Update the URL hash writeURL(); cueAutoSlide(); } /** * Syncs the presentation with the current DOM. Useful * when new slides or control elements are added or when * the configuration has changed. */ function sync() { // Subscribe to input removeEventListeners(); addEventListeners(); // Force a layout to make sure the current config is accounted for layout(); // Reflect the current autoSlide value autoSlide = config.autoSlide; // Start auto-sliding if it's enabled cueAutoSlide(); // Re-create the slide backgrounds createBackgrounds(); // Write the current hash to the URL writeURL(); sortAllFragments(); updateControls(); updateProgress(); updateBackground( true ); updateSlideNumber(); updateSlidesVisibility(); updateNotes(); formatEmbeddedContent(); startEmbeddedContent( currentSlide ); if( isOverview() ) { layoutOverview(); } } /** * Resets all vertical slides so that only the first * is visible. */ function resetVerticalSlides() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { if( y > 0 ) { verticalSlide.classList.remove( 'present' ); verticalSlide.classList.remove( 'past' ); verticalSlide.classList.add( 'future' ); verticalSlide.setAttribute( 'aria-hidden', 'true' ); } } ); } ); } /** * Sorts and formats all of fragments in the * presentation. */ function sortAllFragments() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); horizontalSlides.forEach( function( horizontalSlide ) { var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); verticalSlides.forEach( function( verticalSlide, y ) { sortFragments( verticalSlide.querySelectorAll( '.fragment' ) ); } ); if( verticalSlides.length === 0 ) sortFragments( horizontalSlide.querySelectorAll( '.fragment' ) ); } ); } /** * Randomly shuffles all slides in the deck. */ function shuffle() { var slides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); slides.forEach( function( slide ) { // Insert this slide next to another random slide. This may // cause the slide to insert before itself but that's fine. dom.slides.insertBefore( slide, slides[ Math.floor( Math.random() * slides.length ) ] ); } ); } /** * Updates one dimension of slides by showing the slide * with the specified index. * * @param {String} selector A CSS selector that will fetch * the group of slides we are working with * @param {Number} index The index of the slide that should be * shown * * @return {Number} The index of the slide that is now shown, * might differ from the passed in index if it was out of * bounds. */ function updateSlides( selector, index ) { // Select all slides and convert the NodeList result to // an array var slides = toArray( dom.wrapper.querySelectorAll( selector ) ), slidesLength = slides.length; var printMode = isPrintingPDF(); if( slidesLength ) { // Should the index loop? if( config.loop ) { index %= slidesLength; if( index < 0 ) { index = slidesLength + index; } } // Enforce max and minimum index bounds index = Math.max( Math.min( index, slidesLength - 1 ), 0 ); for( var i = 0; i < slidesLength; i++ ) { var element = slides[i]; var reverse = config.rtl && !isVerticalSlide( element ); element.classList.remove( 'past' ); element.classList.remove( 'present' ); element.classList.remove( 'future' ); // http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute element.setAttribute( 'hidden', '' ); element.setAttribute( 'aria-hidden', 'true' ); // If this element contains vertical slides if( element.querySelector( 'section' ) ) { element.classList.add( 'stack' ); } // If we're printing static slides, all slides are "present" if( printMode ) { element.classList.add( 'present' ); continue; } if( i < index ) { // Any element previous to index is given the 'past' class element.classList.add( reverse ? 'future' : 'past' ); if( config.fragments ) { var pastFragments = toArray( element.querySelectorAll( '.fragment' ) ); // Show all fragments on prior slides while( pastFragments.length ) { var pastFragment = pastFragments.pop(); pastFragment.classList.add( 'visible' ); pastFragment.classList.remove( 'current-fragment' ); } } } else if( i > index ) { // Any element subsequent to index is given the 'future' class element.classList.add( reverse ? 'past' : 'future' ); if( config.fragments ) { var futureFragments = toArray( element.querySelectorAll( '.fragment.visible' ) ); // No fragments in future slides should be visible ahead of time while( futureFragments.length ) { var futureFragment = futureFragments.pop(); futureFragment.classList.remove( 'visible' ); futureFragment.classList.remove( 'current-fragment' ); } } } } // Mark the current slide as present slides[index].classList.add( 'present' ); slides[index].removeAttribute( 'hidden' ); slides[index].removeAttribute( 'aria-hidden' ); // If this slide has a state associated with it, add it // onto the current state of the deck var slideState = slides[index].getAttribute( 'data-state' ); if( slideState ) { state = state.concat( slideState.split( ' ' ) ); } } else { // Since there are no slides we can't be anywhere beyond the // zeroth index index = 0; } return index; } /** * Optimization method; hide all slides that are far away * from the present slide. */ function updateSlidesVisibility() { // Select all slides and convert the NodeList result to // an array var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ), horizontalSlidesLength = horizontalSlides.length, distanceX, distanceY; if( horizontalSlidesLength && typeof indexh !== 'undefined' ) { // The number of steps away from the present slide that will // be visible var viewDistance = isOverview() ? 10 : config.viewDistance; // Limit view distance on weaker devices if( isMobileDevice ) { viewDistance = isOverview() ? 6 : 2; } // All slides need to be visible when exporting to PDF if( isPrintingPDF() ) { viewDistance = Number.MAX_VALUE; } for( var x = 0; x < horizontalSlidesLength; x++ ) { var horizontalSlide = horizontalSlides[x]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ), verticalSlidesLength = verticalSlides.length; // Determine how far away this slide is from the present distanceX = Math.abs( ( indexh || 0 ) - x ) || 0; // If the presentation is looped, distance should measure // 1 between the first and last slides if( config.loop ) { distanceX = Math.abs( ( ( indexh || 0 ) - x ) % ( horizontalSlidesLength - viewDistance ) ) || 0; } // Show the horizontal slide if it's within the view distance if( distanceX < viewDistance ) { showSlide( horizontalSlide ); } else { hideSlide( horizontalSlide ); } if( verticalSlidesLength ) { var oy = getPreviousVerticalIndex( horizontalSlide ); for( var y = 0; y < verticalSlidesLength; y++ ) { var verticalSlide = verticalSlides[y]; distanceY = x === ( indexh || 0 ) ? Math.abs( ( indexv || 0 ) - y ) : Math.abs( y - oy ); if( distanceX + distanceY < viewDistance ) { showSlide( verticalSlide ); } else { hideSlide( verticalSlide ); } } } } } } /** * Pick up notes from the current slide and display tham * to the viewer. * * @see `showNotes` config value */ function updateNotes() { if( config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF() ) { dom.speakerNotes.innerHTML = getSlideNotes() || ''; } } /** * Updates the progress bar to reflect the current slide. */ function updateProgress() { // Update progress if enabled if( config.progress && dom.progressbar ) { dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px'; } } /** * Updates the slide number div to reflect the current slide. * * The following slide number formats are available: * "h.v": horizontal . vertical slide number (default) * "h/v": horizontal / vertical slide number * "c": flattened slide number * "c/t": flattened slide number / total slides */ function updateSlideNumber() { // Update slide number if enabled if( config.slideNumber && dom.slideNumber ) { var value = []; var format = 'h.v'; // Check if a custom number format is available if( typeof config.slideNumber === 'string' ) { format = config.slideNumber; } switch( format ) { case 'c': value.push( getSlidePastCount() + 1 ); break; case 'c/t': value.push( getSlidePastCount() + 1, '/', getTotalSlides() ); break; case 'h/v': value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '/', indexv + 1 ); break; default: value.push( indexh + 1 ); if( isVerticalSlide() ) value.push( '.', indexv + 1 ); } dom.slideNumber.innerHTML = formatSlideNumber( value[0], value[1], value[2] ); } } /** * Applies HTML formatting to a slide number before it's * written to the DOM. */ function formatSlideNumber( a, delimiter, b ) { if( typeof b === 'number' && !isNaN( b ) ) { return '<span class="slide-number-a">'+ a +'</span>' + '<span class="slide-number-delimiter">'+ delimiter +'</span>' + '<span class="slide-number-b">'+ b +'</span>'; } else { return '<span class="slide-number-a">'+ a +'</span>'; } } /** * Updates the state of all control/navigation arrows. */ function updateControls() { var routes = availableRoutes(); var fragments = availableFragments(); // Remove the 'enabled' class from all directions dom.controlsLeft.concat( dom.controlsRight ) .concat( dom.controlsUp ) .concat( dom.controlsDown ) .concat( dom.controlsPrev ) .concat( dom.controlsNext ).forEach( function( node ) { node.classList.remove( 'enabled' ); node.classList.remove( 'fragmented' ); } ); // Add the 'enabled' class to the available routes if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Prev/next buttons if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } ); if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } ); // Highlight fragment directions if( currentSlide ) { // Always apply fragment decorator to prev/next buttons if( fragments.prev ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); // Apply fragment decorators to directional buttons based on // what slide axis they are in if( isVerticalSlide( currentSlide ) ) { if( fragments.prev ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } else { if( fragments.prev ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); if( fragments.next ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'fragmented', 'enabled' ); } ); } } } /** * Updates the background elements to reflect the current * slide. * * @param {Boolean} includeAll If true, the backgrounds of * all vertical slides (not just the present) will be updated. */ function updateBackground( includeAll ) { var currentBackground = null; // Reverse past/future classes when in RTL mode var horizontalPast = config.rtl ? 'future' : 'past', horizontalFuture = config.rtl ? 'past' : 'future'; // Update the classes of all backgrounds to match the // states of their slides (past/present/future) toArray( dom.background.childNodes ).forEach( function( backgroundh, h ) { backgroundh.classList.remove( 'past' ); backgroundh.classList.remove( 'present' ); backgroundh.classList.remove( 'future' ); if( h < indexh ) { backgroundh.classList.add( horizontalPast ); } else if ( h > indexh ) { backgroundh.classList.add( horizontalFuture ); } else { backgroundh.classList.add( 'present' ); // Store a reference to the current background element currentBackground = backgroundh; } if( includeAll || h === indexh ) { toArray( backgroundh.querySelectorAll( '.slide-background' ) ).forEach( function( backgroundv, v ) { backgroundv.classList.remove( 'past' ); backgroundv.classList.remove( 'present' ); backgroundv.classList.remove( 'future' ); if( v < indexv ) { backgroundv.classList.add( 'past' ); } else if ( v > indexv ) { backgroundv.classList.add( 'future' ); } else { backgroundv.classList.add( 'present' ); // Only if this is the present horizontal and vertical slide if( h === indexh ) currentBackground = backgroundv; } } ); } } ); // Stop any currently playing video background if( previousBackground ) { var previousVideo = previousBackground.querySelector( 'video' ); if( previousVideo ) previousVideo.pause(); } if( currentBackground ) { // Start video playback var currentVideo = currentBackground.querySelector( 'video' ); if( currentVideo ) { var startVideo = function() { currentVideo.currentTime = 0; currentVideo.play(); currentVideo.removeEventListener( 'loadeddata', startVideo ); }; if( currentVideo.readyState > 1 ) { startVideo(); } else { currentVideo.addEventListener( 'loadeddata', startVideo ); } } var backgroundImageURL = currentBackground.style.backgroundImage || ''; // Restart GIFs (doesn't work in Firefox) if( /\.gif/i.test( backgroundImageURL ) ) { currentBackground.style.backgroundImage = ''; window.getComputedStyle( currentBackground ).opacity; currentBackground.style.backgroundImage = backgroundImageURL; } // Don't transition between identical backgrounds. This // prevents unwanted flicker. var previousBackgroundHash = previousBackground ? previousBackground.getAttribute( 'data-background-hash' ) : null; var currentBackgroundHash = currentBackground.getAttribute( 'data-background-hash' ); if( currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground ) { dom.background.classList.add( 'no-transition' ); } previousBackground = currentBackground; } // If there's a background brightness flag for this slide, // bubble it to the .reveal container if( currentSlide ) { [ 'has-light-background', 'has-dark-background' ].forEach( function( classToBubble ) { if( currentSlide.classList.contains( classToBubble ) ) { dom.wrapper.classList.add( classToBubble ); } else { dom.wrapper.classList.remove( classToBubble ); } } ); } // Allow the first background to apply without transition setTimeout( function() { dom.background.classList.remove( 'no-transition' ); }, 1 ); } /** * Updates the position of the parallax background based * on the current slide index. */ function updateParallax() { if( config.parallaxBackgroundImage ) { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var backgroundSize = dom.background.style.backgroundSize.split( ' ' ), backgroundWidth, backgroundHeight; if( backgroundSize.length === 1 ) { backgroundWidth = backgroundHeight = parseInt( backgroundSize[0], 10 ); } else { backgroundWidth = parseInt( backgroundSize[0], 10 ); backgroundHeight = parseInt( backgroundSize[1], 10 ); } var slideWidth = dom.background.offsetWidth, horizontalSlideCount = horizontalSlides.length, horizontalOffsetMultiplier, horizontalOffset; if( typeof config.parallaxBackgroundHorizontal === 'number' ) { horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal; } else { horizontalOffsetMultiplier = horizontalSlideCount > 1 ? ( backgroundWidth - slideWidth ) / ( horizontalSlideCount-1 ) : 0; } horizontalOffset = horizontalOffsetMultiplier * indexh * -1; var slideHeight = dom.background.offsetHeight, verticalSlideCount = verticalSlides.length, verticalOffsetMultiplier, verticalOffset; if( typeof config.parallaxBackgroundVertical === 'number' ) { verticalOffsetMultiplier = config.parallaxBackgroundVertical; } else { verticalOffsetMultiplier = ( backgroundHeight - slideHeight ) / ( verticalSlideCount-1 ); } verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0; dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px'; } } /** * Called when the given slide is within the configured view * distance. Shows the slide element and loads any content * that is set to load lazily (data-src). */ function showSlide( slide ) { // Show the slide element slide.style.display = 'block'; // Media elements with data-src attributes toArray( slide.querySelectorAll( 'img[data-src], video[data-src], audio[data-src]' ) ).forEach( function( element ) { element.setAttribute( 'src', element.getAttribute( 'data-src' ) ); element.removeAttribute( 'data-src' ); } ); // Media elements with <source> children toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( media ) { var sources = 0; toArray( media.querySelectorAll( 'source[data-src]' ) ).forEach( function( source ) { source.setAttribute( 'src', source.getAttribute( 'data-src' ) ); source.removeAttribute( 'data-src' ); sources += 1; } ); // If we rewrote sources for this video/audio element, we need // to manually tell it to load from its new origin if( sources > 0 ) { media.load(); } } ); // Show the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'block'; // If the background contains media, load it if( background.hasAttribute( 'data-loaded' ) === false ) { background.setAttribute( 'data-loaded', 'true' ); var backgroundImage = slide.getAttribute( 'data-background-image' ), backgroundVideo = slide.getAttribute( 'data-background-video' ), backgroundVideoLoop = slide.hasAttribute( 'data-background-video-loop' ), backgroundVideoMuted = slide.hasAttribute( 'data-background-video-muted' ), backgroundIframe = slide.getAttribute( 'data-background-iframe' ); // Images if( backgroundImage ) { background.style.backgroundImage = 'url('+ backgroundImage +')'; } // Videos else if ( backgroundVideo && !isSpeakerNotes() ) { var video = document.createElement( 'video' ); if( backgroundVideoLoop ) { video.setAttribute( 'loop', '' ); } if( backgroundVideoMuted ) { video.muted = true; } // Support comma separated lists of video sources backgroundVideo.split( ',' ).forEach( function( source ) { video.innerHTML += '<source src="'+ source +'">'; } ); background.appendChild( video ); } // Iframes else if( backgroundIframe ) { var iframe = document.createElement( 'iframe' ); iframe.setAttribute( 'src', backgroundIframe ); iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.maxHeight = '100%'; iframe.style.maxWidth = '100%'; background.appendChild( iframe ); } } } } /** * Called when the given slide is moved outside of the * configured view distance. */ function hideSlide( slide ) { // Hide the slide element slide.style.display = 'none'; // Hide the corresponding background element var indices = getIndices( slide ); var background = getSlideBackground( indices.h, indices.v ); if( background ) { background.style.display = 'none'; } } /** * Determine what available routes there are for navigation. * * @return {Object} containing four booleans: left/right/up/down */ function availableRoutes() { var horizontalSlides = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ), verticalSlides = dom.wrapper.querySelectorAll( VERTICAL_SLIDES_SELECTOR ); var routes = { left: indexh > 0 || config.loop, right: indexh < horizontalSlides.length - 1 || config.loop, up: indexv > 0, down: indexv < verticalSlides.length - 1 }; // reverse horizontal controls for rtl if( config.rtl ) { var left = routes.left; routes.left = routes.right; routes.right = left; } return routes; } /** * Returns an object describing the available fragment * directions. * * @return {Object} two boolean properties: prev/next */ function availableFragments() { if( currentSlide && config.fragments ) { var fragments = currentSlide.querySelectorAll( '.fragment' ); var hiddenFragments = currentSlide.querySelectorAll( '.fragment:not(.visible)' ); return { prev: fragments.length - hiddenFragments.length > 0, next: !!hiddenFragments.length }; } else { return { prev: false, next: false }; } } /** * Enforces origin-specific format rules for embedded media. */ function formatEmbeddedContent() { var _appendParamToIframeSource = function( sourceAttribute, sourceURL, param ) { toArray( dom.slides.querySelectorAll( 'iframe['+ sourceAttribute +'*="'+ sourceURL +'"]' ) ).forEach( function( el ) { var src = el.getAttribute( sourceAttribute ); if( src && src.indexOf( param ) === -1 ) { el.setAttribute( sourceAttribute, src + ( !/\?/.test( src ) ? '?' : '&' ) + param ); } }); }; // YouTube frames must include "?enablejsapi=1" _appendParamToIframeSource( 'src', 'youtube.com/embed/', 'enablejsapi=1' ); _appendParamToIframeSource( 'data-src', 'youtube.com/embed/', 'enablejsapi=1' ); // Vimeo frames must include "?api=1" _appendParamToIframeSource( 'src', 'player.vimeo.com/', 'api=1' ); _appendParamToIframeSource( 'data-src', 'player.vimeo.com/', 'api=1' ); } /** * Start playback of any embedded content inside of * the targeted slide. */ function startEmbeddedContent( slide ) { if( slide && !isSpeakerNotes() ) { // Restart GIFs toArray( slide.querySelectorAll( 'img[src$=".gif"]' ) ).forEach( function( el ) { // Setting the same unchanged source like this was confirmed // to work in Chrome, FF & Safari el.setAttribute( 'src', el.getAttribute( 'src' ) ); } ); // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) && typeof el.play === 'function' ) { el.play(); } } ); // Normal iframes toArray( slide.querySelectorAll( 'iframe[src]' ) ).forEach( function( el ) { startEmbeddedIframe( { target: el } ); } ); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { if( el.getAttribute( 'src' ) !== el.getAttribute( 'data-src' ) ) { el.removeEventListener( 'load', startEmbeddedIframe ); // remove first to avoid dupes el.addEventListener( 'load', startEmbeddedIframe ); el.setAttribute( 'src', el.getAttribute( 'data-src' ) ); } } ); } } /** * "Starts" the content of an embedded iframe using the * postmessage API. */ function startEmbeddedIframe( event ) { var iframe = event.target; // YouTube postMessage API if( /youtube\.com\/embed\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ); } // Vimeo postMessage API else if( /player\.vimeo\.com\//.test( iframe.getAttribute( 'src' ) ) && iframe.hasAttribute( 'data-autoplay' ) ) { iframe.contentWindow.postMessage( '{"method":"play"}', '*' ); } // Generic postMessage API else { iframe.contentWindow.postMessage( 'slide:start', '*' ); } } /** * Stop playback of any embedded content inside of * the targeted slide. */ function stopEmbeddedContent( slide ) { if( slide && slide.parentNode ) { // HTML5 media elements toArray( slide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.pause === 'function' ) { el.pause(); } } ); // Generic postMessage API for non-lazy loaded iframes toArray( slide.querySelectorAll( 'iframe' ) ).forEach( function( el ) { el.contentWindow.postMessage( 'slide:stop', '*' ); el.removeEventListener( 'load', startEmbeddedIframe ); }); // YouTube postMessage API toArray( slide.querySelectorAll( 'iframe[src*="youtube.com/embed/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"event":"command","func":"pauseVideo","args":""}', '*' ); } }); // Vimeo postMessage API toArray( slide.querySelectorAll( 'iframe[src*="player.vimeo.com/"]' ) ).forEach( function( el ) { if( !el.hasAttribute( 'data-ignore' ) && typeof el.contentWindow.postMessage === 'function' ) { el.contentWindow.postMessage( '{"method":"pause"}', '*' ); } }); // Lazy loading iframes toArray( slide.querySelectorAll( 'iframe[data-src]' ) ).forEach( function( el ) { // Only removing the src doesn't actually unload the frame // in all browsers (Firefox) so we set it to blank first el.setAttribute( 'src', 'about:blank' ); el.removeAttribute( 'src' ); } ); } } /** * Returns the number of past slides. This can be used as a global * flattened index for slides. */ function getSlidePastCount() { var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // The number of past slides var pastCount = 0; // Step through all slides and count the past ones mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) { var horizontalSlide = horizontalSlides[i]; var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) ); for( var j = 0; j < verticalSlides.length; j++ ) { // Stop as soon as we arrive at the present if( verticalSlides[j].classList.contains( 'present' ) ) { break mainLoop; } pastCount++; } // Stop as soon as we arrive at the present if( horizontalSlide.classList.contains( 'present' ) ) { break; } // Don't count the wrapping section for vertical slides if( horizontalSlide.classList.contains( 'stack' ) === false ) { pastCount++; } } return pastCount; } /** * Returns a value ranging from 0-1 that represents * how far into the presentation we have navigated. */ function getProgress() { // The number of past and total slides var totalCount = getTotalSlides(); var pastCount = getSlidePastCount(); if( currentSlide ) { var allFragments = currentSlide.querySelectorAll( '.fragment' ); // If there are fragments in the current slide those should be // accounted for in the progress. if( allFragments.length > 0 ) { var visibleFragments = currentSlide.querySelectorAll( '.fragment.visible' ); // This value represents how big a portion of the slide progress // that is made up by its fragments (0-1) var fragmentWeight = 0.9; // Add fragment progress to the past slide count pastCount += ( visibleFragments.length / allFragments.length ) * fragmentWeight; } } return pastCount / ( totalCount - 1 ); } /** * Checks if this presentation is running inside of the * speaker notes window. */ function isSpeakerNotes() { return !!window.location.search.match( /receiver/gi ); } /** * Reads the current URL (hash) and navigates accordingly. */ function readURL() { var hash = window.location.hash; // Attempt to parse the hash as either an index or name var bits = hash.slice( 2 ).split( '/' ), name = hash.replace( /#|\//gi, '' ); // If the first bit is invalid and there is a name we can // assume that this is a named link if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) { var element; // Ensure the named link is a valid HTML ID attribute if( /^[a-zA-Z][\w:.-]*$/.test( name ) ) { // Find the slide with the specified ID element = document.getElementById( name ); } if( element ) { // Find the position of the named slide and navigate to it var indices = Reveal.getIndices( element ); slide( indices.h, indices.v ); } // If the slide doesn't exist, navigate to the current slide else { slide( indexh || 0, indexv || 0 ); } } else { // Read the index components of the hash var h = parseInt( bits[0], 10 ) || 0, v = parseInt( bits[1], 10 ) || 0; if( h !== indexh || v !== indexv ) { slide( h, v ); } } } /** * Updates the page URL (hash) to reflect the current * state. * * @param {Number} delay The time in ms to wait before * writing the hash */ function writeURL( delay ) { if( config.history ) { // Make sure there's never more than one timeout running clearTimeout( writeURLTimeout ); // If a delay is specified, timeout this call if( typeof delay === 'number' ) { writeURLTimeout = setTimeout( writeURL, delay ); } else if( currentSlide ) { var url = '/'; // Attempt to create a named link based on the slide's ID var id = currentSlide.getAttribute( 'id' ); if( id ) { id = id.replace( /[^a-zA-Z0-9\-\_\:\.]/g, '' ); } // If the current slide has an ID, use that as a named link if( typeof id === 'string' && id.length ) { url = '/' + id; } // Otherwise use the /h/v index else { if( indexh > 0 || indexv > 0 ) url += indexh; if( indexv > 0 ) url += '/' + indexv; } window.location.hash = url; } } } /** * Retrieves the h/v location of the current, or specified, * slide. * * @param {HTMLElement} slide If specified, the returned * index will be for this slide rather than the currently * active one * * @return {Object} { h: <int>, v: <int>, f: <int> } */ function getIndices( slide ) { // By default, return the current indices var h = indexh, v = indexv, f; // If a slide is specified, return the indices of that slide if( slide ) { var isVertical = isVerticalSlide( slide ); var slideh = isVertical ? slide.parentNode : slide; // Select all horizontal slides var horizontalSlides = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ); // Now that we know which the horizontal slide is, get its index h = Math.max( horizontalSlides.indexOf( slideh ), 0 ); // Assume we're not vertical v = undefined; // If this is a vertical slide, grab the vertical index if( isVertical ) { v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 ); } } if( !slide && currentSlide ) { var hasFragments = currentSlide.querySelectorAll( '.fragment' ).length > 0; if( hasFragments ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); if( currentFragment && currentFragment.hasAttribute( 'data-fragment-index' ) ) { f = parseInt( currentFragment.getAttribute( 'data-fragment-index' ), 10 ); } else { f = currentSlide.querySelectorAll( '.fragment.visible' ).length - 1; } } } return { h: h, v: v, f: f }; } /** * Retrieves the total number of slides in this presentation. */ function getTotalSlides() { return dom.wrapper.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length; } /** * Returns the slide element matching the specified index. */ function getSlide( x, y ) { var horizontalSlide = dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ]; var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' ); if( verticalSlides && verticalSlides.length && typeof y === 'number' ) { return verticalSlides ? verticalSlides[ y ] : undefined; } return horizontalSlide; } /** * Returns the background element for the given slide. * All slides, even the ones with no background properties * defined, have a background element so as long as the * index is valid an element will be returned. */ function getSlideBackground( x, y ) { // When printing to PDF the slide backgrounds are nested // inside of the slides if( isPrintingPDF() ) { var slide = getSlide( x, y ); if( slide ) { var background = slide.querySelector( '.slide-background' ); if( background && background.parentNode === slide ) { return background; } } return undefined; } var horizontalBackground = dom.wrapper.querySelectorAll( '.backgrounds>.slide-background' )[ x ]; var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll( '.slide-background' ); if( verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number' ) { return verticalBackgrounds ? verticalBackgrounds[ y ] : undefined; } return horizontalBackground; } /** * Retrieves the speaker notes from a slide. Notes can be * defined in two ways: * 1. As a data-notes attribute on the slide <section> * 2. As an <aside class="notes"> inside of the slide */ function getSlideNotes( slide ) { // Default to the current slide slide = slide || currentSlide; // Notes can be specified via the data-notes attribute... if( slide.hasAttribute( 'data-notes' ) ) { return slide.getAttribute( 'data-notes' ); } // ... or using an <aside class="notes"> element var notesElement = slide.querySelector( 'aside.notes' ); if( notesElement ) { return notesElement.innerHTML; } return null; } /** * Retrieves the current state of the presentation as * an object. This state can then be restored at any * time. */ function getState() { var indices = getIndices(); return { indexh: indices.h, indexv: indices.v, indexf: indices.f, paused: isPaused(), overview: isOverview() }; } /** * Restores the presentation to the given state. * * @param {Object} state As generated by getState() */ function setState( state ) { if( typeof state === 'object' ) { slide( deserialize( state.indexh ), deserialize( state.indexv ), deserialize( state.indexf ) ); var pausedFlag = deserialize( state.paused ), overviewFlag = deserialize( state.overview ); if( typeof pausedFlag === 'boolean' && pausedFlag !== isPaused() ) { togglePause( pausedFlag ); } if( typeof overviewFlag === 'boolean' && overviewFlag !== isOverview() ) { toggleOverview( overviewFlag ); } } } /** * Return a sorted fragments list, ordered by an increasing * "data-fragment-index" attribute. * * Fragments will be revealed in the order that they are returned by * this function, so you can use the index attributes to control the * order of fragment appearance. * * To maintain a sensible default fragment order, fragments are presumed * to be passed in document order. This function adds a "fragment-index" * attribute to each node if such an attribute is not already present, * and sets that attribute to an integer value which is the position of * the fragment within the fragments list. */ function sortFragments( fragments ) { fragments = toArray( fragments ); var ordered = [], unordered = [], sorted = []; // Group ordered and unordered elements fragments.forEach( function( fragment, i ) { if( fragment.hasAttribute( 'data-fragment-index' ) ) { var index = parseInt( fragment.getAttribute( 'data-fragment-index' ), 10 ); if( !ordered[index] ) { ordered[index] = []; } ordered[index].push( fragment ); } else { unordered.push( [ fragment ] ); } } ); // Append fragments without explicit indices in their // DOM order ordered = ordered.concat( unordered ); // Manually count the index up per group to ensure there // are no gaps var index = 0; // Push all fragments in their sorted order to an array, // this flattens the groups ordered.forEach( function( group ) { group.forEach( function( fragment ) { sorted.push( fragment ); fragment.setAttribute( 'data-fragment-index', index ); } ); index ++; } ); return sorted; } /** * Navigate to the specified slide fragment. * * @param {Number} index The index of the fragment that * should be shown, -1 means all are invisible * @param {Number} offset Integer offset to apply to the * fragment index * * @return {Boolean} true if a change was made in any * fragments visibility as part of this call */ function navigateFragment( index, offset ) { if( currentSlide && config.fragments ) { var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) ); if( fragments.length ) { // If no index is specified, find the current if( typeof index !== 'number' ) { var lastVisibleFragment = sortFragments( currentSlide.querySelectorAll( '.fragment.visible' ) ).pop(); if( lastVisibleFragment ) { index = parseInt( lastVisibleFragment.getAttribute( 'data-fragment-index' ) || 0, 10 ); } else { index = -1; } } // If an offset is specified, apply it to the index if( typeof offset === 'number' ) { index += offset; } var fragmentsShown = [], fragmentsHidden = []; toArray( fragments ).forEach( function( element, i ) { if( element.hasAttribute( 'data-fragment-index' ) ) { i = parseInt( element.getAttribute( 'data-fragment-index' ), 10 ); } // Visible fragments if( i <= index ) { if( !element.classList.contains( 'visible' ) ) fragmentsShown.push( element ); element.classList.add( 'visible' ); element.classList.remove( 'current-fragment' ); // Announce the fragments one by one to the Screen Reader dom.statusDiv.textContent = element.textContent; if( i === index ) { element.classList.add( 'current-fragment' ); } } // Hidden fragments else { if( element.classList.contains( 'visible' ) ) fragmentsHidden.push( element ); element.classList.remove( 'visible' ); element.classList.remove( 'current-fragment' ); } } ); if( fragmentsHidden.length ) { dispatchEvent( 'fragmenthidden', { fragment: fragmentsHidden[0], fragments: fragmentsHidden } ); } if( fragmentsShown.length ) { dispatchEvent( 'fragmentshown', { fragment: fragmentsShown[0], fragments: fragmentsShown } ); } updateControls(); updateProgress(); return !!( fragmentsShown.length || fragmentsHidden.length ); } } return false; } /** * Navigate to the next slide fragment. * * @return {Boolean} true if there was a next fragment, * false otherwise */ function nextFragment() { return navigateFragment( null, 1 ); } /** * Navigate to the previous slide fragment. * * @return {Boolean} true if there was a previous fragment, * false otherwise */ function previousFragment() { return navigateFragment( null, -1 ); } /** * Cues a new automated slide if enabled in the config. */ function cueAutoSlide() { cancelAutoSlide(); if( currentSlide ) { var currentFragment = currentSlide.querySelector( '.current-fragment' ); var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute( 'data-autoslide' ) : null; var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute( 'data-autoslide' ) : null; var slideAutoSlide = currentSlide.getAttribute( 'data-autoslide' ); // Pick value in the following priority order: // 1. Current fragment's data-autoslide // 2. Current slide's data-autoslide // 3. Parent slide's data-autoslide // 4. Global autoSlide setting if( fragmentAutoSlide ) { autoSlide = parseInt( fragmentAutoSlide, 10 ); } else if( slideAutoSlide ) { autoSlide = parseInt( slideAutoSlide, 10 ); } else if( parentAutoSlide ) { autoSlide = parseInt( parentAutoSlide, 10 ); } else { autoSlide = config.autoSlide; } // If there are media elements with data-autoplay, // automatically set the autoSlide duration to the // length of that media. Not applicable if the slide // is divided up into fragments. if( currentSlide.querySelectorAll( '.fragment' ).length === 0 ) { toArray( currentSlide.querySelectorAll( 'video, audio' ) ).forEach( function( el ) { if( el.hasAttribute( 'data-autoplay' ) ) { if( autoSlide && el.duration * 1000 > autoSlide ) { autoSlide = ( el.duration * 1000 ) + 1000; } } } ); } // Cue the next auto-slide if: // - There is an autoSlide value // - Auto-sliding isn't paused by the user // - The presentation isn't paused // - The overview isn't active // - The presentation isn't over if( autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && ( !Reveal.isLastSlide() || availableFragments().next || config.loop === true ) ) { autoSlideTimeout = setTimeout( function() { typeof config.autoSlideMethod === 'function' ? config.autoSlideMethod() : navigateNext(); cueAutoSlide(); }, autoSlide ); autoSlideStartTime = Date.now(); } if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( autoSlideTimeout !== -1 ); } } } /** * Cancels any ongoing request to auto-slide. */ function cancelAutoSlide() { clearTimeout( autoSlideTimeout ); autoSlideTimeout = -1; } function pauseAutoSlide() { if( autoSlide && !autoSlidePaused ) { autoSlidePaused = true; dispatchEvent( 'autoslidepaused' ); clearTimeout( autoSlideTimeout ); if( autoSlidePlayer ) { autoSlidePlayer.setPlaying( false ); } } } function resumeAutoSlide() { if( autoSlide && autoSlidePaused ) { autoSlidePaused = false; dispatchEvent( 'autoslideresumed' ); cueAutoSlide(); } } function navigateLeft() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || nextFragment() === false ) && availableRoutes().left ) { slide( indexh + 1 ); } } // Normal navigation else if( ( isOverview() || previousFragment() === false ) && availableRoutes().left ) { slide( indexh - 1 ); } } function navigateRight() { // Reverse for RTL if( config.rtl ) { if( ( isOverview() || previousFragment() === false ) && availableRoutes().right ) { slide( indexh - 1 ); } } // Normal navigation else if( ( isOverview() || nextFragment() === false ) && availableRoutes().right ) { slide( indexh + 1 ); } } function navigateUp() { // Prioritize hiding fragments if( ( isOverview() || previousFragment() === false ) && availableRoutes().up ) { slide( indexh, indexv - 1 ); } } function navigateDown() { // Prioritize revealing fragments if( ( isOverview() || nextFragment() === false ) && availableRoutes().down ) { slide( indexh, indexv + 1 ); } } /** * Navigates backwards, prioritized in the following order: * 1) Previous fragment * 2) Previous vertical slide * 3) Previous horizontal slide */ function navigatePrev() { // Prioritize revealing fragments if( previousFragment() === false ) { if( availableRoutes().up ) { navigateUp(); } else { // Fetch the previous horizontal slide, if there is one var previousSlide; if( config.rtl ) { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop(); } else { previousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop(); } if( previousSlide ) { var v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined; var h = indexh - 1; slide( h, v ); } } } } /** * The reverse of #navigatePrev(). */ function navigateNext() { // Prioritize revealing fragments if( nextFragment() === false ) { if( availableRoutes().down ) { navigateDown(); } else if( config.rtl ) { navigateLeft(); } else { navigateRight(); } } } /** * Checks if the target element prevents the triggering of * swipe navigation. */ function isSwipePrevented( target ) { while( target && typeof target.hasAttribute === 'function' ) { if( target.hasAttribute( 'data-prevent-swipe' ) ) return true; target = target.parentNode; } return false; } // --------------------------------------------------------------------// // ----------------------------- EVENTS -------------------------------// // --------------------------------------------------------------------// /** * Called by all event handlers that are based on user * input. */ function onUserInput( event ) { if( config.autoSlideStoppable ) { pauseAutoSlide(); } } /** * Handler for the document level 'keypress' event. */ function onDocumentKeyPress( event ) { // Check if the pressed key is question mark if( event.shiftKey && event.charCode === 63 ) { if( dom.overlay ) { closeOverlay(); } else { showHelp( true ); } } } /** * Handler for the document level 'keydown' event. */ function onDocumentKeyDown( event ) { // If there's a condition specified and it returns false, // ignore this event if( typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false ) { return true; } // Remember if auto-sliding was paused so we can toggle it var autoSlideWasPaused = autoSlidePaused; onUserInput( event ); // Check if there's a focused element that could be using // the keyboard var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit'; var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test( document.activeElement.tagName ); // Disregard the event if there's a focused element or a // keyboard modifier key is present if( activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey ) return; // While paused only allow resume keyboard events; 'b', '.'' var resumeKeyCodes = [66,190,191]; var key; // Custom key bindings for togglePause should be able to resume if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { if( config.keyboard[key] === 'togglePause' ) { resumeKeyCodes.push( parseInt( key, 10 ) ); } } } if( isPaused() && resumeKeyCodes.indexOf( event.keyCode ) === -1 ) { return false; } var triggered = false; // 1. User defined key bindings if( typeof config.keyboard === 'object' ) { for( key in config.keyboard ) { // Check if this binding matches the pressed key if( parseInt( key, 10 ) === event.keyCode ) { var value = config.keyboard[ key ]; // Callback function if( typeof value === 'function' ) { value.apply( null, [ event ] ); } // String shortcuts to reveal.js API else if( typeof value === 'string' && typeof Reveal[ value ] === 'function' ) { Reveal[ value ].call(); } triggered = true; } } } // 2. System defined key bindings if( triggered === false ) { // Assume true and try to prove false triggered = true; switch( event.keyCode ) { // p, page up case 80: case 33: navigatePrev(); break; // n, page down case 78: case 34: navigateNext(); break; // h, left case 72: case 37: navigateLeft(); break; // l, right case 76: case 39: navigateRight(); break; // k, up case 75: case 38: navigateUp(); break; // j, down case 74: case 40: navigateDown(); break; // home case 36: slide( 0 ); break; // end case 35: slide( Number.MAX_VALUE ); break; // space case 32: isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext(); break; // return case 13: isOverview() ? deactivateOverview() : triggered = false; break; // two-spot, semicolon, b, period, Logitech presenter tools "black screen" button case 58: case 59: case 66: case 190: case 191: togglePause(); break; // f case 70: enterFullscreen(); break; // a case 65: if ( config.autoSlideStoppable ) toggleAutoSlide( autoSlideWasPaused ); break; default: triggered = false; } } // If the input resulted in a triggered action we should prevent // the browsers default behavior if( triggered ) { event.preventDefault && event.preventDefault(); } // ESC or O key else if ( ( event.keyCode === 27 || event.keyCode === 79 ) && features.transforms3d ) { if( dom.overlay ) { closeOverlay(); } else { toggleOverview(); } event.preventDefault && event.preventDefault(); } // If auto-sliding is enabled we need to cue up // another timeout cueAutoSlide(); } /** * Handler for the 'touchstart' event, enables support for * swipe and pinch gestures. */ function onTouchStart( event ) { if( isSwipePrevented( event.target ) ) return true; touch.startX = event.touches[0].clientX; touch.startY = event.touches[0].clientY; touch.startCount = event.touches.length; // If there's two touches we need to memorize the distance // between those two points to detect pinching if( event.touches.length === 2 && config.overview ) { touch.startSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); } } /** * Handler for the 'touchmove' event. */ function onTouchMove( event ) { if( isSwipePrevented( event.target ) ) return true; // Each touch should only trigger one action if( !touch.captured ) { onUserInput( event ); var currentX = event.touches[0].clientX; var currentY = event.touches[0].clientY; // If the touch started with two points and still has // two active touches; test for the pinch gesture if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) { // The current distance in pixels between the two touch points var currentSpan = distanceBetween( { x: event.touches[1].clientX, y: event.touches[1].clientY }, { x: touch.startX, y: touch.startY } ); // If the span is larger than the desire amount we've got // ourselves a pinch if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) { touch.captured = true; if( currentSpan < touch.startSpan ) { activateOverview(); } else { deactivateOverview(); } } event.preventDefault(); } // There was only one touch point, look for a swipe else if( event.touches.length === 1 && touch.startCount !== 2 ) { var deltaX = currentX - touch.startX, deltaY = currentY - touch.startY; if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateLeft(); } else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) { touch.captured = true; navigateRight(); } else if( deltaY > touch.threshold ) { touch.captured = true; navigateUp(); } else if( deltaY < -touch.threshold ) { touch.captured = true; navigateDown(); } // If we're embedded, only block touch events if they have // triggered an action if( config.embedded ) { if( touch.captured || isVerticalSlide( currentSlide ) ) { event.preventDefault(); } } // Not embedded? Block them all to avoid needless tossing // around of the viewport in iOS else { event.preventDefault(); } } } // There's a bug with swiping on some Android devices unless // the default action is always prevented else if( UA.match( /android/gi ) ) { event.preventDefault(); } } /** * Handler for the 'touchend' event. */ function onTouchEnd( event ) { touch.captured = false; } /** * Convert pointer down to touch start. */ function onPointerDown( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchStart( event ); } } /** * Convert pointer move to touch move. */ function onPointerMove( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchMove( event ); } } /** * Convert pointer up to touch end. */ function onPointerUp( event ) { if( event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch" ) { event.touches = [{ clientX: event.clientX, clientY: event.clientY }]; onTouchEnd( event ); } } /** * Handles mouse wheel scrolling, throttled to avoid skipping * multiple slides. */ function onDocumentMouseScroll( event ) { if( Date.now() - lastMouseWheelStep > 600 ) { lastMouseWheelStep = Date.now(); var delta = event.detail || -event.wheelDelta; if( delta > 0 ) { navigateNext(); } else { navigatePrev(); } } } /** * Clicking on the progress bar results in a navigation to the * closest approximate horizontal slide using this equation: * * ( clickX / presentationWidth ) * numberOfSlides */ function onProgressClicked( event ) { onUserInput( event ); event.preventDefault(); var slidesTotal = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length; var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal ); if( config.rtl ) { slideIndex = slidesTotal - slideIndex; } slide( slideIndex ); } /** * Event handler for navigation control buttons. */ function onNavigateLeftClicked( event ) { event.preventDefault(); onUserInput(); navigateLeft(); } function onNavigateRightClicked( event ) { event.preventDefault(); onUserInput(); navigateRight(); } function onNavigateUpClicked( event ) { event.preventDefault(); onUserInput(); navigateUp(); } function onNavigateDownClicked( event ) { event.preventDefault(); onUserInput(); navigateDown(); } function onNavigatePrevClicked( event ) { event.preventDefault(); onUserInput(); navigatePrev(); } function onNavigateNextClicked( event ) { event.preventDefault(); onUserInput(); navigateNext(); } /** * Handler for the window level 'hashchange' event. */ function onWindowHashChange( event ) { readURL(); } /** * Handler for the window level 'resize' event. */ function onWindowResize( event ) { layout(); } /** * Handle for the window level 'visibilitychange' event. */ function onPageVisibilityChange( event ) { var isHidden = document.webkitHidden || document.msHidden || document.hidden; // If, after clicking a link or similar and we're coming back, // focus the document.body to ensure we can use keyboard shortcuts if( isHidden === false && document.activeElement !== document.body ) { // Not all elements support .blur() - SVGs among them. if( typeof document.activeElement.blur === 'function' ) { document.activeElement.blur(); } document.body.focus(); } } /** * Invoked when a slide is and we're in the overview. */ function onOverviewSlideClicked( event ) { // TODO There's a bug here where the event listeners are not // removed after deactivating the overview. if( eventsAreBound && isOverview() ) { event.preventDefault(); var element = event.target; while( element && !element.nodeName.match( /section/gi ) ) { element = element.parentNode; } if( element && !element.classList.contains( 'disabled' ) ) { deactivateOverview(); if( element.nodeName.match( /section/gi ) ) { var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ), v = parseInt( element.getAttribute( 'data-index-v' ), 10 ); slide( h, v ); } } } } /** * Handles clicks on links that are set to preview in the * iframe overlay. */ function onPreviewLinkClicked( event ) { if( event.currentTarget && event.currentTarget.hasAttribute( 'href' ) ) { var url = event.currentTarget.getAttribute( 'href' ); if( url ) { showPreview( url ); event.preventDefault(); } } } /** * Handles click on the auto-sliding controls element. */ function onAutoSlidePlayerClick( event ) { // Replay if( Reveal.isLastSlide() && config.loop === false ) { slide( 0, 0 ); resumeAutoSlide(); } // Resume else if( autoSlidePaused ) { resumeAutoSlide(); } // Pause else { pauseAutoSlide(); } } // --------------------------------------------------------------------// // ------------------------ PLAYBACK COMPONENT ------------------------// // --------------------------------------------------------------------// /** * Constructor for the playback component, which displays * play/pause/progress controls. * * @param {HTMLElement} container The component will append * itself to this * @param {Function} progressCheck A method which will be * called frequently to get the current progress on a range * of 0-1 */ function Playback( container, progressCheck ) { // Cosmetics this.diameter = 100; this.diameter2 = this.diameter/2; this.thickness = 6; // Flags if we are currently playing this.playing = false; // Current progress on a 0-1 range this.progress = 0; // Used to loop the animation smoothly this.progressOffset = 1; this.container = container; this.progressCheck = progressCheck; this.canvas = document.createElement( 'canvas' ); this.canvas.className = 'playback'; this.canvas.width = this.diameter; this.canvas.height = this.diameter; this.canvas.style.width = this.diameter2 + 'px'; this.canvas.style.height = this.diameter2 + 'px'; this.context = this.canvas.getContext( '2d' ); this.container.appendChild( this.canvas ); this.render(); } Playback.prototype.setPlaying = function( value ) { var wasPlaying = this.playing; this.playing = value; // Start repainting if we weren't already if( !wasPlaying && this.playing ) { this.animate(); } else { this.render(); } }; Playback.prototype.animate = function() { var progressBefore = this.progress; this.progress = this.progressCheck(); // When we loop, offset the progress so that it eases // smoothly rather than immediately resetting if( progressBefore > 0.8 && this.progress < 0.2 ) { this.progressOffset = this.progress; } this.render(); if( this.playing ) { features.requestAnimationFrameMethod.call( window, this.animate.bind( this ) ); } }; /** * Renders the current progress and playback state. */ Playback.prototype.render = function() { var progress = this.playing ? this.progress : 0, radius = ( this.diameter2 ) - this.thickness, x = this.diameter2, y = this.diameter2, iconSize = 28; // Ease towards 1 this.progressOffset += ( 1 - this.progressOffset ) * 0.1; var endAngle = ( - Math.PI / 2 ) + ( progress * ( Math.PI * 2 ) ); var startAngle = ( - Math.PI / 2 ) + ( this.progressOffset * ( Math.PI * 2 ) ); this.context.save(); this.context.clearRect( 0, 0, this.diameter, this.diameter ); // Solid background color this.context.beginPath(); this.context.arc( x, y, radius + 4, 0, Math.PI * 2, false ); this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )'; this.context.fill(); // Draw progress track this.context.beginPath(); this.context.arc( x, y, radius, 0, Math.PI * 2, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#666'; this.context.stroke(); if( this.playing ) { // Draw progress on top of track this.context.beginPath(); this.context.arc( x, y, radius, startAngle, endAngle, false ); this.context.lineWidth = this.thickness; this.context.strokeStyle = '#fff'; this.context.stroke(); } this.context.translate( x - ( iconSize / 2 ), y - ( iconSize / 2 ) ); // Draw play/pause icons if( this.playing ) { this.context.fillStyle = '#fff'; this.context.fillRect( 0, 0, iconSize / 2 - 4, iconSize ); this.context.fillRect( iconSize / 2 + 4, 0, iconSize / 2 - 4, iconSize ); } else { this.context.beginPath(); this.context.translate( 4, 0 ); this.context.moveTo( 0, 0 ); this.context.lineTo( iconSize - 4, iconSize / 2 ); this.context.lineTo( 0, iconSize ); this.context.fillStyle = '#fff'; this.context.fill(); } this.context.restore(); }; Playback.prototype.on = function( type, listener ) { this.canvas.addEventListener( type, listener, false ); }; Playback.prototype.off = function( type, listener ) { this.canvas.removeEventListener( type, listener, false ); }; Playback.prototype.destroy = function() { this.playing = false; if( this.canvas.parentNode ) { this.container.removeChild( this.canvas ); } }; // --------------------------------------------------------------------// // ------------------------------- API --------------------------------// // --------------------------------------------------------------------// Reveal = { VERSION: VERSION, initialize: initialize, configure: configure, sync: sync, // Navigation methods slide: slide, left: navigateLeft, right: navigateRight, up: navigateUp, down: navigateDown, prev: navigatePrev, next: navigateNext, // Fragment methods navigateFragment: navigateFragment, prevFragment: previousFragment, nextFragment: nextFragment, // Deprecated aliases navigateTo: slide, navigateLeft: navigateLeft, navigateRight: navigateRight, navigateUp: navigateUp, navigateDown: navigateDown, navigatePrev: navigatePrev, navigateNext: navigateNext, // Forces an update in slide layout layout: layout, // Randomizes the order of slides shuffle: shuffle, // Returns an object with the available routes as booleans (left/right/top/bottom) availableRoutes: availableRoutes, // Returns an object with the available fragments as booleans (prev/next) availableFragments: availableFragments, // Toggles the overview mode on/off toggleOverview: toggleOverview, // Toggles the "black screen" mode on/off togglePause: togglePause, // Toggles the auto slide mode on/off toggleAutoSlide: toggleAutoSlide, // State checks isOverview: isOverview, isPaused: isPaused, isAutoSliding: isAutoSliding, // Adds or removes all internal event listeners (such as keyboard) addEventListeners: addEventListeners, removeEventListeners: removeEventListeners, // Facility for persisting and restoring the presentation state getState: getState, setState: setState, // Presentation progress on range of 0-1 getProgress: getProgress, // Returns the indices of the current, or specified, slide getIndices: getIndices, getTotalSlides: getTotalSlides, // Returns the slide element at the specified index getSlide: getSlide, // Returns the slide background element at the specified index getSlideBackground: getSlideBackground, // Returns the speaker notes string for a slide, or null getSlideNotes: getSlideNotes, // Returns the previous slide element, may be null getPreviousSlide: function() { return previousSlide; }, // Returns the current slide element getCurrentSlide: function() { return currentSlide; }, // Returns the current scale of the presentation content getScale: function() { return scale; }, // Returns the current configuration object getConfig: function() { return config; }, // Helper method, retrieves query string as a key/value hash getQueryHash: function() { var query = {}; location.search.replace( /[A-Z0-9]+?=([\w\.%-]*)/gi, function(a) { query[ a.split( '=' ).shift() ] = a.split( '=' ).pop(); } ); // Basic deserialization for( var i in query ) { var value = query[ i ]; query[ i ] = deserialize( unescape( value ) ); } return query; }, // Returns true if we're currently on the first slide isFirstSlide: function() { return ( indexh === 0 && indexv === 0 ); }, // Returns true if we're currently on the last slide isLastSlide: function() { if( currentSlide ) { // Does this slide has next a sibling? if( currentSlide.nextElementSibling ) return false; // If it's vertical, does its parent have a next sibling? if( isVerticalSlide( currentSlide ) && currentSlide.parentNode.nextElementSibling ) return false; return true; } return false; }, // Checks if reveal.js has been loaded and is ready for use isReady: function() { return loaded; }, // Forward event binding to the reveal DOM element addEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture ); } }, removeEventListener: function( type, listener, useCapture ) { if( 'addEventListener' in window ) { ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture ); } }, // Programatically triggers a keyboard event triggerKey: function( keyCode ) { onDocumentKeyDown( { keyCode: keyCode } ); }, // Registers a new shortcut to include in the help overlay registerKeyboardShortcut: function( key, value ) { keyboardShortcuts[key] = value; } }; return Reveal; }));
lihuma/lihuma.github.io
js/reveal.js
JavaScript
mit
131,510
var Example = Example || {}; Example.staticFriction = function() { var Engine = Matter.Engine, Render = Matter.Render, Runner = Matter.Runner, Body = Matter.Body, Composites = Matter.Composites, Events = Matter.Events, MouseConstraint = Matter.MouseConstraint, Mouse = Matter.Mouse, World = Matter.World, Bodies = Matter.Bodies; // create engine var engine = Engine.create(), world = engine.world; // create renderer var render = Render.create({ element: document.body, engine: engine, options: { width: Math.min(document.documentElement.clientWidth, 800), height: Math.min(document.documentElement.clientHeight, 600), showVelocity: true } }); Render.run(render); // create runner var runner = Runner.create(); Runner.run(runner, engine); // add bodies var body = Bodies.rectangle(400, 500, 200, 60, { isStatic: true, chamfer: 10 }), size = 50, counter = -1; var stack = Composites.stack(350, 470 - 6 * size, 1, 6, 0, 0, function(x, y) { return Bodies.rectangle(x, y, size * 2, size, { slop: 0.5, friction: 1, frictionStatic: Infinity }); }); World.add(world, [ body, stack, // walls Bodies.rectangle(400, 0, 800, 50, { isStatic: true }), Bodies.rectangle(400, 600, 800, 50, { isStatic: true }), Bodies.rectangle(800, 300, 50, 600, { isStatic: true }), Bodies.rectangle(0, 300, 50, 600, { isStatic: true }) ]); Events.on(engine, 'beforeUpdate', function(event) { counter += 0.014; if (counter < 0) { return; } var px = 400 + 100 * Math.sin(counter); // body is static so must manually update velocity for friction to work Body.setVelocity(body, { x: px - body.position.x, y: 0 }); Body.setPosition(body, { x: px, y: body.position.y }); }); // add mouse control var mouse = Mouse.create(render.canvas), mouseConstraint = MouseConstraint.create(engine, { mouse: mouse, constraint: { stiffness: 0.2, render: { visible: false } } }); World.add(world, mouseConstraint); // keep the mouse in sync with rendering render.mouse = mouse; // fit the render viewport to the scene Render.lookAt(render, { min: { x: 0, y: 0 }, max: { x: 800, y: 600 } }); // context for MatterTools.Demo return { engine: engine, runner: runner, render: render, canvas: render.canvas, stop: function() { Matter.Render.stop(render); Matter.Runner.stop(runner); } }; };
lsu-emdm/nx-physicsUI
matter-js/examples/staticFriction.js
JavaScript
mit
2,921
var searchData= [ ['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]] ];
dawidd6/qtictactoe
docs/search/variables_9.js
JavaScript
mit
146
/** * Created by huangyao on 14-10-1. */ var _ = require('lodash'); var color =require('colors'); var fs =require('fs'); var config = require('../config.js'); var path = require('path'); var mongoose = require("mongoose"); var lcommon = require('lush').common; console.log(config.db); mongoose.connect(config.db,function (err) { if(err){ throw new Error('db connect error!\n'+err); } console.log('db connect success!'.yellow); }); // console.log('point'); // var models = { // // init : function (callback) { // fs.readdir(path+'/module',function (err,files) { // if(err){ // throw err; // } // // console.log(files); // return callback(files.filter(function (item) { // return !(item === "index.js" || item === "." || item === ".."); // })); // }); // }, // }; // // // models.init(function (files) { // // console.log(files); // for (var item in files) { // //reuire all modules // // console.log(lcommon.literat(files[item]).slice(0,-3)); // console.log(files[item]); // item = files[item].split('.')[0]; // require('./'+ item); // var m = lcommon.literat(item); // console.log('loading and use ',m,' model'); // exports[m] = mongoose.model(m); // // // _.extend(models,file.exports); // // console.log(file); // } // }); // var models = fs.readdirSync(path.resolve('.','module')); models.forEach(function(item,index){ if(item !== '.' && item !== '..' && item !== 'index.js'){ // console.log(item.indexOf('.js')); //ends with .js if(item.indexOf('.js') == (item.length-3)){ item = item.split('.')[0]; require('./'+ item); var m = lcommon.literat(item); console.log('loading and use ',m,' model'); exports[m] = mongoose.model(m); } } });
NodeAndroid/Action_server
module/index.js
JavaScript
mit
1,812
version https://git-lfs.github.com/spec/v1 oid sha256:054dbc79bbfc64911008a1e140813a8705dfc5cff35cbffd8bf7bc1f74c446b6 size 5257
yogeshsaroya/new-cdnjs
ajax/libs/flot/0.8.0/jquery.flot.fillbetween.js
JavaScript
mit
129
define(["widgetjs/widgetjs", "lodash", "jquery", "prettify", "code", "bootstrap"], function(widgetjs, lodash, jQuery, prettify, code) { var examples = {}; examples.modals = code({ group: "Modals", label: "Modals", links: ["http://getbootstrap.com/javascript/#modals"], example : function(html) { // Modal html.div({"class": "clearfix bs-example-modal"}, html.div({ klass: "modal"}, html.div({ klass: "modal-dialog"}, html.div({ klass: "modal-content"}, html.div({ klass: "modal-header"}, html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"}, "&times;" ), html.h4({ klass: "modal-title"}, "Modal title" ) ), html.div({ klass: "modal-body"}, html.p( "One fine body&hellip;" ) ), html.div({ klass: "modal-footer"}, html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"}, "Close" ), html.button({ type: "button", klass: "btn btn-primary"}, "Save changes" ) ) ) ) ) ); } }); examples.modalsDemo = code({ group: "Modals", label: "Live Demo", links: ["http://getbootstrap.com/javascript/#modals"], example : function(html) { // Modal html.div({ id: "myModal", klass: "modal fade"}, html.div({ klass: "modal-dialog"}, html.div({ klass: "modal-content"}, html.div({ klass: "modal-header"}, html.button({ type: "button", klass: "close", "data-dismiss": "modal", "aria-hidden": "true"}, "&times;" ), html.h4({ klass: "modal-title"}, "Modal title" ) ), html.div({ klass: "modal-body"}, html.p( "One fine body&hellip;" ) ), html.div({ klass: "modal-footer"}, html.button({ type: "button", klass: "btn btn-default", "data-dismiss": "modal"}, "Close" ), html.button({ type: "button", klass: "btn btn-primary"}, "Save changes" ) ) ) ) ); html.button({ klass: "btn btn-primary btn-lg", "data-toggle": "modal", "data-target": "#myModal"}, "Show modal"); } }); examples.toolTips = code({ group: "Tooltips", label: "Live Demo", links: ["http://getbootstrap.com/javascript/#tooltips"], example : function(html) { // TOOLTIPS html.div({ klass: "tooltip-demo"}, html.div({ klass: "bs-example-tooltips"}, html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "left", title: "", "data-original-title": "Tooltip on left"}, "Tooltip on left" ), html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "top", title: "", "data-original-title": "Tooltip on top"}, "Tooltip on top" ), html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "bottom", title: "", "data-original-title": "Tooltip on bottom"}, "Tooltip on bottom" ), html.button({ type: "button", klass: "btn btn-default", "data-toggle": "tooltip", "data-placement": "right", title: "", "data-original-title": "Tooltip on right"}, "Tooltip on right" ) ) ); jQuery(".bs-example-tooltips").tooltip(); } }); examples.popovers = code({ group: "Popovers", label: "Popovers", links: ["http://getbootstrap.com/javascript/#popovers"], example : function(html) { // Popovers html.div({ klass: "bs-example-popovers"}, html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "left", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""}, "Left" ), html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "top", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""}, "Top" ), html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "bottom", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""}, "Bottom" ), html.button({ type: "button", klass: "btn btn-default", "data-container": "body", "data-toggle": "popover", "data-placement": "right", "data-content": "Vivamus sagittis lacus vel augue laoreet rutrum faucibus.", "data-original-title": "", title: ""}, "Right" ) ); jQuery(".bs-example-popovers button").popover(); } }); examples.buttonsCheckbox = code({ group: "Buttons", label: "Checkbox", links: ["http://getbootstrap.com/javascript/#buttons"], example : function(html) { html.div({ style: "padding-bottom: 24px;"}, html.div({ klass: "btn-group", "data-toggle": "buttons"}, html.label({ klass: "btn btn-primary"}, html.input({ type: "checkbox"}), "Option 1" ), html.label({ klass: "btn btn-primary"}, html.input({ type: "checkbox"}), "Option 2" ), html.label({ klass: "btn btn-primary"}, html.input({ type: "checkbox"}), "Option 3" ) ) ); } }); examples.buttonsRadio= code({ group: "Buttons", label: "Radio", links: ["http://getbootstrap.com/javascript/#buttons"], example : function(html) { html.div({ style: "padding-bottom: 24px;"}, html.div({ klass: "btn-group", "data-toggle": "buttons"}, html.label({ klass: "btn btn-primary"}, html.input({ type: "radio"}), "Option 1" ), html.label({ klass: "btn btn-primary"}, html.input({ type: "radio"}), "Option 2" ), html.label({ klass: "btn btn-primary"}, html.input({ type: "radio"}), "Option 3" ) ) ); } }); examples.collapse = code({ group: "Collapse", label: "Collapse", links: ["http://getbootstrap.com/javascript/#collapse"], example : function(html) { html.div({ klass: "panel-group", id: "accordion"}, html.div({ klass: "panel panel-default"}, html.div({ klass: "panel-heading"}, html.h4({ klass: "panel-title"}, html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseOne"}, "Heading #1" ) ) ), html.div({ id: "collapseOne", klass: "panel-collapse collapse in"}, html.div({ klass: "panel-body"}, "Content" ) ) ), html.div({ klass: "panel panel-default"}, html.div({ klass: "panel-heading"}, html.h4({ klass: "panel-title"}, html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseTwo"}, "Heading #2" ) ) ), html.div({ id: "collapseTwo", klass: "panel-collapse collapse"}, html.div({ klass: "panel-body"}, "Content" ) ) ), html.div({ klass: "panel panel-default"}, html.div({ klass: "panel-heading"}, html.h4({ klass: "panel-title"}, html.a({ "data-toggle": "collapse", "data-parent": "#accordion", href: "#collapseThree"}, "Heading #2" ) ) ), html.div({ id: "collapseThree", klass: "panel-collapse collapse"}, html.div({ klass: "panel-body"}, "Content" ) ) ) ); } }); return examples; });
foretagsplatsen/widget-js
sample/bootstrap/javascriptExamples.js
JavaScript
mit
10,606
module.exports = require('./lib/dustjs-browserify');
scottbrady/dustjs-browserify
index.js
JavaScript
mit
52
version https://git-lfs.github.com/spec/v1 oid sha256:94e212e6fc0c837cd9fff7fca8feff0187a0a22a97c7bd4c6d8f05c5cc358519 size 3077
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.16.0/scrollview-list/scrollview-list.js
JavaScript
mit
129
import React from 'react' import Icon from 'react-icon-base' const IoTshirtOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m11.4 6.7l-8.1 2.4 0.8 2.5 3.1-0.3 3-0.4-0.2 3-1.1 19.9h17.2l-1.1-19.9-0.2-3 3 0.4 3.1 0.3 0.8-2.5-8.1-2.4c-0.5 0.6-1 1.1-1.6 1.5-1.2 0.8-2.7 1.2-4.5 1.2-2.7-0.1-4.6-0.9-6.1-2.7z m11.1-2.9l12.5 3.7-2.5 6.9-5-0.6 1.3 22.5h-22.5l1.2-22.5-5 0.6-2.5-6.9 12.5-3.7c1.1 2.1 2.4 3 5 3.1 2.6 0 3.9-1 5-3.1z"/></g> </Icon> ) export default IoTshirtOutline
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/io/tshirt-outline.js
JavaScript
mit
511
declare module "react-apollo" { declare function graphql(query: Object, options: Object): Function; }
NewSpring/apollos-core
.types/react-apollo.js
JavaScript
mit
104
/* * deferred.js * * Copyright 2011, HeavyLifters Network Ltd. All rights reserved. */ ;(function() { var DeferredAPI = { deferred: deferred, all: all, Deferred: Deferred, DeferredList: DeferredList, wrapResult: wrapResult, wrapFailure: wrapFailure, Failure: Failure } // CommonJS module support if (typeof module !== 'undefined') { var DeferredURLRequest = require('./DeferredURLRequest') for (var k in DeferredURLRequest) { DeferredAPI[k] = DeferredURLRequest[k] } module.exports = DeferredAPI } // Browser API else if (typeof window !== 'undefined') { window.deferred = DeferredAPI } // Fake out console if necessary if (typeof console === 'undefined') { var global = function() { return this || (1,eval)('this') } ;(function() { var noop = function(){} global().console = { log: noop, warn: noop, error: noop, dir: noop } }()) } function wrapResult(result) { return new Deferred().resolve(result) } function wrapFailure(error) { return new Deferred().reject(error) } function Failure(v) { this.value = v } // Crockford style constructor function deferred(t) { return new Deferred(t) } function Deferred(canceller) { this.called = false this.running = false this.result = null this.pauseCount = 0 this.callbacks = [] this.verbose = false this._canceller = canceller // If this Deferred is cancelled and the creator of this Deferred // didn't cancel it, then they may not know about the cancellation and // try to resolve or reject it as well. This flag causes the // "already called" error that resolve() or reject() normally throws // to be suppressed once. this._suppressAlreadyCalled = false } if (typeof Object.defineProperty === 'function') { var _consumeThrownExceptions = true Object.defineProperty(Deferred, 'consumeThrownExceptions', { enumerable: false, set: function(v) { _consumeThrownExceptions = v }, get: function() { return _consumeThrownExceptions } }) } else { Deferred.consumeThrownExceptions = true } Deferred.prototype.cancel = function() { if (!this.called) { if (typeof this._canceller === 'function') { this._canceller(this) } else { this._suppressAlreadyCalled = true } if (!this.called) { this.reject('cancelled') } } else if (this.result instanceof Deferred) { this.result.cancel() } } Deferred.prototype.then = function(callback, errback) { this.callbacks.push({callback: callback, errback: errback}) if (this.called) _run(this) return this } Deferred.prototype.fail = function(errback) { this.callbacks.push({callback: null, errback: errback}) if (this.called) _run(this) return this } Deferred.prototype.both = function(callback) { return this.then(callback, callback) } Deferred.prototype.resolve = function(result) { _startRun(this, result) return this } Deferred.prototype.reject = function(err) { if (!(err instanceof Failure)) { err = new Failure(err) } _startRun(this, err) return this } Deferred.prototype.pause = function() { this.pauseCount += 1 if (this.extra) { console.log('Deferred.pause ' + this.pauseCount + ': ' + this.extra) } return this } Deferred.prototype.unpause = function() { this.pauseCount -= 1 if (this.extra) { console.log('Deferred.unpause ' + this.pauseCount + ': ' + this.extra) } if (this.pauseCount <= 0 && this.called) { _run(this) } return this } // For debugging Deferred.prototype.inspect = function(extra, cb) { this.extra = extra var self = this return this.then(function(r) { console.log('Deferred.inspect resolved: ' + self.extra) console.dir(r) return r }, function(e) { console.log('Deferred.inspect rejected: ' + self.extra) console.dir(e) return e }) } /// A couple of sugary methods Deferred.prototype.thenReturn = function(result) { return this.then(function(_) { return result }) } Deferred.prototype.thenCall = function(f) { return this.then(function(result) { f(result) return result }) } Deferred.prototype.failReturn = function(result) { return this.fail(function(_) { return result }) } Deferred.prototype.failCall = function(f) { return this.fail(function(result) { f(result) return result }) } function _continue(d, newResult) { d.result = newResult d.unpause() return d.result } function _nest(outer) { outer.result.both(function(newResult) { return _continue(outer, newResult) }) } function _startRun(d, result) { if (d.called) { if (d._suppressAlreadyCalled) { d._suppressAlreadyCalled = false return } throw new Error("Already resolved Deferred: " + d) } d.called = true d.result = result if (d.result instanceof Deferred) { d.pause() _nest(d) return } _run(d) } function _run(d) { if (d.running) return var link, status, fn if (d.pauseCount > 0) return while (d.callbacks.length > 0) { link = d.callbacks.shift() status = (d.result instanceof Failure) ? 'errback' : 'callback' fn = link[status] if (typeof fn !== 'function') continue try { d.running = true d.result = fn(d.result) d.running = false if (d.result instanceof Deferred) { d.pause() _nest(d) return } } catch (e) { if (Deferred.consumeThrownExceptions) { d.running = false var f = new Failure(e) f.source = f.source || status d.result = f if (d.verbose) { console.warn('uncaught error in deferred ' + status + ': ' + e.message) console.warn('Stack: ' + e.stack) } } else { throw e } } } } /// DeferredList / all function all(ds, opts) { return new DeferredList(ds, opts) } function DeferredList(ds, opts) { opts = opts || {} Deferred.call(this) this._deferreds = ds this._finished = 0 this._length = ds.length this._results = [] this._fireOnFirstResult = opts.fireOnFirstResult this._fireOnFirstError = opts.fireOnFirstError this._consumeErrors = opts.consumeErrors this._cancelDeferredsWhenCancelled = opts.cancelDeferredsWhenCancelled if (this._length === 0 && !this._fireOnFirstResult) { this.resolve(this._results) } for (var i = 0, n = this._length; i < n; ++i) { ds[i].both(deferredListCallback(this, i)) } } if (typeof Object.create === 'function') { DeferredList.prototype = Object.create(Deferred.prototype, { constructor: { value: DeferredList, enumerable: false } }) } else { DeferredList.prototype = new Deferred() DeferredList.prototype.constructor = DeferredList } DeferredList.prototype.cancelDeferredsWhenCancelled = function() { this._cancelDeferredsWhenCancelled = true } var _deferredCancel = Deferred.prototype.cancel DeferredList.prototype.cancel = function() { _deferredCancel.call(this) if (this._cancelDeferredsWhenCancelled) { for (var i = 0; i < this._length; ++i) { this._deferreds[i].cancel() } } } function deferredListCallback(d, i) { return function(result) { var isErr = result instanceof Failure , myResult = (isErr && d._consumeErrors) ? null : result // Support nesting if (result instanceof Deferred) { result.both(deferredListCallback(d, i)) return } d._results[i] = myResult d._finished += 1 if (!d.called) { if (d._fireOnFirstResult && !isErr) { d.resolve(result) } else if (d._fireOnFirstError && isErr) { d.reject(result) } else if (d._finished === d._length) { d.resolve(d._results) } } return myResult } } }())
heavylifters/deferred-js
lib/deferred.js
JavaScript
mit
8,895
'use strict'; var request = require('request'); var querystring = require('querystring'); var FirebaseError = require('./error'); var RSVP = require('rsvp'); var _ = require('lodash'); var logger = require('./logger'); var utils = require('./utils'); var responseToError = require('./responseToError'); var refreshToken; var commandScopes; var scopes = require('./scopes'); var CLI_VERSION = require('../package.json').version; var _request = function(options) { logger.debug('>>> HTTP REQUEST', options.method, options.url, options.body || options.form || '' ); return new RSVP.Promise(function(resolve, reject) { var req = request(options, function(err, response, body) { if (err) { return reject(new FirebaseError('Server Error. ' + err.message, { original: err, exit: 2 })); } logger.debug('<<< HTTP RESPONSE', response.statusCode, response.headers); if (response.statusCode >= 400) { logger.debug('<<< HTTP RESPONSE BODY', response.body); if (!options.resolveOnHTTPError) { return reject(responseToError(response, body, options)); } } return resolve({ status: response.statusCode, response: response, body: body }); }); if (_.size(options.files) > 0) { var form = req.form(); _.forEach(options.files, function(details, param) { form.append(param, details.stream, { knownLength: details.knownLength, filename: details.filename, contentType: details.contentType }); }); } }); }; var _appendQueryData = function(path, data) { if (data && _.size(data) > 0) { path += _.includes(path, '?') ? '&' : '?'; path += querystring.stringify(data); } return path; }; var api = { // "In this context, the client secret is obviously not treated as a secret" // https://developers.google.com/identity/protocols/OAuth2InstalledApp billingOrigin: utils.envOverride('FIREBASE_BILLING_URL', 'https://cloudbilling.googleapis.com'), clientId: utils.envOverride('FIREBASE_CLIENT_ID', '563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com'), clientSecret: utils.envOverride('FIREBASE_CLIENT_SECRET', 'j9iVZfS8kkCEFUPaAeJV0sAi'), cloudloggingOrigin: utils.envOverride('FIREBASE_CLOUDLOGGING_URL', 'https://logging.googleapis.com'), adminOrigin: utils.envOverride('FIREBASE_ADMIN_URL', 'https://admin.firebase.com'), apikeysOrigin: utils.envOverride('FIREBASE_APIKEYS_URL', 'https://apikeys.googleapis.com'), appengineOrigin: utils.envOverride('FIREBASE_APPENGINE_URL', 'https://appengine.googleapis.com'), authOrigin: utils.envOverride('FIREBASE_AUTH_URL', 'https://accounts.google.com'), consoleOrigin: utils.envOverride('FIREBASE_CONSOLE_URL', 'https://console.firebase.google.com'), deployOrigin: utils.envOverride('FIREBASE_DEPLOY_URL', utils.envOverride('FIREBASE_UPLOAD_URL', 'https://deploy.firebase.com')), functionsOrigin: utils.envOverride('FIREBASE_FUNCTIONS_URL', 'https://cloudfunctions.googleapis.com'), googleOrigin: utils.envOverride('FIREBASE_TOKEN_URL', utils.envOverride('FIREBASE_GOOGLE_URL', 'https://www.googleapis.com')), hostingOrigin: utils.envOverride('FIREBASE_HOSTING_URL', 'https://firebaseapp.com'), realtimeOrigin: utils.envOverride('FIREBASE_REALTIME_URL', 'https://firebaseio.com'), rulesOrigin: utils.envOverride('FIREBASE_RULES_URL', 'https://firebaserules.googleapis.com'), runtimeconfigOrigin: utils.envOverride('FIREBASE_RUNTIMECONFIG_URL', 'https://runtimeconfig.googleapis.com'), setToken: function(token) { refreshToken = token; }, setScopes: function(s) { commandScopes = _.uniq(_.flatten([ scopes.EMAIL, scopes.OPENID, scopes.CLOUD_PROJECTS_READONLY, scopes.FIREBASE_PLATFORM ].concat(s || []))); logger.debug('> command requires scopes:', JSON.stringify(commandScopes)); }, getAccessToken: function() { return require('./auth').getAccessToken(refreshToken, commandScopes); }, addRequestHeaders: function(reqOptions) { // Runtime fetch of Auth singleton to prevent circular module dependencies _.set(reqOptions, ['headers', 'User-Agent'], 'FirebaseCLI/' + CLI_VERSION); var auth = require('../lib/auth'); return auth.getAccessToken(refreshToken, commandScopes).then(function(result) { _.set(reqOptions, 'headers.authorization', 'Bearer ' + result.access_token); return reqOptions; }); }, request: function(method, resource, options) { options = _.extend({ data: {}, origin: api.adminOrigin, // default to hitting the admin backend resolveOnHTTPError: false, // by default, status codes >= 400 leads to reject json: true }, options); var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; if (validMethods.indexOf(method) < 0) { method = 'GET'; } var reqOptions = { method: method }; if (options.query) { resource = _appendQueryData(resource, options.query); } if (method === 'GET') { resource = _appendQueryData(resource, options.data); } else { if (_.size(options.data) > 0) { reqOptions.body = options.data; } else if (_.size(options.form) > 0) { reqOptions.form = options.form; } } reqOptions.url = options.origin + resource; reqOptions.files = options.files; reqOptions.resolveOnHTTPError = options.resolveOnHTTPError; reqOptions.json = options.json; if (options.auth === true) { return api.addRequestHeaders(reqOptions).then(function(reqOptionsWithToken) { return _request(reqOptionsWithToken); }); } return _request(reqOptions); }, getProject: function(projectId) { return api.request('GET', '/v1/projects/' + encodeURIComponent(projectId), { auth: true }).then(function(res) { if (res.body && !res.body.error) { return res.body; } return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', { context: res, exit: 2 })); }); }, getProjects: function() { return api.request('GET', '/v1/projects', { auth: true }).then(function(res) { if (res.body && res.body.projects) { return res.body.projects; } return RSVP.reject(new FirebaseError('Server Error: Unexpected Response. Please try again', { context: res, exit: 2 })); }); } }; module.exports = api;
CharlesSanford/personal-site
node_modules/firebase-tools/lib/api.js
JavaScript
mit
6,556
/**! * urllib - test/fixtures/server.js * * Copyright(c) 2011 - 2014 fengmk2 and other contributors. * MIT Licensed * * Authors: * fengmk2 <[email protected]> (http://fengmk2.github.com) */ "use strict"; /** * Module dependencies. */ var should = require('should'); var http = require('http'); var querystring = require('querystring'); var fs = require('fs'); var zlib = require('zlib'); var iconv = require('iconv-lite'); var server = http.createServer(function (req, res) { // req.headers['user-agent'].should.match(/^node\-urllib\/\d+\.\d+\.\d+ node\//); var chunks = []; var size = 0; req.on('data', function (buf) { chunks.push(buf); size += buf.length; }); req.on('end', function () { if (req.url === '/timeout') { return setTimeout(function () { res.end('timeout 500ms'); }, 500); } else if (req.url === '/response_timeout') { res.write('foo'); return setTimeout(function () { res.end('timeout 700ms'); }, 700); } else if (req.url === '/error') { return res.destroy(); } else if (req.url === '/socket.destroy') { res.write('foo haha\n'); setTimeout(function () { res.write('foo haha 2'); setTimeout(function () { res.destroy(); }, 300); }, 200); return; } else if (req.url === '/socket.end') { res.write('foo haha\n'); setTimeout(function () { res.write('foo haha 2'); setTimeout(function () { // res.end(); res.socket.end(); // res.socket.end('foosdfsdf'); }, 300); }, 200); return; } else if (req.url === '/socket.end.error') { res.write('foo haha\n'); setTimeout(function () { res.write('foo haha 2'); setTimeout(function () { res.socket.end('balabala'); }, 300); }, 200); return; } else if (req.url === '/302') { res.statusCode = 302; res.setHeader('Location', '/204'); return res.end('Redirect to /204'); } else if (req.url === '/301') { res.statusCode = 301; res.setHeader('Location', '/204'); return res.end('I am 301 body'); } else if (req.url === '/303') { res.statusCode = 303; res.setHeader('Location', '/204'); return res.end('Redirect to /204'); } else if (req.url === '/307') { res.statusCode = 307; res.setHeader('Location', '/204'); return res.end('I am 307 body'); } else if (req.url === '/redirect_no_location') { res.statusCode = 302; return res.end('I am 302 body'); } else if (req.url === '/204') { res.statusCode = 204; return res.end(); } else if (req.url === '/loop_redirect') { res.statusCode = 302; res.setHeader('Location', '/loop_redirect'); return res.end('Redirect to /loop_redirect'); } else if (req.url === '/post') { res.setHeader('X-Request-Content-Type', req.headers['content-type'] || ''); res.writeHeader(200); return res.end(Buffer.concat(chunks)); } else if (req.url.indexOf('/get') === 0) { res.writeHeader(200); return res.end(req.url); } else if (req.url === '/wrongjson') { res.writeHeader(200); return res.end(new Buffer('{"foo":""')); } else if (req.url === '/wrongjson-gbk') { res.setHeader('content-type', 'application/json; charset=gbk'); res.writeHeader(200); return res.end(fs.readFileSync(__filename)); } else if (req.url === '/writestream') { var s = fs.createReadStream(__filename); return s.pipe(res); } else if (req.url === '/auth') { var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString().split(':'); res.writeHeader(200); return res.end(JSON.stringify({user: auth[0], password: auth[1]})); } else if (req.url === '/stream') { res.writeHeader(200, { 'Content-Length': String(size) }); for (var i = 0; i < chunks.length; i++) { res.write(chunks[i]); } res.end(); return; } else if (req.url.indexOf('/json_mirror') === 0) { res.setHeader('Content-Type', req.headers['content-type'] || 'application/json'); if (req.method === 'GET') { res.end(JSON.stringify({ url: req.url, data: Buffer.concat(chunks).toString(), })); } else { res.end(JSON.stringify(JSON.parse(Buffer.concat(chunks)))); } return; } else if (req.url.indexOf('/no-gzip') === 0) { fs.createReadStream(__filename).pipe(res); return; } else if (req.url.indexOf('/gzip') === 0) { res.setHeader('Content-Encoding', 'gzip'); fs.createReadStream(__filename).pipe(zlib.createGzip()).pipe(res); return; } else if (req.url === '/ua') { res.end(JSON.stringify(req.headers)); return; } else if (req.url === '/gbk/json') { res.setHeader('Content-Type', 'application/json;charset=gbk'); var content = iconv.encode(JSON.stringify({hello: '你好'}), 'gbk'); return res.end(content); } else if (req.url === '/gbk/text') { res.setHeader('Content-Type', 'text/plain;charset=gbk'); var content = iconv.encode('你好', 'gbk'); return res.end(content); } else if (req.url === '/errorcharset') { res.setHeader('Content-Type', 'text/plain;charset=notfound'); return res.end('你好'); } var url = req.url.split('?'); var get = querystring.parse(url[1]); var ret; if (chunks.length > 0) { ret = Buffer.concat(chunks).toString(); } else { ret = '<html><head><meta http-equiv="Content-Type" content="text/html;charset=##{charset}##">...</html>'; } chunks = []; res.writeHead(get.code ? get.code : 200, { 'Content-Type': 'text/html', }); res.end(ret.replace('##{charset}##', get.charset ? get.charset : '')); }); }); module.exports = server;
pmq20/urllib
test/fixtures/server.js
JavaScript
mit
5,950
/** * @license Highcharts JS v8.2.2 (2020-10-22) * @module highcharts/modules/funnel3d * @requires highcharts * @requires highcharts/highcharts-3d * @requires highcharts/modules/cylinder * * Highcharts funnel module * * (c) 2010-2019 Kacper Madej * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/Funnel3DSeries.js';
cdnjs/cdnjs
ajax/libs/highcharts/8.2.2/es-modules/masters/modules/funnel3d.src.js
JavaScript
mit
357
FusionCharts.ready(function () { var gradientCheckBox = document.getElementById('useGradient'); //Set event listener for radio button if (gradientCheckBox.addEventListener) { gradientCheckBox.addEventListener("click", changeGradient); } function changeGradient(evt, obj) { //Set gradient fill for chart using usePlotGradientColor attribute (gradientCheckBox.checked) ?revenueChart.setChartAttribute('usePlotGradientColor', 1) : revenueChart.setChartAttribute('usePlotGradientColor', 0); }; var revenueChart = new FusionCharts({ type: 'column2d', renderAt: 'chart-container', width: '400', height: '300', dataFormat: 'json', dataSource: { "chart": { "caption": "Quarterly Revenue", "subCaption": "Last year", "xAxisName": "Quarter", "yAxisName": "Amount (In USD)", "theme": "fint", "numberPrefix": "$", //Removing default gradient fill from columns "usePlotGradientColor": "1" }, "data": [{ "label": "Q1", "value": "1950000", "color": "#008ee4" }, { "label": "Q2", "value": "1450000", "color": "#9b59b6" }, { "label": "Q3", "value": "1730000", "color": "#6baa01" }, { "label": "Q4", "value": "2120000", "color": "#e44a00" }] } }).render(); });
sguha-work/fiddletest
backup/fiddles/Chart/Data_plots/Configuring_gradient_fill_for_columns_in_column_charts/demo.js
JavaScript
gpl-2.0
1,726
/*! * address.js - Description * Copyright © 2012 by Ingenesis Limited. All rights reserved. * Licensed under the GPLv3 {@see license.txt} */ (function($) { jQuery.fn.upstate = function () { if ( typeof regions === 'undefined' ) return; $(this).change(function (e,init) { var $this = $(this), prefix = $this.attr('id').split('-')[0], country = $this.val(), state = $this.parents().find('#' + prefix + '-state'), menu = $this.parents().find('#' + prefix + '-state-menu'), options = '<option value=""></option>'; if (menu.length == 0) return true; if (menu.hasClass('hidden')) menu.removeClass('hidden').hide(); if (regions[country] || (init && menu.find('option').length > 1)) { state.setDisabled(true).addClass('_important').hide(); if (regions[country]) { $.each(regions[country], function (value,label) { options += '<option value="'+value+'">'+label+'</option>'; }); if (!init) menu.empty().append(options).setDisabled(false).show().focus(); if (menu.hasClass('auto-required')) menu.addClass('required'); } else { if (menu.hasClass('auto-required')) menu.removeClass('required'); } menu.setDisabled(false).show(); $('label[for='+state.attr('id')+']').attr('for',menu.attr('id')); } else { menu.empty().setDisabled(true).hide(); state.setDisabled(false).show().removeClass('_important'); $('label[for='+menu.attr('id')+']').attr('for',state.attr('id')); if (!init) state.val('').focus(); } }).trigger('change',[true]); return $(this); }; })(jQuery); jQuery(document).ready(function($) { var sameaddr = $('.sameaddress'), shipFields = $('#shipping-address-fields'), billFields = $('#billing-address-fields'), keepLastValue = function () { // Save the current value of the field $(this).attr('data-last', $(this).val()); }; // Handle changes to the firstname and lastname fields $('#firstname,#lastname').each(keepLastValue).change(function () { var namefield = $(this); // Reference to the modified field lastfirstname = $('#firstname').attr('data-last'), lastlastname = $('#lastname').attr('data-last'), firstlast = ( ( $('#firstname').val() ).trim() + " " + ( $('#lastname').val() ).trim() ).trim(); namefield.val( (namefield.val()).trim() ); // Update the billing name and shipping name $('#billing-name,#shipping-name').each(function() { var value = $(this).val(); if ( value.trim().length == 0 ) { // Empty billing or shipping name $('#billing-name,#shipping-name').val(firstlast); } else if ( '' != value && ( $('#firstname').val() == value || $('#lastname').val() == value ) ) { // Only one name entered (so far), add the other name $(this).val(firstlast); } else if ( 'firstname' == namefield.attr('id') && value.indexOf(lastlastname) != -1 ) { // firstname changed & last lastname matched $(this).val( value.replace(lastfirstname, namefield.val()).trim() ); } else if ( 'lastname' == namefield.attr('id') && value.indexOf(lastfirstname) != -1 ) { // lastname changed & last firstname matched $(this).val( value.replace(lastlastname, namefield.val()).trim() ); } }); }).change(keepLastValue); // Update state/province $('#billing-country,#shipping-country').upstate(); // Toggle same shipping address sameaddr.change(function (e,init) { var refocus = false, bc = $('#billing-country'), sc = $('#shipping-country'), prime = 'billing' == sameaddr.val() ? shipFields : billFields, alt = 'shipping' == sameaddr.val() ? shipFields : billFields; if (sameaddr.is(':checked')) { prime.removeClass('half'); alt.hide().find('.required').setDisabled(true); } else { prime.addClass('half'); alt.show().find('.disabled:not(._important)').setDisabled(false); if (!init) refocus = true; } if (bc.is(':visible')) bc.trigger('change.localemenu',[init]); if (sc.is(':visible')) sc.trigger('change.localemenu',[init]); if (refocus) alt.find('input:first').focus(); }).trigger('change',[true]) .click(function () { $(this).change(); }); // For IE compatibility });
sharpmachine/whiteantelopestudio.com
wp-content/plugins/shopp/core/ui/behaviors/address.js
JavaScript
gpl-2.0
4,137
var EFA = { log: [], /* Prevent backspace being used as back button in infopath form in modal. Source: http://johnliu.net/blog/2012/3/27/infopath-disabling-backspace-key-in-browser-form.html grab a reference to the modal window object in SharePoint */ OpenPopUpPage: function( url ){ var options = SP.UI.$create_DialogOptions(); options.url = url; var w = SP.UI.ModalDialog.showModalDialog(options); /* Attempt to prevent backspace acting as navigation key on read only input - Doesn't currently work. if (w) { // get the modal window's iFrame element var f = w.get_frameElement(); EFA.f = f; // watch frame's readyState change - when page load is complete, re-attach keydown event // on the new document $(f).ready(function(){ var fwin = this.contentWindow || this.contentDocument; $(fwin.document).on('focus',"input[readonly]",function(){ $(this).blur(); }); }); }*/ }, // get current user checkCurrentUser: function (callback){ ExecuteOrDelayUntilScriptLoaded(checkCurrentUserLoaded, "sp.js"); function checkCurrentUserLoaded() { var context = SP.ClientContext.get_current(); var siteColl = context.get_site(); var web = siteColl.get_rootWeb(); this._currentUser = web.get_currentUser(); context.load(this._currentUser); context.executeQueryAsync(Function.createDelegate(this, callback),Function.createDelegate(this, callback)); } }, CheckUserSucceeded: function(){ EFA['User'] = this._currentUser; }, CheckUserfailed: function(){ //console.log('Failed to get user'); }, DoesUserHaveCreatePermissions: function(url, callback) { var Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\ <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <soap:Body>\ <DoesCurrentUserHavePermissionsToList xmlns=\"http://tempuri.org/\">\ <url>"+ url +"</url>\ </DoesCurrentUserHavePermissionsToList>\ </soap:Body>\ </soap:Envelope>"; $.ajax({ url: "/_layouts/EFA/EFAWebServices.asmx", type: "POST", dataType: "xml", data: Xml, complete: function(xData, Status){ if(Status != 'success') throw "Failed to determine user permissions for " + url; callback(xData); }, contentType: "text/xml; charset=\"utf-8\"" }); } }; /* To access the mapping need to uses keys, therefore need to check if its available for browser and add it if not. Then we can loop through the mapping like so: $.each(keys(config.mapping), function(){ console.log(config.mapping[this.toString()]) }); using this to build the query and create the resultant html */ // SOURCE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object'); var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) result.push(prop); } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]); } } return result; }; })(); } /* Array.indexOf for IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { 'use strict'; if (this == null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } /* Test for Canvas Suppport Source: http://stackoverflow.com/questions/2745432/best-way-to-detect-that-html5-canvas-is-not-supported/2746983#2746983 */ function isCanvasSupported(){ var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); } /* Console.log() for IE 8 */ (function() { if (!window.console) { window.console = {}; } // union of Chrome, FF, IE, and Safari console methods var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; // define undefined methods as noops to prevent errors for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } })();
jwykeham/SharePoint-Bootstrap3-Master
TwitterBootstrapMasterPage/pkg/Debug/TwitterBootstrapMasterPage/Layouts/TB/js/helper.js
JavaScript
gpl-2.0
5,718
var mysql_wn_data_noun_quantity = { "morsel":[["noun.quantity"],["morsel","small indefinite quantity"]], "section":[["noun.quantity","noun.group","noun.location","verb.contact:section","noun.group"],["section","square mile","section2","team","platoon1","section1","area1","section4","discussion section","class3"]], "mate":[["noun.quantity","noun.person","noun.person","adj.all:friendly1^matey","noun.location:Australia","noun.location:Britain","noun.person","verb.contact:mate","noun.Tops:animal"],["mate","fellow","singleton","couple","mate2","first mate","officer4","mate3","friend","mate1"]], "exposure":[["noun.quantity","verb.perception:expose1"],["exposure","light unit"]], "parking":[["noun.quantity","verb.contact:park"],["parking","room"]], "shtik":[["noun.quantity","noun.communication:Yiddish"],["shtik","shtick","schtik","schtick","small indefinite quantity"]], "basket":[["noun.quantity","noun.artifact","noun.person:basketeer"],["basket","basketful","containerful","basket1","basketball hoop","hoop3","goal","basketball equipment"]], "correction":[["noun.quantity","noun.communication"],["correction","fudge factor","indefinite quantity","correction1","editing"]], "footstep":[["noun.quantity","verb.change:pace","verb.motion:pace1","verb.motion:pace","verb.change:step","verb.motion:step3","verb.motion:step1","verb.motion:step","verb.motion:stride3","verb.motion:stride"],["footstep","pace1","step","stride","indefinite quantity"]], "addition":[["noun.quantity","verb.change:increase2","verb.change:increase"],["addition","increase","gain","indefinite quantity"]], "circulation":[["noun.quantity","verb.motion:circulate3","noun.quantity","noun.cognition:library science"],["circulation","count","circulation1","count"]], "breakage":[["noun.quantity"],["breakage","indefinite quantity"]], "craps":[["noun.quantity"],["craps","snake eyes","two"]], "utility":[["noun.quantity","noun.cognition:economics"],["utility","system of measurement"]], "blood count":[["noun.quantity"],["blood count","count"]], "sperm count":[["noun.quantity"],["sperm count","count"]], "eyedrop":[["noun.quantity"],["eyedrop","eye-drop","drop"]], "picking":[["noun.quantity","verb.contact:pick1"],["picking","pick","output"]], "capacity":[["noun.quantity","adj.all:large^capacious","verb.stative:contain13"],["capacity","content","volume"]], "pitcher":[["noun.quantity"],["pitcher","pitcherful","containerful"]], "tankage":[["noun.quantity"],["tankage","indefinite quantity"]], "nip":[["noun.quantity","verb.contact","noun.act:nip1"],["nip","shot","small indefinite quantity","nip2","bite"]], "headroom":[["noun.quantity"],["headroom","headway","clearance","room"]], "population":[["noun.quantity","noun.group","noun.Tops:group"],["population","integer","population1"]], "nit":[["noun.quantity"],["nit","luminance unit"]], "quetzal":[["noun.quantity"],["quetzal","Guatemalan monetary unit"]], "lari":[["noun.quantity"],["lari","Georgian monetary unit"]], "agora":[["noun.quantity"],["agora","shekel","Israeli monetary unit"]], "barn":[["noun.quantity","noun.cognition:atomic physics"],["barn","b","area unit"]], "barrow":[["noun.quantity"],["barrow","barrowful","containerful"]], "basin":[["noun.quantity"],["basin","basinful","containerful"]], "bit":[["noun.quantity","noun.artifact","noun.artifact"],["bit","unit of measurement","byte","bit1","stable gear","bridle","bit2","part","key"]], "carton":[["noun.quantity"],["carton","cartonful","containerful"]], "cordage":[["noun.quantity","noun.Tops:measure"],["cordage"]], "cutoff":[["noun.quantity"],["cutoff","limit"]], "dustpan":[["noun.quantity"],["dustpan","dustpanful","containerful"]], "firkin":[["noun.quantity"],["firkin","British capacity unit","kilderkin"]], "flask":[["noun.quantity"],["flask","flaskful","containerful"]], "frail":[["noun.quantity"],["frail","weight unit"]], "keg":[["noun.quantity"],["keg","kegful","containerful"]], "kettle":[["noun.quantity","noun.artifact","noun.person:tympanist","noun.person:timpanist","noun.person:tympanist","noun.person:timpanist","adj.pert:tympanic1","noun.person:timpanist"],["kettle","kettleful","containerful","kettle1","kettledrum","tympanum","tympani","timpani","percussion instrument"]], "load":[["noun.quantity","noun.artifact","verb.contact","noun.artifact:load","noun.artifact:load2","noun.person:loader","noun.act:loading","noun.artifact:lading","verb.change:fill1","verb.possession","noun.cognition:computer science","verb.contact","noun.artifact:load1","noun.person:loader1","noun.artifact:charge","verb.change:fill1","verb.contact","noun.artifact:load2","noun.artifact:load","noun.person:loader","noun.act:loading"],["load","loading","indefinite quantity","load3","electrical device","load1","lade1","laden1","load up","frames:1","21","load12","transfer1","load2","charge2","load10","put"]], "reservoir":[["noun.quantity","noun.artifact","noun.object:lake"],["reservoir","supply","reservoir1","artificial lake","man-made lake","water system"]], "seventy-eight":[["noun.quantity"],["seventy-eight","78\"","LXXVIII","large integer"]], "sextant":[["noun.quantity","noun.attribute:circumference1"],["sextant","angular unit"]], "singleton":[["noun.quantity"],["singleton","one"]], "skeleton":[["noun.quantity"],["skeleton","minimum"]], "standard":[["noun.quantity","verb.change:standardize","verb.change:standardise"],["standard","volume unit"]], "teacup":[["noun.quantity"],["teacup","teacupful","containerful"]], "thimble":[["noun.quantity"],["thimble","thimbleful","containerful"]], "tub":[["noun.quantity"],["tub","tubful","containerful"]], "twenty-two":[["noun.quantity"],["twenty-two","22\"","XXII","large integer"]], "yard":[["noun.quantity","verb.change:pace","noun.location","noun.artifact","noun.location:field","noun.artifact","noun.location:tract"],["yard","pace","linear unit","fathom1","chain","rod1","lea","yard1","tract","yard2","grounds","curtilage","yard3","railway yard","railyard"]], "yarder":[["noun.quantity","noun.communication:combining form"],["yarder","linear unit"]], "common denominator":[["noun.quantity"],["common denominator","denominator"]], "volume":[["noun.quantity","adj.all:large^voluminous","noun.Tops:quantity","noun.quantity","noun.Tops:quantity"],["volume","volume1"]], "magnetization":[["noun.quantity","verb.communication:magnetize","verb.change:magnetize","noun.Tops:measure"],["magnetization","magnetisation"]], "precipitation":[["noun.quantity","verb.weather:precipitate"],["precipitation","indefinite quantity"]], "degree":[["noun.quantity","noun.state","noun.Tops:state","noun.quantity"],["degree","arcdegree","angular unit","oxtant","sextant","degree1","level","stage","point","degree3","temperature unit"]], "solubility":[["noun.quantity","adj.all:soluble1","noun.substance:solution"],["solubility","definite quantity"]], "lumen":[["noun.quantity"],["lumen","lm","luminous flux unit"]], "headful":[["noun.quantity"],["headful","containerful"]], "palm":[["noun.quantity","verb.contact:palm"],["palm","linear unit"]], "digit":[["noun.quantity","verb.change:digitize","verb.change:digitise","verb.change:digitalize"],["digit","figure","integer"]], "point system":[["noun.quantity"],["point system","system of measurement"]], "constant":[["noun.quantity"],["constant","number"]], "one":[["noun.quantity"],["one","1\"","I","ace","single","unity","digit"]], "region":[["noun.quantity","noun.location","noun.Tops:location"],["region","neighborhood","indefinite quantity","region1"]], "word":[["noun.quantity","noun.communication","verb.communication:word","noun.communication"],["word","kilobyte","computer memory unit","word3","statement","word6","order3"]], "quota":[["noun.quantity"],["quota","number"]], "dollar":[["noun.quantity","noun.possession"],["dollar","monetary unit","dollar1","coin2"]], "e":[["noun.quantity"],["e","transcendental number"]], "gamma":[["noun.quantity"],["gamma","oersted","field strength unit"]], "pi":[["noun.quantity"],["pi","transcendental number"]], "radical":[["noun.quantity","noun.Tops:measure","noun.cognition:mathematics"],["radical"]], "pascal":[["noun.quantity"],["pascal","Pa","pressure unit"]], "guarani":[["noun.quantity"],["guarani","Paraguayan monetary unit"]], "pengo":[["noun.quantity"],["pengo","Hungarian monetary unit"]], "outage":[["noun.quantity"],["outage","indefinite quantity"]], "couple":[["noun.quantity","verb.contact:couple2","verb.contact:pair3","verb.contact:pair4","verb.contact","noun.artifact:coupler","noun.artifact:coupling"],["couple","pair","twosome","twain","brace","span2","yoke","couplet","distich","duo","duet","dyad","duad","two","couple1","uncouple","couple on","couple up","attach1"]], "yuan":[["noun.quantity"],["yuan","kwai","Chinese monetary unit"]], "battalion":[["noun.quantity","adj.all:incalculable^multitudinous"],["battalion","large number","multitude","plurality1","pack","large indefinite quantity"]], "moiety":[["noun.quantity"],["moiety","mediety","one-half"]], "maximum":[["noun.quantity","verb.change:maximize1","verb.change:maximize","verb.change:maximise1","verb.change:maximise"],["maximum","minimum","upper limit","extremum","large indefinite quantity"]], "minimum":[["noun.quantity","verb.communication:minimize1","verb.communication:minimize","verb.change:minimize","verb.communication:minimise1","verb.change:minimise"],["minimum","maximum","lower limit","extremum","small indefinite quantity"]], "cordoba":[["noun.quantity"],["cordoba","Nicaraguan monetary unit"]], "troy":[["noun.quantity"],["troy","troy weight","system of weights"]], "acre":[["noun.quantity","noun.location"],["acre","area unit","Acre1","district","Brazil"]], "sucre":[["noun.quantity"],["sucre","Ecuadoran monetary unit"]], "tanga":[["noun.quantity"],["tanga","Tajikistani monetary unit"]], "lepton":[["noun.quantity"],["lepton","drachma","Greek monetary unit"]], "ocean":[["noun.quantity","adj.all:unlimited^oceanic"],["ocean","sea","large indefinite quantity"]], "para":[["noun.quantity"],["para","Yugoslavian monetary unit","Yugoslavian dinar"]], "swath":[["noun.quantity","noun.shape:space"],["swath"]], "bel":[["noun.quantity"],["Bel","B3","sound unit"]], "denier":[["noun.quantity"],["denier","unit of measurement"]], "miler":[["noun.quantity","noun.quantity:mile6","noun.quantity:mile5","noun.quantity:mile4","noun.quantity:mile3","noun.quantity:mile2","noun.quantity:mile1","noun.event:mile","noun.communication:combining form"],["miler","linear unit"]], "welterweight":[["noun.quantity","noun.person","noun.person"],["welterweight","weight unit","welterweight1","wrestler","welterweight2","boxer"]], "balboa":[["noun.quantity"],["balboa","Panamanian monetary unit"]], "bolivar":[["noun.quantity"],["bolivar","Venezuelan monetary unit"]], "cicero":[["noun.quantity"],["cicero","linear unit"]], "coulomb":[["noun.quantity"],["coulomb","C","ampere-second","charge unit","abcoulomb","ampere-minute"]], "curie":[["noun.quantity","noun.person"],["curie","Ci","radioactivity unit","Curie1","Pierre Curie","physicist"]], "gauss":[["noun.quantity"],["gauss","flux density unit","tesla"]], "gilbert":[["noun.quantity","noun.person","noun.person","noun.person","adj.pert:gilbertian"],["gilbert","Gb1","Gi","magnetomotive force unit","Gilbert1","Humphrey Gilbert","Sir Humphrey Gilbert","navigator","Gilbert2","William Gilbert","physician","physicist","Gilbert3","William Gilbert1","William S. Gilbert","William Schwenk Gilbert","Sir William Gilbert","librettist","poet"]], "gram":[["noun.quantity"],["gram","gramme","gm","g","metric weight unit","dekagram"]], "henry":[["noun.quantity","noun.person","noun.person"],["henry","H","inductance unit","Henry1","Patrick Henry","American Revolutionary leader","orator","Henry2","William Henry","chemist"]], "joule":[["noun.quantity"],["joule","J","watt second","work unit"]], "kelvin":[["noun.quantity"],["kelvin","K5","temperature unit"]], "lambert":[["noun.quantity"],["lambert","L7","illumination unit"]], "langley":[["noun.quantity"],["langley","unit of measurement"]], "maxwell":[["noun.quantity"],["maxwell","Mx","flux unit","weber"]], "newton":[["noun.quantity"],["newton","N1","force unit","sthene"]], "oersted":[["noun.quantity"],["oersted","field strength unit"]], "ohm":[["noun.quantity","adj.pert:ohmic"],["ohm","resistance unit","megohm"]], "rand":[["noun.quantity"],["rand","South African monetary unit"]], "roentgen":[["noun.quantity"],["roentgen","R","radioactivity unit"]], "rutherford":[["noun.quantity","noun.person"],["rutherford","radioactivity unit","Rutherford1","Daniel Rutherford","chemist"]], "sabin":[["noun.quantity"],["sabin","absorption unit"]], "tesla":[["noun.quantity"],["tesla","flux density unit"]], "watt":[["noun.quantity"],["watt","W","power unit","kilowatt","horsepower"]], "weber":[["noun.quantity","noun.person","noun.person","noun.person","noun.person"],["weber","Wb","flux unit","Weber1","Carl Maria von Weber","Baron Karl Maria Friedrich Ernst von Weber","conductor","composer","Weber2","Max Weber","sociologist","Weber3","Max Weber1","painter","Weber4","Wilhelm Eduard Weber","physicist"]], "scattering":[["noun.quantity","verb.contact:sprinkle1"],["scattering","sprinkling","small indefinite quantity"]], "accretion":[["noun.quantity","adj.all:increasing^accretionary","noun.process","adj.all:increasing^accretionary","noun.cognition:geology","noun.process","adj.all:increasing^accretionary","verb.change:accrete1","noun.cognition:biology","noun.process","adj.all:increasing^accretionary","noun.cognition:astronomy"],["accretion","addition","accretion1","increase","accretion2","increase","accretion3","increase"]], "dividend":[["noun.quantity"],["dividend","number"]], "linage":[["noun.quantity"],["linage","lineage","number"]], "penny":[["noun.quantity"],["penny","fractional monetary unit","Irish pound","British pound"]], "double eagle":[["noun.quantity","noun.act:golf"],["double eagle","score"]], "spoilage":[["noun.quantity"],["spoilage","indefinite quantity"]], "fundamental quantity":[["noun.quantity","noun.Tops:measure"],["fundamental quantity","fundamental measure"]], "definite quantity":[["noun.quantity","noun.Tops:measure"],["definite quantity"]], "indefinite quantity":[["noun.quantity","noun.Tops:measure"],["indefinite quantity"]], "relative quantity":[["noun.quantity","noun.Tops:measure"],["relative quantity"]], "system of measurement":[["noun.quantity","noun.Tops:measure"],["system of measurement","metric"]], "system of weights and measures":[["noun.quantity"],["system of weights and measures","system of measurement"]], "british imperial system":[["noun.quantity"],["British Imperial System","English system","British system","system of weights and measures"]], "metric system":[["noun.quantity"],["metric system","system of weights and measures"]], "cgs":[["noun.quantity"],["cgs","cgs system","metric system"]], "systeme international d'unites":[["noun.quantity"],["Systeme International d'Unites","Systeme International","SI system","SI","SI unit","International System of Units","International System","metric system"]], "united states customary system":[["noun.quantity"],["United States Customary System","system of weights and measures"]], "information measure":[["noun.quantity"],["information measure","system of measurement"]], "bandwidth":[["noun.quantity"],["bandwidth","information measure"]], "baud":[["noun.quantity","noun.cognition:computer science"],["baud","baud rate","information measure"]], "octane number":[["noun.quantity","noun.Tops:measure"],["octane number","octane rating"]], "marginal utility":[["noun.quantity","noun.cognition:economics"],["marginal utility","utility"]], "enough":[["noun.quantity","adj.all:sufficient^enough","adj.all:sufficient","verb.stative:suffice"],["enough","sufficiency","relative quantity"]], "absolute value":[["noun.quantity"],["absolute value","numerical value","definite quantity"]], "acid value":[["noun.quantity","noun.cognition:chemistry"],["acid value","definite quantity"]], "chlorinity":[["noun.quantity"],["chlorinity","definite quantity"]], "quire":[["noun.quantity"],["quire","definite quantity","ream"]], "toxicity":[["noun.quantity","adj.all:toxic"],["toxicity","definite quantity"]], "cytotoxicity":[["noun.quantity"],["cytotoxicity","toxicity"]], "unit of measurement":[["noun.quantity","verb.social:unitize","verb.change:unitize"],["unit of measurement","unit","definite quantity"]], "measuring unit":[["noun.quantity"],["measuring unit","measuring block","unit of measurement"]], "diopter":[["noun.quantity"],["diopter","dioptre","unit of measurement"]], "karat":[["noun.quantity"],["karat","carat2","kt","unit of measurement"]], "decimal":[["noun.quantity","verb.change:decimalize","verb.change:decimalise"],["decimal1","number"]], "avogadro's number":[["noun.quantity"],["Avogadro's number","Avogadro number","constant"]], "boltzmann's constant":[["noun.quantity"],["Boltzmann's constant","constant"]], "coefficient":[["noun.quantity"],["coefficient","constant"]], "absorption coefficient":[["noun.quantity"],["absorption coefficient","coefficient of absorption","absorptance","coefficient"]], "drag coefficient":[["noun.quantity"],["drag coefficient","coefficient of drag","coefficient"]], "coefficient of friction":[["noun.quantity"],["coefficient of friction","coefficient"]], "coefficient of mutual induction":[["noun.quantity"],["coefficient of mutual induction","mutual inductance","coefficient"]], "coefficient of self induction":[["noun.quantity"],["coefficient of self induction","self-inductance","coefficient"]], "modulus":[["noun.quantity","noun.cognition:physics","noun.quantity","noun.quantity"],["modulus","coefficient","modulus1","absolute value","modulus2","integer"]], "coefficient of elasticity":[["noun.quantity","noun.cognition:physics"],["coefficient of elasticity","modulus of elasticity","elastic modulus","modulus"]], "bulk modulus":[["noun.quantity"],["bulk modulus","coefficient of elasticity"]], "modulus of rigidity":[["noun.quantity"],["modulus of rigidity","coefficient of elasticity"]], "young's modulus":[["noun.quantity"],["Young's modulus","coefficient of elasticity"]], "coefficient of expansion":[["noun.quantity"],["coefficient of expansion","expansivity","coefficient"]], "coefficient of reflection":[["noun.quantity"],["coefficient of reflection","reflection factor","reflectance","reflectivity","coefficient"]], "transmittance":[["noun.quantity"],["transmittance","transmission","coefficient"]], "coefficient of viscosity":[["noun.quantity"],["coefficient of viscosity","absolute viscosity","dynamic viscosity","coefficient"]], "cosmological constant":[["noun.quantity"],["cosmological constant","constant"]], "equilibrium constant":[["noun.quantity","noun.cognition:chemistry"],["equilibrium constant","constant"]], "dissociation constant":[["noun.quantity"],["dissociation constant","equilibrium constant"]], "gas constant":[["noun.quantity","noun.cognition:physics"],["gas constant","universal gas constant","R1","constant"]], "gravitational constant":[["noun.quantity","noun.cognition:law of gravitation","noun.cognition:physics"],["gravitational constant","universal gravitational constant","constant of gravitation","G8","constant"]], "hubble's constant":[["noun.quantity","noun.cognition:cosmology"],["Hubble's constant","Hubble constant","Hubble's parameter","Hubble parameter","constant"]], "ionic charge":[["noun.quantity"],["ionic charge","constant"]], "planck's constant":[["noun.quantity"],["Planck's constant","h1","factor of proportionality"]], "oxidation number":[["noun.quantity"],["oxidation number","oxidation state","number"]], "cardinality":[["noun.quantity","noun.cognition:mathematics"],["cardinality","number"]], "body count":[["noun.quantity"],["body count","count"]], "head count":[["noun.quantity"],["head count","headcount","count"]], "pollen count":[["noun.quantity"],["pollen count","count"]], "conversion factor":[["noun.quantity"],["conversion factor","factor1"]], "factor of proportionality":[["noun.quantity"],["factor of proportionality","constant of proportionality","factor1","constant"]], "fibonacci number":[["noun.quantity"],["Fibonacci number","number"]], "prime factor":[["noun.quantity"],["prime factor","divisor1"]], "prime number":[["noun.quantity"],["prime number","prime"]], "composite number":[["noun.quantity"],["composite number","number"]], "double-bogey":[["noun.quantity","verb.contact:double bogey","noun.act:golf"],["double-bogey","score"]], "compound number":[["noun.quantity"],["compound number","number"]], "ordinal number":[["noun.quantity","adj.all:ordinal"],["ordinal number","ordinal","no.","number"]], "cardinal number":[["noun.quantity"],["cardinal number","cardinal","number"]], "floating-point number":[["noun.quantity"],["floating-point number","number"]], "fixed-point number":[["noun.quantity"],["fixed-point number","number"]], "googol":[["noun.quantity"],["googol","cardinal number"]], "googolplex":[["noun.quantity"],["googolplex","cardinal number"]], "atomic number":[["noun.quantity"],["atomic number","number"]], "magic number":[["noun.quantity"],["magic number","atomic number"]], "baryon number":[["noun.quantity"],["baryon number","number"]], "long measure":[["noun.quantity"],["long measure","linear unit"]], "magnetic flux":[["noun.quantity"],["magnetic flux","magnetization"]], "absorption unit":[["noun.quantity"],["absorption unit","unit of measurement"]], "acceleration unit":[["noun.quantity"],["acceleration unit","unit of measurement"]], "angular unit":[["noun.quantity"],["angular unit","unit of measurement"]], "area unit":[["noun.quantity"],["area unit","square measure","unit of measurement"]], "volume unit":[["noun.quantity"],["volume unit","capacity unit","capacity measure","cubage unit","cubic measure","cubic content unit","displacement unit","cubature unit","unit of measurement","volume"]], "cubic inch":[["noun.quantity"],["cubic inch","cu in","volume unit"]], "cubic foot":[["noun.quantity"],["cubic foot","cu ft","volume unit"]], "computer memory unit":[["noun.quantity"],["computer memory unit","unit of measurement"]], "electromagnetic unit":[["noun.quantity"],["electromagnetic unit","emu","unit of measurement"]], "explosive unit":[["noun.quantity"],["explosive unit","unit of measurement"]], "force unit":[["noun.quantity"],["force unit","unit of measurement"]], "linear unit":[["noun.quantity"],["linear unit","linear measure","unit of measurement"]], "metric unit":[["noun.quantity"],["metric unit","metric1","unit of measurement"]], "miles per gallon":[["noun.quantity"],["miles per gallon","unit of measurement"]], "monetary unit":[["noun.quantity"],["monetary unit","unit of measurement"]], "megaflop":[["noun.quantity","noun.cognition:computer science"],["megaflop","MFLOP","million floating point operations per second","unit of measurement","teraflop"]], "teraflop":[["noun.quantity","noun.cognition:computer science"],["teraflop","trillion floating point operations per second","unit of measurement"]], "mips":[["noun.quantity","noun.cognition:computer science"],["MIPS","million instructions per second","unit of measurement"]], "pain unit":[["noun.quantity"],["pain unit","unit of measurement"]], "pressure unit":[["noun.quantity"],["pressure unit","unit of measurement"]], "printing unit":[["noun.quantity"],["printing unit","unit of measurement"]], "sound unit":[["noun.quantity"],["sound unit","unit of measurement"]], "telephone unit":[["noun.quantity"],["telephone unit","unit of measurement"]], "temperature unit":[["noun.quantity"],["temperature unit","unit of measurement"]], "weight unit":[["noun.quantity"],["weight unit","weight","unit of measurement"]], "mass unit":[["noun.quantity"],["mass unit","unit of measurement"]], "unit of viscosity":[["noun.quantity"],["unit of viscosity","unit of measurement"]], "work unit":[["noun.quantity"],["work unit","heat unit","energy unit","unit of measurement"]], "brinell number":[["noun.quantity"],["Brinell number","unit of measurement"]], "brix scale":[["noun.quantity"],["Brix scale","system of measurement"]], "set point":[["noun.quantity","noun.act:tennis"],["set point","point1"]], "match point":[["noun.quantity","noun.act:tennis"],["match point","point1"]], "circular measure":[["noun.quantity"],["circular measure","system of measurement"]], "mil":[["noun.quantity","noun.quantity","noun.quantity"],["mil3","angular unit","mil1","linear unit","inch","mil4","Cypriot pound","Cypriot monetary unit"]], "microradian":[["noun.quantity"],["microradian","angular unit","milliradian"]], "milliradian":[["noun.quantity"],["milliradian","angular unit","radian"]], "radian":[["noun.quantity"],["radian","rad1","angular unit"]], "grad":[["noun.quantity","noun.shape:right angle"],["grad","grade","angular unit"]], "oxtant":[["noun.quantity"],["oxtant","angular unit"]], "straight angle":[["noun.quantity","noun.attribute:circumference1"],["straight angle","angular unit"]], "steradian":[["noun.quantity","noun.shape:sphere1"],["steradian","sr","angular unit"]], "square inch":[["noun.quantity"],["square inch","sq in","area unit"]], "square foot":[["noun.quantity"],["square foot","sq ft","area unit"]], "square yard":[["noun.quantity"],["square yard","sq yd","area unit"]], "square meter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["square meter","square metre","centare","area unit"]], "square mile":[["noun.quantity"],["square mile","area unit"]], "quarter section":[["noun.quantity"],["quarter section","area unit"]], "are":[["noun.quantity"],["are","ar","area unit","hectare"]], "hectare":[["noun.quantity"],["hectare","area unit"]], "arpent":[["noun.quantity"],["arpent","area unit"]], "dessiatine":[["noun.quantity"],["dessiatine","area unit"]], "morgen":[["noun.quantity"],["morgen","area unit"]], "liquid unit":[["noun.quantity"],["liquid unit","liquid measure","capacity unit"]], "dry unit":[["noun.quantity"],["dry unit","dry measure","capacity unit"]], "united states liquid unit":[["noun.quantity"],["United States liquid unit","liquid unit"]], "british capacity unit":[["noun.quantity"],["British capacity unit","Imperial capacity unit","liquid unit","dry unit"]], "metric capacity unit":[["noun.quantity"],["metric capacity unit","capacity unit","metric unit"]], "ardeb":[["noun.quantity"],["ardeb","dry unit"]], "arroba":[["noun.quantity","noun.quantity"],["arroba2","liquid unit","arroba1","weight unit"]], "cran":[["noun.quantity"],["cran","capacity unit"]], "ephah":[["noun.quantity"],["ephah","epha","dry unit","homer"]], "field capacity":[["noun.quantity"],["field capacity","capacity unit"]], "hin":[["noun.quantity"],["hin","capacity unit"]], "acre-foot":[["noun.quantity"],["acre-foot","volume unit"]], "acre inch":[["noun.quantity"],["acre inch","volume unit"]], "board measure":[["noun.quantity"],["board measure","system of measurement"]], "board foot":[["noun.quantity"],["board foot","volume unit"]], "cubic yard":[["noun.quantity"],["cubic yard","yard1","volume unit"]], "mutchkin":[["noun.quantity"],["mutchkin","liquid unit"]], "oka":[["noun.quantity","noun.quantity"],["oka2","liquid unit","oka1","weight unit"]], "minim":[["noun.quantity","noun.quantity"],["minim1","United States liquid unit","fluidram1","minim2","British capacity unit","fluidram2"]], "fluidram":[["noun.quantity","noun.quantity"],["fluidram1","fluid dram1","fluid drachm1","drachm1","United States liquid unit","fluidounce1","fluidram2","fluid dram2","fluid drachm2","drachm2","British capacity unit","fluidounce2"]], "fluidounce":[["noun.quantity","noun.quantity"],["fluidounce1","fluid ounce1","United States liquid unit","gill1","fluidounce2","fluid ounce2","British capacity unit","gill2"]], "pint":[["noun.quantity","noun.quantity","noun.quantity"],["pint1","United States liquid unit","quart1","pint3","dry pint","United States dry unit","quart3","pint2","British capacity unit","quart2"]], "quart":[["noun.quantity","noun.quantity","noun.quantity"],["quart1","United States liquid unit","gallon1","quart3","dry quart","United States dry unit","peck1","quart2","British capacity unit","gallon2"]], "gallon":[["noun.quantity","noun.quantity"],["gallon1","gal","United States liquid unit","barrel1","gallon2","Imperial gallon","congius","British capacity unit","bushel1","barrel1","firkin"]], "united states dry unit":[["noun.quantity"],["United States dry unit","dry unit"]], "bushel":[["noun.quantity","noun.quantity"],["bushel2","United States dry unit","bushel1","British capacity unit","quarter4"]], "kilderkin":[["noun.quantity"],["kilderkin","British capacity unit"]], "chaldron":[["noun.quantity"],["chaldron","British capacity unit"]], "cubic millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic millimeter","cubic millimetre","metric capacity unit","milliliter"]], "milliliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["milliliter","millilitre","mil2","ml","cubic centimeter","cubic centimetre","cc","metric capacity unit","centiliter"]], "centiliter":[["noun.quantity"],["centiliter","centilitre","cl","metric capacity unit","deciliter"]], "deciliter":[["noun.quantity"],["deciliter","decilitre","dl","metric capacity unit","liter"]], "liter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["liter","litre","l","cubic decimeter","cubic decimetre","metric capacity unit","dekaliter"]], "dekaliter":[["noun.quantity"],["dekaliter","dekalitre","decaliter","decalitre","dal","dkl","metric capacity unit","hectoliter"]], "hectoliter":[["noun.quantity"],["hectoliter","hectolitre","hl","metric capacity unit","kiloliter"]], "kiloliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kiloliter","kilolitre","cubic meter","cubic metre","metric capacity unit","cubic kilometer"]], "cubic kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic kilometer","cubic kilometre","metric capacity unit"]], "parity bit":[["noun.quantity","noun.cognition:computer science"],["parity bit","parity","check bit","bit"]], "nybble":[["noun.quantity","verb.consumption:nibble1","verb.contact:nibble"],["nybble","nibble","byte","computer memory unit"]], "byte":[["noun.quantity"],["byte","computer memory unit","word"]], "bad block":[["noun.quantity","noun.cognition:computer science"],["bad block","block"]], "allocation unit":[["noun.quantity"],["allocation unit","computer memory unit"]], "kilobyte":[["noun.quantity","noun.quantity"],["kilobyte","kibibyte","K","KB","kB1","KiB","mebibyte","computer memory unit","kilobyte1","K1","KB2","kB3","megabyte1","computer memory unit"]], "kilobit":[["noun.quantity"],["kilobit","kbit","kb4","megabit","computer memory unit"]], "kibibit":[["noun.quantity"],["kibibit","kibit","mebibit","computer memory unit"]], "megabyte":[["noun.quantity","noun.quantity"],["megabyte","mebibyte","M2","MB","MiB","gibibyte","computer memory unit","megabyte1","M3","MB1","gigabyte1","computer memory unit"]], "megabit":[["noun.quantity"],["megabit","Mbit","Mb2","gigabit","computer memory unit"]], "mebibit":[["noun.quantity"],["mebibit","Mibit","gibibit","computer memory unit"]], "gigabyte":[["noun.quantity","noun.quantity"],["gigabyte","gibibyte","G2","GB2","GiB","tebibyte","computer memory unit","gigabyte1","G3","GB3","terabyte1","computer memory unit"]], "gigabit":[["noun.quantity"],["gigabit","Gbit","Gb4","terabit","computer memory unit"]], "gibibit":[["noun.quantity"],["gibibit","Gibit","tebibit","computer memory unit"]], "terabyte":[["noun.quantity","noun.quantity"],["terabyte","tebibyte","TB","TiB","pebibyte","computer memory unit","terabyte1","TB1","petabyte1","computer memory unit"]], "terabit":[["noun.quantity"],["terabit","Tbit","Tb2","petabit","computer memory unit"]], "tebibit":[["noun.quantity"],["tebibit","Tibit","pebibit","computer memory unit"]], "petabyte":[["noun.quantity","noun.quantity"],["petabyte","pebibyte","PB","PiB","exbibyte","computer memory unit","petabyte1","PB1","exabyte1","computer memory unit"]], "petabit":[["noun.quantity"],["petabit","Pbit","Pb2","exabit","computer memory unit"]], "pebibit":[["noun.quantity"],["pebibit","Pibit","exbibit","computer memory unit"]], "exabyte":[["noun.quantity","noun.quantity"],["exabyte","exbibyte","EB","EiB","zebibyte","computer memory unit","exabyte1","EB1","zettabyte1","computer memory unit"]], "exabit":[["noun.quantity"],["exabit","Ebit","Eb2","zettabit","computer memory unit"]], "exbibit":[["noun.quantity"],["exbibit","Eibit","zebibit","computer memory unit"]], "zettabyte":[["noun.quantity","noun.quantity"],["zettabyte","zebibyte","ZB","ZiB","yobibyte","computer memory unit","zettabyte1","ZB1","yottabyte1","computer memory unit"]], "zettabit":[["noun.quantity"],["zettabit","Zbit","Zb2","yottabit","computer memory unit"]], "zebibit":[["noun.quantity"],["zebibit","Zibit","yobibit","computer memory unit"]], "yottabyte":[["noun.quantity","noun.quantity"],["yottabyte","yobibyte","YB","YiB","computer memory unit","yottabyte1","YB1","computer memory unit"]], "yottabit":[["noun.quantity"],["yottabit","Ybit","Yb2","computer memory unit"]], "yobibit":[["noun.quantity"],["yobibit","Yibit","computer memory unit"]], "capacitance unit":[["noun.quantity"],["capacitance unit","electromagnetic unit"]], "charge unit":[["noun.quantity"],["charge unit","quantity unit","electromagnetic unit"]], "conductance unit":[["noun.quantity"],["conductance unit","electromagnetic unit"]], "current unit":[["noun.quantity"],["current unit","electromagnetic unit"]], "elastance unit":[["noun.quantity"],["elastance unit","electromagnetic unit"]], "field strength unit":[["noun.quantity"],["field strength unit","electromagnetic unit"]], "flux density unit":[["noun.quantity"],["flux density unit","electromagnetic unit"]], "flux unit":[["noun.quantity"],["flux unit","magnetic flux unit","magnetic flux"]], "inductance unit":[["noun.quantity"],["inductance unit","electromagnetic unit"]], "light unit":[["noun.quantity"],["light unit","electromagnetic unit"]], "magnetomotive force unit":[["noun.quantity"],["magnetomotive force unit","electromagnetic unit"]], "potential unit":[["noun.quantity"],["potential unit","electromagnetic unit"]], "power unit":[["noun.quantity"],["power unit","electromagnetic unit"]], "radioactivity unit":[["noun.quantity"],["radioactivity unit","electromagnetic unit"]], "resistance unit":[["noun.quantity"],["resistance unit","electromagnetic unit"]], "electrostatic unit":[["noun.quantity"],["electrostatic unit","unit of measurement"]], "picofarad":[["noun.quantity"],["picofarad","capacitance unit","microfarad"]], "microfarad":[["noun.quantity"],["microfarad","capacitance unit","millifarad"]], "millifarad":[["noun.quantity"],["millifarad","capacitance unit","farad"]], "farad":[["noun.quantity"],["farad","F","capacitance unit","abfarad"]], "abfarad":[["noun.quantity"],["abfarad","capacitance unit"]], "abcoulomb":[["noun.quantity"],["abcoulomb","charge unit"]], "ampere-minute":[["noun.quantity"],["ampere-minute","charge unit","ampere-hour"]], "ampere-hour":[["noun.quantity"],["ampere-hour","charge unit"]], "mho":[["noun.quantity"],["mho","siemens","reciprocal ohm","S","conductance unit"]], "ampere":[["noun.quantity","noun.quantity"],["ampere","amp","A","current unit","abampere","ampere2","international ampere","current unit"]], "milliampere":[["noun.quantity"],["milliampere","mA","current unit","ampere"]], "abampere":[["noun.quantity"],["abampere","abamp","current unit"]], "daraf":[["noun.quantity"],["daraf","elastance unit"]], "microgauss":[["noun.quantity"],["microgauss","flux density unit","gauss"]], "abhenry":[["noun.quantity"],["abhenry","inductance unit","henry"]], "millihenry":[["noun.quantity"],["millihenry","inductance unit","henry"]], "illumination unit":[["noun.quantity"],["illumination unit","light unit"]], "luminance unit":[["noun.quantity"],["luminance unit","light unit"]], "luminous flux unit":[["noun.quantity"],["luminous flux unit","light unit"]], "luminous intensity unit":[["noun.quantity"],["luminous intensity unit","candlepower unit","light unit"]], "footcandle":[["noun.quantity"],["footcandle","illumination unit"]], "lux":[["noun.quantity"],["lux","lx1","illumination unit","phot"]], "phot":[["noun.quantity"],["phot","illumination unit"]], "foot-lambert":[["noun.quantity"],["foot-lambert","ft-L","luminance unit"]], "international candle":[["noun.quantity"],["international candle","luminous intensity unit"]], "ampere-turn":[["noun.quantity"],["ampere-turn","magnetomotive force unit"]], "magneton":[["noun.quantity"],["magneton","magnetomotive force unit"]], "abvolt":[["noun.quantity"],["abvolt","potential unit","volt"]], "millivolt":[["noun.quantity"],["millivolt","mV","potential unit","volt"]], "microvolt":[["noun.quantity"],["microvolt","potential unit","volt"]], "nanovolt":[["noun.quantity"],["nanovolt","potential unit","volt"]], "picovolt":[["noun.quantity"],["picovolt","potential unit","volt"]], "femtovolt":[["noun.quantity"],["femtovolt","potential unit","volt"]], "volt":[["noun.quantity","adj.pert:voltaic"],["volt","V","potential unit","kilovolt"]], "kilovolt":[["noun.quantity"],["kilovolt","kV","potential unit"]], "rydberg":[["noun.quantity"],["rydberg","rydberg constant","rydberg unit","wave number"]], "wave number":[["noun.quantity","noun.time:frequency"],["wave number"]], "abwatt":[["noun.quantity"],["abwatt","power unit","milliwatt"]], "milliwatt":[["noun.quantity"],["milliwatt","power unit","watt"]], "kilowatt":[["noun.quantity"],["kilowatt","kW","power unit","megawatt"]], "megawatt":[["noun.quantity"],["megawatt","power unit"]], "horsepower":[["noun.quantity","H.P."],["horsepower","HP","power unit"]], "volt-ampere":[["noun.quantity"],["volt-ampere","var","power unit","kilovolt-ampere"]], "kilovolt-ampere":[["noun.quantity"],["kilovolt-ampere","power unit"]], "millicurie":[["noun.quantity"],["millicurie","radioactivity unit","curie"]], "rem":[["noun.quantity"],["rem","radioactivity unit"]], "mrem":[["noun.quantity"],["mrem","millirem","radioactivity unit"]], "rad":[["noun.quantity"],["rad","radioactivity unit"]], "abohm":[["noun.quantity"],["abohm","resistance unit","ohm"]], "megohm":[["noun.quantity"],["megohm","resistance unit"]], "kiloton":[["noun.quantity"],["kiloton","avoirdupois unit","megaton"]], "megaton":[["noun.quantity"],["megaton","avoirdupois unit"]], "dyne":[["noun.quantity"],["dyne","force unit","newton"]], "sthene":[["noun.quantity"],["sthene","force unit"]], "poundal":[["noun.quantity"],["poundal","pdl","force unit"]], "pounder":[["noun.quantity","noun.communication:combining form"],["pounder","force unit"]], "astronomy unit":[["noun.quantity"],["astronomy unit","linear unit"]], "metric linear unit":[["noun.quantity"],["metric linear unit","linear unit","metric unit"]], "nautical linear unit":[["noun.quantity"],["nautical linear unit","linear unit"]], "inch":[["noun.quantity","verb.motion:inch","noun.location:US","noun.location:Britain"],["inch","in","linear unit","foot"]], "footer":[["noun.quantity","noun.communication:combining form"],["footer","linear unit"]], "furlong":[["noun.quantity"],["furlong","linear unit","mile1"]], "half mile":[["noun.quantity"],["half mile","880 yards","linear unit","mile1"]], "quarter mile":[["noun.quantity"],["quarter mile","440 yards","linear unit","mile1"]], "ligne":[["noun.quantity"],["ligne","linear unit","inch"]], "archine":[["noun.quantity"],["archine","linear unit"]], "kos":[["noun.quantity"],["kos","coss","linear unit"]], "vara":[["noun.quantity"],["vara","linear unit"]], "verst":[["noun.quantity"],["verst","linear unit"]], "gunter's chain":[["noun.quantity"],["Gunter's chain","chain","furlong"]], "engineer's chain":[["noun.quantity"],["engineer's chain","chain"]], "cubit":[["noun.quantity"],["cubit","linear unit"]], "fistmele":[["noun.quantity"],["fistmele","linear unit"]], "body length":[["noun.quantity"],["body length","linear unit"]], "extremum":[["noun.quantity","adj.all:high3^peaky","verb.motion:peak"],["extremum","peak","limit"]], "handbreadth":[["noun.quantity"],["handbreadth","handsbreadth","linear unit"]], "lea":[["noun.quantity"],["lea","linear unit"]], "li":[["noun.quantity"],["li","linear unit"]], "roman pace":[["noun.quantity"],["Roman pace","linear unit"]], "geometric pace":[["noun.quantity"],["geometric pace","linear unit"]], "military pace":[["noun.quantity"],["military pace","linear unit"]], "survey mile":[["noun.quantity"],["survey mile","linear unit"]], "light year":[["noun.quantity"],["light year","light-year","astronomy unit"]], "light hour":[["noun.quantity"],["light hour","astronomy unit","light year"]], "light minute":[["noun.quantity"],["light minute","astronomy unit","light year"]], "light second":[["noun.quantity"],["light second","astronomy unit","light year"]], "astronomical unit":[["noun.quantity"],["Astronomical Unit","AU","astronomy unit"]], "parsec":[["noun.quantity"],["parsec","secpar","astronomy unit"]], "femtometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["femtometer","femtometre","fermi","metric linear unit","picometer"]], "picometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["picometer","picometre","micromicron","metric linear unit","angstrom"]], "angstrom":[["noun.quantity"],["angstrom","angstrom unit","A1","metric linear unit","nanometer"]], "nanometer":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["nanometer","nanometre","nm","millimicron","micromillimeter","micromillimetre","metric linear unit","micron"]], "micron":[["noun.quantity"],["micron","micrometer","metric linear unit","millimeter"]], "millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["millimeter","millimetre","mm","metric linear unit","centimeter"]], "centimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["centimeter","centimetre","cm","metric linear unit","decimeter"]], "decimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["decimeter","decimetre","dm","metric linear unit","meter"]], "decameter":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["decameter","dekameter","decametre","dekametre","dam","dkm","metric linear unit","hectometer"]], "hectometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["hectometer","hectometre","hm","metric linear unit","kilometer"]], "kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kilometer","kilometre","km","klick","metric linear unit","myriameter"]], "myriameter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["myriameter","myriametre","mym","metric linear unit"]], "nautical chain":[["noun.quantity"],["nautical chain","chain"]], "nautical mile":[["noun.quantity","noun.quantity:miler","noun.quantity","noun.quantity:miler"],["nautical mile1","mile4","mi4","naut mi","international nautical mile","air mile","nautical linear unit","nautical mile2","naut mi1","mile6","mi5","geographical mile","Admiralty mile","nautical linear unit"]], "sea mile":[["noun.quantity","noun.quantity:miler"],["sea mile","mile5","nautical linear unit"]], "halfpennyworth":[["noun.quantity"],["halfpennyworth","ha'p'orth","worth"]], "pennyworth":[["noun.quantity"],["pennyworth","penn'orth","worth"]], "euro":[["noun.quantity"],["euro","monetary unit"]], "franc":[["noun.quantity"],["franc","monetary unit"]], "fractional monetary unit":[["noun.quantity"],["fractional monetary unit","subunit","monetary unit"]], "afghan monetary unit":[["noun.quantity"],["Afghan monetary unit","monetary unit"]], "afghani":[["noun.quantity"],["afghani","Afghan monetary unit"]], "pul":[["noun.quantity"],["pul","afghani","Afghan monetary unit"]], "argentine monetary unit":[["noun.quantity"],["Argentine monetary unit","monetary unit"]], "austral":[["noun.quantity"],["austral","Argentine monetary unit"]], "thai monetary unit":[["noun.quantity"],["Thai monetary unit","monetary unit"]], "baht":[["noun.quantity"],["baht","tical","Thai monetary unit"]], "satang":[["noun.quantity"],["satang","baht","Thai monetary unit"]], "panamanian monetary unit":[["noun.quantity"],["Panamanian monetary unit","monetary unit"]], "ethiopian monetary unit":[["noun.quantity"],["Ethiopian monetary unit","monetary unit"]], "birr":[["noun.quantity"],["birr","Ethiopian monetary unit"]], "cent":[["noun.quantity"],["cent","fractional monetary unit","birr","dollar","gulden1","leone","lilangeni","rand","Mauritian rupee","Seychelles rupee","Sri Lanka rupee","shilling1"]], "centesimo":[["noun.quantity"],["centesimo","fractional monetary unit","balboa","Italian lira","Uruguayan peso","Chilean peso"]], "centimo":[["noun.quantity"],["centimo","fractional monetary unit","bolivar","Costa Rican colon","guarani","peseta"]], "centavo":[["noun.quantity"],["centavo","fractional monetary unit","austral","El Salvadoran colon","dobra","escudo1","escudo2","cordoba","lempira","metical","boliviano","peso3","peso4","peso5","peso6","peso7","peso8","peso10","quetzal","real1","sucre"]], "centime":[["noun.quantity"],["centime","fractional monetary unit","franc","Algerian dinar","Belgian franc","Burkina Faso franc","Burundi franc","Cameroon franc","Chadian franc","Congo franc","Gabon franc","Ivory Coast franc","Luxembourg franc","Mali franc","Moroccan dirham","Niger franc","Rwanda franc","Senegalese franc","Swiss franc","Togo franc"]], "venezuelan monetary unit":[["noun.quantity"],["Venezuelan monetary unit","monetary unit"]], "ghanian monetary unit":[["noun.quantity"],["Ghanian monetary unit","monetary unit"]], "cedi":[["noun.quantity"],["cedi","Ghanian monetary unit"]], "pesewa":[["noun.quantity"],["pesewa","cedi","Ghanian monetary unit"]], "costa rican monetary unit":[["noun.quantity"],["Costa Rican monetary unit","monetary unit"]], "el salvadoran monetary unit":[["noun.quantity"],["El Salvadoran monetary unit","monetary unit"]], "brazilian monetary unit":[["noun.quantity"],["Brazilian monetary unit","monetary unit"]], "gambian monetary unit":[["noun.quantity"],["Gambian monetary unit","monetary unit"]], "dalasi":[["noun.quantity"],["dalasi","Gambian monetary unit"]], "butut":[["noun.quantity"],["butut","butat","dalasi","Gambian monetary unit"]], "algerian monetary unit":[["noun.quantity"],["Algerian monetary unit","monetary unit"]], "algerian dinar":[["noun.quantity"],["Algerian dinar","dinar","Algerian monetary unit"]], "algerian centime":[["noun.quantity"],["Algerian centime","centime","Algerian dinar"]], "bahrainian monetary unit":[["noun.quantity"],["Bahrainian monetary unit","monetary unit"]], "bahrain dinar":[["noun.quantity"],["Bahrain dinar","dinar1","Bahrainian monetary unit"]], "fils":[["noun.quantity"],["fils","fractional monetary unit","Bahrain dinar","Iraqi dinar","Jordanian dinar","Kuwaiti dirham"]], "iraqi monetary unit":[["noun.quantity"],["Iraqi monetary unit","monetary unit"]], "iraqi dinar":[["noun.quantity"],["Iraqi dinar","dinar2","Iraqi monetary unit"]], "jordanian monetary unit":[["noun.quantity"],["Jordanian monetary unit","monetary unit"]], "jordanian dinar":[["noun.quantity"],["Jordanian dinar","dinar3","Jordanian monetary unit"]], "kuwaiti monetary unit":[["noun.quantity"],["Kuwaiti monetary unit","monetary unit"]], "kuwaiti dinar":[["noun.quantity"],["Kuwaiti dinar","dinar4","Kuwaiti monetary unit"]], "kuwaiti dirham":[["noun.quantity"],["Kuwaiti dirham","dirham1","Kuwaiti monetary unit","Kuwaiti dinar"]], "libyan monetary unit":[["noun.quantity"],["Libyan monetary unit","monetary unit"]], "libyan dinar":[["noun.quantity"],["Libyan dinar","dinar5","Libyan monetary unit"]], "libyan dirham":[["noun.quantity"],["Libyan dirham","dirham2","Libyan monetary unit","Libyan dinar"]], "tunisian monetary unit":[["noun.quantity"],["Tunisian monetary unit","monetary unit"]], "tunisian dinar":[["noun.quantity"],["Tunisian dinar","dinar7","Tunisian monetary unit"]], "tunisian dirham":[["noun.quantity"],["Tunisian dirham","dirham3","Tunisian monetary unit","Tunisian dinar"]], "millime":[["noun.quantity"],["millime","Tunisian monetary unit","Tunisian dirham"]], "yugoslavian monetary unit":[["noun.quantity"],["Yugoslavian monetary unit","monetary unit"]], "yugoslavian dinar":[["noun.quantity"],["Yugoslavian dinar","dinar8","Yugoslavian monetary unit"]], "moroccan monetary unit":[["noun.quantity"],["Moroccan monetary unit","monetary unit"]], "moroccan dirham":[["noun.quantity"],["Moroccan dirham","dirham4","Moroccan monetary unit"]], "united arab emirate monetary unit":[["noun.quantity"],["United Arab Emirate monetary unit","monetary unit"]], "united arab emirate dirham":[["noun.quantity"],["United Arab Emirate dirham","dirham5","United Arab Emirate monetary unit"]], "australian dollar":[["noun.quantity"],["Australian dollar","dollar"]], "bahamian dollar":[["noun.quantity"],["Bahamian dollar","dollar"]], "barbados dollar":[["noun.quantity"],["Barbados dollar","dollar"]], "belize dollar":[["noun.quantity"],["Belize dollar","dollar"]], "bermuda dollar":[["noun.quantity"],["Bermuda dollar","dollar"]], "brunei dollar":[["noun.quantity"],["Brunei dollar","dollar"]], "sen":[["noun.quantity"],["sen","fractional monetary unit","rupiah","riel","ringgit","yen"]], "canadian dollar":[["noun.quantity"],["Canadian dollar","loonie","dollar"]], "cayman islands dollar":[["noun.quantity"],["Cayman Islands dollar","dollar"]], "dominican dollar":[["noun.quantity"],["Dominican dollar","dollar"]], "fiji dollar":[["noun.quantity"],["Fiji dollar","dollar"]], "grenada dollar":[["noun.quantity"],["Grenada dollar","dollar"]], "guyana dollar":[["noun.quantity"],["Guyana dollar","dollar"]], "hong kong dollar":[["noun.quantity"],["Hong Kong dollar","dollar"]], "jamaican dollar":[["noun.quantity"],["Jamaican dollar","dollar"]], "kiribati dollar":[["noun.quantity"],["Kiribati dollar","dollar"]], "liberian dollar":[["noun.quantity"],["Liberian dollar","dollar"]], "new zealand dollar":[["noun.quantity"],["New Zealand dollar","dollar"]], "singapore dollar":[["noun.quantity"],["Singapore dollar","dollar"]], "taiwan dollar":[["noun.quantity"],["Taiwan dollar","dollar"]], "trinidad and tobago dollar":[["noun.quantity"],["Trinidad and Tobago dollar","dollar"]], "tuvalu dollar":[["noun.quantity"],["Tuvalu dollar","dollar"]], "united states dollar":[["noun.quantity"],["United States dollar","dollar"]], "eurodollar":[["noun.quantity","noun.possession:Eurocurrency"],["Eurodollar","United States dollar"]], "zimbabwean dollar":[["noun.quantity"],["Zimbabwean dollar","dollar"]], "vietnamese monetary unit":[["noun.quantity"],["Vietnamese monetary unit","monetary unit"]], "dong":[["noun.quantity"],["dong","Vietnamese monetary unit"]], "hao":[["noun.quantity"],["hao","dong","Vietnamese monetary unit"]], "greek monetary unit":[["noun.quantity"],["Greek monetary unit","monetary unit"]], "drachma":[["noun.quantity"],["drachma","Greek drachma","Greek monetary unit"]], "sao thome e principe monetary unit":[["noun.quantity"],["Sao Thome e Principe monetary unit","monetary unit"]], "dobra":[["noun.quantity"],["dobra","Sao Thome e Principe monetary unit"]], "cape verde monetary unit":[["noun.quantity"],["Cape Verde monetary unit","monetary unit"]], "cape verde escudo":[["noun.quantity"],["Cape Verde escudo","escudo1","Cape Verde monetary unit"]], "portuguese monetary unit":[["noun.quantity"],["Portuguese monetary unit","monetary unit"]], "portuguese escudo":[["noun.quantity"],["Portuguese escudo","escudo2","Portuguese monetary unit","conto"]], "conto":[["noun.quantity"],["conto","Portuguese monetary unit"]], "hungarian monetary unit":[["noun.quantity"],["Hungarian monetary unit","monetary unit"]], "forint":[["noun.quantity"],["forint","Hungarian monetary unit"]], "belgian franc":[["noun.quantity"],["Belgian franc","franc"]], "benin franc":[["noun.quantity"],["Benin franc","franc"]], "burundi franc":[["noun.quantity"],["Burundi franc","franc"]], "cameroon franc":[["noun.quantity"],["Cameroon franc","franc"]], "central african republic franc":[["noun.quantity"],["Central African Republic franc","franc"]], "chadian franc":[["noun.quantity"],["Chadian franc","franc"]], "congo franc":[["noun.quantity"],["Congo franc","franc"]], "djibouti franc":[["noun.quantity"],["Djibouti franc","franc"]], "french franc":[["noun.quantity"],["French franc","franc"]], "gabon franc":[["noun.quantity"],["Gabon franc","franc"]], "ivory coast franc":[["noun.quantity"],["Ivory Coast franc","Cote d'Ivoire franc","franc"]], "luxembourg franc":[["noun.quantity"],["Luxembourg franc","franc"]], "madagascar franc":[["noun.quantity"],["Madagascar franc","franc"]], "mali franc":[["noun.quantity"],["Mali franc","franc"]], "niger franc":[["noun.quantity"],["Niger franc","franc"]], "rwanda franc":[["noun.quantity"],["Rwanda franc","franc"]], "senegalese franc":[["noun.quantity"],["Senegalese franc","franc"]], "swiss franc":[["noun.quantity"],["Swiss franc","franc"]], "togo franc":[["noun.quantity"],["Togo franc","franc"]], "burkina faso franc":[["noun.quantity"],["Burkina Faso franc","franc"]], "haitian monetary unit":[["noun.quantity"],["Haitian monetary unit","monetary unit"]], "gourde":[["noun.quantity"],["gourde","Haitian monetary unit"]], "haitian centime":[["noun.quantity"],["Haitian centime","centime","gourde"]], "paraguayan monetary unit":[["noun.quantity"],["Paraguayan monetary unit","monetary unit"]], "dutch monetary unit":[["noun.quantity"],["Dutch monetary unit","monetary unit"]], "guilder":[["noun.quantity","noun.quantity"],["guilder1","gulden1","florin1","Dutch florin","Dutch monetary unit","guilder2","gulden2","florin2","Surinamese monetary unit"]], "surinamese monetary unit":[["noun.quantity"],["Surinamese monetary unit","monetary unit"]], "peruvian monetary unit":[["noun.quantity"],["Peruvian monetary unit","monetary unit"]], "inti":[["noun.quantity"],["inti","Peruvian monetary unit"]], "papuan monetary unit":[["noun.quantity"],["Papuan monetary unit","monetary unit"]], "kina":[["noun.quantity"],["kina","Papuan monetary unit"]], "toea":[["noun.quantity"],["toea","kina","Papuan monetary unit"]], "laotian monetary unit":[["noun.quantity"],["Laotian monetary unit","monetary unit"]], "at":[["noun.quantity"],["at","kip","Laotian monetary unit"]], "czech monetary unit":[["noun.quantity"],["Czech monetary unit","monetary unit"]], "koruna":[["noun.quantity","noun.quantity"],["koruna","Czech monetary unit","koruna1","Slovakian monetary unit"]], "haler":[["noun.quantity","noun.quantity"],["haler","heller","koruna","Czech monetary unit","haler1","heller1","Slovakian monetary unit","koruna"]], "slovakian monetary unit":[["noun.quantity"],["Slovakian monetary unit","monetary unit"]], "icelandic monetary unit":[["noun.quantity"],["Icelandic monetary unit","monetary unit"]], "icelandic krona":[["noun.quantity"],["Icelandic krona","krona1","Icelandic monetary unit"]], "eyrir":[["noun.quantity"],["eyrir","Icelandic krona","Icelandic monetary unit"]], "swedish monetary unit":[["noun.quantity"],["Swedish monetary unit","monetary unit"]], "swedish krona":[["noun.quantity"],["Swedish krona","krona2","Swedish monetary unit"]], "danish monetary unit":[["noun.quantity"],["Danish monetary unit","monetary unit"]], "danish krone":[["noun.quantity"],["Danish krone","krone1","Danish monetary unit"]], "norwegian monetary unit":[["noun.quantity"],["Norwegian monetary unit","monetary unit"]], "norwegian krone":[["noun.quantity"],["Norwegian krone","krone2","Norwegian monetary unit"]], "malawian monetary unit":[["noun.quantity"],["Malawian monetary unit","monetary unit"]], "malawi kwacha":[["noun.quantity"],["Malawi kwacha","kwacha1","Malawian monetary unit"]], "tambala":[["noun.quantity"],["tambala","Malawi kwacha","Malawian monetary unit"]], "zambian monetary unit":[["noun.quantity"],["Zambian monetary unit","monetary unit"]], "zambian kwacha":[["noun.quantity"],["Zambian kwacha","kwacha2","Zambian monetary unit"]], "ngwee":[["noun.quantity"],["ngwee","Zambian kwacha","Zambian monetary unit"]], "angolan monetary unit":[["noun.quantity"],["Angolan monetary unit","monetary unit"]], "kwanza":[["noun.quantity"],["kwanza","Angolan monetary unit"]], "lwei":[["noun.quantity"],["lwei","kwanza","Angolan monetary unit"]], "myanmar monetary unit":[["noun.quantity","noun.location:Burma"],["Myanmar monetary unit","monetary unit"]], "kyat":[["noun.quantity"],["kyat","Myanmar monetary unit"]], "pya":[["noun.quantity"],["pya","kyat","Myanmar monetary unit"]], "albanian monetary unit":[["noun.quantity"],["Albanian monetary unit","monetary unit"]], "lek":[["noun.quantity"],["lek","Albanian monetary unit"]], "qindarka":[["noun.quantity"],["qindarka","qintar","lek","Albanian monetary unit"]], "honduran monetary unit":[["noun.quantity"],["Honduran monetary unit","monetary unit"]], "lempira":[["noun.quantity"],["lempira","Honduran monetary unit"]], "sierra leone monetary unit":[["noun.quantity"],["Sierra Leone monetary unit","monetary unit"]], "leone":[["noun.quantity"],["leone","Sierra Leone monetary unit"]], "romanian monetary unit":[["noun.quantity"],["Romanian monetary unit","monetary unit"]], "leu":[["noun.quantity","noun.quantity"],["leu","Romanian monetary unit","leu1","Moldovan monetary unit"]], "bulgarian monetary unit":[["noun.quantity"],["Bulgarian monetary unit","monetary unit"]], "lev":[["noun.quantity"],["lev","Bulgarian monetary unit"]], "stotinka":[["noun.quantity"],["stotinka","lev","Bulgarian monetary unit"]], "swaziland monetary unit":[["noun.quantity"],["Swaziland monetary unit","monetary unit"]], "lilangeni":[["noun.quantity"],["lilangeni","Swaziland monetary unit"]], "italian monetary unit":[["noun.quantity"],["Italian monetary unit","monetary unit"]], "lira":[["noun.quantity","noun.quantity","noun.quantity"],["lira1","Italian lira","Italian monetary unit","lira2","Turkish lira","Turkish monetary unit","lira3","Maltese lira","Maltese monetary unit"]], "british monetary unit":[["noun.quantity"],["British monetary unit","monetary unit"]], "british pound":[["noun.quantity"],["British pound","pound1","British pound sterling","pound sterling","quid","British monetary unit"]], "british shilling":[["noun.quantity"],["British shilling","shilling1","bob","British monetary unit"]], "turkish monetary unit":[["noun.quantity"],["Turkish monetary unit","monetary unit"]], "kurus":[["noun.quantity"],["kurus","piaster1","piastre1","lira2","Turkish monetary unit"]], "asper":[["noun.quantity"],["asper","kurus","Turkish monetary unit"]], "lesotho monetary unit":[["noun.quantity"],["Lesotho monetary unit","monetary unit"]], "loti":[["noun.quantity"],["loti","Lesotho monetary unit"]], "sente":[["noun.quantity"],["sente","loti","Lesotho monetary unit"]], "german monetary unit":[["noun.quantity"],["German monetary unit","monetary unit"]], "pfennig":[["noun.quantity"],["pfennig","German monetary unit","mark"]], "finnish monetary unit":[["noun.quantity"],["Finnish monetary unit","monetary unit"]], "markka":[["noun.quantity"],["markka","Finnish mark","Finnish monetary unit"]], "penni":[["noun.quantity"],["penni","markka","Finnish monetary unit"]], "mozambique monetary unit":[["noun.quantity"],["Mozambique monetary unit","monetary unit"]], "metical":[["noun.quantity"],["metical","Mozambique monetary unit"]], "nigerian monetary unit":[["noun.quantity"],["Nigerian monetary unit","monetary unit"]], "naira":[["noun.quantity"],["naira","Nigerian monetary unit"]], "kobo":[["noun.quantity"],["kobo","naira","Nigerian monetary unit"]], "bhutanese monetary unit":[["noun.quantity"],["Bhutanese monetary unit","monetary unit"]], "ngultrum":[["noun.quantity"],["ngultrum","Bhutanese monetary unit"]], "chetrum":[["noun.quantity"],["chetrum","ngultrum","Bhutanese monetary unit"]], "mauritanian monetary unit":[["noun.quantity"],["Mauritanian monetary unit","monetary unit"]], "ouguiya":[["noun.quantity"],["ouguiya","Mauritanian monetary unit"]], "khoum":[["noun.quantity"],["khoum","ouguiya","Mauritanian monetary unit"]], "tongan monetary unit":[["noun.quantity"],["Tongan monetary unit","monetary unit"]], "pa'anga":[["noun.quantity"],["pa'anga","Tongan monetary unit"]], "seniti":[["noun.quantity"],["seniti","pa'anga","Tongan monetary unit"]], "macao monetary unit":[["noun.quantity"],["Macao monetary unit","monetary unit"]], "pataca":[["noun.quantity"],["pataca","Macao monetary unit"]], "avo":[["noun.quantity"],["avo","pataca","Macao monetary unit"]], "spanish monetary unit":[["noun.quantity"],["Spanish monetary unit","monetary unit"]], "peseta":[["noun.quantity"],["peseta","Spanish peseta","Spanish monetary unit"]], "bolivian monetary unit":[["noun.quantity"],["Bolivian monetary unit","monetary unit"]], "boliviano":[["noun.quantity"],["boliviano","Bolivian monetary unit"]], "nicaraguan monetary unit":[["noun.quantity"],["Nicaraguan monetary unit","monetary unit"]], "chilean monetary unit":[["noun.quantity"],["Chilean monetary unit","monetary unit"]], "chilean peso":[["noun.quantity"],["Chilean peso","peso9","Chilean monetary unit"]], "colombian monetary unit":[["noun.quantity"],["Colombian monetary unit","monetary unit"]], "colombian peso":[["noun.quantity"],["Colombian peso","peso3","Colombian monetary unit"]], "cuban monetary unit":[["noun.quantity"],["Cuban monetary unit","monetary unit"]], "cuban peso":[["noun.quantity"],["Cuban peso","peso4","Cuban monetary unit"]], "dominican monetary unit":[["noun.quantity"],["Dominican monetary unit","monetary unit"]], "dominican peso":[["noun.quantity"],["Dominican peso","peso5","Dominican monetary unit"]], "guinea-bissau monetary unit":[["noun.quantity"],["Guinea-Bissau monetary unit","monetary unit"]], "guinea-bissau peso":[["noun.quantity"],["Guinea-Bissau peso","peso10","Guinea-Bissau monetary unit"]], "mexican monetary unit":[["noun.quantity"],["Mexican monetary unit","monetary unit"]], "mexican peso":[["noun.quantity"],["Mexican peso","peso6","Mexican monetary unit"]], "philippine monetary unit":[["noun.quantity"],["Philippine monetary unit","monetary unit"]], "philippine peso":[["noun.quantity"],["Philippine peso","peso7","Philippine monetary unit"]], "uruguayan monetary unit":[["noun.quantity"],["Uruguayan monetary unit","monetary unit"]], "uruguayan peso":[["noun.quantity"],["Uruguayan peso","peso8","Uruguayan monetary unit"]], "cypriot monetary unit":[["noun.quantity"],["Cypriot monetary unit","monetary unit"]], "cypriot pound":[["noun.quantity"],["Cypriot pound","pound2","Cypriot monetary unit"]], "egyptian monetary unit":[["noun.quantity"],["Egyptian monetary unit","monetary unit"]], "egyptian pound":[["noun.quantity"],["Egyptian pound","pound3","Egyptian monetary unit"]], "piaster":[["noun.quantity"],["piaster","piastre","fractional monetary unit","Egyptian pound","Lebanese pound","Sudanese pound","Syrian pound"]], "irish monetary unit":[["noun.quantity"],["Irish monetary unit","monetary unit"]], "irish pound":[["noun.quantity"],["Irish pound","Irish punt","punt","pound4","Irish monetary unit"]], "lebanese monetary unit":[["noun.quantity"],["Lebanese monetary unit","monetary unit"]], "lebanese pound":[["noun.quantity"],["Lebanese pound","pound5","Lebanese monetary unit"]], "maltese monetary unit":[["noun.quantity"],["Maltese monetary unit","monetary unit"]], "sudanese monetary unit":[["noun.quantity"],["Sudanese monetary unit","monetary unit"]], "sudanese pound":[["noun.quantity"],["Sudanese pound","pound7","Sudanese monetary unit"]], "syrian monetary unit":[["noun.quantity"],["Syrian monetary unit","monetary unit"]], "syrian pound":[["noun.quantity"],["Syrian pound","pound8","Syrian monetary unit"]], "botswana monetary unit":[["noun.quantity"],["Botswana monetary unit","monetary unit"]], "pula":[["noun.quantity"],["pula","Botswana monetary unit"]], "thebe":[["noun.quantity"],["thebe","pula","Botswana monetary unit"]], "guatemalan monetary unit":[["noun.quantity"],["Guatemalan monetary unit","monetary unit"]], "south african monetary unit":[["noun.quantity"],["South African monetary unit","monetary unit"]], "iranian monetary unit":[["noun.quantity"],["Iranian monetary unit","monetary unit"]], "iranian rial":[["noun.quantity"],["Iranian rial","rial1","Iranian monetary unit"]], "iranian dinar":[["noun.quantity"],["Iranian dinar","dinar9","Iranian monetary unit","Iranian rial"]], "omani monetary unit":[["noun.quantity"],["Omani monetary unit","monetary unit"]], "riyal-omani":[["noun.quantity"],["riyal-omani","Omani rial","rial2","Omani monetary unit"]], "baiza":[["noun.quantity"],["baiza","baisa","Omani monetary unit","riyal-omani"]], "yemeni monetary unit":[["noun.quantity"],["Yemeni monetary unit","monetary unit"]], "yemeni rial":[["noun.quantity"],["Yemeni rial","rial","Yemeni monetary unit"]], "yemeni fils":[["noun.quantity"],["Yemeni fils","fils1","Yemeni monetary unit"]], "cambodian monetary unit":[["noun.quantity"],["Cambodian monetary unit","monetary unit"]], "riel":[["noun.quantity"],["riel","Cambodian monetary unit"]], "malaysian monetary unit":[["noun.quantity"],["Malaysian monetary unit","monetary unit"]], "ringgit":[["noun.quantity"],["ringgit","Malaysian monetary unit"]], "qatari monetary unit":[["noun.quantity"],["Qatari monetary unit","monetary unit"]], "qatari riyal":[["noun.quantity"],["Qatari riyal","riyal2","Qatari monetary unit"]], "qatari dirham":[["noun.quantity"],["Qatari dirham","dirham6","Qatari monetary unit","Qatari riyal"]], "saudi arabian monetary unit":[["noun.quantity"],["Saudi Arabian monetary unit","monetary unit"]], "saudi arabian riyal":[["noun.quantity"],["Saudi Arabian riyal","riyal3","Saudi Arabian monetary unit"]], "qurush":[["noun.quantity"],["qurush","Saudi Arabian riyal","Saudi Arabian monetary unit"]], "russian monetary unit":[["noun.quantity"],["Russian monetary unit","monetary unit"]], "ruble":[["noun.quantity","noun.quantity"],["ruble","rouble","Russian monetary unit","ruble1","Tajikistani monetary unit"]], "kopek":[["noun.quantity"],["kopek","kopeck","copeck","ruble","Russian monetary unit"]], "armenian monetary unit":[["noun.quantity"],["Armenian monetary unit","monetary unit"]], "dram":[["noun.quantity","noun.quantity","noun.quantity"],["dram","Armenian monetary unit","dram1","avoirdupois unit","ounce1","dram2","drachm","drachma2","apothecaries' unit","ounce2"]], "lumma":[["noun.quantity"],["lumma","Armenian monetary unit"]], "azerbaijani monetary unit":[["noun.quantity"],["Azerbaijani monetary unit","monetary unit"]], "manat":[["noun.quantity","noun.quantity"],["manat","Azerbaijani monetary unit","manat1","Turkmen monetary unit"]], "qepiq":[["noun.quantity"],["qepiq","Azerbaijani monetary unit"]], "belarusian monetary unit":[["noun.quantity"],["Belarusian monetary unit","monetary unit"]], "rubel":[["noun.quantity"],["rubel","Belarusian monetary unit"]], "kapeika":[["noun.quantity"],["kapeika","Belarusian monetary unit"]], "estonian monetary unit":[["noun.quantity"],["Estonian monetary unit","monetary unit"]], "kroon":[["noun.quantity"],["kroon","Estonian monetary unit"]], "sent":[["noun.quantity"],["sent","Estonian monetary unit"]], "georgian monetary unit":[["noun.quantity"],["Georgian monetary unit","monetary unit"]], "tetri":[["noun.quantity"],["tetri","Georgian monetary unit","lari"]], "kazakhstani monetary unit":[["noun.quantity"],["Kazakhstani monetary unit","monetary unit"]], "tenge":[["noun.quantity","noun.quantity"],["tenge","Kazakhstani monetary unit","tenge1","Turkmen monetary unit"]], "tiyin":[["noun.quantity","noun.quantity"],["tiyin","Kazakhstani monetary unit","tiyin1","Uzbekistani monetary unit"]], "latvian monetary unit":[["noun.quantity"],["Latvian monetary unit","monetary unit"]], "lats":[["noun.quantity"],["lats","Latvian monetary unit"]], "santims":[["noun.quantity"],["santims","Latvian monetary unit"]], "lithuanian monetary unit":[["noun.quantity"],["Lithuanian monetary unit","monetary unit"]], "litas":[["noun.quantity"],["litas","Lithuanian monetary unit"]], "centas":[["noun.quantity"],["centas","Lithuanian monetary unit"]], "kyrgyzstani monetary unit":[["noun.quantity"],["Kyrgyzstani monetary unit","monetary unit"]], "som":[["noun.quantity","noun.quantity"],["som","Kyrgyzstani monetary unit","som1","Uzbekistani monetary unit"]], "tyiyn":[["noun.quantity"],["tyiyn","Kyrgyzstani monetary unit"]], "moldovan monetary unit":[["noun.quantity"],["Moldovan monetary unit","monetary unit"]], "tajikistani monetary unit":[["noun.quantity"],["Tajikistani monetary unit","monetary unit"]], "turkmen monetary unit":[["noun.quantity"],["Turkmen monetary unit","monetary unit"]], "ukranian monetary unit":[["noun.quantity"],["Ukranian monetary unit","monetary unit"]], "hryvnia":[["noun.quantity"],["hryvnia","Ukranian monetary unit"]], "kopiyka":[["noun.quantity"],["kopiyka","Ukranian monetary unit","hryvnia"]], "uzbekistani monetary unit":[["noun.quantity"],["Uzbekistani monetary unit","monetary unit"]], "indian monetary unit":[["noun.quantity"],["Indian monetary unit","monetary unit"]], "indian rupee":[["noun.quantity"],["Indian rupee","rupee1","Indian monetary unit"]], "paisa":[["noun.quantity"],["paisa","fractional monetary unit","Indian rupee","Nepalese rupee","Pakistani rupee","taka"]], "pakistani monetary unit":[["noun.quantity"],["Pakistani monetary unit","monetary unit"]], "pakistani rupee":[["noun.quantity"],["Pakistani rupee","rupee2","Pakistani monetary unit"]], "anna":[["noun.quantity"],["anna","Pakistani monetary unit","Indian monetary unit"]], "mauritian monetary unit":[["noun.quantity"],["Mauritian monetary unit","monetary unit"]], "mauritian rupee":[["noun.quantity"],["Mauritian rupee","rupee3","Mauritian monetary unit"]], "nepalese monetary unit":[["noun.quantity"],["Nepalese monetary unit","monetary unit"]], "nepalese rupee":[["noun.quantity"],["Nepalese rupee","rupee4","Nepalese monetary unit"]], "seychelles monetary unit":[["noun.quantity"],["Seychelles monetary unit","monetary unit"]], "seychelles rupee":[["noun.quantity"],["Seychelles rupee","rupee5","Seychelles monetary unit"]], "sri lankan monetary unit":[["noun.quantity"],["Sri Lankan monetary unit","monetary unit"]], "sri lanka rupee":[["noun.quantity"],["Sri Lanka rupee","rupee6","Sri Lankan monetary unit"]], "indonesian monetary unit":[["noun.quantity"],["Indonesian monetary unit","monetary unit"]], "rupiah":[["noun.quantity"],["rupiah","Indonesian monetary unit"]], "austrian monetary unit":[["noun.quantity"],["Austrian monetary unit","monetary unit"]], "schilling":[["noun.quantity"],["schilling","Austrian schilling","Austrian monetary unit"]], "groschen":[["noun.quantity"],["groschen","schilling","Austrian monetary unit"]], "israeli monetary unit":[["noun.quantity"],["Israeli monetary unit","monetary unit"]], "shekel":[["noun.quantity"],["shekel","Israeli monetary unit"]], "kenyan monetary unit":[["noun.quantity"],["Kenyan monetary unit","monetary unit"]], "kenyan shilling":[["noun.quantity"],["Kenyan shilling","shilling2","kenyan monetary unit"]], "somalian monetary unit":[["noun.quantity"],["Somalian monetary unit","monetary unit"]], "somalian shilling":[["noun.quantity"],["Somalian shilling","shilling3","Somalian monetary unit"]], "tanzanian monetary unit":[["noun.quantity"],["Tanzanian monetary unit","monetary unit"]], "tanzanian shilling":[["noun.quantity"],["Tanzanian shilling","shilling4","Tanzanian monetary unit"]], "ugandan monetary unit":[["noun.quantity"],["Ugandan monetary unit","monetary unit"]], "ugandan shilling":[["noun.quantity"],["Ugandan shilling","shilling5","Ugandan monetary unit"]], "ecuadoran monetary unit":[["noun.quantity"],["Ecuadoran monetary unit","monetary unit"]], "guinean monetary unit":[["noun.quantity"],["Guinean monetary unit","monetary unit"]], "guinean franc":[["noun.quantity"],["Guinean franc","franc"]], "bangladeshi monetary unit":[["noun.quantity"],["Bangladeshi monetary unit","monetary unit"]], "taka":[["noun.quantity"],["taka","Bangladeshi monetary unit"]], "western samoan monetary unit":[["noun.quantity"],["Western Samoan monetary unit","monetary unit"]], "tala":[["noun.quantity"],["tala","Western Samoan monetary unit"]], "sene":[["noun.quantity"],["sene","tala","Western Samoan monetary unit"]], "mongolian monetary unit":[["noun.quantity"],["Mongolian monetary unit","monetary unit"]], "tugrik":[["noun.quantity"],["tugrik","tughrik","Mongolian monetary unit"]], "mongo":[["noun.quantity"],["mongo","tugrik","Mongolian monetary unit"]], "north korean monetary unit":[["noun.quantity"],["North Korean monetary unit","monetary unit"]], "north korean won":[["noun.quantity"],["North Korean won","won1","North Korean monetary unit"]], "chon":[["noun.quantity","noun.quantity"],["chon1","North Korean monetary unit","North Korean won","chon2","South Korean monetary unit","South Korean won"]], "south korean monetary unit":[["noun.quantity"],["South Korean monetary unit","monetary unit"]], "south korean won":[["noun.quantity"],["South Korean won","won2","South Korean monetary unit"]], "japanese monetary unit":[["noun.quantity"],["Japanese monetary unit","monetary unit"]], "yen":[["noun.quantity"],["yen","Japanese monetary unit"]], "chinese monetary unit":[["noun.quantity"],["Chinese monetary unit","monetary unit"]], "jiao":[["noun.quantity"],["jiao","yuan","Chinese monetary unit"]], "fen":[["noun.quantity"],["fen","Chinese monetary unit","jiao"]], "zairese monetary unit":[["noun.quantity"],["Zairese monetary unit","monetary unit"]], "zaire":[["noun.quantity"],["zaire","Zairese monetary unit"]], "likuta":[["noun.quantity"],["likuta","zaire","Zairese monetary unit"]], "polish monetary unit":[["noun.quantity"],["Polish monetary unit","monetary unit"]], "zloty":[["noun.quantity"],["zloty","Polish monetary unit"]], "grosz":[["noun.quantity"],["grosz","zloty","Polish monetary unit"]], "dol":[["noun.quantity"],["dol","pain unit"]], "standard atmosphere":[["noun.quantity"],["standard atmosphere","atmosphere","atm","standard pressure","pressure unit"]], "torr":[["noun.quantity"],["torr","millimeter of mercury","mm Hg","pressure unit"]], "pounds per square inch":[["noun.quantity"],["pounds per square inch","psi","pressure unit"]], "millibar":[["noun.quantity"],["millibar","pressure unit","bar"]], "barye":[["noun.quantity"],["barye","bar absolute","microbar","pressure unit","bar"]], "em":[["noun.quantity","noun.quantity"],["em2","pica em","pica","linear unit","inch","em1","em quad","mutton quad","area unit"]], "en":[["noun.quantity"],["en","nut","linear unit","em2"]], "agate line":[["noun.quantity"],["agate line","line","area unit"]], "milline":[["noun.quantity"],["milline","printing unit"]], "column inch":[["noun.quantity"],["column inch","inch2","area unit"]], "decibel":[["noun.quantity"],["decibel","dB","sound unit"]], "sone":[["noun.quantity"],["sone","sound unit","phon"]], "phon":[["noun.quantity"],["phon","sound unit"]], "erlang":[["noun.quantity"],["Erlang","telephone unit"]], "millidegree":[["noun.quantity"],["millidegree","temperature unit"]], "degree centigrade":[["noun.quantity"],["degree centigrade","degree Celsius","C2","degree3"]], "degree fahrenheit":[["noun.quantity"],["degree Fahrenheit","F2","degree3"]], "rankine":[["noun.quantity"],["Rankine","temperature unit"]], "degree day":[["noun.quantity"],["degree day","temperature unit"]], "standard temperature":[["noun.quantity"],["standard temperature","degree centigrade"]], "atomic mass unit":[["noun.quantity"],["atomic mass unit","mass unit"]], "mass number":[["noun.quantity"],["mass number","nucleon number","mass unit"]], "system of weights":[["noun.quantity"],["system of weights","weight1","system of measurement"]], "avoirdupois":[["noun.quantity"],["avoirdupois","avoirdupois weight","system of weights"]], "avoirdupois unit":[["noun.quantity"],["avoirdupois unit","mass unit","avoirdupois weight","English system"]], "troy unit":[["noun.quantity"],["troy unit","weight unit","troy weight"]], "apothecaries' unit":[["noun.quantity"],["apothecaries' unit","apothecaries' weight","weight unit"]], "metric weight unit":[["noun.quantity"],["metric weight unit","weight unit2","mass unit","metric unit","metric system"]], "catty":[["noun.quantity","noun.location:China"],["catty","cattie","weight unit"]], "crith":[["noun.quantity"],["crith","weight unit"]], "maund":[["noun.quantity"],["maund","weight unit"]], "obolus":[["noun.quantity"],["obolus","weight unit","gram"]], "picul":[["noun.quantity"],["picul","weight unit"]], "pood":[["noun.quantity"],["pood","weight unit"]], "rotl":[["noun.quantity"],["rotl","weight unit"]], "tael":[["noun.quantity"],["tael","weight unit"]], "tod":[["noun.quantity","noun.location:Britain"],["tod","weight unit"]], "ounce":[["noun.quantity","noun.quantity"],["ounce1","oz.","avoirdupois unit","pound9","ounce2","troy ounce","apothecaries' ounce","apothecaries' unit","troy unit","troy pound"]], "half pound":[["noun.quantity"],["half pound","avoirdupois unit","pound9"]], "quarter pound":[["noun.quantity"],["quarter pound","avoirdupois unit","pound"]], "hundredweight":[["noun.quantity","noun.quantity","noun.quantity"],["hundredweight1","cwt1","long hundredweight","avoirdupois unit","long ton","hundredweight2","cwt2","short hundredweight","centner1","cental","quintal1","avoirdupois unit","short ton","hundredweight3","metric hundredweight","doppelzentner","centner3","metric weight unit","quintal2"]], "long ton":[["noun.quantity"],["long ton","ton1","gross ton","avoirdupois unit"]], "short ton":[["noun.quantity"],["short ton","ton2","net ton","avoirdupois unit","kiloton"]], "pennyweight":[["noun.quantity"],["pennyweight","troy unit","ounce2"]], "troy pound":[["noun.quantity"],["troy pound","apothecaries' pound","apothecaries' unit","troy unit"]], "microgram":[["noun.quantity"],["microgram","mcg","metric weight unit","milligram"]], "milligram":[["noun.quantity"],["milligram","mg","metric weight unit","grain3"]], "nanogram":[["noun.quantity"],["nanogram","ng","metric weight unit","microgram"]], "decigram":[["noun.quantity"],["decigram","dg","metric weight unit","carat"]], "carat":[["noun.quantity"],["carat","metric weight unit","gram"]], "gram atom":[["noun.quantity"],["gram atom","gram-atomic weight","metric weight unit"]], "gram molecule":[["noun.quantity","adj.pert:molal","adj.pert:molar2","adj.pert:molar"],["gram molecule","mole","mol","metric weight unit"]], "dekagram":[["noun.quantity"],["dekagram","decagram","dkg","dag","metric weight unit","hectogram"]], "hectogram":[["noun.quantity"],["hectogram","hg","metric weight unit","kilogram"]], "kilogram":[["noun.quantity"],["kilogram","kg","kilo","metric weight unit","myriagram"]], "myriagram":[["noun.quantity"],["myriagram","myg","metric weight unit","centner2"]], "centner":[["noun.quantity"],["centner2","metric weight unit","hundredweight3"]], "quintal":[["noun.quantity"],["quintal2","metric weight unit","metric ton"]], "metric ton":[["noun.quantity"],["metric ton","MT","tonne","t1","metric weight unit"]], "erg":[["noun.quantity"],["erg","work unit","joule"]], "electron volt":[["noun.quantity"],["electron volt","eV","work unit"]], "calorie":[["noun.quantity","adj.pert:caloric","noun.quantity","adj.pert:caloric2"],["calorie1","gram calorie","small calorie","work unit","Calorie2","Calorie2","kilogram calorie","kilocalorie","large calorie","nutritionist's calorie","work unit"]], "british thermal unit":[["noun.quantity","B.Th.U."],["British thermal unit","BTU","work unit","therm"]], "therm":[["noun.quantity"],["therm","work unit"]], "watt-hour":[["noun.quantity"],["watt-hour","work unit","kilowatt hour"]], "kilowatt hour":[["noun.quantity","B.T.U."],["kilowatt hour","kW-hr","Board of Trade unit","work unit"]], "foot-pound":[["noun.quantity"],["foot-pound","work unit","foot-ton"]], "foot-ton":[["noun.quantity"],["foot-ton","work unit"]], "foot-poundal":[["noun.quantity"],["foot-poundal","work unit"]], "horsepower-hour":[["noun.quantity"],["horsepower-hour","work unit"]], "kilogram-meter":[["noun.quantity"],["kilogram-meter","work unit"]], "natural number":[["noun.quantity"],["natural number","number"]], "integer":[["noun.quantity"],["integer","whole number","number"]], "addend":[["noun.quantity"],["addend","number"]], "augend":[["noun.quantity"],["augend","number"]], "minuend":[["noun.quantity"],["minuend","number"]], "subtrahend":[["noun.quantity"],["subtrahend","number"]], "complex number":[["noun.quantity","noun.cognition:mathematics"],["complex number","complex quantity","imaginary number","imaginary","number"]], "complex conjugate":[["noun.quantity"],["complex conjugate","complex number"]], "real number":[["noun.quantity"],["real number","real","complex number"]], "pure imaginary number":[["noun.quantity"],["pure imaginary number","complex number"]], "imaginary part":[["noun.quantity"],["imaginary part","imaginary part of a complex number","pure imaginary number","complex number"]], "rational number":[["noun.quantity"],["rational number","rational","real number"]], "irrational number":[["noun.quantity"],["irrational number","irrational","real number"]], "transcendental number":[["noun.quantity"],["transcendental number","irrational number"]], "algebraic number":[["noun.quantity"],["algebraic number","irrational number"]], "biquadrate":[["noun.quantity","adj.pert:biquadratic","adj.pert:biquadratic"],["biquadrate","biquadratic","quartic","fourth power","number"]], "square root":[["noun.quantity"],["square root","root"]], "cube root":[["noun.quantity"],["cube root","root"]], "common fraction":[["noun.quantity"],["common fraction","simple fraction","fraction"]], "numerator":[["noun.quantity"],["numerator","dividend"]], "denominator":[["noun.quantity"],["denominator","divisor"]], "divisor":[["noun.quantity","noun.quantity","verb.cognition:factor","verb.cognition:factorize"],["divisor","number","divisor1","factor","integer"]], "multiplier":[["noun.quantity","verb.cognition:multiply"],["multiplier","multiplier factor","number"]], "multiplicand":[["noun.quantity"],["multiplicand","number"]], "scale factor":[["noun.quantity"],["scale factor","multiplier"]], "time-scale factor":[["noun.quantity","noun.cognition:simulation"],["time-scale factor","scale factor"]], "equivalent-binary-digit factor":[["noun.quantity"],["equivalent-binary-digit factor","divisor1"]], "aliquot":[["noun.quantity","adj.all:fractional^aliquot"],["aliquot","aliquant","aliquot part","divisor"]], "aliquant":[["noun.quantity"],["aliquant","aliquot","aliquant part","divisor"]], "common divisor":[["noun.quantity"],["common divisor","common factor","common measure","divisor1"]], "greatest common divisor":[["noun.quantity"],["greatest common divisor","greatest common factor","highest common factor","common divisor"]], "common multiple":[["noun.quantity"],["common multiple","integer"]], "improper fraction":[["noun.quantity"],["improper fraction","fraction"]], "proper fraction":[["noun.quantity"],["proper fraction","fraction"]], "complex fraction":[["noun.quantity"],["complex fraction","compound fraction","fraction"]], "decimal fraction":[["noun.quantity","verb.change:decimalize1","verb.change:decimalise1"],["decimal fraction","decimal","proper fraction"]], "circulating decimal":[["noun.quantity"],["circulating decimal","recurring decimal","repeating decimal","decimal fraction"]], "continued fraction":[["noun.quantity"],["continued fraction","fraction"]], "one-half":[["noun.quantity"],["one-half","half","common fraction"]], "fifty percent":[["noun.quantity"],["fifty percent","one-half"]], "one-third":[["noun.quantity"],["one-third","third","tierce","common fraction"]], "two-thirds":[["noun.quantity"],["two-thirds","common fraction"]], "one-fourth":[["noun.quantity","verb.contact:quarter1","verb.social:quarter"],["one-fourth","fourth","one-quarter","quarter1","fourth part","twenty-five percent","quartern","common fraction"]], "three-fourths":[["noun.quantity"],["three-fourths","three-quarters","common fraction"]], "one-fifth":[["noun.quantity"],["one-fifth","fifth","fifth part","twenty percent","common fraction"]], "one-sixth":[["noun.quantity"],["one-sixth","sixth","common fraction"]], "one-seventh":[["noun.quantity"],["one-seventh","seventh","common fraction"]], "one-eighth":[["noun.quantity"],["one-eighth","eighth","common fraction"]], "one-ninth":[["noun.quantity"],["one-ninth","ninth","common fraction"]], "one-tenth":[["noun.quantity"],["one-tenth","tenth","tenth part","ten percent","common fraction"]], "one-twelfth":[["noun.quantity"],["one-twelfth","twelfth","twelfth part","duodecimal","common fraction"]], "one-sixteenth":[["noun.quantity"],["one-sixteenth","sixteenth","sixteenth part","common fraction"]], "one-thirty-second":[["noun.quantity"],["one-thirty-second","thirty-second","thirty-second part","common fraction"]], "one-sixtieth":[["noun.quantity"],["one-sixtieth","sixtieth","common fraction"]], "one-sixty-fourth":[["noun.quantity"],["one-sixty-fourth","sixty-fourth","common fraction"]], "one-hundredth":[["noun.quantity"],["one-hundredth","hundredth","one percent","common fraction"]], "one-thousandth":[["noun.quantity"],["one-thousandth","thousandth","common fraction"]], "one-ten-thousandth":[["noun.quantity"],["one-ten-thousandth","ten-thousandth","common fraction"]], "one-hundred-thousandth":[["noun.quantity"],["one-hundred-thousandth","common fraction"]], "one-millionth":[["noun.quantity"],["one-millionth","millionth","common fraction"]], "one-hundred-millionth":[["noun.quantity"],["one-hundred-millionth","common fraction"]], "one-billionth":[["noun.quantity"],["one-billionth","billionth","common fraction"]], "one-trillionth":[["noun.quantity"],["one-trillionth","trillionth","common fraction"]], "one-quadrillionth":[["noun.quantity"],["one-quadrillionth","quadrillionth","common fraction"]], "one-quintillionth":[["noun.quantity"],["one-quintillionth","quintillionth","common fraction"]], "nothing":[["noun.quantity","verb.change:zero1"],["nothing","nil","nix","nada","null","aught","cipher","cypher","goose egg","naught","zero2","zilch","zip","zippo","relative quantity"]], "nihil":[["noun.quantity","noun.communication:Latin"],["nihil","nothing"]], "bugger all":[["noun.quantity","noun.location:Britain","noun.communication:obscenity"],["bugger all","fuck all","Fanny Adams","sweet Fanny Adams","nothing"]], "binary digit":[["noun.quantity"],["binary digit","digit"]], "octal digit":[["noun.quantity"],["octal digit","digit"]], "decimal digit":[["noun.quantity"],["decimal digit","digit"]], "duodecimal digit":[["noun.quantity"],["duodecimal digit","digit"]], "hexadecimal digit":[["noun.quantity"],["hexadecimal digit","digit"]], "significant digit":[["noun.quantity"],["significant digit","significant figure","digit"]], "two":[["noun.quantity"],["two","2\"","II","deuce","digit"]], "doubleton":[["noun.quantity","noun.act:bridge"],["doubleton","couple"]], "three":[["noun.quantity"],["three","3\"","III","trio","threesome","tierce1","leash","troika","triad","trine","trinity","ternary","ternion","triplet","tercet","terzetto","trey","deuce-ace","digit"]], "four":[["noun.quantity"],["four","4\"","IV","tetrad","quatern","quaternion","quaternary","quaternity","quartet","quadruplet","foursome","Little Joe","digit"]], "five":[["noun.quantity"],["five","5\"","V2","cinque","quint","quintet","fivesome","quintuplet","pentad","fin","Phoebe","Little Phoebe","digit"]], "six":[["noun.quantity"],["six","6\"","VI","sixer","sise","Captain Hicks","half a dozen","sextet","sestet","sextuplet","hexad","digit"]], "seven":[["noun.quantity","adj.all:cardinal^seven"],["seven","7\"","VII","sevener","heptad","septet","septenary","digit"]], "eight":[["noun.quantity"],["eight","8\"","VIII","eighter","eighter from Decatur","octad","ogdoad","octonary","octet","digit"]], "nine":[["noun.quantity"],["nine","9\"","IX","niner","Nina from Carolina","ennead","digit"]], "large integer":[["noun.quantity"],["large integer","integer"]], "double digit":[["noun.quantity"],["double digit","integer"]], "ten":[["noun.quantity"],["ten","10\"","X","tenner","decade","large integer"]], "eleven":[["noun.quantity"],["eleven","11\"","XI","large integer"]], "twelve":[["noun.quantity","adj.all:cardinal^dozen"],["twelve","12\"","XII","dozen","large integer"]], "boxcars":[["noun.quantity","noun.communication:plural"],["boxcars","twelve"]], "thirteen":[["noun.quantity"],["thirteen","13\"","XIII","baker's dozen","long dozen","large integer"]], "fourteen":[["noun.quantity"],["fourteen","14\"","XIV","large integer"]], "fifteen":[["noun.quantity","adj.all:cardinal^fifteen"],["fifteen","15\"","XV","large integer"]], "sixteen":[["noun.quantity"],["sixteen","16\"","XVI","large integer"]], "seventeen":[["noun.quantity","adj.all:cardinal^seventeen"],["seventeen","17\"","XVII","large integer"]], "eighteen":[["noun.quantity"],["eighteen","18\"","XVIII","large integer"]], "nineteen":[["noun.quantity","adj.all:cardinal^nineteen"],["nineteen","19\"","XIX","large integer"]], "twenty":[["noun.quantity"],["twenty","20\"","XX","large integer"]], "twenty-one":[["noun.quantity"],["twenty-one","21\"","XXI","large integer"]], "twenty-three":[["noun.quantity"],["twenty-three","23\"","XXIII","large integer"]], "twenty-four":[["noun.quantity"],["twenty-four","24\"","XXIV","two dozen","large integer"]], "twenty-five":[["noun.quantity"],["twenty-five","25\"","XXV","large integer"]], "twenty-six":[["noun.quantity"],["twenty-six","26\"","XXVI","large integer"]], "twenty-seven":[["noun.quantity"],["twenty-seven","27\"","XXVII","large integer"]], "twenty-eight":[["noun.quantity"],["twenty-eight","28\"","XXVIII","large integer"]], "twenty-nine":[["noun.quantity"],["twenty-nine","29\"","XXIX","large integer"]], "thirty":[["noun.quantity"],["thirty","30\"","XXX","large integer"]], "forty":[["noun.quantity"],["forty","40\"","XL","large integer"]], "fifty":[["noun.quantity","adj.all:cardinal^fifty"],["fifty","50\"","L6","large integer"]], "sixty":[["noun.quantity"],["sixty","60\"","LX","large integer"]], "seventy":[["noun.quantity","adj.all:cardinal^seventy"],["seventy","70\"","LXX","large integer"]], "eighty":[["noun.quantity"],["eighty","80\"","LXXX","fourscore","large integer"]], "ninety":[["noun.quantity"],["ninety","90\"","XC","large integer"]], "hundred":[["noun.quantity"],["hundred","100\"","C1","century","one C","large integer"]], "long hundred":[["noun.quantity"],["long hundred","great hundred","120\"","large integer"]], "five hundred":[["noun.quantity"],["five hundred","500\"","D","large integer"]], "thousand":[["noun.quantity"],["thousand","one thousand","1000\"","M1","K6","chiliad","G1","grand","thou","yard2","large integer"]], "millenary":[["noun.quantity"],["millenary","thousand"]], "great gross":[["noun.quantity"],["great gross","1728\"","large integer"]], "ten thousand":[["noun.quantity"],["ten thousand","10000\"","myriad","large integer"]], "hundred thousand":[["noun.quantity"],["hundred thousand","100000\"","lakh","large integer"]], "million":[["noun.quantity","noun.quantity"],["million","1000000\"","one thousand thousand","meg","large integer","million1","billion2","trillion2","zillion","jillion","gazillion","bazillion","large indefinite quantity"]], "crore":[["noun.quantity","noun.location:India"],["crore","large integer"]], "billion":[["noun.quantity","adj.all:cardinal^billion","noun.location:US","noun.quantity","adj.all:cardinal^billion1","noun.location:Britain"],["billion","one thousand million","1000000000\"","large integer","billion1","one million million","1000000000000\"","large integer"]], "milliard":[["noun.quantity","noun.location:Britain"],["milliard","billion"]], "trillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["trillion","one million million1","1000000000000\"1","large integer","trillion1","one million million million","large integer"]], "quadrillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["quadrillion","large integer","quadrillion1","large integer"]], "quintillion":[["noun.quantity","noun.location:US","noun.location:France"],["quintillion","large integer"]], "sextillion":[["noun.quantity","noun.location:US","noun.location:France"],["sextillion","large integer"]], "septillion":[["noun.quantity","noun.location:US","noun.location:France"],["septillion","large integer"]], "octillion":[["noun.quantity","noun.location:US","noun.location:France"],["octillion","large integer"]], "aleph-null":[["noun.quantity"],["aleph-null","aleph-nought","aleph-zero","large integer"]], "formatted capacity":[["noun.quantity","noun.cognition:computer science"],["formatted capacity","capacity1"]], "unformatted capacity":[["noun.quantity","noun.cognition:computer science"],["unformatted capacity","capacity1"]], "containerful":[["noun.quantity"],["containerful","indefinite quantity"]], "headspace":[["noun.quantity"],["headspace","indefinite quantity"]], "large indefinite quantity":[["noun.quantity"],["large indefinite quantity","large indefinite amount","indefinite quantity"]], "chunk":[["noun.quantity"],["chunk","large indefinite quantity"]], "pulmonary reserve":[["noun.quantity"],["pulmonary reserve","reserve"]], "small indefinite quantity":[["noun.quantity"],["small indefinite quantity","small indefinite amount","indefinite quantity"]], "hair's-breadth":[["noun.quantity"],["hair's-breadth","hairsbreadth","hair","whisker","small indefinite quantity"]], "modicum":[["noun.quantity"],["modicum","small indefinite quantity"]], "shoestring":[["noun.quantity"],["shoestring","shoe string","small indefinite quantity"]], "little":[["noun.quantity"],["little","small indefinite quantity"]], "shtikl":[["noun.quantity"],["shtikl","shtickl","schtikl","schtickl","shtik"]], "tad":[["noun.quantity"],["tad","shade","small indefinite quantity"]], "spillage":[["noun.quantity"],["spillage","indefinite quantity"]], "ullage":[["noun.quantity"],["ullage","indefinite quantity"]], "top-up":[["noun.quantity","noun.location:Britain"],["top-up","indefinite quantity"]], "armful":[["noun.quantity"],["armful","containerful"]], "barnful":[["noun.quantity"],["barnful","containerful"]], "busload":[["noun.quantity"],["busload","large indefinite quantity"]], "capful":[["noun.quantity"],["capful","containerful"]], "carful":[["noun.quantity"],["carful","containerful"]], "cartload":[["noun.quantity"],["cartload","containerful"]], "cask":[["noun.quantity"],["cask","caskful","containerful"]], "handful":[["noun.quantity","noun.quantity"],["handful","fistful","containerful","handful1","smattering","small indefinite quantity"]], "hatful":[["noun.quantity"],["hatful","containerful"]], "houseful":[["noun.quantity"],["houseful","containerful"]], "lapful":[["noun.quantity"],["lapful","containerful"]], "mouthful":[["noun.quantity"],["mouthful","containerful"]], "pail":[["noun.quantity"],["pail","pailful","containerful"]], "pipeful":[["noun.quantity"],["pipeful","containerful"]], "pocketful":[["noun.quantity"],["pocketful","containerful"]], "roomful":[["noun.quantity"],["roomful","containerful"]], "shelfful":[["noun.quantity"],["shelfful","containerful"]], "shoeful":[["noun.quantity"],["shoeful","containerful"]], "skinful":[["noun.quantity","noun.communication:slang"],["skinful","indefinite quantity"]], "skepful":[["noun.quantity"],["skepful","containerful"]], "dessertspoon":[["noun.quantity"],["dessertspoon","dessertspoonful","containerful"]], "droplet":[["noun.quantity","noun.shape:drop","noun.quantity:drop"],["droplet","drop"]], "dollop":[["noun.quantity"],["dollop","small indefinite quantity"]], "trainload":[["noun.quantity"],["trainload","load"]], "dreg":[["noun.quantity"],["dreg","small indefinite quantity"]], "tot":[["noun.quantity"],["tot","small indefinite quantity"]], "barrels":[["noun.quantity"],["barrels","large indefinite quantity"]], "billyo":[["noun.quantity"],["billyo","billyoh","billy-ho","all get out","large indefinite quantity"]], "boatload":[["noun.quantity"],["boatload","shipload","carload","large indefinite quantity"]], "haymow":[["noun.quantity"],["haymow","batch"]], "infinitude":[["noun.quantity"],["infinitude","large indefinite quantity"]], "much":[["noun.quantity"],["much","large indefinite quantity"]], "myriad":[["noun.quantity","adj.all:incalculable^myriad"],["myriad1","large indefinite quantity"]], "small fortune":[["noun.quantity"],["small fortune","large indefinite quantity"]], "tons":[["noun.quantity"],["tons","dozens","heaps","lots","piles","scores","stacks","loads","rafts","slews","wads","oodles","gobs","scads","lashings","large indefinite quantity"]], "breathing room":[["noun.quantity"],["breathing room","breathing space","room"]], "houseroom":[["noun.quantity"],["houseroom","room"]], "living space":[["noun.quantity"],["living space","lebensraum","room"]], "sea room":[["noun.quantity"],["sea room","room"]], "vital capacity":[["noun.quantity","noun.cognition:diagnostic test"],["vital capacity","capacity"]], "stp":[["noun.quantity","s.t.p."],["STP","standard temperature","standard pressure"]] }
Seagat2011/NLP-Story-Engine
wn/DICT/mysql-wn-data.noun.quantity.js
JavaScript
gpl-2.0
96,743
var hilbert = (function() { // From Mike Bostock: http://bl.ocks.org/597287 // Adapted from Nick Johnson: http://bit.ly/biWkkq var pairs = [ [[0, 3], [1, 0], [3, 1], [2, 0]], [[2, 1], [1, 1], [3, 0], [0, 2]], [[2, 2], [3, 3], [1, 2], [0, 1]], [[0, 0], [3, 2], [1, 3], [2, 3]] ]; // d2xy and rot are from: // http://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms var rot = function(n, x, y, rx, ry) { if (ry === 0) { if (rx === 1) { x = n - 1 - x; y = n - 1 - y; } return [y, x]; } return [x, y]; }; return { xy2d: function(x, y, z) { var quad = 0, pair, i = 0; while (--z >= 0) { pair = pairs[quad][(x & (1 << z) ? 2 : 0) | (y & (1 << z) ? 1 : 0)]; i = (i << 2) | pair[0]; quad = pair[1]; } return i; }, d2xy: function(z, t) { var n = 1 << z, x = 0, y = 0; for (var s = 1; s < n; s *= 2) { var rx = 1 & (t / 2), ry = 1 & (t ^ rx); var xy = rot(s, x, y, rx, ry); x = xy[0] + s * rx; y = xy[1] + s * ry; t /= 4; } return [x, y]; } }; })();
eggla/LA-glazed
sites/all/modules/openlayers/modules/openlayers_library/src/Plugin/Component/Hilbert/js/hilbert_algo.js
JavaScript
gpl-2.0
1,468
/** * @file * Provides Ajax page updating via jQuery $.ajax. * * Ajax is a method of making a request via JavaScript while viewing an HTML * page. The request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with `#ajax['url']` and * `#ajax['wrapper']` properties. If set, this file will automatically be * included to provide Ajax capabilities. */ (function ($, window, Drupal, drupalSettings) { 'use strict'; /** * Attaches the Ajax behavior to each Ajax form element. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Initialize all {@link Drupal.Ajax} objects declared in * `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from * DOM elements having the `use-ajax-submit` or `use-ajax` css class. * @prop {Drupal~behaviorDetach} detach * During `unload` remove all {@link Drupal.Ajax} objects related to * the removed content. */ Drupal.behaviors.AJAX = { attach: function (context, settings) { function loadAjaxBehavior(base) { var element_settings = settings.ajax[base]; if (typeof element_settings.selector === 'undefined') { element_settings.selector = '#' + base; } $(element_settings.selector).once('drupal-ajax').each(function () { element_settings.element = this; element_settings.base = base; Drupal.ajax(element_settings); }); } // Load all Ajax behaviors specified in the settings. for (var base in settings.ajax) { if (settings.ajax.hasOwnProperty(base)) { loadAjaxBehavior(base); } } // Bind Ajax behaviors to all items showing the class. $('.use-ajax').once('ajax').each(function () { var element_settings = {}; // Clicked links look better with the throbber than the progress bar. element_settings.progress = {type: 'throbber'}; // For anchor tags, these will go to the target of the anchor rather // than the usual location. var href = $(this).attr('href'); if (href) { element_settings.url = href; element_settings.event = 'click'; } element_settings.dialogType = $(this).data('dialog-type'); element_settings.dialog = $(this).data('dialog-options'); element_settings.base = $(this).attr('id'); element_settings.element = this; Drupal.ajax(element_settings); }); // This class means to submit the form to the action using Ajax. $('.use-ajax-submit').once('ajax').each(function () { var element_settings = {}; // Ajax submits specified in this manner automatically submit to the // normal form action. element_settings.url = $(this.form).attr('action'); // Form submit button clicks need to tell the form what was clicked so // it gets passed in the POST request. element_settings.setClick = true; // Form buttons use the 'click' event rather than mousedown. element_settings.event = 'click'; // Clicked form buttons look better with the throbber than the progress // bar. element_settings.progress = {type: 'throbber'}; element_settings.base = $(this).attr('id'); element_settings.element = this; Drupal.ajax(element_settings); }); }, detach: function (context, settings, trigger) { if (trigger === 'unload') { Drupal.ajax.expired().forEach(function (instance) { // Set this to null and allow garbage collection to reclaim // the memory. Drupal.ajax.instances[instance.instanceIndex] = null; }); } } }; /** * Extends Error to provide handling for Errors in Ajax. * * @constructor * * @augments Error * * @param {XMLHttpRequest} xmlhttp * XMLHttpRequest object used for the failed request. * @param {string} uri * The URI where the error occurred. * @param {string} customMessage * The custom message. */ Drupal.AjaxError = function (xmlhttp, uri, customMessage) { var statusCode; var statusText; var pathText; var responseText; var readyStateText; if (xmlhttp.status) { statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status}); } else { statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.'); } statusCode += '\n' + Drupal.t('Debugging information follows.'); pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri}); statusText = ''; // In some cases, when statusCode === 0, xmlhttp.statusText may not be // defined. Unfortunately, testing for it with typeof, etc, doesn't seem to // catch that and the test causes an exception. So we need to catch the // exception here. try { statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)}); } catch (e) { // Empty. } responseText = ''; // Again, we don't have a way to know for sure whether accessing // xmlhttp.responseText is going to throw an exception. So we'll catch it. try { responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)}); } catch (e) { // Empty. } // Make the responseText more readable by stripping HTML tags and newlines. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, ''); responseText = responseText.replace(/[\n]+\s+/g, '\n'); // We don't need readyState except for status == 0. readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : ''; customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : ''; /** * Formatted and translated error message. * * @type {string} */ this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText; /** * Used by some browsers to display a more accurate stack trace. * * @type {string} */ this.name = 'AjaxError'; }; Drupal.AjaxError.prototype = new Error(); Drupal.AjaxError.prototype.constructor = Drupal.AjaxError; /** * Provides Ajax page updating via jQuery $.ajax. * * This function is designed to improve developer experience by wrapping the * initialization of {@link Drupal.Ajax} objects and storing all created * objects in the {@link Drupal.ajax.instances} array. * * @example * Drupal.behaviors.myCustomAJAXStuff = { * attach: function (context, settings) { * * var ajaxSettings = { * url: 'my/url/path', * // If the old version of Drupal.ajax() needs to be used those * // properties can be added * base: 'myBase', * element: $(context).find('.someElement') * }; * * var myAjaxObject = Drupal.ajax(ajaxSettings); * * // Declare a new Ajax command specifically for this Ajax object. * myAjaxObject.commands.insert = function (ajax, response, status) { * $('#my-wrapper').append(response.data); * alert('New content was appended to #my-wrapper'); * }; * * // This command will remove this Ajax object from the page. * myAjaxObject.commands.destroyObject = function (ajax, response, status) { * Drupal.ajax.instances[this.instanceIndex] = null; * }; * * // Programmatically trigger the Ajax request. * myAjaxObject.execute(); * } * }; * * @param {object} settings * The settings object passed to {@link Drupal.Ajax} constructor. * @param {string} [settings.base] * Base is passed to {@link Drupal.Ajax} constructor as the 'base' * parameter. * @param {HTMLElement} [settings.element] * Element parameter of {@link Drupal.Ajax} constructor, element on which * event listeners will be bound. * * @return {Drupal.Ajax} * The created Ajax object. * * @see Drupal.AjaxCommands */ Drupal.ajax = function (settings) { if (arguments.length !== 1) { throw new Error('Drupal.ajax() function must be called with one configuration object only'); } // Map those config keys to variables for the old Drupal.ajax function. var base = settings.base || false; var element = settings.element || false; delete settings.base; delete settings.element; // By default do not display progress for ajax calls without an element. if (!settings.progress && !element) { settings.progress = false; } var ajax = new Drupal.Ajax(base, element, settings); ajax.instanceIndex = Drupal.ajax.instances.length; Drupal.ajax.instances.push(ajax); return ajax; }; /** * Contains all created Ajax objects. * * @type {Array.<Drupal.Ajax|null>} */ Drupal.ajax.instances = []; /** * List all objects where the associated element is not in the DOM * * This method ignores {@link Drupal.Ajax} objects not bound to DOM elements * when created with {@link Drupal.ajax}. * * @return {Array.<Drupal.Ajax>} * The list of expired {@link Drupal.Ajax} objects. */ Drupal.ajax.expired = function () { return Drupal.ajax.instances.filter(function (instance) { return instance && instance.element !== false && !document.body.contains(instance.element); }); }; /** * Settings for an Ajax object. * * @typedef {object} Drupal.Ajax~element_settings * * @prop {string} url * Target of the Ajax request. * @prop {?string} [event] * Event bound to settings.element which will trigger the Ajax request. * @prop {bool} [keypress=true] * Triggers a request on keypress events. * @prop {?string} selector * jQuery selector targeting the element to bind events to or used with * {@link Drupal.AjaxCommands}. * @prop {string} [effect='none'] * Name of the jQuery method to use for displaying new Ajax content. * @prop {string|number} [speed='none'] * Speed with which to apply the effect. * @prop {string} [method] * Name of the jQuery method used to insert new content in the targeted * element. * @prop {object} [progress] * Settings for the display of a user-friendly loader. * @prop {string} [progress.type='throbber'] * Type of progress element, core provides `'bar'`, `'throbber'` and * `'fullscreen'`. * @prop {string} [progress.message=Drupal.t('Please wait...')] * Custom message to be used with the bar indicator. * @prop {object} [submit] * Extra data to be sent with the Ajax request. * @prop {bool} [submit.js=true] * Allows the PHP side to know this comes from an Ajax request. * @prop {object} [dialog] * Options for {@link Drupal.dialog}. * @prop {string} [dialogType] * One of `'modal'` or `'dialog'`. * @prop {string} [prevent] * List of events on which to stop default action and stop propagation. */ /** * Ajax constructor. * * The Ajax request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with `#ajax['url']` and * `#ajax['wrapper']` properties. If set, this file will automatically be * included to provide Ajax capabilities. * * @constructor * * @param {string} [base] * Base parameter of {@link Drupal.Ajax} constructor * @param {HTMLElement} [element] * Element parameter of {@link Drupal.Ajax} constructor, element on which * event listeners will be bound. * @param {Drupal.Ajax~element_settings} element_settings * Settings for this Ajax object. */ Drupal.Ajax = function (base, element, element_settings) { var defaults = { event: element ? 'mousedown' : null, keypress: true, selector: base ? '#' + base : null, effect: 'none', speed: 'none', method: 'replaceWith', progress: { type: 'throbber', message: Drupal.t('Please wait...') }, submit: { js: true } }; $.extend(this, defaults, element_settings); /** * @type {Drupal.AjaxCommands} */ this.commands = new Drupal.AjaxCommands(); /** * @type {bool|number} */ this.instanceIndex = false; // @todo Remove this after refactoring the PHP code to: // - Call this 'selector'. // - Include the '#' for ID-based selectors. // - Support non-ID-based selectors. if (this.wrapper) { /** * @type {string} */ this.wrapper = '#' + this.wrapper; } /** * @type {HTMLElement} */ this.element = element; /** * @type {Drupal.Ajax~element_settings} */ this.element_settings = element_settings; // If there isn't a form, jQuery.ajax() will be used instead, allowing us to // bind Ajax to links as well. if (this.element && this.element.form) { /** * @type {jQuery} */ this.$form = $(this.element.form); } // If no Ajax callback URL was given, use the link href or form action. if (!this.url) { var $element = $(this.element); if ($element.is('a')) { this.url = $element.attr('href'); } else if (this.element && element.form) { this.url = this.$form.attr('action'); } } // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let // the server detect when it needs to degrade gracefully. // There are four scenarios to check for: // 1. /nojs/ // 2. /nojs$ - The end of a URL string. // 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar). // 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment). var originalUrl = this.url; /** * Processed Ajax URL. * * @type {string} */ this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1'); // If the 'nojs' version of the URL is trusted, also trust the 'ajax' // version. if (drupalSettings.ajaxTrustedUrl[originalUrl]) { drupalSettings.ajaxTrustedUrl[this.url] = true; } // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ajax = this; /** * Options for the jQuery.ajax function. * * @name Drupal.Ajax#options * * @type {object} * * @prop {string} url * Ajax URL to be called. * @prop {object} data * Ajax payload. * @prop {function} beforeSerialize * Implement jQuery beforeSerialize function to call * {@link Drupal.Ajax#beforeSerialize}. * @prop {function} beforeSubmit * Implement jQuery beforeSubmit function to call * {@link Drupal.Ajax#beforeSubmit}. * @prop {function} beforeSend * Implement jQuery beforeSend function to call * {@link Drupal.Ajax#beforeSend}. * @prop {function} success * Implement jQuery success function to call * {@link Drupal.Ajax#success}. * @prop {function} complete * Implement jQuery success function to clean up ajax state and trigger an * error if needed. * @prop {string} dataType='json' * Type of the response expected. * @prop {string} type='POST' * HTTP method to use for the Ajax request. */ ajax.options = { url: ajax.url, data: ajax.submit, beforeSerialize: function (element_settings, options) { return ajax.beforeSerialize(element_settings, options); }, beforeSubmit: function (form_values, element_settings, options) { ajax.ajaxing = true; return ajax.beforeSubmit(form_values, element_settings, options); }, beforeSend: function (xmlhttprequest, options) { ajax.ajaxing = true; return ajax.beforeSend(xmlhttprequest, options); }, success: function (response, status, xmlhttprequest) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof response === 'string') { response = $.parseJSON(response); } // Prior to invoking the response's commands, verify that they can be // trusted by checking for a response header. See // \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details. // - Empty responses are harmless so can bypass verification. This // avoids an alert message for server-generated no-op responses that // skip Ajax rendering. // - Ajax objects with trusted URLs (e.g., ones defined server-side via // #ajax) can bypass header verification. This is especially useful // for Ajax with multipart forms. Because IFRAME transport is used, // the response headers cannot be accessed for verification. if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) { if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') { var customMessage = Drupal.t('The response failed verification so will not be processed.'); return ajax.error(xmlhttprequest, ajax.url, customMessage); } } return ajax.success(response, status); }, complete: function (xmlhttprequest, status) { ajax.ajaxing = false; if (status === 'error' || status === 'parsererror') { return ajax.error(xmlhttprequest, ajax.url); } }, dataType: 'json', type: 'POST' }; if (element_settings.dialog) { ajax.options.data.dialogOptions = element_settings.dialog; } // Ensure that we have a valid URL by adding ? when no query parameter is // yet available, otherwise append using &. if (ajax.options.url.indexOf('?') === -1) { ajax.options.url += '?'; } else { ajax.options.url += '&'; } ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax'); // Bind the ajaxSubmit function to the element event. $(ajax.element).on(element_settings.event, function (event) { if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) { throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url})); } return ajax.eventResponse(this, event); }); // If necessary, enable keyboard submission so that Ajax behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(ajax.element).on('keypress', function (event) { return ajax.keypressResponse(this, event); }); } // If necessary, prevent the browser default action of an additional event. // For example, prevent the browser default action of a click, even if the // Ajax behavior binds to mousedown. if (element_settings.prevent) { $(ajax.element).on(element_settings.prevent, false); } }; /** * URL query attribute to indicate the wrapper used to render a request. * * The wrapper format determines how the HTML is wrapped, for example in a * modal dialog. * * @const {string} * * @default */ Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format'; /** * Request parameter to indicate that a request is a Drupal Ajax request. * * @const {string} * * @default */ Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax'; /** * Execute the ajax request. * * Allows developers to execute an Ajax request manually without specifying * an event to respond to. * * @return {object} * Returns the jQuery.Deferred object underlying the Ajax request. If * pre-serialization fails, the Deferred will be returned in the rejected * state. */ Drupal.Ajax.prototype.execute = function () { // Do not perform another ajax command if one is already in progress. if (this.ajaxing) { return; } try { this.beforeSerialize(this.element, this.options); // Return the jqXHR so that external code can hook into the Deferred API. return $.ajax(this.options); } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. this.ajaxing = false; window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message); // For consistency, return a rejected Deferred (i.e., jqXHR's superclass) // so that calling code can take appropriate action. return $.Deferred().reject(); } }; /** * Handle a key press. * * The Ajax object will, if instructed, bind to a key press response. This * will test to see if the key press is valid to trigger this event and * if it is, trigger it for us and prevent other keypresses from triggering. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13 * and 32. RETURN is often used to submit a form when in a textfield, and * SPACE is often used to activate an element without submitting. * * @param {HTMLElement} element * Element the event was triggered on. * @param {jQuery.Event} event * Triggered event. */ Drupal.Ajax.prototype.keypressResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Detect enter key and space bar and allow the standard response for them, // except for form elements of type 'text', 'tel', 'number' and 'textarea', // where the spacebar activation causes inappropriate activation if // #ajax['keypress'] is TRUE. On a text-type widget a space should always // be a space. if (event.which === 13 || (event.which === 32 && element.type !== 'text' && element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) { event.preventDefault(); event.stopPropagation(); $(ajax.element_settings.element).trigger(ajax.element_settings.event); } }; /** * Handle an event that triggers an Ajax response. * * When an event that triggers an Ajax response happens, this method will * perform the actual Ajax call. It is bound to the event using * bind() in the constructor, and it uses the options specified on the * Ajax object. * * @param {HTMLElement} element * Element the event was triggered on. * @param {jQuery.Event} event * Triggered event. */ Drupal.Ajax.prototype.eventResponse = function (element, event) { event.preventDefault(); event.stopPropagation(); // Create a synonym for this to reduce code confusion. var ajax = this; // Do not perform another Ajax command if one is already in progress. if (ajax.ajaxing) { return; } try { if (ajax.$form) { // If setClick is set, we must set this to ensure that the button's // value is passed. if (ajax.setClick) { // Mark the clicked button. 'form.clk' is a special variable for // ajaxSubmit that tells the system which element got clicked to // trigger the submit. Without it there would be no 'op' or // equivalent. element.form.clk = element; } ajax.$form.ajaxSubmit(ajax.options); } else { ajax.beforeSerialize(ajax.element, ajax.options); $.ajax(ajax.options); } } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. ajax.ajaxing = false; window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message); } }; /** * Handler for the form serialization. * * Runs before the beforeSend() handler (see below), and unlike that one, runs * before field data is collected. * * @param {object} [element] * Ajax object's `element_settings`. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSerialize = function (element, options) { // Allow detaching behaviors to update field values before collecting them. // This is only needed when field values are added to the POST data, so only // when there is a form such that this.$form.ajaxSubmit() is used instead of // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize() // isn't called, but don't rely on that: explicitly check this.$form. if (this.$form) { var settings = this.settings || drupalSettings; Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize'); } // Inform Drupal that this is an AJAX request. options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1; // Allow Drupal to return new JavaScript and CSS files to load without // returning the ones already loaded. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset() // @see system_js_settings_alter() var pageState = drupalSettings.ajaxPageState; options.data['ajax_page_state[theme]'] = pageState.theme; options.data['ajax_page_state[theme_token]'] = pageState.theme_token; options.data['ajax_page_state[libraries]'] = pageState.libraries; }; /** * Modify form values prior to form submission. * * @param {Array.<object>} form_values * Processed form values. * @param {jQuery} element * The form node as a jQuery object. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) { // This function is left empty to make it simple to override for modules // that wish to add functionality here. }; /** * Prepare the Ajax request before it is sent. * * @param {XMLHttpRequest} xmlhttprequest * Native Ajax object. * @param {object} options * jQuery.ajax options. */ Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) { // For forms without file inputs, the jQuery Form plugin serializes the // form values, and then calls jQuery's $.ajax() function, which invokes // this handler. In this circumstance, options.extraData is never used. For // forms with file inputs, the jQuery Form plugin uses the browser's normal // form submission mechanism, but captures the response in a hidden IFRAME. // In this circumstance, it calls this handler first, and then appends // hidden fields to the form to submit the values in options.extraData. // There is no simple way to know which submission mechanism will be used, // so we add to extraData regardless, and allow it to be ignored in the // former case. if (this.$form) { options.extraData = options.extraData || {}; // Let the server know when the IFRAME submission mechanism is used. The // server can use this information to wrap the JSON response in a // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload. options.extraData.ajax_iframe_upload = '1'; // The triggering element is about to be disabled (see below), but if it // contains a value (e.g., a checkbox, textfield, select, etc.), ensure // that value is included in the submission. As per above, submissions // that use $.ajax() are already serialized prior to the element being // disabled, so this is only needed for IFRAME submissions. var v = $.fieldValue(this.element); if (v !== null) { options.extraData[this.element.name] = v; } } // Disable the element that received the change to prevent user interface // interaction while the Ajax request is in progress. ajax.ajaxing prevents // the element from triggering a new request, but does not prevent the user // from changing its value. $(this.element).prop('disabled', true); if (!this.progress || !this.progress.type) { return; } // Insert progress indicator. var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase(); if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') { this[progressIndicatorMethod].call(this); } }; /** * Sets the progress bar progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorBar = function () { var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); }; /** * Sets the throbber progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () { this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>'); } $(this.element).after(this.progress.element); }; /** * Sets the fullscreen progress indicator. */ Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () { this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>'); $('body').after(this.progress.element); }; /** * Handler for the form redirection completion. * * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response * Drupal Ajax response. * @param {number} status * XMLHttpRequest status. */ Drupal.Ajax.prototype.success = function (response, status) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).prop('disabled', false); // Save element's ancestors tree so if the element is removed from the dom // we can try to refocus one of its parents. Using addBack reverse the // result array, meaning that index 0 is the highest parent in the hierarchy // in this situation it is usually a <form> element. var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray(); // Track if any command is altering the focus so we can avoid changing the // focus set by the Ajax command. var focusChanged = false; for (var i in response) { if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) { this.commands[response[i].command](this, response[i], status); if (response[i].command === 'invoke' && response[i].method === 'focus') { focusChanged = true; } } } // If the focus hasn't be changed by the ajax commands, try to refocus the // triggering element or one of its parents if that element does not exist // anymore. if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) { var target = false; for (var n = elementParents.length - 1; !target && n > 0; n--) { target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]'); } if (target) { $(target).trigger('focus'); } } // Reattach behaviors, if they were detached in beforeSerialize(). The // attachBehaviors() called on the new content from processing the response // commands is not sufficient, because behaviors from the entire form need // to be reattached. if (this.$form) { var settings = this.settings || drupalSettings; Drupal.attachBehaviors(this.$form.get(0), settings); } // Remove any response-specific settings so they don't get used on the next // call by mistake. this.settings = null; }; /** * Build an effect object to apply an effect when adding new HTML. * * @param {object} response * Drupal Ajax response. * @param {string} [response.effect] * Override the default value of {@link Drupal.Ajax#element_settings}. * @param {string|number} [response.speed] * Override the default value of {@link Drupal.Ajax#element_settings}. * * @return {object} * Returns an object with `showEffect`, `hideEffect` and `showSpeed` * properties. */ Drupal.Ajax.prototype.getEffect = function (response) { var type = response.effect || this.effect; var speed = response.speed || this.speed; var effect = {}; if (type === 'none') { effect.showEffect = 'show'; effect.hideEffect = 'hide'; effect.showSpeed = ''; } else if (type === 'fade') { effect.showEffect = 'fadeIn'; effect.hideEffect = 'fadeOut'; effect.showSpeed = speed; } else { effect.showEffect = type + 'Toggle'; effect.hideEffect = type + 'Toggle'; effect.showSpeed = speed; } return effect; }; /** * Handler for the form redirection error. * * @param {object} xmlhttprequest * Native XMLHttpRequest object. * @param {string} uri * Ajax Request URI. * @param {string} [customMessage] * Extra message to print with the Ajax error. */ Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).prop('disabled', false); // Reattach behaviors, if they were detached in beforeSerialize(). if (this.$form) { var settings = this.settings || drupalSettings; Drupal.attachBehaviors(this.$form.get(0), settings); } throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage); }; /** * @typedef {object} Drupal.AjaxCommands~commandDefinition * * @prop {string} command * @prop {string} [method] * @prop {string} [selector] * @prop {string} [data] * @prop {object} [settings] * @prop {bool} [asterisk] * @prop {string} [text] * @prop {string} [title] * @prop {string} [url] * @prop {object} [argument] * @prop {string} [name] * @prop {string} [value] * @prop {string} [old] * @prop {string} [new] * @prop {bool} [merge] * @prop {Array} [args] * * @see Drupal.AjaxCommands */ /** * Provide a series of commands that the client will perform. * * @constructor */ Drupal.AjaxCommands = function () {}; Drupal.AjaxCommands.prototype = { /** * Command to insert new content into the DOM. * * @param {Drupal.Ajax} ajax * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.data * The data to use with the jQuery method. * @param {string} [response.method] * The jQuery DOM manipulation method to be used. * @param {string} [response.selector] * A optional jQuery selector string. * @param {object} [response.settings] * An optional array of settings that will be used. * @param {number} [status] * The XMLHttpRequest status. */ insert: function (ajax, response, status) { // Get information from the response. If it is not there, default to // our presets. var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper); var method = response.method || ajax.method; var effect = ajax.getEffect(response); var settings; // We don't know what response.data contains: it might be a string of text // without HTML, so don't rely on jQuery correctly interpreting // $(response.data) as new HTML rather than a CSS selector. Also, if // response.data contains top-level text nodes, they get lost with either // $(response.data) or $('<div></div>').replaceWith(response.data). var $new_content_wrapped = $('<div></div>').html(response.data); var $new_content = $new_content_wrapped.contents(); // For legacy reasons, the effects processing code assumes that // $new_content consists of a single top-level element. Also, it has not // been sufficiently tested whether attachBehaviors() can be successfully // called with a context object that includes top-level text nodes. // However, to give developers full control of the HTML appearing in the // page, and to enable Ajax content to be inserted in places where <div> // elements are not allowed (e.g., within <table>, <tr>, and <span> // parents), we check if the new content satisfies the requirement // of a single top-level element, and only use the container <div> created // above when it doesn't. For more information, please see // https://www.drupal.org/node/736066. if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) { $new_content = $new_content_wrapped; } // If removing content from the wrapper, detach behaviors first. switch (method) { case 'html': case 'replaceWith': case 'replaceAll': case 'empty': case 'remove': settings = response.settings || ajax.settings || drupalSettings; Drupal.detachBehaviors($wrapper.get(0), settings); } // Add the new content to the page. $wrapper[method]($new_content); // Immediately hide the new content if we're using any effects. if (effect.showEffect !== 'show') { $new_content.hide(); } // Determine which effect to use and what content will receive the // effect, then show the new content. if ($new_content.find('.ajax-new-content').length > 0) { $new_content.find('.ajax-new-content').hide(); $new_content.show(); $new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed); } else if (effect.showEffect !== 'show') { $new_content[effect.showEffect](effect.showSpeed); } // Attach all JavaScript behaviors to the new content, if it was // successfully added to the page, this if statement allows // `#ajax['wrapper']` to be optional. if ($new_content.parents('html').length > 0) { // Apply any settings from the returned JSON if available. settings = response.settings || ajax.settings || drupalSettings; Drupal.attachBehaviors($new_content.get(0), settings); } }, /** * Command to remove a chunk from the page. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {object} [response.settings] * An optional array of settings that will be used. * @param {number} [status] * The XMLHttpRequest status. */ remove: function (ajax, response, status) { var settings = response.settings || ajax.settings || drupalSettings; $(response.selector).each(function () { Drupal.detachBehaviors(this, settings); }) .remove(); }, /** * Command to mark a chunk changed. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The JSON response object from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {bool} [response.asterisk] * An optional CSS selector. If specified, an asterisk will be * appended to the HTML inside the provided selector. * @param {number} [status] * The request status. */ changed: function (ajax, response, status) { var $element = $(response.selector); if (!$element.hasClass('ajax-changed')) { $element.addClass('ajax-changed'); if (response.asterisk) { $element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> '); } } }, /** * Command to provide an alert. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The JSON response from the Ajax request. * @param {string} response.text * The text that will be displayed in an alert dialog. * @param {number} [status] * The XMLHttpRequest status. */ alert: function (ajax, response, status) { window.alert(response.text, response.title); }, /** * Command to set the window.location, redirecting the browser. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.url * The URL to redirect to. * @param {number} [status] * The XMLHttpRequest status. */ redirect: function (ajax, response, status) { window.location = response.url; }, /** * Command to provide the jQuery css() function. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {object} response.argument * An array of key/value pairs to set in the CSS for the selector. * @param {number} [status] * The XMLHttpRequest status. */ css: function (ajax, response, status) { $(response.selector).css(response.argument); }, /** * Command to set the settings used for other commands in this response. * * This method will also remove expired `drupalSettings.ajax` settings. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {bool} response.merge * Determines whether the additional settings should be merged to the * global settings. * @param {object} response.settings * Contains additional settings to add to the global settings. * @param {number} [status] * The XMLHttpRequest status. */ settings: function (ajax, response, status) { var ajaxSettings = drupalSettings.ajax; // Clean up drupalSettings.ajax. if (ajaxSettings) { Drupal.ajax.expired().forEach(function (instance) { // If the Ajax object has been created through drupalSettings.ajax // it will have a selector. When there is no selector the object // has been initialized with a special class name picked up by the // Ajax behavior. if (instance.selector) { var selector = instance.selector.replace('#', ''); if (selector in ajaxSettings) { delete ajaxSettings[selector]; } } }); } if (response.merge) { $.extend(true, drupalSettings, response.settings); } else { ajax.settings = response.settings; } }, /** * Command to attach data using jQuery's data API. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.name * The name or key (in the key value pair) of the data attached to this * selector. * @param {string} response.selector * A jQuery selector string. * @param {string|object} response.value * The value of to be attached. * @param {number} [status] * The XMLHttpRequest status. */ data: function (ajax, response, status) { $(response.selector).data(response.name, response.value); }, /** * Command to apply a jQuery method. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {Array} response.args * An array of arguments to the jQuery method, if any. * @param {string} response.method * The jQuery method to invoke. * @param {string} response.selector * A jQuery selector string. * @param {number} [status] * The XMLHttpRequest status. */ invoke: function (ajax, response, status) { var $element = $(response.selector); $element[response.method].apply($element, response.args); }, /** * Command to restripe a table. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.selector * A jQuery selector string. * @param {number} [status] * The XMLHttpRequest status. */ restripe: function (ajax, response, status) { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $(response.selector).find('> tbody > tr:visible, > tr:visible') .removeClass('odd even') .filter(':even').addClass('odd').end() .filter(':odd').addClass('even'); }, /** * Command to update a form's build ID. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.old * The old form build ID. * @param {string} response.new * The new form build ID. * @param {number} [status] * The XMLHttpRequest status. */ update_build_id: function (ajax, response, status) { $('input[name="form_build_id"][value="' + response.old + '"]').val(response.new); }, /** * Command to add css. * * Uses the proprietary addImport method if available as browsers which * support that method ignore @import statements in dynamically added * stylesheets. * * @param {Drupal.Ajax} [ajax] * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * The response from the Ajax request. * @param {string} response.data * A string that contains the styles to be added. * @param {number} [status] * The XMLHttpRequest status. */ add_css: function (ajax, response, status) { // Add the styles in the normal way. $('head').prepend(response.data); // Add imports in the styles using the addImport method if available. var match; var importMatch = /^@import url\("(.*)"\);$/igm; if (document.styleSheets[0].addImport && importMatch.test(response.data)) { importMatch.lastIndex = 0; do { match = importMatch.exec(response.data); document.styleSheets[0].addImport(match[1]); } while (match); } } }; })(jQuery, window, Drupal, drupalSettings); ; /** * @file * Adds an HTML element and method to trigger audio UAs to read system messages. * * Use {@link Drupal.announce} to indicate to screen reader users that an * element on the page has changed state. For instance, if clicking a link * loads 10 more items into a list, one might announce the change like this. * * @example * $('#search-list') * .on('itemInsert', function (event, data) { * // Insert the new items. * $(data.container.el).append(data.items.el); * // Announce the change to the page contents. * Drupal.announce(Drupal.t('@count items added to @container', * {'@count': data.items.length, '@container': data.container.title} * )); * }); */ (function (Drupal, debounce) { 'use strict'; var liveElement; var announcements = []; /** * Builds a div element with the aria-live attribute and add it to the DOM. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the behavior for drupalAnnouce. */ Drupal.behaviors.drupalAnnounce = { attach: function (context) { // Create only one aria-live element. if (!liveElement) { liveElement = document.createElement('div'); liveElement.id = 'drupal-live-announce'; liveElement.className = 'visually-hidden'; liveElement.setAttribute('aria-live', 'polite'); liveElement.setAttribute('aria-busy', 'false'); document.body.appendChild(liveElement); } } }; /** * Concatenates announcements to a single string; appends to the live region. */ function announce() { var text = []; var priority = 'polite'; var announcement; // Create an array of announcement strings to be joined and appended to the // aria live region. var il = announcements.length; for (var i = 0; i < il; i++) { announcement = announcements.pop(); text.unshift(announcement.text); // If any of the announcements has a priority of assertive then the group // of joined announcements will have this priority. if (announcement.priority === 'assertive') { priority = 'assertive'; } } if (text.length) { // Clear the liveElement so that repeated strings will be read. liveElement.innerHTML = ''; // Set the busy state to true until the node changes are complete. liveElement.setAttribute('aria-busy', 'true'); // Set the priority to assertive, or default to polite. liveElement.setAttribute('aria-live', priority); // Print the text to the live region. Text should be run through // Drupal.t() before being passed to Drupal.announce(). liveElement.innerHTML = text.join('\n'); // The live text area is updated. Allow the AT to announce the text. liveElement.setAttribute('aria-busy', 'false'); } } /** * Triggers audio UAs to read the supplied text. * * The aria-live region will only read the text that currently populates its * text node. Replacing text quickly in rapid calls to announce results in * only the text from the most recent call to {@link Drupal.announce} being * read. By wrapping the call to announce in a debounce function, we allow for * time for multiple calls to {@link Drupal.announce} to queue up their * messages. These messages are then joined and append to the aria-live region * as one text node. * * @param {string} text * A string to be read by the UA. * @param {string} [priority='polite'] * A string to indicate the priority of the message. Can be either * 'polite' or 'assertive'. * * @return {function} * The return of the call to debounce. * * @see http://www.w3.org/WAI/PF/aria-practices/#liveprops */ Drupal.announce = function (text, priority) { // Save the text and priority into a closure variable. Multiple simultaneous // announcements will be concatenated and read in sequence. announcements.push({ text: text, priority: priority }); // Immediately invoke the function that debounce returns. 200 ms is right at // the cusp where humans notice a pause, so we will wait // at most this much time before the set of queued announcements is read. return (debounce(announce, 200)()); }; }(Drupal, Drupal.debounce)); ; (function(){if(window.matchMedia&&window.matchMedia("all").addListener){return false}var e=window.matchMedia,i=e("only all").matches,n=false,t=0,a=[],r=function(i){clearTimeout(t);t=setTimeout(function(){for(var i=0,n=a.length;i<n;i++){var t=a[i].mql,r=a[i].listeners||[],o=e(t.media).matches;if(o!==t.matches){t.matches=o;for(var s=0,l=r.length;s<l;s++){r[s].call(window,t)}}}},30)};window.matchMedia=function(t){var o=e(t),s=[],l=0;o.addListener=function(e){if(!i){return}if(!n){n=true;window.addEventListener("resize",r,true)}if(l===0){l=a.push({mql:o,listeners:s})}s.push(e)};o.removeListener=function(e){for(var i=0,n=s.length;i<n;i++){if(s[i]===e){s.splice(i,1)}}};return o}})(); ; /** * @file * Manages elements that can offset the size of the viewport. * * Measures and reports viewport offset dimensions from elements like the * toolbar that can potentially displace the positioning of other elements. */ /** * @typedef {object} Drupal~displaceOffset * * @prop {number} top * @prop {number} left * @prop {number} right * @prop {number} bottom */ /** * Triggers when layout of the page changes. * * This is used to position fixed element on the page during page resize and * Toolbar toggling. * * @event drupalViewportOffsetChange */ (function ($, Drupal, debounce) { 'use strict'; /** * @name Drupal.displace.offsets * * @type {Drupal~displaceOffset} */ var offsets = { top: 0, right: 0, bottom: 0, left: 0 }; /** * Registers a resize handler on the window. * * @type {Drupal~behavior} */ Drupal.behaviors.drupalDisplace = { attach: function () { // Mark this behavior as processed on the first pass. if (this.displaceProcessed) { return; } this.displaceProcessed = true; $(window).on('resize.drupalDisplace', debounce(displace, 200)); } }; /** * Informs listeners of the current offset dimensions. * * @function Drupal.displace * * @prop {Drupal~displaceOffset} offsets * * @param {bool} [broadcast] * When true or undefined, causes the recalculated offsets values to be * broadcast to listeners. * * @return {Drupal~displaceOffset} * An object whose keys are the for sides an element -- top, right, bottom * and left. The value of each key is the viewport displacement distance for * that edge. * * @fires event:drupalViewportOffsetChange */ function displace(broadcast) { offsets = Drupal.displace.offsets = calculateOffsets(); if (typeof broadcast === 'undefined' || broadcast) { $(document).trigger('drupalViewportOffsetChange', offsets); } return offsets; } /** * Determines the viewport offsets. * * @return {Drupal~displaceOffset} * An object whose keys are the for sides an element -- top, right, bottom * and left. The value of each key is the viewport displacement distance for * that edge. */ function calculateOffsets() { return { top: calculateOffset('top'), right: calculateOffset('right'), bottom: calculateOffset('bottom'), left: calculateOffset('left') }; } /** * Gets a specific edge's offset. * * Any element with the attribute data-offset-{edge} e.g. data-offset-top will * be considered in the viewport offset calculations. If the attribute has a * numeric value, that value will be used. If no value is provided, one will * be calculated using the element's dimensions and placement. * * @function Drupal.displace.calculateOffset * * @param {string} edge * The name of the edge to calculate. Can be 'top', 'right', * 'bottom' or 'left'. * * @return {number} * The viewport displacement distance for the requested edge. */ function calculateOffset(edge) { var edgeOffset = 0; var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']'); var n = displacingElements.length; for (var i = 0; i < n; i++) { var el = displacingElements[i]; // If the element is not visible, do consider its dimensions. if (el.style.display === 'none') { continue; } // If the offset data attribute contains a displacing value, use it. var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10); // If the element's offset data attribute exits // but is not a valid number then get the displacement // dimensions directly from the element. if (isNaN(displacement)) { displacement = getRawOffset(el, edge); } // If the displacement value is larger than the current value for this // edge, use the displacement value. edgeOffset = Math.max(edgeOffset, displacement); } return edgeOffset; } /** * Calculates displacement for element based on its dimensions and placement. * * @param {HTMLElement} el * The jQuery element whose dimensions and placement will be measured. * * @param {string} edge * The name of the edge of the viewport that the element is associated * with. * * @return {number} * The viewport displacement distance for the requested edge. */ function getRawOffset(el, edge) { var $el = $(el); var documentElement = document.documentElement; var displacement = 0; var horizontal = (edge === 'left' || edge === 'right'); // Get the offset of the element itself. var placement = $el.offset()[horizontal ? 'left' : 'top']; // Subtract scroll distance from placement to get the distance // to the edge of the viewport. placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal ? 'Left' : 'Top')] || 0; // Find the displacement value according to the edge. switch (edge) { // Left and top elements displace as a sum of their own offset value // plus their size. case 'top': // Total displacement is the sum of the elements placement and size. displacement = placement + $el.outerHeight(); break; case 'left': // Total displacement is the sum of the elements placement and size. displacement = placement + $el.outerWidth(); break; // Right and bottom elements displace according to their left and // top offset. Their size isn't important. case 'bottom': displacement = documentElement.clientHeight - placement; break; case 'right': displacement = documentElement.clientWidth - placement; break; default: displacement = 0; } return displacement; } /** * Assign the displace function to a property of the Drupal global object. * * @ignore */ Drupal.displace = displace; $.extend(Drupal.displace, { /** * Expose offsets to other scripts to avoid having to recalculate offsets. * * @ignore */ offsets: offsets, /** * Expose method to compute a single edge offsets. * * @ignore */ calculateOffset: calculateOffset }); })(jQuery, Drupal, Drupal.debounce); ; /** * @file * Builds a nested accordion widget. * * Invoke on an HTML list element with the jQuery plugin pattern. * * @example * $('.toolbar-menu').drupalToolbarMenu(); */ (function ($, Drupal, drupalSettings) { 'use strict'; /** * Store the open menu tray. */ var activeItem = Drupal.url(drupalSettings.path.currentPath); $.fn.drupalToolbarMenu = function () { var ui = { handleOpen: Drupal.t('Extend'), handleClose: Drupal.t('Collapse') }; /** * Handle clicks from the disclosure button on an item with sub-items. * * @param {Object} event * A jQuery Event object. */ function toggleClickHandler(event) { var $toggle = $(event.target); var $item = $toggle.closest('li'); // Toggle the list item. toggleList($item); // Close open sibling menus. var $openItems = $item.siblings().filter('.open'); toggleList($openItems, false); } /** * Handle clicks from a menu item link. * * @param {Object} event * A jQuery Event object. */ function linkClickHandler(event) { // If the toolbar is positioned fixed (and therefore hiding content // underneath), then users expect clicks in the administration menu tray // to take them to that destination but for the menu tray to be closed // after clicking: otherwise the toolbar itself is obstructing the view // of the destination they chose. if (!Drupal.toolbar.models.toolbarModel.get('isFixed')) { Drupal.toolbar.models.toolbarModel.set('activeTab', null); } // Stopping propagation to make sure that once a toolbar-box is clicked // (the whitespace part), the page is not redirected anymore. event.stopPropagation(); } /** * Toggle the open/close state of a list is a menu. * * @param {jQuery} $item * The li item to be toggled. * * @param {Boolean} switcher * A flag that forces toggleClass to add or a remove a class, rather than * simply toggling its presence. */ function toggleList($item, switcher) { var $toggle = $item.children('.toolbar-box').children('.toolbar-handle'); switcher = (typeof switcher !== 'undefined') ? switcher : !$item.hasClass('open'); // Toggle the item open state. $item.toggleClass('open', switcher); // Twist the toggle. $toggle.toggleClass('open', switcher); // Adjust the toggle text. $toggle .find('.action') // Expand Structure, Collapse Structure. .text((switcher) ? ui.handleClose : ui.handleOpen); } /** * Add markup to the menu elements. * * Items with sub-elements have a list toggle attached to them. Menu item * links and the corresponding list toggle are wrapped with in a div * classed with .toolbar-box. The .toolbar-box div provides a positioning * context for the item list toggle. * * @param {jQuery} $menu * The root of the menu to be initialized. */ function initItems($menu) { var options = { class: 'toolbar-icon toolbar-handle', action: ui.handleOpen, text: '' }; // Initialize items and their links. $menu.find('li > a').wrap('<div class="toolbar-box">'); // Add a handle to each list item if it has a menu. $menu.find('li').each(function (index, element) { var $item = $(element); if ($item.children('ul.toolbar-menu').length) { var $box = $item.children('.toolbar-box'); options.text = Drupal.t('@label', {'@label': $box.find('a').text()}); $item.children('.toolbar-box') .append(Drupal.theme('toolbarMenuItemToggle', options)); } }); } /** * Adds a level class to each list based on its depth in the menu. * * This function is called recursively on each sub level of lists elements * until the depth of the menu is exhausted. * * @param {jQuery} $lists * A jQuery object of ul elements. * * @param {number} level * The current level number to be assigned to the list elements. */ function markListLevels($lists, level) { level = (!level) ? 1 : level; var $lis = $lists.children('li').addClass('level-' + level); $lists = $lis.children('ul'); if ($lists.length) { markListLevels($lists, level + 1); } } /** * On page load, open the active menu item. * * Marks the trail of the active link in the menu back to the root of the * menu with .menu-item--active-trail. * * @param {jQuery} $menu * The root of the menu. */ function openActiveItem($menu) { var pathItem = $menu.find('a[href="' + location.pathname + '"]'); if (pathItem.length && !activeItem) { activeItem = location.pathname; } if (activeItem) { var $activeItem = $menu.find('a[href="' + activeItem + '"]').addClass('menu-item--active'); var $activeTrail = $activeItem.parentsUntil('.root', 'li').addClass('menu-item--active-trail'); toggleList($activeTrail, true); } } // Return the jQuery object. return this.each(function (selector) { var $menu = $(this).once('toolbar-menu'); if ($menu.length) { // Bind event handlers. $menu .on('click.toolbar', '.toolbar-box', toggleClickHandler) .on('click.toolbar', '.toolbar-box a', linkClickHandler); $menu.addClass('root'); initItems($menu); markListLevels($menu); // Restore previous and active states. openActiveItem($menu); } }); }; /** * A toggle is an interactive element often bound to a click handler. * * @param {object} options * Options for the button. * @param {string} options.class * Class to set on the button. * @param {string} options.action * Action for the button. * @param {string} options.text * Used as label for the button. * * @return {string} * A string representing a DOM fragment. */ Drupal.theme.toolbarMenuItemToggle = function (options) { return '<button class="' + options['class'] + '"><span class="action">' + options.action + '</span><span class="label">' + options.text + '</span></button>'; }; }(jQuery, Drupal, drupalSettings)); ; /** * @file * Defines the behavior of the Drupal administration toolbar. */ (function ($, Drupal, drupalSettings) { 'use strict'; // Merge run-time settings with the defaults. var options = $.extend( { breakpoints: { 'toolbar.narrow': '', 'toolbar.standard': '', 'toolbar.wide': '' } }, drupalSettings.toolbar, // Merge strings on top of drupalSettings so that they are not mutable. { strings: { horizontal: Drupal.t('Horizontal orientation'), vertical: Drupal.t('Vertical orientation') } } ); /** * Registers tabs with the toolbar. * * The Drupal toolbar allows modules to register top-level tabs. These may * point directly to a resource or toggle the visibility of a tray. * * Modules register tabs with hook_toolbar(). * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the toolbar rendering functionality to the toolbar element. */ Drupal.behaviors.toolbar = { attach: function (context) { // Verify that the user agent understands media queries. Complex admin // toolbar layouts require media query support. if (!window.matchMedia('only screen').matches) { return; } // Process the administrative toolbar. $(context).find('#toolbar-administration').once('toolbar').each(function () { // Establish the toolbar models and views. var model = Drupal.toolbar.models.toolbarModel = new Drupal.toolbar.ToolbarModel({ locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')) || false, activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID'))) }); Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({ el: this, model: model, strings: options.strings }); Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({ el: this, model: model, strings: options.strings }); Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({ el: this, model: model }); // Render collapsible menus. var menuModel = Drupal.toolbar.models.menuModel = new Drupal.toolbar.MenuModel(); Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({ el: $(this).find('.toolbar-menu-administration').get(0), model: menuModel, strings: options.strings }); // Handle the resolution of Drupal.toolbar.setSubtrees. // This is handled with a deferred so that the function may be invoked // asynchronously. Drupal.toolbar.setSubtrees.done(function (subtrees) { menuModel.set('subtrees', subtrees); var theme = drupalSettings.ajaxPageState.theme; localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees)); // Indicate on the toolbarModel that subtrees are now loaded. model.set('areSubtreesLoaded', true); }); // Attach a listener to the configured media query breakpoints. for (var label in options.breakpoints) { if (options.breakpoints.hasOwnProperty(label)) { var mq = options.breakpoints[label]; var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq); // Curry the model and the label of the media query breakpoint to // the mediaQueryChangeHandler function. mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label)); // Fire the mediaQueryChangeHandler for each configured breakpoint // so that they process once. Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql); } } // Trigger an initial attempt to load menu subitems. This first attempt // is made after the media query handlers have had an opportunity to // process. The toolbar starts in the vertical orientation by default, // unless the viewport is wide enough to accommodate a horizontal // orientation. Thus we give the Toolbar a chance to determine if it // should be set to horizontal orientation before attempting to load // menu subtrees. Drupal.toolbar.views.toolbarVisualView.loadSubtrees(); $(document) // Update the model when the viewport offset changes. .on('drupalViewportOffsetChange.toolbar', function (event, offsets) { model.set('offsets', offsets); }); // Broadcast model changes to other modules. model .on('change:orientation', function (model, orientation) { $(document).trigger('drupalToolbarOrientationChange', orientation); }) .on('change:activeTab', function (model, tab) { $(document).trigger('drupalToolbarTabChange', tab); }) .on('change:activeTray', function (model, tray) { $(document).trigger('drupalToolbarTrayChange', tray); }); // If the toolbar's orientation is horizontal and no active tab is // defined then show the tray of the first toolbar tab by default (but // not the first 'Home' toolbar tab). if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) { Drupal.toolbar.models.toolbarModel.set({ activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0) }); } }); } }; /** * Toolbar methods of Backbone objects. * * @namespace */ Drupal.toolbar = { /** * A hash of View instances. * * @type {object.<string, Backbone.View>} */ views: {}, /** * A hash of Model instances. * * @type {object.<string, Backbone.Model>} */ models: {}, /** * A hash of MediaQueryList objects tracked by the toolbar. * * @type {object.<string, object>} */ mql: {}, /** * Accepts a list of subtree menu elements. * * A deferred object that is resolved by an inlined JavaScript callback. * * @type {jQuery.Deferred} * * @see toolbar_subtrees_jsonp(). */ setSubtrees: new $.Deferred(), /** * Respond to configured narrow media query changes. * * @param {Drupal.toolbar.ToolbarModel} model * A toolbar model * @param {string} label * Media query label. * @param {object} mql * A MediaQueryList object. */ mediaQueryChangeHandler: function (model, label, mql) { switch (label) { case 'toolbar.narrow': model.set({ isOriented: mql.matches, isTrayToggleVisible: false }); // If the toolbar doesn't have an explicit orientation yet, or if the // narrow media query doesn't match then set the orientation to // vertical. if (!mql.matches || !model.get('orientation')) { model.set({orientation: 'vertical'}, {validate: true}); } break; case 'toolbar.standard': model.set({ isFixed: mql.matches }); break; case 'toolbar.wide': model.set({ orientation: ((mql.matches) ? 'horizontal' : 'vertical') }, {validate: true}); // The tray orientation toggle visibility does not need to be // validated. model.set({ isTrayToggleVisible: mql.matches }); break; default: break; } } }; /** * A toggle is an interactive element often bound to a click handler. * * @return {string} * A string representing a DOM fragment. */ Drupal.theme.toolbarOrientationToggle = function () { return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' + '<button class="toolbar-icon" type="button"></button>' + '</div></div>'; }; /** * Ajax command to set the toolbar subtrees. * * @param {Drupal.Ajax} ajax * {@link Drupal.Ajax} object created by {@link Drupal.ajax}. * @param {object} response * JSON response from the Ajax request. * @param {number} [status] * XMLHttpRequest status. */ Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) { Drupal.toolbar.setSubtrees.resolve(response.subtrees); }; }(jQuery, Drupal, drupalSettings)); ; /** * @file * A Backbone Model for collapsible menus. */ (function (Backbone, Drupal) { 'use strict'; /** * Backbone Model for collapsible menus. * * @constructor * * @augments Backbone.Model */ Drupal.toolbar.MenuModel = Backbone.Model.extend(/** @lends Drupal.toolbar.MenuModel# */{ /** * @type {object} * * @prop {object} subtrees */ defaults: /** @lends Drupal.toolbar.MenuModel# */{ /** * @type {object} */ subtrees: {} } }); }(Backbone, Drupal)); ; /** * @file * A Backbone Model for the toolbar. */ (function (Backbone, Drupal) { 'use strict'; /** * Backbone model for the toolbar. * * @constructor * * @augments Backbone.Model */ Drupal.toolbar.ToolbarModel = Backbone.Model.extend(/** @lends Drupal.toolbar.ToolbarModel# */{ /** * @type {object} * * @prop activeTab * @prop activeTray * @prop isOriented * @prop isFixed * @prop areSubtreesLoaded * @prop isViewportOverflowConstrained * @prop orientation * @prop locked * @prop isTrayToggleVisible * @prop height * @prop offsets */ defaults: /** @lends Drupal.toolbar.ToolbarModel# */{ /** * The active toolbar tab. All other tabs should be inactive under * normal circumstances. It will remain active across page loads. The * active item is stored as an ID selector e.g. '#toolbar-item--1'. * * @type {string} */ activeTab: null, /** * Represents whether a tray is open or not. Stored as an ID selector e.g. * '#toolbar-item--1-tray'. * * @type {string} */ activeTray: null, /** * Indicates whether the toolbar is displayed in an oriented fashion, * either horizontal or vertical. * * @type {bool} */ isOriented: false, /** * Indicates whether the toolbar is positioned absolute (false) or fixed * (true). * * @type {bool} */ isFixed: false, /** * Menu subtrees are loaded through an AJAX request only when the Toolbar * is set to a vertical orientation. * * @type {bool} */ areSubtreesLoaded: false, /** * If the viewport overflow becomes constrained, isFixed must be true so * that elements in the trays aren't lost off-screen and impossible to * get to. * * @type {bool} */ isViewportOverflowConstrained: false, /** * The orientation of the active tray. * * @type {string} */ orientation: 'vertical', /** * A tray is locked if a user toggled it to vertical. Otherwise a tray * will switch between vertical and horizontal orientation based on the * configured breakpoints. The locked state will be maintained across page * loads. * * @type {bool} */ locked: false, /** * Indicates whether the tray orientation toggle is visible. * * @type {bool} */ isTrayToggleVisible: false, /** * The height of the toolbar. * * @type {number} */ height: null, /** * The current viewport offsets determined by {@link Drupal.displace}. The * offsets suggest how a module might position is components relative to * the viewport. * * @type {object} * * @prop {number} top * @prop {number} right * @prop {number} bottom * @prop {number} left */ offsets: { top: 0, right: 0, bottom: 0, left: 0 } }, /** * @inheritdoc * * @param {object} attributes * Attributes for the toolbar. * @param {object} options * Options for the toolbar. * * @return {string|undefined} * Returns an error message if validation failed. */ validate: function (attributes, options) { // Prevent the orientation being set to horizontal if it is locked, unless // override has not been passed as an option. if (attributes.orientation === 'horizontal' && this.get('locked') && !options.override) { return Drupal.t('The toolbar cannot be set to a horizontal orientation when it is locked.'); } } }); }(Backbone, Drupal)); ; /** * @file * A Backbone view for the body element. */ (function ($, Drupal, Backbone) { 'use strict'; Drupal.toolbar.BodyVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.BodyVisualView# */{ /** * Adjusts the body element with the toolbar position and dimension changes. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:orientation change:offsets change:activeTray change:isOriented change:isFixed change:isViewportOverflowConstrained', this.render); }, /** * @inheritdoc */ render: function () { var $body = $('body'); var orientation = this.model.get('orientation'); var isOriented = this.model.get('isOriented'); var isViewportOverflowConstrained = this.model.get('isViewportOverflowConstrained'); $body // We are using JavaScript to control media-query handling for two // reasons: (1) Using JavaScript let's us leverage the breakpoint // configurations and (2) the CSS is really complex if we try to hide // some styling from browsers that don't understand CSS media queries. // If we drive the CSS from classes added through JavaScript, // then the CSS becomes simpler and more robust. .toggleClass('toolbar-vertical', (orientation === 'vertical')) .toggleClass('toolbar-horizontal', (isOriented && orientation === 'horizontal')) // When the toolbar is fixed, it will not scroll with page scrolling. .toggleClass('toolbar-fixed', (isViewportOverflowConstrained || this.model.get('isFixed'))) // Toggle the toolbar-tray-open class on the body element. The class is // applied when a toolbar tray is active. Padding might be applied to // the body element to prevent the tray from overlapping content. .toggleClass('toolbar-tray-open', !!this.model.get('activeTray')) // Apply padding to the top of the body to offset the placement of the // toolbar bar element. .css('padding-top', this.model.get('offsets').top); } }); }(jQuery, Drupal, Backbone)); ; /** * @file * A Backbone view for the collapsible menus. */ (function ($, Backbone, Drupal) { 'use strict'; Drupal.toolbar.MenuVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.MenuVisualView# */{ /** * Backbone View for collapsible menus. * * @constructs * * @augments Backbone.View */ initialize: function () { this.listenTo(this.model, 'change:subtrees', this.render); }, /** * @inheritdoc */ render: function () { var subtrees = this.model.get('subtrees'); // Add subtrees. for (var id in subtrees) { if (subtrees.hasOwnProperty(id)) { this.$el .find('#toolbar-link-' + id) .once('toolbar-subtrees') .after(subtrees[id]); } } // Render the main menu as a nested, collapsible accordion. if ('drupalToolbarMenu' in $.fn) { this.$el .children('.toolbar-menu') .drupalToolbarMenu(); } } }); }(jQuery, Backbone, Drupal)); ; /** * @file * A Backbone view for the aural feedback of the toolbar. */ (function (Backbone, Drupal) { 'use strict'; Drupal.toolbar.ToolbarAuralView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarAuralView# */{ /** * Backbone view for the aural feedback of the toolbar. * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view. * @param {object} options.strings * Various strings to use in the view. */ initialize: function (options) { this.strings = options.strings; this.listenTo(this.model, 'change:orientation', this.onOrientationChange); this.listenTo(this.model, 'change:activeTray', this.onActiveTrayChange); }, /** * Announces an orientation change. * * @param {Drupal.toolbar.ToolbarModel} model * The toolbar model in question. * @param {string} orientation * The new value of the orientation attribute in the model. */ onOrientationChange: function (model, orientation) { Drupal.announce(Drupal.t('Tray orientation changed to @orientation.', { '@orientation': orientation })); }, /** * Announces a changed active tray. * * @param {Drupal.toolbar.ToolbarModel} model * The toolbar model in question. * @param {HTMLElement} tray * The new value of the tray attribute in the model. */ onActiveTrayChange: function (model, tray) { var relevantTray = (tray === null) ? model.previous('activeTray') : tray; var action = (tray === null) ? Drupal.t('closed') : Drupal.t('opened'); var trayNameElement = relevantTray.querySelector('.toolbar-tray-name'); var text; if (trayNameElement !== null) { text = Drupal.t('Tray "@tray" @action.', { '@tray': trayNameElement.textContent, '@action': action }); } else { text = Drupal.t('Tray @action.', {'@action': action}); } Drupal.announce(text); } }); }(Backbone, Drupal)); ; /** * @file * A Backbone view for the toolbar element. Listens to mouse & touch. */ (function ($, Drupal, drupalSettings, Backbone) { 'use strict'; Drupal.toolbar.ToolbarVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarVisualView# */{ /** * Event map for the `ToolbarVisualView`. * * @return {object} * A map of events. */ events: function () { // Prevents delay and simulated mouse events. var touchEndToClick = function (event) { event.preventDefault(); event.target.click(); }; return { 'click .toolbar-bar .toolbar-tab .trigger': 'onTabClick', 'click .toolbar-toggle-orientation button': 'onOrientationToggleClick', 'touchend .toolbar-bar .toolbar-tab .trigger': touchEndToClick, 'touchend .toolbar-toggle-orientation button': touchEndToClick }; }, /** * Backbone view for the toolbar element. Listens to mouse & touch. * * @constructs * * @augments Backbone.View * * @param {object} options * Options for the view object. * @param {object} options.strings * Various strings to use in the view. */ initialize: function (options) { this.strings = options.strings; this.listenTo(this.model, 'change:activeTab change:orientation change:isOriented change:isTrayToggleVisible', this.render); this.listenTo(this.model, 'change:mqMatches', this.onMediaQueryChange); this.listenTo(this.model, 'change:offsets', this.adjustPlacement); // Add the tray orientation toggles. this.$el .find('.toolbar-tray .toolbar-lining') .append(Drupal.theme('toolbarOrientationToggle')); // Trigger an activeTab change so that listening scripts can respond on // page load. This will call render. this.model.trigger('change:activeTab'); }, /** * @inheritdoc * * @return {Drupal.toolbar.ToolbarVisualView} * The `ToolbarVisualView` instance. */ render: function () { this.updateTabs(); this.updateTrayOrientation(); this.updateBarAttributes(); // Load the subtrees if the orientation of the toolbar is changed to // vertical. This condition responds to the case that the toolbar switches // from horizontal to vertical orientation. The toolbar starts in a // vertical orientation by default and then switches to horizontal during // initialization if the media query conditions are met. Simply checking // that the orientation is vertical here would result in the subtrees // always being loaded, even when the toolbar initialization ultimately // results in a horizontal orientation. // // @see Drupal.behaviors.toolbar.attach() where admin menu subtrees // loading is invoked during initialization after media query conditions // have been processed. if (this.model.changed.orientation === 'vertical' || this.model.changed.activeTab) { this.loadSubtrees(); } // Trigger a recalculation of viewport displacing elements. Use setTimeout // to ensure this recalculation happens after changes to visual elements // have processed. window.setTimeout(function () { Drupal.displace(true); }, 0); return this; }, /** * Responds to a toolbar tab click. * * @param {jQuery.Event} event * The event triggered. */ onTabClick: function (event) { // If this tab has a tray associated with it, it is considered an // activatable tab. if (event.target.hasAttribute('data-toolbar-tray')) { var activeTab = this.model.get('activeTab'); var clickedTab = event.target; // Set the event target as the active item if it is not already. this.model.set('activeTab', (!activeTab || clickedTab !== activeTab) ? clickedTab : null); event.preventDefault(); event.stopPropagation(); } }, /** * Toggles the orientation of a toolbar tray. * * @param {jQuery.Event} event * The event triggered. */ onOrientationToggleClick: function (event) { var orientation = this.model.get('orientation'); // Determine the toggle-to orientation. var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical'; var locked = antiOrientation === 'vertical'; // Remember the locked state. if (locked) { localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true'); } else { localStorage.removeItem('Drupal.toolbar.trayVerticalLocked'); } // Update the model. this.model.set({ locked: locked, orientation: antiOrientation }, { validate: true, override: true }); event.preventDefault(); event.stopPropagation(); }, /** * Updates the display of the tabs: toggles a tab and the associated tray. */ updateTabs: function () { var $tab = $(this.model.get('activeTab')); // Deactivate the previous tab. $(this.model.previous('activeTab')) .removeClass('is-active') .prop('aria-pressed', false); // Deactivate the previous tray. $(this.model.previous('activeTray')) .removeClass('is-active'); // Activate the selected tab. if ($tab.length > 0) { $tab .addClass('is-active') // Mark the tab as pressed. .prop('aria-pressed', true); var name = $tab.attr('data-toolbar-tray'); // Store the active tab name or remove the setting. var id = $tab.get(0).id; if (id) { localStorage.setItem('Drupal.toolbar.activeTabID', JSON.stringify(id)); } // Activate the associated tray. var $tray = this.$el.find('[data-toolbar-tray="' + name + '"].toolbar-tray'); if ($tray.length) { $tray.addClass('is-active'); this.model.set('activeTray', $tray.get(0)); } else { // There is no active tray. this.model.set('activeTray', null); } } else { // There is no active tray. this.model.set('activeTray', null); localStorage.removeItem('Drupal.toolbar.activeTabID'); } }, /** * Update the attributes of the toolbar bar element. */ updateBarAttributes: function () { var isOriented = this.model.get('isOriented'); if (isOriented) { this.$el.find('.toolbar-bar').attr('data-offset-top', ''); } else { this.$el.find('.toolbar-bar').removeAttr('data-offset-top'); } // Toggle between a basic vertical view and a more sophisticated // horizontal and vertical display of the toolbar bar and trays. this.$el.toggleClass('toolbar-oriented', isOriented); }, /** * Updates the orientation of the active tray if necessary. */ updateTrayOrientation: function () { var orientation = this.model.get('orientation'); // The antiOrientation is used to render the view of action buttons like // the tray orientation toggle. var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical'; // Update the orientation of the trays. var $trays = this.$el.find('.toolbar-tray') .removeClass('toolbar-tray-horizontal toolbar-tray-vertical') .addClass('toolbar-tray-' + orientation); // Update the tray orientation toggle button. var iconClass = 'toolbar-icon-toggle-' + orientation; var iconAntiClass = 'toolbar-icon-toggle-' + antiOrientation; var $orientationToggle = this.$el.find('.toolbar-toggle-orientation') .toggle(this.model.get('isTrayToggleVisible')); $orientationToggle.find('button') .val(antiOrientation) .attr('title', this.strings[antiOrientation]) .text(this.strings[antiOrientation]) .removeClass(iconClass) .addClass(iconAntiClass); // Update data offset attributes for the trays. var dir = document.documentElement.dir; var edge = (dir === 'rtl') ? 'right' : 'left'; // Remove data-offset attributes from the trays so they can be refreshed. $trays.removeAttr('data-offset-left data-offset-right data-offset-top'); // If an active vertical tray exists, mark it as an offset element. $trays.filter('.toolbar-tray-vertical.is-active').attr('data-offset-' + edge, ''); // If an active horizontal tray exists, mark it as an offset element. $trays.filter('.toolbar-tray-horizontal.is-active').attr('data-offset-top', ''); }, /** * Sets the tops of the trays so that they align with the bottom of the bar. */ adjustPlacement: function () { var $trays = this.$el.find('.toolbar-tray'); if (!this.model.get('isOriented')) { $trays.css('margin-top', 0); $trays.removeClass('toolbar-tray-horizontal').addClass('toolbar-tray-vertical'); } else { // The toolbar container is invisible. Its placement is used to // determine the container for the trays. $trays.css('margin-top', this.$el.find('.toolbar-bar').outerHeight()); } }, /** * Calls the endpoint URI that builds an AJAX command with the rendered * subtrees. * * The rendered admin menu subtrees HTML is cached on the client in * localStorage until the cache of the admin menu subtrees on the server- * side is invalidated. The subtreesHash is stored in localStorage as well * and compared to the subtreesHash in drupalSettings to determine when the * admin menu subtrees cache has been invalidated. */ loadSubtrees: function () { var $activeTab = $(this.model.get('activeTab')); var orientation = this.model.get('orientation'); // Only load and render the admin menu subtrees if: // (1) They have not been loaded yet. // (2) The active tab is the administration menu tab, indicated by the // presence of the data-drupal-subtrees attribute. // (3) The orientation of the tray is vertical. if (!this.model.get('areSubtreesLoaded') && typeof $activeTab.data('drupal-subtrees') !== 'undefined' && orientation === 'vertical') { var subtreesHash = drupalSettings.toolbar.subtreesHash; var theme = drupalSettings.ajaxPageState.theme; var endpoint = Drupal.url('toolbar/subtrees/' + subtreesHash); var cachedSubtreesHash = localStorage.getItem('Drupal.toolbar.subtreesHash.' + theme); var cachedSubtrees = JSON.parse(localStorage.getItem('Drupal.toolbar.subtrees.' + theme)); var isVertical = this.model.get('orientation') === 'vertical'; // If we have the subtrees in localStorage and the subtree hash has not // changed, then use the cached data. if (isVertical && subtreesHash === cachedSubtreesHash && cachedSubtrees) { Drupal.toolbar.setSubtrees.resolve(cachedSubtrees); } // Only make the call to get the subtrees if the orientation of the // toolbar is vertical. else if (isVertical) { // Remove the cached menu information. localStorage.removeItem('Drupal.toolbar.subtreesHash.' + theme); localStorage.removeItem('Drupal.toolbar.subtrees.' + theme); // The AJAX response's command will trigger the resolve method of the // Drupal.toolbar.setSubtrees Promise. Drupal.ajax({url: endpoint}).execute(); // Cache the hash for the subtrees locally. localStorage.setItem('Drupal.toolbar.subtreesHash.' + theme, subtreesHash); } } } }); }(jQuery, Drupal, drupalSettings, Backbone)); ;
schnitzel25/conta
sites/default/files/js/js_3YI8rlQtCphHC8k7Vs22nkB6_u47OqwXcD7P8Jm9QQg_BHuNkXbS1MEkV6lGkimSfQE6366BcKxzYtd8U65iUpM.js
JavaScript
gpl-2.0
96,793
/* NicEdit - Micro Inline WYSIWYG * Copyright 2007-2008 Brian Kirchoff * * NicEdit is distributed under the terms of the MIT license * For more information visit http://nicedit.com/ * Do not remove this copyright message */ var bkExtend = function(){ var args = arguments; if (args.length == 1) args = [this, args[0]]; for (var prop in args[1]) args[0][prop] = args[1][prop]; return args[0]; }; function bkClass() { } bkClass.prototype.construct = function() {}; bkClass.extend = function(def) { var classDef = function() { if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments); } }; var proto = new this(bkClass); bkExtend(proto,def); classDef.prototype = proto; classDef.extend = this.extend; return classDef; }; var bkElement = bkClass.extend({ construct : function(elm,d) { if(typeof(elm) == "string") { elm = (d || document).createElement(elm); } elm = $BK(elm); return elm; }, appendTo : function(elm) { elm.appendChild(this); return this; }, appendBefore : function(elm) { elm.parentNode.insertBefore(this,elm); return this; }, addEvent : function(type, fn) { bkLib.addEvent(this,type,fn); return this; }, setContent : function(c) { this.innerHTML = c; return this; }, pos : function() { var curleft = curtop = 0; var o = obj = this; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } var b = (!window.opera) ? parseInt(this.getStyle('border-width') || this.style.border) || 0 : 0; return [curleft+b,curtop+b+this.offsetHeight]; }, noSelect : function() { bkLib.noSelect(this); return this; }, parentTag : function(t) { var elm = this; do { if(elm && elm.nodeName && elm.nodeName.toUpperCase() == t) { return elm; } elm = elm.parentNode; } while(elm); return false; }, hasClass : function(cls) { return this.className.match(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)')); }, addClass : function(cls) { if (!this.hasClass(cls)) { this.className += " nicEdit-"+cls }; return this; }, removeClass : function(cls) { if (this.hasClass(cls)) { this.className = this.className.replace(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'),' '); } return this; }, setStyle : function(st) { var elmStyle = this.style; for(var itm in st) { switch(itm) { case 'float': elmStyle['cssFloat'] = elmStyle['styleFloat'] = st[itm]; break; case 'opacity': elmStyle.opacity = st[itm]; elmStyle.filter = "alpha(opacity=" + Math.round(st[itm]*100) + ")"; break; case 'className': this.className = st[itm]; break; default: //if(document.compatMode || itm != "cursor") { // Nasty Workaround for IE 5.5 elmStyle[itm] = st[itm]; //} } } return this; }, getStyle : function( cssRule, d ) { var doc = (!d) ? document.defaultView : d; if(this.nodeType == 1) return (doc && doc.getComputedStyle) ? doc.getComputedStyle( this, null ).getPropertyValue(cssRule) : this.currentStyle[ bkLib.camelize(cssRule) ]; }, remove : function() { this.parentNode.removeChild(this); return this; }, setAttributes : function(at) { for(var itm in at) { this[itm] = at[itm]; } return this; } }); var bkLib = { isMSIE : (navigator.appVersion.indexOf("MSIE") != -1), addEvent : function(obj, type, fn) { (obj.addEventListener) ? obj.addEventListener( type, fn, false ) : obj.attachEvent("on"+type, fn); }, toArray : function(iterable) { var length = iterable.length, results = new Array(length); while (length--) { results[length] = iterable[length] }; return results; }, noSelect : function(element) { if(element.setAttribute && element.nodeName.toLowerCase() != 'input' && element.nodeName.toLowerCase() != 'textarea') { element.setAttribute('unselectable','on'); } for(var i=0;i<element.childNodes.length;i++) { bkLib.noSelect(element.childNodes[i]); } }, camelize : function(s) { return s.replace(/\-(.)/g, function(m, l){return l.toUpperCase()}); }, inArray : function(arr,item) { return (bkLib.search(arr,item) != null); }, search : function(arr,itm) { for(var i=0; i < arr.length; i++) { if(arr[i] == itm) return i; } return null; }, cancelEvent : function(e) { e = e || window.event; if(e.preventDefault && e.stopPropagation) { e.preventDefault(); e.stopPropagation(); } return false; }, domLoad : [], domLoaded : function() { if (arguments.callee.done) return; arguments.callee.done = true; for (i = 0;i < bkLib.domLoad.length;i++) bkLib.domLoad[i](); }, onDomLoaded : function(fireThis) { this.domLoad.push(fireThis); if (document.addEventListener) { document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null); } else if(bkLib.isMSIE) { document.write("<style>.nicEdit-main p { margin: 0; }</style><scr"+"ipt id=__ie_onload defer " + ((location.protocol == "https:") ? "src='javascript:void(0)'" : "src=//0") + "><\/scr"+"ipt>"); $BK("__ie_onload").onreadystatechange = function() { if (this.readyState == "complete"){bkLib.domLoaded();} }; } window.onload = bkLib.domLoaded; } }; function $BK(elm) { if(typeof(elm) == "string") { elm = document.getElementById(elm); } return (elm && !elm.appendTo) ? bkExtend(elm,bkElement.prototype) : elm; } var bkEvent = { addEvent : function(evType, evFunc) { if(evFunc) { this.eventList = this.eventList || {}; this.eventList[evType] = this.eventList[evType] || []; this.eventList[evType].push(evFunc); } return this; }, fireEvent : function() { var args = bkLib.toArray(arguments), evType = args.shift(); if(this.eventList && this.eventList[evType]) { for(var i=0;i<this.eventList[evType].length;i++) { this.eventList[evType][i].apply(this,args); } } } }; function __(s) { return s; } Function.prototype.closure = function() { var __method = this, args = bkLib.toArray(arguments), obj = args.shift(); return function() { if(typeof(bkLib) != 'undefined') { return __method.apply(obj,args.concat(bkLib.toArray(arguments))); } }; } Function.prototype.closureListener = function() { var __method = this, args = bkLib.toArray(arguments), object = args.shift(); return function(e) { e = e || window.event; if(e.target) { var target = e.target; } else { var target = e.srcElement }; return __method.apply(object, [e,target].concat(args) ); }; } /* START CONFIG */ var nicEditorConfig = bkClass.extend({ buttons : { 'bold' : {name : __('Click to Bold'), command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'}, 'italic' : {name : __('Click to Italic'), command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'}, 'underline' : {name : __('Click to Underline'), command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'}, 'left' : {name : __('Left Align'), command : 'justifyleft', noActive : true}, 'center' : {name : __('Center Align'), command : 'justifycenter', noActive : true}, 'right' : {name : __('Right Align'), command : 'justifyright', noActive : true}, 'justify' : {name : __('Justify Align'), command : 'justifyfull', noActive : true}, 'ol' : {name : __('Insert Ordered List'), command : 'insertorderedlist', tags : ['OL']}, 'ul' : {name : __('Insert Unordered List'), command : 'insertunorderedlist', tags : ['UL']}, 'subscript' : {name : __('Click to Subscript'), command : 'subscript', tags : ['SUB']}, 'superscript' : {name : __('Click to Superscript'), command : 'superscript', tags : ['SUP']}, 'strikethrough' : {name : __('Click to Strike Through'), command : 'strikeThrough', css : {'text-decoration' : 'line-through'}}, 'removeformat' : {name : __('Remove Formatting'), command : 'removeformat', noActive : true}, 'indent' : {name : __('Indent Text'), command : 'indent', noActive : true}, 'outdent' : {name : __('Remove Indent'), command : 'outdent', noActive : true}, 'hr' : {name : __('Horizontal Rule'), command : 'insertHorizontalRule', noActive : true} }, iconsPath : '../nicEditorIcons.gif', buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'], iconList : {"xhtml":1,"bgcolor":2,"forecolor":3,"bold":4,"center":5,"hr":6,"indent":7,"italic":8,"justify":9,"left":10,"ol":11,"outdent":12,"removeformat":13,"right":14,"save":25,"strikethrough":16,"subscript":17,"superscript":18,"ul":19,"underline":20,"image":21,"link":22,"unlink":23,"close":24,"arrow":26,"upload":27} }); /* END CONFIG */ var nicEditors = { nicPlugins : [], editors : [], registerPlugin : function(plugin,options) { this.nicPlugins.push({p : plugin, o : options}); }, allTextAreas : function(nicOptions) { var textareas = document.getElementsByTagName("textarea"); for(var i=0;i<textareas.length;i++) { nicEditors.editors.push(new nicEditor(nicOptions).panelInstance(textareas[i])); } return nicEditors.editors; }, findEditor : function(e) { var editors = nicEditors.editors; for(var i=0;i<editors.length;i++) { if(editors[i].instanceById(e)) { return editors[i].instanceById(e); } } } }; var nicEditor = bkClass.extend({ construct : function(o) { this.options = new nicEditorConfig(); bkExtend(this.options,o); this.nicInstances = new Array(); this.loadedPlugins = new Array(); var plugins = nicEditors.nicPlugins; for(var i=0;i<plugins.length;i++) { this.loadedPlugins.push(new plugins[i].p(this,plugins[i].o)); } nicEditors.editors.push(this); bkLib.addEvent(document.body,'mousedown', this.selectCheck.closureListener(this) ); }, panelInstance : function(e,o) { e = this.checkReplace($BK(e)); var panelElm = new bkElement('DIV').setStyle({width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px'}).appendBefore(e); this.setPanel(panelElm); return this.addInstance(e,o); }, checkReplace : function(e) { var r = nicEditors.findEditor(e); if(r) { r.removeInstance(e); r.removePanel(); } return e; }, addInstance : function(e,o) { e = this.checkReplace($BK(e)); if( e.contentEditable || !!window.opera ) { var newInstance = new nicEditorInstance(e,o,this); } else { var newInstance = new nicEditorIFrameInstance(e,o,this); } this.nicInstances.push(newInstance); return this; }, removeInstance : function(e) { e = $BK(e); var instances = this.nicInstances; for(var i=0;i<instances.length;i++) { if(instances[i].e == e) { instances[i].remove(); this.nicInstances.splice(i,1); } } }, removePanel : function(e) { if(this.nicPanel) { this.nicPanel.remove(); this.nicPanel = null; } }, instanceById : function(e) { e = $BK(e); var instances = this.nicInstances; for(var i=0;i<instances.length;i++) { if(instances[i].e == e) { return instances[i]; } } }, setPanel : function(e) { this.nicPanel = new nicEditorPanel($BK(e),this.options,this); this.fireEvent('panel',this.nicPanel); return this; }, nicCommand : function(cmd,args) { if(this.selectedInstance) { this.selectedInstance.nicCommand(cmd,args); } }, getIcon : function(iconName,options) { var icon = this.options.iconList[iconName]; var file = (options.iconFiles) ? options.iconFiles[iconName] : ''; return {backgroundImage : "url('"+((icon) ? this.options.iconsPath : file)+"')", backgroundPosition : ((icon) ? ((icon-1)*-18) : 0)+'px 0px'}; }, selectCheck : function(e,t) { var found = false; do{ if(t.className && t.className.indexOf('nicEdit') != -1) { return false; } } while(t = t.parentNode); this.fireEvent('blur',this.selectedInstance,t); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; return false; } }); nicEditor = nicEditor.extend(bkEvent); var nicEditorInstance = bkClass.extend({ isSelected : false, construct : function(e,options,nicEditor) { this.ne = nicEditor; this.elm = this.e = e; this.options = options || {}; newX = parseInt(e.getStyle('width')) || e.clientWidth; newY = parseInt(e.getStyle('height')) || e.clientHeight; this.initialHeight = newY-8; var isTextarea = (e.nodeName.toLowerCase() == "textarea"); if(isTextarea || this.options.hasPanel) { var ie7s = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat")) var s = {width: newX+'px', border : '1px solid #ccc', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' }; s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null; this.editorContain = new bkElement('DIV').setStyle(s).appendBefore(e); var editorElm = new bkElement('DIV').setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain); e.setStyle({display : 'none'}); editorElm.innerHTML = e.innerHTML; if(isTextarea) { editorElm.setContent(e.value); this.copyElm = e; var f = e.parentTag('FORM'); if(f) { bkLib.addEvent( f, 'submit', this.saveContent.closure(this)); } } editorElm.setStyle((ie7s) ? {height : newY+'px'} : {overflow: 'hidden'}); this.elm = editorElm; } this.ne.addEvent('blur',this.blur.closure(this)); this.init(); this.blur(); }, init : function() { this.elm.setAttribute('contentEditable','true'); if(this.getContent() == "") { this.setContent('<br />'); } this.instanceDoc = document.defaultView; this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this)); this.ne.fireEvent('add',this); }, remove : function() { this.saveContent(); if(this.copyElm || this.options.hasPanel) { this.editorContain.remove(); this.e.setStyle({'display' : 'block'}); this.ne.removePanel(); } this.disable(); this.ne.fireEvent('remove',this); }, disable : function() { this.elm.setAttribute('contentEditable','false'); }, getSel : function() { return (window.getSelection) ? window.getSelection() : document.selection; }, getRng : function() { var s = this.getSel(); if(!s || s.rangeCount === 0) { return; } return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange(); }, selRng : function(rng,s) { if(window.getSelection) { s.removeAllRanges(); s.addRange(rng); } else { rng.select(); } }, selElm : function() { var r = this.getRng(); if(!r) { return; } if(r.startContainer) { var contain = r.startContainer; if(r.cloneContents().childNodes.length == 1) { for(var i=0;i<contain.childNodes.length;i++) { var rng = contain.childNodes[i].ownerDocument.createRange(); rng.selectNode(contain.childNodes[i]); if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 && r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) { return $BK(contain.childNodes[i]); } } } return $BK(contain); } else { return $BK((this.getSel().type == "Control") ? r.item(0) : r.parentElement()); } }, saveRng : function() { this.savedRange = this.getRng(); this.savedSel = this.getSel(); }, restoreRng : function() { if(this.savedRange) { this.selRng(this.savedRange,this.savedSel); } }, keyDown : function(e,t) { if(e.ctrlKey) { this.ne.fireEvent('key',this,e); } }, selected : function(e,t) { if(!t && !(t = this.selElm)) { t = this.selElm(); } if(!e.ctrlKey) { var selInstance = this.ne.selectedInstance; if(selInstance != this) { if(selInstance) { this.ne.fireEvent('blur',selInstance,t); } this.ne.selectedInstance = this; this.ne.fireEvent('focus',selInstance,t); } this.ne.fireEvent('selected',selInstance,t); this.isFocused = true; this.elm.addClass('selected'); } return false; }, blur : function() { this.isFocused = false; this.elm.removeClass('selected'); }, saveContent : function() { if(this.copyElm || this.options.hasPanel) { this.ne.fireEvent('save',this); (this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent(); } }, getElm : function() { return this.elm; }, getContent : function() { this.content = this.getElm().innerHTML; this.ne.fireEvent('get',this); return this.content; }, setContent : function(e) { this.content = e; this.ne.fireEvent('set',this); this.elm.innerHTML = this.content; }, nicCommand : function(cmd,args) { document.execCommand(cmd,false,args); } }); var nicEditorIFrameInstance = nicEditorInstance.extend({ savedStyles : [], init : function() { var c = this.elm.innerHTML.replace(/^\s+|\s+$/g, ''); this.elm.innerHTML = ''; (!c) ? c = "<br />" : c; this.initialContent = c; this.elmFrame = new bkElement('iframe').setAttributes({'src' : 'javascript:;', 'frameBorder' : 0, 'allowTransparency' : 'true', 'scrolling' : 'no'}).setStyle({height: '100px', width: '100%'}).addClass('frame').appendTo(this.elm); if(this.copyElm) { this.elmFrame.setStyle({width : (this.elm.offsetWidth-4)+'px'}); } var styleList = ['font-size','font-family','font-weight','color']; for(itm in styleList) { this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm); } setTimeout(this.initFrame.closure(this),50); }, disable : function() { this.elm.innerHTML = this.getContent(); }, initFrame : function() { var fd = $BK(this.elmFrame.contentWindow.document); fd.designMode = "on"; fd.open(); var css = this.ne.options.externalCSS; fd.write('<html><head>'+((css) ? '<link href="'+css+'" rel="stylesheet" type="text/css" />' : '')+'</head><body id="nicEditContent" style="margin: 0 !important; background-color: transparent !important;">'+this.initialContent+'</body></html>'); fd.close(); this.frameDoc = fd; this.frameWin = $BK(this.elmFrame.contentWindow); this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles); this.instanceDoc = this.frameWin.document.defaultView; this.heightUpdate(); this.frameDoc.addEvent('mousedown', this.selected.closureListener(this)).addEvent('keyup',this.heightUpdate.closureListener(this)).addEvent('keydown',this.keyDown.closureListener(this)).addEvent('keyup',this.selected.closure(this)); this.ne.fireEvent('add',this); }, getElm : function() { return this.frameContent; }, setContent : function(c) { this.content = c; this.ne.fireEvent('set',this); this.frameContent.innerHTML = this.content; this.heightUpdate(); }, getSel : function() { return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection; }, heightUpdate : function() { this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight,this.initialHeight)+'px'; }, nicCommand : function(cmd,args) { this.frameDoc.execCommand(cmd,false,args); setTimeout(this.heightUpdate.closure(this),100); } }); var nicEditorPanel = bkClass.extend({ construct : function(e,options,nicEditor) { this.elm = e; this.options = options; this.ne = nicEditor; this.panelButtons = new Array(); this.buttonList = bkExtend([],this.ne.options.buttonList); this.panelContain = new bkElement('DIV').setStyle({overflow : 'hidden', width : '100%', border : '1px solid #cccccc', backgroundColor : '#efefef'}).addClass('panelContain'); this.panelElm = new bkElement('DIV').setStyle({margin : '2px', marginTop : '0px', zoom : 1, overflow : 'hidden'}).addClass('panel').appendTo(this.panelContain); this.panelContain.appendTo(e); var opt = this.ne.options; var buttons = opt.buttons; for(button in buttons) { this.addButton(button,opt,true); } this.reorder(); e.noSelect(); }, addButton : function(buttonName,options,noOrder) { var button = options.buttons[buttonName]; var type = (button['type']) ? eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';') : nicEditorButton; var hasButton = bkLib.inArray(this.buttonList,buttonName); if(type && (hasButton || this.ne.options.fullPanel)) { this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne)); if(!hasButton) { this.buttonList.push(buttonName); } } }, findButton : function(itm) { for(var i=0;i<this.panelButtons.length;i++) { if(this.panelButtons[i].name == itm) return this.panelButtons[i]; } }, reorder : function() { var bl = this.buttonList; for(var i=0;i<bl.length;i++) { var button = this.findButton(bl[i]); if(button) { this.panelElm.appendChild(button.margin); } } }, remove : function() { this.elm.remove(); } }); var nicEditorButton = bkClass.extend({ construct : function(e,buttonName,options,nicEditor) { this.options = options.buttons[buttonName]; this.name = buttonName; this.ne = nicEditor; this.elm = e; this.margin = new bkElement('DIV').setStyle({'float' : 'left', marginTop : '2px'}).appendTo(e); this.contain = new bkElement('DIV').setStyle({width : '20px', height : '20px'}).addClass('buttonContain').appendTo(this.margin); this.border = new bkElement('DIV').setStyle({backgroundColor : '#efefef', border : '1px solid #efefef'}).appendTo(this.contain); this.button = new bkElement('DIV').setStyle({width : '18px', height : '18px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass('button').setStyle(this.ne.getIcon(buttonName,options)).appendTo(this.border); this.button.addEvent('mouseover', this.hoverOn.closure(this)).addEvent('mouseout',this.hoverOff.closure(this)).addEvent('mousedown',this.mouseClick.closure(this)).noSelect(); if(!window.opera) { this.button.onmousedown = this.button.onclick = bkLib.cancelEvent; } nicEditor.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)).addEvent('key',this.key.closure(this)); this.disable(); this.init(); }, init : function() { }, hide : function() { this.contain.setStyle({display : 'none'}); }, updateState : function() { if(this.isDisabled) { this.setBg(); } else if(this.isHover) { this.setBg('hover'); } else if(this.isActive) { this.setBg('active'); } else { this.setBg(); } }, setBg : function(state) { switch(state) { case 'hover': var stateStyle = {border : '1px solid #666', backgroundColor : '#ddd'}; break; case 'active': var stateStyle = {border : '1px solid #666', backgroundColor : '#ccc'}; break; default: var stateStyle = {border : '1px solid #efefef', backgroundColor : '#efefef'}; } this.border.setStyle(stateStyle).addClass('button-'+state); }, checkNodes : function(e) { var elm = e; do { if(this.options.tags && bkLib.inArray(this.options.tags,elm.nodeName)) { this.activate(); return true; } } while(elm = elm.parentNode && elm.className != "nicEdit"); elm = $BK(e); while(elm.nodeType == 3) { elm = $BK(elm.parentNode); } if(this.options.css) { for(itm in this.options.css) { if(elm.getStyle(itm,this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) { this.activate(); return true; } } } this.deactivate(); return false; }, activate : function() { if(!this.isDisabled) { this.isActive = true; this.updateState(); this.ne.fireEvent('buttonActivate',this); } }, deactivate : function() { this.isActive = false; this.updateState(); if(!this.isDisabled) { this.ne.fireEvent('buttonDeactivate',this); } }, enable : function(ins,t) { this.isDisabled = false; this.contain.setStyle({'opacity' : 1}).addClass('buttonEnabled'); this.updateState(); this.checkNodes(t); }, disable : function(ins,t) { this.isDisabled = true; this.contain.setStyle({'opacity' : 0.6}).removeClass('buttonEnabled'); this.updateState(); }, toggleActive : function() { (this.isActive) ? this.deactivate() : this.activate(); }, hoverOn : function() { if(!this.isDisabled) { this.isHover = true; this.updateState(); this.ne.fireEvent("buttonOver",this); } }, hoverOff : function() { this.isHover = false; this.updateState(); this.ne.fireEvent("buttonOut",this); }, mouseClick : function() { if(this.options.command) { this.ne.nicCommand(this.options.command,this.options.commandArgs); if(!this.options.noActive) { this.toggleActive(); } } this.ne.fireEvent("buttonClick",this); }, key : function(nicInstance,e) { if(this.options.key && e.ctrlKey && String.fromCharCode(e.keyCode || e.charCode).toLowerCase() == this.options.key) { this.mouseClick(); if(e.preventDefault) e.preventDefault(); } } }); var nicPlugin = bkClass.extend({ construct : function(nicEditor,options) { this.options = options; this.ne = nicEditor; this.ne.addEvent('panel',this.loadPanel.closure(this)); this.init(); }, loadPanel : function(np) { var buttons = this.options.buttons; for(var button in buttons) { np.addButton(button,this.options); } np.reorder(); }, init : function() { } }); /* START CONFIG */ var nicPaneOptions = { }; /* END CONFIG */ var nicEditorPane = bkClass.extend({ construct : function(elm,nicEditor,options,openButton) { this.ne = nicEditor; this.elm = elm; this.pos = elm.pos(); this.contain = new bkElement('div').setStyle({zIndex : '99999', overflow : 'hidden', position : 'absolute', left : this.pos[0]+'px', top : this.pos[1]+'px'}) this.pane = new bkElement('div').setStyle({fontSize : '12px', border : '1px solid #ccc', 'overflow': 'hidden', padding : '4px', textAlign: 'left', backgroundColor : '#ffffc9'}).addClass('pane').setStyle(options).appendTo(this.contain); if(openButton && !openButton.options.noClose) { this.close = new bkElement('div').setStyle({'float' : 'right', height: '16px', width : '16px', cursor : 'pointer'}).setStyle(this.ne.getIcon('close',nicPaneOptions)).addEvent('mousedown',openButton.removePane.closure(this)).appendTo(this.pane); } this.contain.noSelect().appendTo(document.body); this.position(); this.init(); }, init : function() { }, position : function() { if(this.ne.nicPanel) { var panelElm = this.ne.nicPanel.elm; var panelPos = panelElm.pos(); var newLeft = panelPos[0]+parseInt(panelElm.getStyle('width'))-(parseInt(this.pane.getStyle('width'))+8); if(newLeft < this.pos[0]) { this.contain.setStyle({left : newLeft+'px'}); } } }, toggle : function() { this.isVisible = !this.isVisible; this.contain.setStyle({display : ((this.isVisible) ? 'block' : 'none')}); }, remove : function() { if(this.contain) { this.contain.remove(); this.contain = null; } }, append : function(c) { c.appendTo(this.pane); }, setContent : function(c) { this.pane.setContent(c); } }); var nicEditorAdvancedButton = nicEditorButton.extend({ init : function() { this.ne.addEvent('selected',this.removePane.closure(this)).addEvent('blur',this.removePane.closure(this)); }, mouseClick : function() { if(!this.isDisabled) { if(this.pane && this.pane.pane) { this.removePane(); } else { this.pane = new nicEditorPane(this.contain,this.ne,{width : (this.width || '270px'), backgroundColor : '#fff'},this); this.addPane(); this.ne.selectedInstance.saveRng(); } } }, addForm : function(f,elm) { this.form = new bkElement('form').addEvent('submit',this.submit.closureListener(this)); this.pane.append(this.form); this.inputs = {}; for(itm in f) { var field = f[itm]; var val = ''; if(elm) { val = elm.getAttribute(itm); } if(!val) { val = field['value'] || ''; } var type = f[itm].type; if(type == 'title') { new bkElement('div').setContent(field.txt).setStyle({fontSize : '14px', fontWeight: 'bold', padding : '0px', margin : '2px 0'}).appendTo(this.form); } else { var contain = new bkElement('div').setStyle({overflow : 'hidden', clear : 'both'}).appendTo(this.form); if(field.txt) { new bkElement('label').setAttributes({'for' : itm}).setContent(field.txt).setStyle({margin : '2px 4px', fontSize : '13px', width: '50px', lineHeight : '20px', textAlign : 'right', 'float' : 'left'}).appendTo(contain); } switch(type) { case 'text': this.inputs[itm] = new bkElement('input').setAttributes({id : itm, 'value' : val, 'type' : 'text'}).setStyle({margin : '2px 0', fontSize : '13px', 'float' : 'left', height : '20px', border : '1px solid #ccc', overflow : 'hidden'}).setStyle(field.style).appendTo(contain); break; case 'select': this.inputs[itm] = new bkElement('select').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left', margin : '2px 0'}).appendTo(contain); for(opt in field.options) { var o = new bkElement('option').setAttributes({value : opt, selected : (opt == val) ? 'selected' : ''}).setContent(field.options[opt]).appendTo(this.inputs[itm]); } break; case 'content': this.inputs[itm] = new bkElement('textarea').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left'}).setStyle(field.style).appendTo(contain); this.inputs[itm].value = val; } } } new bkElement('input').setAttributes({'type' : 'submit'}).setStyle({backgroundColor : '#efefef',border : '1px solid #ccc', margin : '3px 0', 'float' : 'left', 'clear' : 'both'}).appendTo(this.form); this.form.onsubmit = bkLib.cancelEvent; }, submit : function() { }, findElm : function(tag,attr,val) { var list = this.ne.selectedInstance.getElm().getElementsByTagName(tag); for(var i=0;i<list.length;i++) { if(list[i].getAttribute(attr) == val) { return $BK(list[i]); } } }, removePane : function() { if(this.pane) { this.pane.remove(); this.pane = null; this.ne.selectedInstance.restoreRng(); } } }); var nicButtonTips = bkClass.extend({ construct : function(nicEditor) { this.ne = nicEditor; nicEditor.addEvent('buttonOver',this.show.closure(this)).addEvent('buttonOut',this.hide.closure(this)); }, show : function(button) { this.timer = setTimeout(this.create.closure(this,button),400); }, create : function(button) { this.timer = null; if(!this.pane) { this.pane = new nicEditorPane(button.button,this.ne,{fontSize : '12px', marginTop : '5px'}); this.pane.setContent(button.options.name); } }, hide : function(button) { if(this.timer) { clearTimeout(this.timer); } if(this.pane) { this.pane = this.pane.remove(); } } }); nicEditors.registerPlugin(nicButtonTips); /* START CONFIG */ var nicSelectOptions = { buttons : { 'fontSize' : {name : __('Select Font Size'), type : 'nicEditorFontSizeSelect', command : 'fontsize'}, 'fontFamily' : {name : __('Select Font Family'), type : 'nicEditorFontFamilySelect', command : 'fontname'}, 'fontFormat' : {name : __('Select Font Format'), type : 'nicEditorFontFormatSelect', command : 'formatBlock'} } }; /* END CONFIG */ var nicEditorSelect = bkClass.extend({ construct : function(e,buttonName,options,nicEditor) { this.options = options.buttons[buttonName]; this.elm = e; this.ne = nicEditor; this.name = buttonName; this.selOptions = new Array(); this.margin = new bkElement('div').setStyle({'float' : 'left', margin : '2px 1px 0 1px'}).appendTo(this.elm); this.contain = new bkElement('div').setStyle({width: '90px', height : '20px', cursor : 'pointer', overflow: 'hidden'}).addClass('selectContain').addEvent('click',this.toggle.closure(this)).appendTo(this.margin); this.items = new bkElement('div').setStyle({overflow : 'hidden', zoom : 1, border: '1px solid #ccc', paddingLeft : '3px', backgroundColor : '#fff'}).appendTo(this.contain); this.control = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'right', height: '18px', width : '16px'}).addClass('selectControl').setStyle(this.ne.getIcon('arrow',options)).appendTo(this.items); this.txt = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'left', width : '66px', height : '14px', marginTop : '1px', fontFamily : 'sans-serif', textAlign : 'center', fontSize : '12px'}).addClass('selectTxt').appendTo(this.items); if(!window.opera) { this.contain.onmousedown = this.control.onmousedown = this.txt.onmousedown = bkLib.cancelEvent; } this.margin.noSelect(); this.ne.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)); this.disable(); this.init(); }, disable : function() { this.isDisabled = true; this.close(); this.contain.setStyle({opacity : 0.6}); }, enable : function(t) { this.isDisabled = false; this.close(); this.contain.setStyle({opacity : 1}); }, setDisplay : function(txt) { this.txt.setContent(txt); }, toggle : function() { if(!this.isDisabled) { (this.pane) ? this.close() : this.open(); } }, open : function() { this.pane = new nicEditorPane(this.items,this.ne,{width : '88px', padding: '0px', borderTop : 0, borderLeft : '1px solid #ccc', borderRight : '1px solid #ccc', borderBottom : '0px', backgroundColor : '#fff'}); for(var i=0;i<this.selOptions.length;i++) { var opt = this.selOptions[i]; var itmContain = new bkElement('div').setStyle({overflow : 'hidden', borderBottom : '1px solid #ccc', width: '88px', textAlign : 'left', overflow : 'hidden', cursor : 'pointer'}); var itm = new bkElement('div').setStyle({padding : '0px 4px'}).setContent(opt[1]).appendTo(itmContain).noSelect(); itm.addEvent('click',this.update.closure(this,opt[0])).addEvent('mouseover',this.over.closure(this,itm)).addEvent('mouseout',this.out.closure(this,itm)).setAttributes('id',opt[0]); this.pane.append(itmContain); if(!window.opera) { itm.onmousedown = bkLib.cancelEvent; } } }, close : function() { if(this.pane) { this.pane = this.pane.remove(); } }, over : function(opt) { opt.setStyle({backgroundColor : '#ccc'}); }, out : function(opt) { opt.setStyle({backgroundColor : '#fff'}); }, add : function(k,v) { this.selOptions.push(new Array(k,v)); }, update : function(elm) { this.ne.nicCommand(this.options.command,elm); this.close(); } }); var nicEditorFontSizeSelect = nicEditorSelect.extend({ sel : {1 : '1&nbsp;(8pt)', 2 : '2&nbsp;(10pt)', 3 : '3&nbsp;(12pt)', 4 : '4&nbsp;(14pt)', 5 : '5&nbsp;(18pt)', 6 : '6&nbsp;(24pt)'}, init : function() { this.setDisplay('Font&nbsp;Size...'); for(itm in this.sel) { this.add(itm,'<font size="'+itm+'">'+this.sel[itm]+'</font>'); } } }); var nicEditorFontFamilySelect = nicEditorSelect.extend({ sel : {'arial' : 'Arial','comic sans ms' : 'Comic Sans','courier new' : 'Courier New','georgia' : 'Georgia', 'helvetica' : 'Helvetica', 'impact' : 'Impact', 'times new roman' : 'Times', 'trebuchet ms' : 'Trebuchet', 'verdana' : 'Verdana'}, init : function() { this.setDisplay('Font&nbsp;Family...'); for(itm in this.sel) { this.add(itm,'<font face="'+itm+'">'+this.sel[itm]+'</font>'); } } }); var nicEditorFontFormatSelect = nicEditorSelect.extend({ sel : {'p' : 'Paragraph', 'pre' : 'Pre', 'h6' : 'Heading&nbsp;6', 'h5' : 'Heading&nbsp;5', 'h4' : 'Heading&nbsp;4', 'h3' : 'Heading&nbsp;3', 'h2' : 'Heading&nbsp;2', 'h1' : 'Heading&nbsp;1'}, init : function() { this.setDisplay('Font&nbsp;Format...'); for(itm in this.sel) { var tag = itm.toUpperCase(); this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>'); } } }); nicEditors.registerPlugin(nicPlugin,nicSelectOptions); /* START CONFIG */ var nicLinkOptions = { buttons : { 'link' : {name : 'Add Link', type : 'nicLinkButton', tags : ['A']}, 'unlink' : {name : 'Remove Link', command : 'unlink', noActive : true} } }; /* END CONFIG */ var nicLinkButton = nicEditorAdvancedButton.extend({ addPane : function() { this.ln = this.ne.selectedInstance.selElm().parentTag('A'); this.addForm({ '' : {type : 'title', txt : 'Add/Edit Link'}, 'href' : {type : 'text', txt : 'URL', value : 'http://', style : {width: '150px'}}, 'title' : {type : 'text', txt : 'Title'}, 'target' : {type : 'select', txt : 'Open In', options : {'' : 'Current Window', '_blank' : 'New Window'},style : {width : '100px'}} },this.ln); }, submit : function(e) { var url = this.inputs['href'].value; if(url == "http://" || url == "") { alert("You must enter a URL to Create a Link"); return false; } this.removePane(); if(!this.ln) { var tmp = 'javascript:nicTemp();'; this.ne.nicCommand("createlink",tmp); this.ln = this.findElm('A','href',tmp); } if(this.ln) { this.ln.setAttributes({ href : this.inputs['href'].value, title : this.inputs['title'].value, target : this.inputs['target'].options[this.inputs['target'].selectedIndex].value }); } } }); nicEditors.registerPlugin(nicPlugin,nicLinkOptions); /* START CONFIG */ var nicColorOptions = { buttons : { 'forecolor' : {name : __('Change Text Color'), type : 'nicEditorColorButton', noClose : true}, 'bgcolor' : {name : __('Change Background Color'), type : 'nicEditorBgColorButton', noClose : true} } }; /* END CONFIG */ var nicEditorColorButton = nicEditorAdvancedButton.extend({ addPane : function() { var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'}; var colorItems = new bkElement('DIV').setStyle({width: '270px'}); for(var r in colorList) { for(var b in colorList) { for(var g in colorList) { var colorCode = '#'+colorList[r]+colorList[g]+colorList[b]; var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems); var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare); var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder); if(!window.opera) { colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent; } } } } this.pane.append(colorItems.noSelect()); }, colorSelect : function(c) { this.ne.nicCommand('foreColor',c); this.removePane(); }, on : function(colorBorder) { colorBorder.setStyle({border : '2px solid #000'}); }, off : function(colorBorder,colorCode) { colorBorder.setStyle({border : '2px solid '+colorCode}); } }); var nicEditorBgColorButton = nicEditorColorButton.extend({ colorSelect : function(c) { this.ne.nicCommand('hiliteColor',c); this.removePane(); } }); nicEditors.registerPlugin(nicPlugin,nicColorOptions); /* START CONFIG */ var nicImageOptions = { buttons : { 'image' : {name : 'Add Image', type : 'nicImageButton', tags : ['IMG']} } }; /* END CONFIG */ var nicImageButton = nicEditorAdvancedButton.extend({ addPane : function() { this.im = this.ne.selectedInstance.selElm().parentTag('IMG'); this.addForm({ '' : {type : 'title', txt : 'Add/Edit Image'}, 'src' : {type : 'text', txt : 'URL', 'value' : 'http://', style : {width: '150px'}}, 'alt' : {type : 'text', txt : 'Alt Text', style : {width: '100px'}}, 'align' : {type : 'select', txt : 'Align', options : {none : 'Default','left' : 'Left', 'right' : 'Right'}} },this.im); }, submit : function(e) { var src = this.inputs['src'].value; if(src == "" || src == "http://") { alert("You must enter a Image URL to insert"); return false; } this.removePane(); if(!this.im) { var tmp = 'javascript:nicImTemp();'; this.ne.nicCommand("insertImage",tmp); this.im = this.findElm('IMG','src',tmp); } if(this.im) { this.im.setAttributes({ src : this.inputs['src'].value, alt : this.inputs['alt'].value, align : this.inputs['align'].value }); } } }); nicEditors.registerPlugin(nicPlugin,nicImageOptions); /* START CONFIG */ var nicSaveOptions = { buttons : { 'save' : {name : __('Save this content'), type : 'nicEditorSaveButton'} } }; /* END CONFIG */ var nicEditorSaveButton = nicEditorButton.extend({ init : function() { if(!this.ne.options.onSave) { this.margin.setStyle({'display' : 'none'}); } }, mouseClick : function() { var onSave = this.ne.options.onSave; var selectedInstance = this.ne.selectedInstance; onSave(selectedInstance.getContent(), selectedInstance.elm.id, selectedInstance); } }); nicEditors.registerPlugin(nicPlugin,nicSaveOptions); /* START CONFIG */ var nicUploadOptions = { buttons : { 'upload' : {name : 'Upload Image', type : 'nicUploadButton'} } }; /* END CONFIG */ var nicUploadButton = nicEditorAdvancedButton.extend({ nicURI : 'http://api.imgur.com/2/upload.json', errorText : 'Failed to upload image', addPane : function() { if(typeof window.FormData === "undefined") { return this.onError("Image uploads are not supported in this browser, use Chrome, Firefox, or Safari instead."); } this.im = this.ne.selectedInstance.selElm().parentTag('IMG'); var container = new bkElement('div') .setStyle({ padding: '10px' }) .appendTo(this.pane.pane); new bkElement('div') .setStyle({ fontSize: '14px', fontWeight : 'bold', paddingBottom: '5px' }) .setContent('Insert an Image') .appendTo(container); this.fileInput = new bkElement('input') .setAttributes({ 'type' : 'file' }) .appendTo(container); this.progress = new bkElement('progress') .setStyle({ width : '100%', display: 'none' }) .setAttributes('max', 100) .appendTo(container); this.fileInput.onchange = this.uploadFile.closure(this); }, onError : function(msg) { this.removePane(); alert(msg || "Failed to upload image"); }, uploadFile : function() { var file = this.fileInput.files[0]; if (!file || !file.type.match(/image.*/)) { this.onError("Only image files can be uploaded"); return; } this.fileInput.setStyle({ display: 'none' }); this.setProgress(0); var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ fd.append("image", file); fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660"); var xhr = new XMLHttpRequest(); xhr.open("POST", this.ne.options.uploadURI || this.nicURI); xhr.onload = function() { try { var res = JSON.parse(xhr.responseText); } catch(e) { return this.onError(); } this.onUploaded(res.upload); }.closure(this); xhr.onerror = this.onError.closure(this); xhr.upload.onprogress = function(e) { this.setProgress(e.loaded / e.total); }.closure(this); xhr.send(fd); }, setProgress : function(percent) { this.progress.setStyle({ display: 'block' }); if(percent < .98) { this.progress.value = percent; } else { this.progress.removeAttribute('value'); } }, onUploaded : function(options) { this.removePane(); var src = options.links.original; if(!this.im) { this.ne.selectedInstance.restoreRng(); var tmp = 'javascript:nicImTemp();'; this.ne.nicCommand("insertImage", src); this.im = this.findElm('IMG','src', src); } var w = parseInt(this.ne.selectedInstance.elm.getStyle('width')); if(this.im) { this.im.setAttributes({ src : src, width : (w && options.image.width) ? Math.min(w, options.image.width) : '' }); } } }); nicEditors.registerPlugin(nicPlugin,nicUploadOptions); var nicXHTML = bkClass.extend({ stripAttributes : ['_moz_dirty','_moz_resizing','_extended'], noShort : ['style','title','script','textarea','a'], cssReplace : {'font-weight:bold;' : 'strong', 'font-style:italic;' : 'em'}, sizes : {1 : 'xx-small', 2 : 'x-small', 3 : 'small', 4 : 'medium', 5 : 'large', 6 : 'x-large'}, construct : function(nicEditor) { this.ne = nicEditor; if(this.ne.options.xhtml) { nicEditor.addEvent('get',this.cleanup.closure(this)); } }, cleanup : function(ni) { var node = ni.getElm(); var xhtml = this.toXHTML(node); ni.content = xhtml; }, toXHTML : function(n,r,d) { var txt = ''; var attrTxt = ''; var cssTxt = ''; var nType = n.nodeType; var nName = n.nodeName.toLowerCase(); var nChild = n.hasChildNodes && n.hasChildNodes(); var extraNodes = new Array(); switch(nType) { case 1: var nAttributes = n.attributes; switch(nName) { case 'b': nName = 'strong'; break; case 'i': nName = 'em'; break; case 'font': nName = 'span'; break; } if(r) { for(var i=0;i<nAttributes.length;i++) { var attr = nAttributes[i]; var attributeName = attr.nodeName.toLowerCase(); var attributeValue = attr.nodeValue; if(!attr.specified || !attributeValue || bkLib.inArray(this.stripAttributes,attributeName) || typeof(attributeValue) == "function") { continue; } switch(attributeName) { case 'style': var css = attributeValue.replace(/ /g,""); for(itm in this.cssReplace) { if(css.indexOf(itm) != -1) { extraNodes.push(this.cssReplace[itm]); css = css.replace(itm,''); } } cssTxt += css; attributeValue = ""; break; case 'class': attributeValue = attributeValue.replace("Apple-style-span",""); break; case 'size': cssTxt += "font-size:"+this.sizes[attributeValue]+';'; attributeValue = ""; break; } if(attributeValue) { attrTxt += ' '+attributeName+'="'+attributeValue+'"'; } } if(cssTxt) { attrTxt += ' style="'+cssTxt+'"'; } for(var i=0;i<extraNodes.length;i++) { txt += '<'+extraNodes[i]+'>'; } if(attrTxt == "" && nName == "span") { r = false; } if(r) { txt += '<'+nName; if(nName != 'br') { txt += attrTxt; } } } if(!nChild && !bkLib.inArray(this.noShort,attributeName)) { if(r) { txt += ' />'; } } else { if(r) { txt += '>'; } for(var i=0;i<n.childNodes.length;i++) { var results = this.toXHTML(n.childNodes[i],true,true); if(results) { txt += results; } } } if(r && nChild) { txt += '</'+nName+'>'; } for(var i=0;i<extraNodes.length;i++) { txt += '</'+extraNodes[i]+'>'; } break; case 3: //if(n.nodeValue != '\n') { txt += n.nodeValue; //} break; } return txt; } }); nicEditors.registerPlugin(nicXHTML); var nicBBCode = bkClass.extend({ construct : function(nicEditor) { this.ne = nicEditor; if(this.ne.options.bbCode) { nicEditor.addEvent('get',this.bbGet.closure(this)); nicEditor.addEvent('set',this.bbSet.closure(this)); var loadedPlugins = this.ne.loadedPlugins; for(itm in loadedPlugins) { if(loadedPlugins[itm].toXHTML) { this.xhtml = loadedPlugins[itm]; } } } }, bbGet : function(ni) { var xhtml = this.xhtml.toXHTML(ni.getElm()); ni.content = this.toBBCode(xhtml); }, bbSet : function(ni) { ni.content = this.fromBBCode(ni.content); }, toBBCode : function(xhtml) { function rp(r,m) { xhtml = xhtml.replace(r,m); } rp(/\n/gi,""); rp(/<strong>(.*?)<\/strong>/gi,"[b]$1[/b]"); rp(/<em>(.*?)<\/em>/gi,"[i]$1[/i]"); rp(/<span.*?style="text-decoration:underline;">(.*?)<\/span>/gi,"[u]$1[/u]"); rp(/<ul>(.*?)<\/ul>/gi,"[list]$1[/list]"); rp(/<li>(.*?)<\/li>/gi,"[*]$1[/*]"); rp(/<ol>(.*?)<\/ol>/gi,"[list=1]$1[/list]"); rp(/<img.*?src="(.*?)".*?>/gi,"[img]$1[/img]"); rp(/<a.*?href="(.*?)".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]"); rp(/<br.*?>/gi,"\n"); rp(/<.*?>.*?<\/.*?>/gi,""); return xhtml; }, fromBBCode : function(bbCode) { function rp(r,m) { bbCode = bbCode.replace(r,m); } rp(/\[b\](.*?)\[\/b\]/gi,"<strong>$1</strong>"); rp(/\[i\](.*?)\[\/i\]/gi,"<em>$1</em>"); rp(/\[u\](.*?)\[\/u\]/gi,"<span style=\"text-decoration:underline;\">$1</span>"); rp(/\[list\](.*?)\[\/list\]/gi,"<ul>$1</ul>"); rp(/\[list=1\](.*?)\[\/list\]/gi,"<ol>$1</ol>"); rp(/\[\*\](.*?)\[\/\*\]/gi,"<li>$1</li>"); rp(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />"); rp(/\[url=(.*?)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>"); rp(/\n/gi,"<br />"); //rp(/\[.*?\](.*?)\[\/.*?\]/gi,"$1"); return bbCode; } }); nicEditors.registerPlugin(nicBBCode); nicEditor = nicEditor.extend({ floatingPanel : function() { this.floating = new bkElement('DIV').setStyle({position: 'absolute', top : '-1000px'}).appendTo(document.body); this.addEvent('focus', this.reposition.closure(this)).addEvent('blur', this.hide.closure(this)); this.setPanel(this.floating); }, reposition : function() { var e = this.selectedInstance.e; this.floating.setStyle({ width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px' }); var top = e.offsetTop-this.floating.offsetHeight; if(top < 0) { top = e.offsetTop+e.offsetHeight; } this.floating.setStyle({ top : top+'px', left : e.offsetLeft+'px', display : 'block' }); }, hide : function() { this.floating.setStyle({ top : '-1000px'}); } }); /* START CONFIG */ var nicCodeOptions = { buttons : { 'xhtml' : {name : 'Edit HTML', type : 'nicCodeButton'} } }; /* END CONFIG */ var nicCodeButton = nicEditorAdvancedButton.extend({ width : '350px', addPane : function() { this.addForm({ '' : {type : 'title', txt : 'Edit HTML'}, 'code' : {type : 'content', 'value' : this.ne.selectedInstance.getContent(), style : {width: '340px', height : '200px'}} }); }, submit : function(e) { var code = this.inputs['code'].value; this.ne.selectedInstance.setContent(code); this.removePane(); } }); nicEditors.registerPlugin(nicPlugin,nicCodeOptions);
drupaals/demo.com
d7/sites/all/libraries/nicedit/nicEdit.js
JavaScript
gpl-2.0
50,796
/** * Client UI Javascript for the Calendar plugin * * @version @package_version@ * @author Lazlo Westerhof <[email protected]> * @author Thomas Bruederli <[email protected]> * * Copyright (C) 2010, Lazlo Westerhof <[email protected]> * Copyright (C) 2012, Kolab Systems AG <[email protected]> * * This program 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, either version 3 of the * License, or (at your option) any later version. * * This program 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/>. */ // Roundcube calendar UI client class function rcube_calendar_ui(settings) { // extend base class rcube_calendar.call(this, settings); /*** member vars ***/ this.is_loading = false; this.selected_event = null; this.selected_calendar = null; this.search_request = null; this.saving_lock; /*** private vars ***/ var DAY_MS = 86400000; var HOUR_MS = 3600000; var me = this; var gmt_offset = (new Date().getTimezoneOffset() / -60) - (settings.timezone || 0) - (settings.dst || 0); var client_timezone = new Date().getTimezoneOffset(); var day_clicked = day_clicked_ts = 0; var ignore_click = false; var event_defaults = { free_busy:'busy', alarms:'' }; var event_attendees = []; var attendees_list; var freebusy_ui = { workinhoursonly:false, needsupdate:false }; var freebusy_data = {}; var current_view = null; var exec_deferred = bw.ie6 ? 5 : 1; var sensitivitylabels = { 'public':rcmail.gettext('public','calendar'), 'private':rcmail.gettext('private','calendar'), 'confidential':rcmail.gettext('confidential','calendar') }; var ui_loading = rcmail.set_busy(true, 'loading'); // general datepicker settings var datepicker_settings = { // translate from fullcalendar format to datepicker format dateFormat: settings['date_format'].replace(/M/g, 'm').replace(/mmmmm/, 'MM').replace(/mmm/, 'M').replace(/dddd/, 'DD').replace(/ddd/, 'D').replace(/yy/g, 'y'), firstDay : settings['first_day'], dayNamesMin: settings['days_short'], monthNames: settings['months'], monthNamesShort: settings['months'], changeMonth: false, showOtherMonths: true, selectOtherMonths: true }; /*** imports ***/ var Q = this.quote_html; var text2html = this.text2html; var event_date_text = this.event_date_text; var parse_datetime = this.parse_datetime; var date2unixtime = this.date2unixtime; var fromunixtime = this.fromunixtime; var parseISO8601 = this.parseISO8601; var init_alarms_edit = this.init_alarms_edit; /*** private methods ***/ // same as str.split(delimiter) but it ignores delimiters within quoted strings var explode_quoted_string = function(str, delimiter) { var result = [], strlen = str.length, q, p, i, char, last; for (q = p = i = 0; i < strlen; i++) { char = str.charAt(i); if (char == '"' && last != '\\') { q = !q; } else if (!q && char == delimiter) { result.push(str.substring(p, i)); p = i + 1; } last = char; } result.push(str.substr(p)); return result; }; // clone the given date object and optionally adjust time var clone_date = function(date, adjust) { var d = new Date(date.getTime()); // set time to 00:00 if (adjust == 1) { d.setHours(0); d.setMinutes(0); } // set time to 23:59 else if (adjust == 2) { d.setHours(23); d.setMinutes(59); } return d; }; // fix date if jumped over a DST change var fix_date = function(date) { if (date.getHours() == 23) date.setTime(date.getTime() + HOUR_MS); else if (date.getHours() > 0) date.setHours(0); }; // turn the given date into an ISO 8601 date string understandable by PHPs strtotime() var date2servertime = function(date) { return date.getFullYear()+'-'+zeropad(date.getMonth()+1)+'-'+zeropad(date.getDate()) + 'T'+zeropad(date.getHours())+':'+zeropad(date.getMinutes())+':'+zeropad(date.getSeconds()); } var date2timestring = function(date, dateonly) { return date2servertime(date).replace(/[^0-9]/g, '').substr(0, (dateonly ? 8 : 14)); } var zeropad = function(num) { return (num < 10 ? '0' : '') + num; } var render_link = function(url) { var islink = false, href = url; if (url.match(/^[fhtpsmailo]+?:\/\//i)) { islink = true; } else if (url.match(/^[a-z0-9.-:]+(\/|$)/i)) { islink = true; href = 'http://' + url; } return islink ? '<a href="' + Q(href) + '" target="_blank">' + Q(url) + '</a>' : Q(url); } // determine whether the given date is on a weekend var is_weekend = function(date) { return date.getDay() == 0 || date.getDay() == 6; }; var is_workinghour = function(date) { if (settings['work_start'] > settings['work_end']) return date.getHours() >= settings['work_start'] || date.getHours() < settings['work_end']; else return date.getHours() >= settings['work_start'] && date.getHours() < settings['work_end']; }; // check if the event has 'real' attendees, excluding the current user var has_attendees = function(event) { return (event.attendees && event.attendees.length && (event.attendees.length > 1 || String(event.attendees[0].email).toLowerCase() != settings.identity.email)); }; // check if the current user is an attendee of this event var is_attendee = function(event, role, email) { var emails = email ? ';'+email.toLowerCase() : settings.identity.emails; for (var i=0; event.attendees && i < event.attendees.length; i++) { if ((!role || event.attendees[i].role == role) && event.attendees[i].email && emails.indexOf(';'+event.attendees[i].email.toLowerCase()) >= 0) return event.attendees[i]; } return false; }; // check if the current user is the organizer var is_organizer = function(event, email) { return is_attendee(event, 'ORGANIZER', email) || !event.id; }; var load_attachment = function(event, att) { var qstring = '_id='+urlencode(att.id)+'&_event='+urlencode(event.recurrence_id||event.id)+'&_cal='+urlencode(event.calendar); // open attachment in frame if it's of a supported mimetype if (id && att.mimetype && $.inArray(att.mimetype, settings.mimetypes)>=0) { if (rcmail.open_window(rcmail.env.comm_path+'&_action=get-attachment&'+qstring+'&_frame=1', true, true)) { return; } } rcmail.goto_url('get-attachment', qstring+'&_download=1', false); }; // build event attachments list var event_show_attachments = function(list, container, event, edit) { var i, id, len, img, content, li, elem, ul = document.createElement('UL'); ul.className = 'attachmentslist'; for (i=0, len=list.length; i<len; i++) { elem = list[i]; li = document.createElement('LI'); li.className = elem.classname; if (edit) { rcmail.env.attachments[elem.id] = elem; // delete icon content = document.createElement('A'); content.href = '#delete'; content.title = rcmail.gettext('delete'); content.className = 'delete'; $(content).click({id: elem.id}, function(e) { remove_attachment(this, e.data.id); return false; }); if (!rcmail.env.deleteicon) content.innerHTML = rcmail.gettext('delete'); else { img = document.createElement('IMG'); img.src = rcmail.env.deleteicon; img.alt = rcmail.gettext('delete'); content.appendChild(img); } li.appendChild(content); } // name/link content = document.createElement('A'); content.innerHTML = elem.name; content.className = 'file'; content.href = '#load'; $(content).click({event: event, att: elem}, function(e) { load_attachment(e.data.event, e.data.att); return false; }); li.appendChild(content); ul.appendChild(li); } if (edit && rcmail.gui_objects.attachmentlist) { ul.id = rcmail.gui_objects.attachmentlist.id; rcmail.gui_objects.attachmentlist = ul; } container.empty().append(ul); }; var remove_attachment = function(elem, id) { $(elem.parentNode).hide(); rcmail.env.deleted_attachments.push(id); delete rcmail.env.attachments[id]; }; // event details dialog (show only) var event_show_dialog = function(event) { var $dialog = $("#eventshow").removeClass().addClass('uidialog'); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:false }; me.selected_event = event; // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); $dialog.find('div.event-section, div.event-line').hide(); $('#event-title').html(Q(event.title)).show(); if (event.location) $('#event-location').html('@ ' + text2html(event.location)).show(); if (event.description) $('#event-description').show().children('.event-text').html(text2html(event.description, 300, 6)); if (event.vurl) $('#event-url').show().children('.event-text').html(render_link(event.vurl)); // render from-to in a nice human-readable way // -> now shown in dialog title // $('#event-date').html(Q(me.event_date_text(event))).show(); if (event.recurrence && event.recurrence_text) $('#event-repeat').show().children('.event-text').html(Q(event.recurrence_text)); if (event.alarms && event.alarms_text) $('#event-alarm').show().children('.event-text').html(Q(event.alarms_text)); if (calendar.name) $('#event-calendar').show().children('.event-text').html(Q(calendar.name)).removeClass().addClass('event-text').addClass('cal-'+calendar.id); if (event.categories) $('#event-category').show().children('.event-text').html(Q(event.categories)).removeClass().addClass('event-text cat-'+String(event.categories).replace(rcmail.identifier_expr, '')); if (event.free_busy) $('#event-free-busy').show().children('.event-text').html(Q(rcmail.gettext(event.free_busy, 'calendar'))); if (event.priority > 0) { var priolabels = [ '', rcmail.gettext('highest'), rcmail.gettext('high'), '', '', rcmail.gettext('normal'), '', '', rcmail.gettext('low'), rcmail.gettext('lowest') ]; $('#event-priority').show().children('.event-text').html(Q(event.priority+' '+priolabels[event.priority])); } if (event.sensitivity && event.sensitivity != 'public') { $('#event-sensitivity').show().children('.event-text').html(Q(sensitivitylabels[event.sensitivity])); $dialog.addClass('sensitivity-'+event.sensitivity); } // create attachments list if ($.isArray(event.attachments)) { event_show_attachments(event.attachments, $('#event-attachments').children('.event-text'), event); if (event.attachments.length > 0) { $('#event-attachments').show(); } } else if (calendar.attachments) { // fetch attachments, some drivers doesn't set 'attachments' prop of the event? } // list event attendees if (calendar.attendees && event.attendees) { var data, dispname, organizer = false, rsvp = false, line, morelink, html = '',overflow = ''; for (var j=0; j < event.attendees.length; j++) { data = event.attendees[j]; dispname = Q(data.name || data.email); if (data.email) { dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>'; if (data.role == 'ORGANIZER') organizer = true; else if ((data.status == 'NEEDS-ACTION' || data.status == 'TENTATIVE') && settings.identity.emails.indexOf(';'+data.email) >= 0) rsvp = data.status.toLowerCase(); } line = '<span class="attendee ' + String(data.role == 'ORGANIZER' ? 'organizer' : data.status).toLowerCase() + '">' + dispname + '</span> '; if (morelink) overflow += line; else html += line; // stop listing attendees if (j == 7 && event.attendees.length >= 7) { morelink = $('<a href="#more" class="morelink"></a>').html(rcmail.gettext('andnmore', 'calendar').replace('$nr', event.attendees.length - j - 1)); } } if (html && (event.attendees.length > 1 || !organizer)) { $('#event-attendees').show() .children('.event-text') .html(html) .find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); // display all attendees in a popup when clicking the "more" link if (morelink) { $('#event-attendees .event-text').append(morelink); morelink.click(function(e){ rcmail.show_popup_dialog( '<div id="all-event-attendees" class="event-attendees">' + html + overflow + '</div>', rcmail.gettext('tabattendees','calendar'), null, { width:450, modal:false }); $('#all-event-attendees a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); return false; }) } } $('#event-rsvp')[(rsvp&&!organizer?'show':'hide')](); $('#event-rsvp .rsvp-buttons input').prop('disabled', false).filter('input[rel='+rsvp+']').prop('disabled', true); } var buttons = {}; if (calendar.editable && event.editable !== false) { buttons[rcmail.gettext('edit', 'calendar')] = function() { event_edit_dialog('edit', event); }; buttons[rcmail.gettext('remove', 'calendar')] = function() { me.delete_event(event); $dialog.dialog('close'); }; } else { buttons[rcmail.gettext('close', 'calendar')] = function(){ $dialog.dialog('close'); }; } // open jquery UI dialog $dialog.dialog({ modal: false, resizable: !bw.ie6, closeOnEscape: (!bw.ie6 && !bw.ie7), // disable for performance reasons title: Q(me.event_date_text(event)), open: function() { $dialog.parent().find('.ui-button').first().focus(); }, close: function() { $dialog.dialog('destroy').hide(); }, buttons: buttons, minWidth: 320, width: 420 }).show(); // set dialog size according to content me.dialog_resize($dialog.get(0), $dialog.height(), 420); /* // add link for "more options" drop-down $('<a>') .attr('href', '#') .html('More Options') .addClass('dropdown-link') .click(function(){ return false; }) .insertBefore($dialog.parent().find('.ui-dialog-buttonset').children().first()); */ }; // bring up the event dialog (jquery-ui popup) var event_edit_dialog = function(action, event) { // close show dialog first $("#eventshow:ui-dialog").dialog('close'); var $dialog = $('<div>'); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:action=='new' }; me.selected_event = $.extend($.extend({}, event_defaults), event); // clone event object (with defaults) event = me.selected_event; // change reference to clone freebusy_ui.needsupdate = false; // reset dialog first $('#eventtabs').get(0).reset(); // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); // event details var title = $('#edit-title').val(event.title || ''); var location = $('#edit-location').val(event.location || ''); var description = $('#edit-description').html(event.description || ''); var vurl = $('#edit-url').val(event.vurl || ''); var categories = $('#edit-categories').val(event.categories); var calendars = $('#edit-calendar').val(event.calendar); var freebusy = $('#edit-free-busy').val(event.free_busy); var priority = $('#edit-priority').val(event.priority); var sensitivity = $('#edit-sensitivity').val(event.sensitivity); var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000); var startdate = $('#edit-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration); var starttime = $('#edit-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show(); var enddate = $('#edit-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format'])); var endtime = $('#edit-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show(); var allday = $('#edit-allday').get(0); var notify = $('#edit-attendees-donotify').get(0); var invite = $('#edit-attendees-invite').get(0); notify.checked = has_attendees(event), invite.checked = true; if (event.allDay) { starttime.val("12:00").hide(); endtime.val("13:00").hide(); allday.checked = true; } else { allday.checked = false; } // set alarm(s) // TODO: support multiple alarm entries if (event.alarms || action != 'new') { if (typeof event.alarms == 'string') event.alarms = event.alarms.split(';'); var valarms = event.alarms || ['']; for (var alarm, i=0; i < valarms.length; i++) { alarm = String(valarms[i]).split(':'); if (!alarm[1] && alarm[0]) alarm[1] = 'DISPLAY'; $('#eventedit select.edit-alarm-type').val(alarm[1]); if (alarm[0].match(/@(\d+)/)) { var ondate = fromunixtime(parseInt(RegExp.$1)); $('#eventedit select.edit-alarm-offset').val('@'); $('#eventedit input.edit-alarm-date').val($.fullCalendar.formatDate(ondate, settings['date_format'])); $('#eventedit input.edit-alarm-time').val($.fullCalendar.formatDate(ondate, settings['time_format'])); } else if (alarm[0].match(/([-+])(\d+)([MHD])/)) { $('#eventedit input.edit-alarm-value').val(RegExp.$2); $('#eventedit select.edit-alarm-offset').val(''+RegExp.$1+RegExp.$3); } } } // set correct visibility by triggering onchange handlers $('#eventedit select.edit-alarm-type, #eventedit select.edit-alarm-offset').change(); // enable/disable alarm property according to backend support $('#edit-alarms')[(calendar.alarms ? 'show' : 'hide')](); // check categories drop-down: add value if not exists if (event.categories && !categories.find("option[value='"+event.categories+"']").length) { $('<option>').attr('value', event.categories).text(event.categories).appendTo(categories).prop('selected', true); } // set recurrence form var recurrence, interval, rrtimes, rrenddate; var load_recurrence_tab = function() { recurrence = $('#edit-recurrence-frequency').val(event.recurrence ? event.recurrence.FREQ : '').change(); interval = $('#eventedit select.edit-recurrence-interval').val(event.recurrence ? event.recurrence.INTERVAL : 1); rrtimes = $('#edit-recurrence-repeat-times').val(event.recurrence ? event.recurrence.COUNT : 1); rrenddate = $('#edit-recurrence-enddate').val(event.recurrence && event.recurrence.UNTIL ? $.fullCalendar.formatDate(parseISO8601(event.recurrence.UNTIL), settings['date_format']) : ''); $('#eventedit input.edit-recurrence-until:checked').prop('checked', false); var weekdays = ['SU','MO','TU','WE','TH','FR','SA']; var rrepeat_id = '#edit-recurrence-repeat-forever'; if (event.recurrence && event.recurrence.COUNT) rrepeat_id = '#edit-recurrence-repeat-count'; else if (event.recurrence && event.recurrence.UNTIL) rrepeat_id = '#edit-recurrence-repeat-until'; $(rrepeat_id).prop('checked', true); if (event.recurrence && event.recurrence.BYDAY && event.recurrence.FREQ == 'WEEKLY') { var wdays = event.recurrence.BYDAY.split(','); $('input.edit-recurrence-weekly-byday').val(wdays); } if (event.recurrence && event.recurrence.BYMONTHDAY) { $('input.edit-recurrence-monthly-bymonthday').val(String(event.recurrence.BYMONTHDAY).split(',')); $('input.edit-recurrence-monthly-mode').val(['BYMONTHDAY']); } if (event.recurrence && event.recurrence.BYDAY && (event.recurrence.FREQ == 'MONTHLY' || event.recurrence.FREQ == 'YEARLY')) { var byday, section = event.recurrence.FREQ.toLowerCase(); if ((byday = String(event.recurrence.BYDAY).match(/(-?[1-4])([A-Z]+)/))) { $('#edit-recurrence-'+section+'-prefix').val(byday[1]); $('#edit-recurrence-'+section+'-byday').val(byday[2]); } $('input.edit-recurrence-'+section+'-mode').val(['BYDAY']); } else if (event.start) { $('#edit-recurrence-monthly-byday').val(weekdays[event.start.getDay()]); } if (event.recurrence && event.recurrence.BYMONTH) { $('input.edit-recurrence-yearly-bymonth').val(String(event.recurrence.BYMONTH).split(',')); } else if (event.start) { $('input.edit-recurrence-yearly-bymonth').val([String(event.start.getMonth()+1)]); } }; // show warning if editing a recurring event if (event.id && event.recurrence) { var sel = event.thisandfuture ? 'future' : (event.isexception ? 'current' : 'all'); $('#edit-recurring-warning').show(); $('input.edit-recurring-savemode[value="'+sel+'"]').prop('checked', true); } else $('#edit-recurring-warning').hide(); // init attendees tab var organizer = !event.attendees || is_organizer(event), allow_invitations = organizer || (calendar.owner && calendar.owner == 'anonymous') || settings.invite_shared; event_attendees = []; attendees_list = $('#edit-attendees-table > tbody').html(''); $('#edit-attendees-notify')[(notify.checked && allow_invitations ? 'show' : 'hide')](); $('#edit-localchanges-warning')[(has_attendees(event) && !(allow_invitations || (calendar.owner && is_organizer(event, calendar.owner))) ? 'show' : 'hide')](); var load_attendees_tab = function() { if (event.attendees) { for (var j=0; j < event.attendees.length; j++) add_attendee(event.attendees[j], !allow_invitations); } // select the correct organizer identity var identity_id = 0; $.each(settings.identities, function(i,v){ if (organizer && v == organizer.email) { identity_id = i; return false; } }); $('#edit-identities-list').val(identity_id); $('#edit-attendees-form')[(allow_invitations?'show':'hide')](); $('#edit-attendee-schedule')[(calendar.freebusy?'show':'hide')](); }; // attachments var load_attachments_tab = function() { rcmail.enable_command('remove-attachment', !calendar.readonly); rcmail.env.deleted_attachments = []; // we're sharing some code for uploads handling with app.js rcmail.env.attachments = []; rcmail.env.compose_id = event.id; // for rcmail.async_upload_form() if ($.isArray(event.attachments)) { event_show_attachments(event.attachments, $('#edit-attachments'), event, true); } else { $('#edit-attachments > ul').empty(); // fetch attachments, some drivers doesn't set 'attachments' array for event? } }; // init dialog buttons var buttons = {}; // save action buttons[rcmail.gettext('save', 'calendar')] = function() { var start = parse_datetime(allday.checked ? '12:00' : starttime.val(), startdate.val()); var end = parse_datetime(allday.checked ? '13:00' : endtime.val(), enddate.val()); // basic input validatetion if (start.getTime() > end.getTime()) { alert(rcmail.gettext('invalideventdates', 'calendar')); return false; } // post data to server var data = { calendar: event.calendar, start: date2servertime(start), end: date2servertime(end), allday: allday.checked?1:0, title: title.val(), description: description.val(), location: location.val(), categories: categories.val(), vurl: vurl.val(), free_busy: freebusy.val(), priority: priority.val(), sensitivity: sensitivity.val(), recurrence: '', alarms: '', attendees: event_attendees, deleted_attachments: rcmail.env.deleted_attachments, attachments: [] }; // serialize alarm settings // TODO: support multiple alarm entries var alarm = $('#eventedit select.edit-alarm-type').val(); if (alarm) { var val, offset = $('#eventedit select.edit-alarm-offset').val(); if (offset == '@') data.alarms = '@' + date2unixtime(parse_datetime($('#eventedit input.edit-alarm-time').val(), $('#eventedit input.edit-alarm-date').val())) + ':' + alarm; else if ((val = parseInt($('#eventedit input.edit-alarm-value').val())) && !isNaN(val) && val >= 0) data.alarms = offset[0] + val + offset[1] + ':' + alarm; } // uploaded attachments list for (var i in rcmail.env.attachments) if (i.match(/^rcmfile(.+)/)) data.attachments.push(RegExp.$1); // read attendee roles $('select.edit-attendee-role').each(function(i, elem){ if (data.attendees[i]) data.attendees[i].role = $(elem).val(); }); if (organizer) data._identity = $('#edit-identities-list option:selected').val(); // don't submit attendees if only myself is added as organizer if (data.attendees.length == 1 && data.attendees[0].role == 'ORGANIZER' && String(data.attendees[0].email).toLowerCase() == settings.identity.email) data.attendees = []; // tell server to send notifications if ((data.attendees.length || (event.id && event.attendees.length)) && allow_invitations && (notify.checked || invite.checked)) { data._notify = 1; } // gather recurrence settings var freq; if ((freq = recurrence.val()) != '') { data.recurrence = { FREQ: freq, INTERVAL: $('#edit-recurrence-interval-'+freq.toLowerCase()).val() }; var until = $('input.edit-recurrence-until:checked').val(); if (until == 'count') data.recurrence.COUNT = rrtimes.val(); else if (until == 'until') data.recurrence.UNTIL = date2servertime(parse_datetime(endtime.val(), rrenddate.val())); if (freq == 'WEEKLY') { var byday = []; $('input.edit-recurrence-weekly-byday:checked').each(function(){ byday.push(this.value); }); if (byday.length) data.recurrence.BYDAY = byday.join(','); } else if (freq == 'MONTHLY') { var mode = $('input.edit-recurrence-monthly-mode:checked').val(), bymonday = []; if (mode == 'BYMONTHDAY') { $('input.edit-recurrence-monthly-bymonthday:checked').each(function(){ bymonday.push(this.value); }); if (bymonday.length) data.recurrence.BYMONTHDAY = bymonday.join(','); } else data.recurrence.BYDAY = $('#edit-recurrence-monthly-prefix').val() + $('#edit-recurrence-monthly-byday').val(); } else if (freq == 'YEARLY') { var byday, bymonth = []; $('input.edit-recurrence-yearly-bymonth:checked').each(function(){ bymonth.push(this.value); }); if (bymonth.length) data.recurrence.BYMONTH = bymonth.join(','); if ((byday = $('#edit-recurrence-yearly-byday').val())) data.recurrence.BYDAY = $('#edit-recurrence-yearly-prefix').val() + byday; } } data.calendar = calendars.val(); if (event.id) { data.id = event.id; if (event.recurrence) data._savemode = $('input.edit-recurring-savemode:checked').val(); if (data.calendar && data.calendar != event.calendar) data._fromcalendar = event.calendar; } update_event(action, data); $dialog.dialog("close"); }; if (event.id) { buttons[rcmail.gettext('remove', 'calendar')] = function() { me.delete_event(event); $dialog.dialog('close'); }; } buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // show/hide tabs according to calendar's feature support $('#edit-tab-attendees')[(calendar.attendees?'show':'hide')](); $('#edit-tab-attachments')[(calendar.attachments?'show':'hide')](); // activate the first tab $('#eventtabs').tabs('select', 0); // hack: set task to 'calendar' to make all dialog actions work correctly var comm_path_before = rcmail.env.comm_path; rcmail.env.comm_path = comm_path_before.replace(/_task=[a-z]+/, '_task=calendar'); var editform = $("#eventedit"); // open jquery UI dialog $dialog.dialog({ modal: true, resizable: (!bw.ie6 && !bw.ie7), // disable for performance reasons closeOnEscape: false, title: rcmail.gettext((action == 'edit' ? 'edit_event' : 'new_event'), 'calendar'), close: function() { editform.hide().appendTo(document.body); $dialog.dialog("destroy").remove(); rcmail.ksearch_blur(); rcmail.ksearch_destroy(); freebusy_data = {}; rcmail.env.comm_path = comm_path_before; // restore comm_path }, buttons: buttons, minWidth: 500, width: 580 }).append(editform.show()); // adding form content AFTERWARDS massively speeds up opening on IE6 // set dialog size according to form content me.dialog_resize($dialog.get(0), editform.height() + (bw.ie ? 20 : 0), 530); title.select(); // init other tabs asynchronously window.setTimeout(load_recurrence_tab, exec_deferred); if (calendar.attendees) window.setTimeout(load_attendees_tab, exec_deferred); if (calendar.attachments) window.setTimeout(load_attachments_tab, exec_deferred); }; // open a dialog to display detailed free-busy information and to find free slots var event_freebusy_dialog = function() { var $dialog = $('#eventfreebusy'), event = me.selected_event; if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (!event_attendees.length) return false; // set form elements var allday = $('#edit-allday').get(0); var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000); freebusy_ui.startdate = $('#schedule-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration); freebusy_ui.starttime = $('#schedule-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show(); freebusy_ui.enddate = $('#schedule-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format'])); freebusy_ui.endtime = $('#schedule-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show(); if (allday.checked) { freebusy_ui.starttime.val("12:00").hide(); freebusy_ui.endtime.val("13:00").hide(); event.allDay = true; } // read attendee roles from drop-downs $('select.edit-attendee-role').each(function(i, elem){ if (event_attendees[i]) event_attendees[i].role = $(elem).val(); }); // render time slots var now = new Date(), fb_start = new Date(), fb_end = new Date(); fb_start.setTime(event.start); fb_start.setHours(0); fb_start.setMinutes(0); fb_start.setSeconds(0); fb_start.setMilliseconds(0); fb_end.setTime(fb_start.getTime() + DAY_MS); freebusy_data = { required:{}, all:{} }; freebusy_ui.loading = 1; // prevent render_freebusy_grid() to load data yet freebusy_ui.numdays = Math.max(allday.checked ? 14 : 1, Math.ceil(duration * 2 / 86400)); freebusy_ui.interval = allday.checked ? 1440 : 60; freebusy_ui.start = fb_start; freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); render_freebusy_grid(0); // render list of attendees freebusy_ui.attendees = {}; var domid, dispname, data, role_html, list_html = ''; for (var i=0; i < event_attendees.length; i++) { data = event_attendees[i]; dispname = Q(data.name || data.email); domid = String(data.email).replace(rcmail.identifier_expr, ''); role_html = '<a class="attendee-role-toggle" id="rcmlia' + domid + '" title="' + Q(rcmail.gettext('togglerole', 'calendar')) + '">&nbsp;</a>'; list_html += '<div class="attendee ' + String(data.role).toLowerCase() + '" id="rcmli' + domid + '">' + role_html + dispname + '</div>'; // clone attendees data for local modifications freebusy_ui.attendees[i] = freebusy_ui.attendees[domid] = $.extend({}, data); } // add total row list_html += '<div class="attendee spacer">&nbsp;</div>'; list_html += '<div class="attendee total">' + rcmail.gettext('reqallattendees','calendar') + '</div>'; $('#schedule-attendees-list').html(list_html) .unbind('click.roleicons') .bind('click.roleicons', function(e){ // toggle attendee status upon click on icon if (e.target.id && e.target.id.match(/rcmlia(.+)/)) { var attendee, domid = RegExp.$1, roles = [ 'REQ-PARTICIPANT', 'OPT-PARTICIPANT', 'CHAIR' ]; if ((attendee = freebusy_ui.attendees[domid]) && attendee.role != 'ORGANIZER') { var req = attendee.role != 'OPT-PARTICIPANT'; var j = $.inArray(attendee.role, roles); j = (j+1) % roles.length; attendee.role = roles[j]; $(e.target).parent().removeClass().addClass('attendee '+String(attendee.role).toLowerCase()); // update total display if required-status changed if (req != (roles[j] != 'OPT-PARTICIPANT')) { compute_freebusy_totals(); update_freebusy_display(attendee.email); } } } return false; }); // enable/disable buttons $('#shedule-find-prev').button('option', 'disabled', (fb_start.getTime() < now.getTime())); // dialog buttons var buttons = {}; buttons[rcmail.gettext('select', 'calendar')] = function() { $('#edit-startdate').val(freebusy_ui.startdate.val()); $('#edit-starttime').val(freebusy_ui.starttime.val()); $('#edit-enddate').val(freebusy_ui.enddate.val()); $('#edit-endtime').val(freebusy_ui.endtime.val()); // write role changes back to main dialog $('select.edit-attendee-role').each(function(i, elem){ if (event_attendees[i] && freebusy_ui.attendees[i]) { event_attendees[i].role = freebusy_ui.attendees[i].role; $(elem).val(event_attendees[i].role); } }); if (freebusy_ui.needsupdate) update_freebusy_status(me.selected_event); freebusy_ui.needsupdate = false; $dialog.dialog("close"); }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; $dialog.dialog({ modal: true, resizable: true, closeOnEscape: (!bw.ie6 && !bw.ie7), title: rcmail.gettext('scheduletime', 'calendar'), open: function() { $dialog.parent().find('.ui-dialog-buttonset .ui-button').first().focus(); }, close: function() { if (bw.ie6) $("#edit-attendees-table").css('visibility','visible'); $dialog.dialog("destroy").hide(); }, resizeStop: function() { render_freebusy_overlay(); }, buttons: buttons, minWidth: 640, width: 850 }).show(); // hide edit dialog on IE6 because of drop-down elements if (bw.ie6) $("#edit-attendees-table").css('visibility','hidden'); // adjust dialog size to fit grid without scrolling var gridw = $('#schedule-freebusy-times').width(); var overflow = gridw - $('#attendees-freebusy-table td.times').width() + 1; me.dialog_resize($dialog.get(0), $dialog.height() + (bw.ie ? 20 : 0), 800 + Math.max(0, overflow)); // fetch data from server freebusy_ui.loading = 0; load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); }; // render an HTML table showing free-busy status for all the event attendees var render_freebusy_grid = function(delta) { if (delta) { freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); // skip weekends if in workinhoursonly-mode if (Math.abs(delta) == 1 && freebusy_ui.workinhoursonly) { while (is_weekend(freebusy_ui.start)) freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); } freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); } var dayslots = Math.floor(1440 / freebusy_ui.interval); var date_format = 'ddd '+ (dayslots <= 2 ? settings.date_short : settings.date_format); var lastdate, datestr, css, curdate = new Date(), allday = (freebusy_ui.interval == 1440), times_css = (allday ? 'allday ' : ''), dates_row = '<tr class="dates">', times_row = '<tr class="times">', slots_row = ''; for (var s = 0, t = freebusy_ui.start.getTime(); t < freebusy_ui.end.getTime(); s++) { curdate.setTime(t); datestr = fc.fullCalendar('formatDate', curdate, date_format); if (datestr != lastdate) { if (lastdate && !allday) break; dates_row += '<th colspan="' + dayslots + '" class="boxtitle date' + $.fullCalendar.formatDate(curdate, 'ddMMyyyy') + '">' + Q(datestr) + '</th>'; lastdate = datestr; } // set css class according to working hours css = is_weekend(curdate) || (freebusy_ui.interval <= 60 && !is_workinghour(curdate)) ? 'offhours' : 'workinghours'; times_row += '<td class="' + times_css + css + '" id="t-' + Math.floor(t/1000) + '">' + Q(allday ? rcmail.gettext('all-day','calendar') : $.fullCalendar.formatDate(curdate, settings['time_format'])) + '</td>'; slots_row += '<td class="' + css + ' unknown">&nbsp;</td>'; t += freebusy_ui.interval * 60000; } dates_row += '</tr>'; times_row += '</tr>'; // render list of attendees var domid, data, list_html = '', times_html = ''; for (var i=0; i < event_attendees.length; i++) { data = event_attendees[i]; domid = String(data.email).replace(rcmail.identifier_expr, ''); times_html += '<tr id="fbrow' + domid + '">' + slots_row + '</tr>'; } // add line for all/required attendees times_html += '<tr class="spacer"><td colspan="' + (dayslots * freebusy_ui.numdays) + '">&nbsp;</td>'; times_html += '<tr id="fbrowall">' + slots_row + '</tr>'; var table = $('#schedule-freebusy-times'); table.children('thead').html(dates_row + times_row); table.children('tbody').html(times_html); // initialize event handlers on grid if (!freebusy_ui.grid_events) { freebusy_ui.grid_events = true; table.children('thead').click(function(e){ // move event to the clicked date/time if (e.target.id && e.target.id.match(/t-(\d+)/)) { var newstart = new Date(RegExp.$1 * 1000); // set time to 00:00 if (me.selected_event.allDay) { newstart.setMinutes(0); newstart.setHours(0); } update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); render_freebusy_overlay(); } }) } // if we have loaded free-busy data, show it if (!freebusy_ui.loading) { if (freebusy_ui.start < freebusy_data.start || freebusy_ui.end > freebusy_data.end || freebusy_ui.interval != freebusy_data.interval) { load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); } else { for (var email, i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) update_freebusy_display(email); } } } // render current event date/time selection over grid table // use timeout to let the dom attributes (width/height/offset) be set first window.setTimeout(function(){ render_freebusy_overlay(); }, 10); }; // render overlay element over the grid to visiualize the current event date/time var render_freebusy_overlay = function() { var overlay = $('#schedule-event-time'); if (me.selected_event.end.getTime() <= freebusy_ui.start.getTime() || me.selected_event.start.getTime() >= freebusy_ui.end.getTime()) { overlay.hide(); if (overlay.data('isdraggable')) overlay.draggable('disable'); } else { var table = $('#schedule-freebusy-times'), width = 0, pos = { top:table.children('thead').height(), left:0 }, eventstart = date2unixtime(clone_date(me.selected_event.start, me.selected_event.allDay?1:0)), eventend = date2unixtime(clone_date(me.selected_event.end, me.selected_event.allDay?2:0)) - 60, slotstart = date2unixtime(freebusy_ui.start), slotsize = freebusy_ui.interval * 60, slotend, fraction, $cell; // iterate through slots to determine position and size of the overlay table.children('thead').find('td').each(function(i, cell){ slotend = slotstart + slotsize - 1; // event starts in this slot: compute left if (eventstart >= slotstart && eventstart <= slotend) { fraction = 1 - (slotend - eventstart) / slotsize; pos.left = Math.round(cell.offsetLeft + cell.offsetWidth * fraction); } // event ends in this slot: compute width if (eventend >= slotstart && eventend <= slotend) { fraction = 1 - (slotend - eventend) / slotsize; width = Math.round(cell.offsetLeft + cell.offsetWidth * fraction) - pos.left; } slotstart = slotstart + slotsize; }); if (!width) width = table.width() - pos.left; // overlay is visible if (width > 0) { overlay.css({ width: (width-5)+'px', height:(table.children('tbody').height() - 4)+'px', left:pos.left+'px', top:pos.top+'px' }).show(); // configure draggable if (!overlay.data('isdraggable')) { overlay.draggable({ axis: 'x', scroll: true, stop: function(e, ui){ // convert pixels to time var px = ui.position.left; var range_p = $('#schedule-freebusy-times').width(); var range_t = freebusy_ui.end.getTime() - freebusy_ui.start.getTime(); var newstart = new Date(freebusy_ui.start.getTime() + px * (range_t / range_p)); newstart.setSeconds(0); newstart.setMilliseconds(0); // snap to day boundaries if (me.selected_event.allDay) { if (newstart.getHours() >= 12) // snap to next day newstart.setTime(newstart.getTime() + DAY_MS); newstart.setMinutes(0); newstart.setHours(0); } else { // round to 5 minutes var round = newstart.getMinutes() % 5; if (round > 2.5) newstart.setTime(newstart.getTime() + (5 - round) * 60000); else if (round > 0) newstart.setTime(newstart.getTime() - round * 60000); } // update event times and display update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); if (me.selected_event.allDay) render_freebusy_overlay(); } }).data('isdraggable', true); } else overlay.draggable('enable'); } else overlay.draggable('disable').hide(); } }; // fetch free-busy information for each attendee from server var load_freebusy_data = function(from, interval) { var start = new Date(from.getTime() - DAY_MS * 2); // start 2 days before event fix_date(start); var end = new Date(start.getTime() + DAY_MS * Math.max(14, freebusy_ui.numdays + 7)); // load min. 14 days freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; // load free-busy information for every attendee var domid, email; for (var i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) { domid = String(email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).addClass('loading'); freebusy_ui.loading++; $.ajax({ type: 'GET', dataType: 'json', url: rcmail.url('freebusy-times'), data: { email:email, start:date2servertime(clone_date(start, 1)), end:date2servertime(clone_date(end, 2)), interval:interval, _remote:1 }, success: function(data) { freebusy_ui.loading--; // find attendee var attendee = null; for (var i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].email == data.email) { attendee = freebusy_ui.attendees[i]; break; } } // copy data to member var var ts, req = attendee.role != 'OPT-PARTICIPANT'; freebusy_data.start = parseISO8601(data.start); freebusy_data[data.email] = {}; for (var i=0; i < data.slots.length; i++) { ts = data.times[i] + ''; freebusy_data[data.email][ts] = data.slots[i]; // set totals if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (req) freebusy_data.required[ts][data.slots[i]]++; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; freebusy_data.all[ts][data.slots[i]]++; } freebusy_data.end = parseISO8601(data.end); freebusy_data.interval = data.interval; // hide loading indicator var domid = String(data.email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).removeClass('loading'); // update display update_freebusy_display(data.email); } }); // count required attendees if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT') freebusy_ui.numrequired++; } } }; // re-calculate total status after role change var compute_freebusy_totals = function() { freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; var email, req, status; for (var i=0; i < event_attendees.length; i++) { if (!(email = event_attendees[i].email)) continue; req = freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT'; if (req) freebusy_ui.numrequired++; for (var ts in freebusy_data[email]) { if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; status = freebusy_data[email][ts]; freebusy_data.all[ts][status]++; if (req) freebusy_data.required[ts][status]++; } } }; // update free-busy grid with status loaded from server var update_freebusy_display = function(email) { var status_classes = ['unknown','free','busy','tentative','out-of-office']; var domid = String(email).replace(rcmail.identifier_expr, ''); var row = $('#fbrow' + domid); var rowall = $('#fbrowall').children(); var dateonly = freebusy_ui.interval > 60, t, ts = date2timestring(freebusy_ui.start, dateonly), curdate = new Date(), fbdata = freebusy_data[email]; if (fbdata && fbdata[ts] !== undefined && row.length) { t = freebusy_ui.start.getTime(); row.children().each(function(i, cell){ curdate.setTime(t); ts = date2timestring(curdate, dateonly); cell.className = cell.className.replace('unknown', fbdata[ts] ? status_classes[fbdata[ts]] : 'unknown'); // also update total row if all data was loaded if (freebusy_ui.loading == 0 && freebusy_data.all[ts] && (cell = rowall.get(i))) { var workinghours = cell.className.indexOf('workinghours') >= 0; var all_status = freebusy_data.all[ts][2] ? 'busy' : 'unknown'; req_status = freebusy_data.required[ts][2] ? 'busy' : 'free'; for (var j=1; j < status_classes.length; j++) { if (freebusy_ui.numrequired && freebusy_data.required[ts][j] >= freebusy_ui.numrequired) req_status = status_classes[j]; if (freebusy_data.all[ts][j] == event_attendees.length) all_status = status_classes[j]; } cell.className = (workinghours ? 'workinghours ' : 'offhours ') + req_status + ' all-' + all_status; } t += freebusy_ui.interval * 60000; }); } }; // write changed event date/times back to form fields var update_freebusy_dates = function(start, end) { // fix all-day evebt times if (me.selected_event.allDay) { var numdays = Math.floor((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / DAY_MS); start.setHours(12); start.setMinutes(0); end.setTime(start.getTime() + numdays * DAY_MS); end.setHours(13); end.setMinutes(0); } me.selected_event.start = start; me.selected_event.end = end; freebusy_ui.startdate.val($.fullCalendar.formatDate(start, settings['date_format'])); freebusy_ui.starttime.val($.fullCalendar.formatDate(start, settings['time_format'])); freebusy_ui.enddate.val($.fullCalendar.formatDate(end, settings['date_format'])); freebusy_ui.endtime.val($.fullCalendar.formatDate(end, settings['time_format'])); freebusy_ui.needsupdate = true; }; // attempt to find a time slot where all attemdees are available var freebusy_find_slot = function(dir) { // exit if free-busy data isn't available yet if (!freebusy_data || !freebusy_data.start) return false; var event = me.selected_event, eventstart = clone_date(event.start, event.allDay ? 1 : 0).getTime(), // calculate with integers eventend = clone_date(event.end, event.allDay ? 2 : 0).getTime(), duration = eventend - eventstart - (event.allDay ? HOUR_MS : 0), // make sure we don't cross day borders on DST change sinterval = freebusy_data.interval * 60000, intvlslots = 1, numslots = Math.ceil(duration / sinterval), checkdate, slotend, email, ts, slot, slotdate = new Date(); // shift event times to next possible slot eventstart += sinterval * intvlslots * dir; eventend += sinterval * intvlslots * dir; // iterate through free-busy slots and find candidates var candidatecount = 0, candidatestart = candidateend = success = false; for (slot = dir > 0 ? freebusy_data.start.getTime() : freebusy_data.end.getTime() - sinterval; (dir > 0 && slot < freebusy_data.end.getTime()) || (dir < 0 && slot >= freebusy_data.start.getTime()); slot += sinterval * dir) { slotdate.setTime(slot); // fix slot if just crossed a DST change if (event.allDay) { fix_date(slotdate); slot = slotdate.getTime(); } slotend = slot + sinterval; if ((dir > 0 && slotend <= eventstart) || (dir < 0 && slot >= eventend)) // skip continue; // respect workingours setting if (freebusy_ui.workinhoursonly) { if (is_weekend(slotdate) || (freebusy_data.interval <= 60 && !is_workinghour(slotdate))) { // skip off-hours candidatestart = candidateend = false; candidatecount = 0; continue; } } if (!candidatestart) candidatestart = slot; // check freebusy data for all attendees ts = date2timestring(slotdate, freebusy_data.interval > 60); for (var i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT' && (email = freebusy_ui.attendees[i].email) && freebusy_data[email] && freebusy_data[email][ts] > 1) { candidatestart = candidateend = false; break; } } // occupied slot if (!candidatestart) { slot += Math.max(0, intvlslots - candidatecount - 1) * sinterval * dir; candidatecount = 0; continue; } // set candidate end to slot end time candidatecount++; if (dir < 0 && !candidateend) candidateend = slotend; // if candidate is big enough, this is it! if (candidatecount == numslots) { if (dir > 0) { event.start.setTime(candidatestart); event.end.setTime(candidatestart + duration); } else { event.end.setTime(candidateend); event.start.setTime(candidateend - duration); } success = true; break; } } // update event date/time display if (success) { update_freebusy_dates(event.start, event.end); // move freebusy grid if necessary var offset = Math.ceil((event.start.getTime() - freebusy_ui.end.getTime()) / DAY_MS); if (event.start.getTime() >= freebusy_ui.end.getTime()) render_freebusy_grid(Math.max(1, offset)); else if (event.end.getTime() <= freebusy_ui.start.getTime()) render_freebusy_grid(Math.min(-1, offset)); else render_freebusy_overlay(); var now = new Date(); $('#shedule-find-prev').button('option', 'disabled', (event.start.getTime() < now.getTime())); } else { alert(rcmail.gettext('noslotfound','calendar')); } }; // update event properties and attendees availability if event times have changed var event_times_changed = function() { if (me.selected_event) { var allday = $('#edit-allday').get(0); me.selected_event.allDay = allday.checked; me.selected_event.start = parse_datetime(allday.checked ? '12:00' : $('#edit-starttime').val(), $('#edit-startdate').val()); me.selected_event.end = parse_datetime(allday.checked ? '13:00' : $('#edit-endtime').val(), $('#edit-enddate').val()); if (event_attendees) freebusy_ui.needsupdate = true; $('#edit-startdate').data('duration', Math.round((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / 1000)); } }; // add the given list of participants var add_attendees = function(names) { names = explode_quoted_string(names.replace(/,\s*$/, ''), ','); // parse name/email pairs var item, email, name, success = false; for (var i=0; i < names.length; i++) { email = name = ''; item = $.trim(names[i]); if (!item.length) { continue; } // address in brackets without name (do nothing) else if (item.match(/^<[^@]+@[^>]+>$/)) { email = item.replace(/[<>]/g, ''); } // address without brackets and without name (add brackets) else if (rcube_check_email(item)) { email = item; } // address with name else if (item.match(/([^\s<@]+@[^>]+)>*$/)) { email = RegExp.$1; name = item.replace(email, '').replace(/^["\s<>]+/, '').replace(/["\s<>]+$/, ''); } if (email) { add_attendee({ email:email, name:name, role:'REQ-PARTICIPANT', status:'NEEDS-ACTION' }); success = true; } else { alert(rcmail.gettext('noemailwarning')); } } return success; }; // add the given attendee to the list var add_attendee = function(data, readonly) { // check for dupes... var exists = false; $.each(event_attendees, function(i, v){ exists |= (v.email == data.email); }); if (exists) return false; var dispname = Q(data.name || data.email); if (data.email) dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>'; // role selection var organizer = data.role == 'ORGANIZER'; var opts = {}; if (organizer) opts.ORGANIZER = rcmail.gettext('calendar.roleorganizer'); opts['REQ-PARTICIPANT'] = rcmail.gettext('calendar.rolerequired'); opts['OPT-PARTICIPANT'] = rcmail.gettext('calendar.roleoptional'); opts['CHAIR'] = rcmail.gettext('calendar.rolechair'); if (organizer && !readonly) dispname = rcmail.env['identities-selector']; var select = '<select class="edit-attendee-role"' + (organizer || readonly ? ' disabled="true"' : '') + '>'; for (var r in opts) select += '<option value="'+ r +'" class="' + r.toLowerCase() + '"' + (data.role == r ? ' selected="selected"' : '') +'>' + Q(opts[r]) + '</option>'; select += '</select>'; // availability var avail = data.email ? 'loading' : 'unknown'; // delete icon var icon = rcmail.env.deleteicon ? '<img src="' + rcmail.env.deleteicon + '" alt="" />' : rcmail.gettext('delete'); var dellink = '<a href="#delete" class="iconlink delete deletelink" title="' + Q(rcmail.gettext('delete')) + '">' + icon + '</a>'; var html = '<td class="role">' + select + '</td>' + '<td class="name">' + dispname + '</td>' + '<td class="availability"><img src="./program/resources/blank.gif" class="availabilityicon ' + avail + '" /></td>' + '<td class="confirmstate"><span class="' + String(data.status).toLowerCase() + '">' + Q(data.status) + '</span></td>' + '<td class="options">' + (organizer || readonly ? '' : dellink) + '</td>'; var tr = $('<tr>') .addClass(String(data.role).toLowerCase()) .html(html) .appendTo(attendees_list); tr.find('a.deletelink').click({ id:(data.email || data.name) }, function(e) { remove_attendee(this, e.data.id); return false; }); tr.find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); // select organizer identity if (data.identity_id) $('#edit-identities-list').val(data.identity_id); // check free-busy status if (avail == 'loading') { check_freebusy_status(tr.find('img.availabilityicon'), data.email, me.selected_event); } event_attendees.push(data); }; // iterate over all attendees and update their free-busy status display var update_freebusy_status = function(event) { var icons = attendees_list.find('img.availabilityicon'); for (var i=0; i < event_attendees.length; i++) { if (icons.get(i) && event_attendees[i].email) check_freebusy_status(icons.get(i), event_attendees[i].email, event); } freebusy_ui.needsupdate = false; }; // load free-busy status from server and update icon accordingly var check_freebusy_status = function(icon, email, event) { var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { freebusy:false }; if (!calendar.freebusy) { $(icon).removeClass().addClass('availabilityicon unknown'); return; } icon = $(icon).removeClass().addClass('availabilityicon loading'); $.ajax({ type: 'GET', dataType: 'html', url: rcmail.url('freebusy-status'), data: { email:email, start:date2servertime(clone_date(event.start, event.allDay?1:0)), end:date2servertime(clone_date(event.end, event.allDay?2:0)), _remote: 1 }, success: function(status){ icon.removeClass('loading').addClass(String(status).toLowerCase()); }, error: function(){ icon.removeClass('loading').addClass('unknown'); } }); }; // remove an attendee from the list var remove_attendee = function(elem, id) { $(elem).closest('tr').remove(); event_attendees = $.grep(event_attendees, function(data){ return (data.name != id && data.email != id) }); }; // when the user accepts or declines an event invitation var event_rsvp = function(response) { if (me.selected_event && me.selected_event.attendees && response) { // update attendee status for (var data, i=0; i < me.selected_event.attendees.length; i++) { data = me.selected_event.attendees[i]; if (settings.identity.emails.indexOf(';'+String(data.email).toLowerCase()) >= 0) data.status = response.toUpperCase(); } event_show_dialog(me.selected_event); // submit status change to server me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('event', { action:'rsvp', e:me.selected_event, status:response }); } } // post the given event data to server var update_event = function(action, data) { me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar/event', { action:action, e:data }); // render event temporarily into the calendar if ((data.start && data.end) || data.id) { var event = data.id ? $.extend(fc.fullCalendar('clientEvents', function(e){ return e.id == data.id; })[0], data) : data; if (data.start) event.start = data.start; if (data.end) event.end = data.end; if (data.allday !== undefined) event.allDay = data.allday; event.editable = false; event.temp = true; event.className = 'fc-event-cal-'+data.calendar+' fc-event-temp'; fc.fullCalendar(data.id ? 'updateEvent' : 'renderEvent', event); } }; // mouse-click handler to check if the show dialog is still open and prevent default action var dialog_check = function(e) { var showd = $("#eventshow"); if (showd.is(':visible') && !$(e.target).closest('.ui-dialog').length) { showd.dialog('close'); e.stopImmediatePropagation(); ignore_click = true; return false; } else if (ignore_click) { window.setTimeout(function(){ ignore_click = false; }, 20); return false; } return true; }; // display confirm dialog when modifying/deleting an event var update_event_confirm = function(action, event, data) { if (!data) data = event; var decline = false, notify = false, html = '', cal = me.calendars[event.calendar]; // event has attendees, ask whether to notify them if (has_attendees(event)) { if (is_organizer(event)) { notify = true; html += '<div class="message">' + '<label><input class="confirm-attendees-donotify" type="checkbox" checked="checked" value="1" name="notify" />&nbsp;' + rcmail.gettext((action == 'remove' ? 'sendcancellation' : 'sendnotifications'), 'calendar') + '</label></div>'; } else if (action == 'remove' && is_attendee(event)) { decline = true; html += '<div class="message">' + '<label><input class="confirm-attendees-decline" type="checkbox" checked="checked" value="1" name="decline" />&nbsp;' + rcmail.gettext('itipdeclineevent', 'calendar') + '</label></div>'; } else { html += '<div class="message">' + rcmail.gettext('localchangeswarning', 'calendar') + '</div>'; } } // recurring event: user needs to select the savemode if (event.recurrence) { html += '<div class="message"><span class="ui-icon ui-icon-alert"></span>' + rcmail.gettext((action == 'remove' ? 'removerecurringeventwarning' : 'changerecurringeventwarning'), 'calendar') + '</div>' + '<div class="savemode">' + '<a href="#current" class="button">' + rcmail.gettext('currentevent', 'calendar') + '</a>' + '<a href="#future" class="button">' + rcmail.gettext('futurevents', 'calendar') + '</a>' + '<a href="#all" class="button">' + rcmail.gettext('allevents', 'calendar') + '</a>' + (action != 'remove' ? '<a href="#new" class="button">' + rcmail.gettext('saveasnew', 'calendar') + '</a>' : '') + '</div>'; } // show dialog if (html) { var $dialog = $('<div>').html(html); $dialog.find('a.button').button().click(function(e){ data._savemode = String(this.href).replace(/.+#/, ''); if ($dialog.find('input.confirm-attendees-donotify').get(0)) data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; if (decline && $dialog.find('input.confirm-attendees-decline:checked')) data.decline = 1; update_event(action, data); $dialog.dialog("destroy").hide(); return false; }); var buttons = [{ text: rcmail.gettext('cancel', 'calendar'), click: function() { $(this).dialog("close"); } }]; if (!event.recurrence) { buttons.push({ text: rcmail.gettext((action == 'remove' ? 'remove' : 'save'), 'calendar'), click: function() { data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; data.decline = decline && $dialog.find('input.confirm-attendees-decline:checked').length ? 1 : 0; update_event(action, data); $(this).dialog("close"); } }); } $dialog.dialog({ modal: true, width: 460, dialogClass: 'warning', title: rcmail.gettext((action == 'remove' ? 'removeeventconfirm' : 'changeeventconfirm'), 'calendar'), buttons: buttons, close: function(){ $dialog.dialog("destroy").hide(); if (!rcmail.busy) fc.fullCalendar('refetchEvents'); } }).addClass('event-update-confirm').show(); return false; } // show regular confirm box when deleting else if (action == 'remove' && !cal.undelete) { if (!confirm(rcmail.gettext('deleteventconfirm', 'calendar'))) return false; } // do update update_event(action, data); return true; }; var update_agenda_toolbar = function() { $('#agenda-listrange').val(fc.fullCalendar('option', 'listRange')); $('#agenda-listsections').val(fc.fullCalendar('option', 'listSections')); } /*** fullcalendar event handlers ***/ var fc_event_render = function(event, element, view) { if (view.name != 'list' && view.name != 'table') { var prefix = event.sensitivity && event.sensitivity != 'public' ? String(sensitivitylabels[event.sensitivity]).toUpperCase()+': ' : ''; element.attr('title', prefix + event.title); } if (view.name != 'month') { if (event.location) { element.find('div.fc-event-title').after('<div class="fc-event-location">@&nbsp;' + Q(event.location) + '</div>'); } if (event.sensitivity && event.sensitivity != 'public') element.find('div.fc-event-time').append('<i class="fc-icon-sensitive"></i>'); if (event.recurrence) element.find('div.fc-event-time').append('<i class="fc-icon-recurring"></i>'); if (event.alarms) element.find('div.fc-event-time').append('<i class="fc-icon-alarms"></i>'); } }; /*** public methods ***/ /** * Remove saving lock and free the UI for new input */ this.unlock_saving = function() { if (me.saving_lock) rcmail.set_busy(false, null, me.saving_lock); }; // opens calendar day-view in a popup this.fisheye_view = function(date) { $('#fish-eye-view:ui-dialog').dialog('close'); // create list of active event sources var src, cals = {}, sources = []; for (var id in this.calendars) { src = $.extend({}, this.calendars[id]); src.editable = false; src.url = null; src.events = []; if (src.active) { cals[id] = src; sources.push(src); } } // copy events already loaded var events = fc.fullCalendar('clientEvents'); for (var event, i=0; i< events.length; i++) { event = events[i]; if (event.source && (src = cals[event.source.id])) { src.events.push(event); } } var h = $(window).height() - 50; var dialog = $('<div>') .attr('id', 'fish-eye-view') .dialog({ modal: true, width: 680, height: h, title: $.fullCalendar.formatDate(date, 'dddd ' + settings['date_long']), close: function(){ dialog.dialog("destroy"); me.fisheye_date = null; } }) .fullCalendar({ header: { left: '', center: '', right: '' }, height: h - 50, defaultView: 'agendaDay', date: date.getDate(), month: date.getMonth(), year: date.getFullYear(), ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone eventSources: sources, monthNames : settings['months'], monthNamesShort : settings['months_short'], dayNames : settings['days'], dayNamesShort : settings['days_short'], firstDay : settings['first_day'], firstHour : settings['first_hour'], slotMinutes : 60/settings['timeslots'], timeFormat: { '': settings['time_format'] }, axisFormat : settings['time_format'], columnFormat: { day: 'dddd ' + settings['date_short'] }, titleFormat: { day: 'dddd ' + settings['date_long'] }, allDayText: rcmail.gettext('all-day', 'calendar'), currentTimeIndicator: settings.time_indicator, eventRender: fc_event_render, eventClick: function(event) { event_show_dialog(event); } }); this.fisheye_date = date; }; //public method to show the print dialog. this.print_calendars = function(view) { if (!view) view = fc.fullCalendar('getView').name; var date = fc.fullCalendar('getDate') || new Date(); var range = fc.fullCalendar('option', 'listRange'); var sections = fc.fullCalendar('option', 'listSections'); rcmail.open_window(rcmail.url('print', { view: view, date: date2unixtime(date), range: range, sections: sections, search: this.search_query }), true, true); }; // public method to bring up the new event dialog this.add_event = function(templ) { if (this.selected_calendar) { var now = new Date(); var date = fc.fullCalendar('getDate'); if (typeof date != 'Date') date = now; date.setHours(now.getHours()+1); date.setMinutes(0); var end = new Date(date.getTime()); end.setHours(date.getHours()+1); event_edit_dialog('new', $.extend({ start:date, end:end, allDay:false, calendar:this.selected_calendar }, templ || {})); } }; // delete the given event after showing a confirmation dialog this.delete_event = function(event) { // show confirm dialog for recurring events, use jquery UI dialog return update_event_confirm('remove', event, { id:event.id, calendar:event.calendar, attendees:event.attendees }); }; // opens a jquery UI dialog with event properties (or empty for creating a new calendar) this.calendar_edit_dialog = function(calendar) { // close show dialog first var $dialog = $("#calendarform"); if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (!calendar) calendar = { name:'', color:'cc0000', editable:true, showalarms:true }; var form, name, color, alarms; $dialog.html(rcmail.get_label('loading')); $.ajax({ type: 'GET', dataType: 'html', url: rcmail.url('calendar'), data: { action:(calendar.id ? 'form-edit' : 'form-new'), c:{ id:calendar.id } }, success: function(data) { $dialog.html(data); // resize and reposition dialog window form = $('#calendarpropform'); me.dialog_resize('#calendarform', form.height(), form.width()); name = $('#calendar-name').prop('disabled', !calendar.editable).val(calendar.editname || calendar.name); color = $('#calendar-color').val(calendar.color).miniColors({ value: calendar.color, colorValues:rcmail.env.mscolors }); alarms = $('#calendar-showalarms').prop('checked', calendar.showalarms).get(0); name.select(); } }); // dialog buttons var buttons = {}; buttons[rcmail.gettext('save', 'calendar')] = function() { // form is not loaded if (!form || !form.length) return; // TODO: do some input validation if (!name.val() || name.val().length < 2) { alert(rcmail.gettext('invalidcalendarproperties', 'calendar')); name.select(); return; } // post data to server var data = form.serializeJSON(); if (data.color) data.color = data.color.replace(/^#/, ''); if (calendar.id) data.id = calendar.id; if (alarms) data.showalarms = alarms.checked ? 1 : 0; me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar', { action:(calendar.id ? 'edit' : 'new'), c:data }); $dialog.dialog("close"); }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: true, closeOnEscape: false, title: rcmail.gettext((calendar.id ? 'editcalendar' : 'createcalendar'), 'calendar'), close: function() { $dialog.html('').dialog("destroy").hide(); }, buttons: buttons, minWidth: 400, width: 420 }).show(); }; this.calendar_remove = function(calendar) { if (confirm(rcmail.gettext(calendar.children ? 'deletecalendarconfirmrecursive' : 'deletecalendarconfirm', 'calendar'))) { rcmail.http_post('calendar', { action:'remove', c:{ id:calendar.id } }); return true; } return false; }; this.calendar_destroy_source = function(id) { var delete_ids = []; if (this.calendars[id]) { // find sub-calendars if (this.calendars[id].children) { for (var child_id in this.calendars) { if (String(child_id).indexOf(id) == 0) delete_ids.push(child_id); } } else { delete_ids.push(id); } } // delete all calendars in the list for (var i=0; i < delete_ids.length; i++) { id = delete_ids[i]; fc.fullCalendar('removeEventSource', this.calendars[id]); $(rcmail.get_folder_li(id, 'rcmlical')).remove(); $('#edit-calendar option[value="'+id+'"]').remove(); delete this.calendars[id]; } }; // open a dialog to upload an .ics file with events to be imported this.import_events = function(calendar) { // close show dialog first var $dialog = $("#eventsimport"), form = rcmail.gui_objects.importform; if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (calendar) $('#event-import-calendar').val(calendar.id); var buttons = {}; buttons[rcmail.gettext('import', 'calendar')] = function() { if (form && form.elements._data.value) { rcmail.async_upload_form(form, 'import_events', function(e) { rcmail.set_busy(false, null, me.saving_lock); $('.ui-dialog-buttonpane button', $dialog.parent()).button('enable'); // display error message if no sophisticated response from server arrived (e.g. iframe load error) if (me.import_succeeded === null) rcmail.display_message(rcmail.get_label('importerror', 'calendar'), 'error'); }); // display upload indicator (with extended timeout) var timeout = rcmail.env.request_timeout; rcmail.env.request_timeout = 600; me.import_succeeded = null; me.saving_lock = rcmail.set_busy(true, 'uploading'); $('.ui-dialog-buttonpane button', $dialog.parent()).button('disable'); // restore settings rcmail.env.request_timeout = timeout; } }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: false, closeOnEscape: false, title: rcmail.gettext('importevents', 'calendar'), close: function() { $('.ui-dialog-buttonpane button', $dialog.parent()).button('enable'); $dialog.dialog("destroy").hide(); }, buttons: buttons, width: 520 }).show(); }; // callback from server if import succeeded this.import_success = function(p) { this.import_succeeded = true; $("#eventsimport:ui-dialog").dialog('close'); rcmail.set_busy(false, null, me.saving_lock); rcmail.gui_objects.importform.reset(); if (p.refetch) this.refresh(p); }; // callback from server to report errors on import this.import_error = function(p) { this.import_succeeded = false; rcmail.display_message(p.message || rcmail.get_label('importerror', 'calendar'), 'error'); } // show URL of the given calendar in a dialog box this.showurl = function(calendar) { var $dialog = $('#calendarurlbox'); if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (calendar.feedurl) { if (calendar.caldavurl) { $('#caldavurl').val(calendar.caldavurl); $('#calendarcaldavurl').show(); } else { $('#calendarcaldavurl').hide(); } $dialog.dialog({ resizable: true, closeOnEscape: true, title: rcmail.gettext('showurl', 'calendar'), close: function() { $dialog.dialog("destroy").hide(); }, width: 520 }).show(); $('#calfeedurl').val(calendar.feedurl).select(); } }; // refresh the calendar view after saving event data this.refresh = function(p) { var source = me.calendars[p.source]; if (source && (p.refetch || (p.update && !source.active))) { // activate event source if new event was added to an invisible calendar if (!source.active) { source.active = true; fc.fullCalendar('addEventSource', source); $('#' + rcmail.get_folder_li(source.id, 'rcmlical').id + ' input').prop('checked', true); } else fc.fullCalendar('refetchEvents', source); } // add/update single event object else if (source && p.update) { var event = p.update; event.temp = false; event.editable = source.editable; var existing = fc.fullCalendar('clientEvents', event._id); if (existing.length) { $.extend(existing[0], event); fc.fullCalendar('updateEvent', existing[0]); } else { event.source = source; // link with source fc.fullCalendar('renderEvent', event); } // refresh fish-eye view if (me.fisheye_date) me.fisheye_view(me.fisheye_date); } // remove temp events fc.fullCalendar('removeEvents', function(e){ return e.temp; }); }; // modify query parameters for refresh requests this.before_refresh = function(query) { var view = fc.fullCalendar('getView'); query.start = date2unixtime(view.visStart); query.end = date2unixtime(view.visEnd); if (this.search_query) query.q = this.search_query; return query; }; /*** event searching ***/ // execute search this.quicksearch = function() { if (rcmail.gui_objects.qsearchbox) { var q = rcmail.gui_objects.qsearchbox.value; if (q != '') { var id = 'search-'+q; var sources = []; if (this._search_message) rcmail.hide_message(this._search_message); for (var sid in this.calendars) { if (this.calendars[sid]) { this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, '') + '&q='+escape(q); sources.push(sid); } } id += '@'+sources.join(','); // ignore if query didn't change if (this.search_request == id) { return; } // remember current view else if (!this.search_request) { this.default_view = fc.fullCalendar('getView').name; } this.search_request = id; this.search_query = q; // change to list view fc.fullCalendar('option', 'listSections', 'month') .fullCalendar('option', 'listRange', Math.max(60, settings['agenda_range'])) .fullCalendar('changeView', 'table'); update_agenda_toolbar(); // refetch events with new url (if not already triggered by changeView) if (!this.is_loading) fc.fullCalendar('refetchEvents'); } else // empty search input equals reset this.reset_quicksearch(); } }; // reset search and get back to normal event listing this.reset_quicksearch = function() { $(rcmail.gui_objects.qsearchbox).val(''); if (this._search_message) rcmail.hide_message(this._search_message); if (this.search_request) { // hide bottom links of agenda view fc.find('.fc-list-content > .fc-listappend').hide(); // restore original event sources and view mode from fullcalendar fc.fullCalendar('option', 'listSections', settings['agenda_sections']) .fullCalendar('option', 'listRange', settings['agenda_range']); update_agenda_toolbar(); for (var sid in this.calendars) { if (this.calendars[sid]) this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, ''); } if (this.default_view) fc.fullCalendar('changeView', this.default_view); if (!this.is_loading) fc.fullCalendar('refetchEvents'); this.search_request = this.search_query = null; } }; // callback if all sources have been fetched from server this.events_loaded = function(count) { var addlinks, append = ''; // enhance list view when searching if (this.search_request) { if (!count) { this._search_message = rcmail.display_message(rcmail.gettext('searchnoresults', 'calendar'), 'notice'); append = '<div class="message">' + rcmail.gettext('searchnoresults', 'calendar') + '</div>'; } append += '<div class="fc-bottomlinks formlinks"></div>'; addlinks = true; } if (fc.fullCalendar('getView').name == 'table') { var container = fc.find('.fc-list-content > .fc-listappend'); if (append) { if (!container.length) container = $('<div class="fc-listappend"></div>').appendTo(fc.find('.fc-list-content')); container.html(append).show(); } else if (container.length) container.hide(); // add links to adjust search date range if (addlinks) { var lc = container.find('.fc-bottomlinks'); $('<a>').attr('href', '#').html(rcmail.gettext('searchearlierdates', 'calendar')).appendTo(lc).click(function(){ fc.fullCalendar('incrementDate', 0, -1, 0); }); lc.append(" "); $('<a>').attr('href', '#').html(rcmail.gettext('searchlaterdates', 'calendar')).appendTo(lc).click(function(){ var range = fc.fullCalendar('option', 'listRange'); if (range < 90) { fc.fullCalendar('option', 'listRange', fc.fullCalendar('option', 'listRange') + 30).fullCalendar('render'); update_agenda_toolbar(); } else fc.fullCalendar('incrementDate', 0, 1, 0); }); } } if (this.fisheye_date) this.fisheye_view(this.fisheye_date); }; // resize and reposition (center) the dialog window this.dialog_resize = function(id, height, width) { var win = $(window), w = win.width(), h = win.height(); $(id).dialog('option', { height: Math.min(h-20, height+130), width: Math.min(w-20, width+50) }) .dialog('option', 'position', ['center', 'center']); // only works in a separate call (!?) }; // adjust calendar view size this.view_resize = function() { var footer = fc.fullCalendar('getView').name == 'table' ? $('#agendaoptions').outerHeight() : 0; fc.fullCalendar('option', 'height', $('#calendar').height() - footer); }; /*** startup code ***/ // create list of event sources AKA calendars this.calendars = {}; var li, cal, active, event_sources = []; for (var id in rcmail.env.calendars) { cal = rcmail.env.calendars[id]; this.calendars[id] = $.extend({ url: "./?_task=calendar&_action=load_events&source="+escape(id), editable: !cal.readonly, className: 'fc-event-cal-'+id, id: id }, cal); this.calendars[id].color = settings.event_coloring % 2 ? '' : '#' + cal.color; if ((active = cal.active || false)) { event_sources.push(this.calendars[id]); } // init event handler on calendar list checkbox if ((li = rcmail.get_folder_li(id, 'rcmlical'))) { $('#'+li.id+' input').click(function(e){ var id = $(this).data('id'); if (me.calendars[id]) { // add or remove event source on click var action; if (this.checked) { action = 'addEventSource'; me.calendars[id].active = true; } else { action = 'removeEventSource'; me.calendars[id].active = false; } // add/remove event source fc.fullCalendar(action, me.calendars[id]); rcmail.http_post('calendar', { action:'subscribe', c:{ id:id, active:me.calendars[id].active?1:0 } }); } }).data('id', id).get(0).checked = active; $(li).click(function(e){ var id = $(this).data('id'); rcmail.select_folder(id, 'rcmlical'); rcmail.enable_command('calendar-edit', true); rcmail.enable_command('calendar-remove', 'calendar-showurl', true); me.selected_calendar = id; }) .dblclick(function(){ me.calendar_edit_dialog(me.calendars[me.selected_calendar]); }) .data('id', id); } if (!cal.readonly && !this.selected_calendar) { this.selected_calendar = id; rcmail.enable_command('addevent', true); } } // select default calendar if (settings.default_calendar && this.calendars[settings.default_calendar] && !this.calendars[settings.default_calendar].readonly) this.selected_calendar = settings.default_calendar; var viewdate = new Date(); if (rcmail.env.date) viewdate.setTime(fromunixtime(rcmail.env.date)); // initalize the fullCalendar plugin var fc = $('#calendar').fullCalendar({ header: { right: 'prev,next today', center: 'title', left: 'agendaDay,agendaWeek,month,table' }, aspectRatio: 1, date: viewdate.getDate(), month: viewdate.getMonth(), year: viewdate.getFullYear(), ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone height: $('#calendar').height(), eventSources: event_sources, monthNames : settings['months'], monthNamesShort : settings['months_short'], dayNames : settings['days'], dayNamesShort : settings['days_short'], firstDay : settings['first_day'], firstHour : settings['first_hour'], slotMinutes : 60/settings['timeslots'], timeFormat: { '': settings['time_format'], agenda: settings['time_format'] + '{ - ' + settings['time_format'] + '}', list: settings['time_format'] + '{ - ' + settings['time_format'] + '}', table: settings['time_format'] + '{ - ' + settings['time_format'] + '}' }, axisFormat : settings['time_format'], columnFormat: { month: 'ddd', // Mon week: 'ddd ' + settings['date_short'], // Mon 9/7 day: 'dddd ' + settings['date_short'], // Monday 9/7 table: settings['date_agenda'] }, titleFormat: { month: 'MMMM yyyy', week: settings['dates_long'], day: 'dddd ' + settings['date_long'], table: settings['dates_long'] }, listPage: 1, // advance one day in agenda view listRange: settings['agenda_range'], listSections: settings['agenda_sections'], tableCols: ['handle', 'date', 'time', 'title', 'location'], defaultView: rcmail.env.view || settings['default_view'], allDayText: rcmail.gettext('all-day', 'calendar'), buttonText: { prev: (bw.ie6 ? '&nbsp;&lt;&lt;&nbsp;' : '&nbsp;&#9668;&nbsp;'), next: (bw.ie6 ? '&nbsp;&gt;&gt;&nbsp;' : '&nbsp;&#9658;&nbsp;'), today: settings['today'], day: rcmail.gettext('day', 'calendar'), week: rcmail.gettext('week', 'calendar'), month: rcmail.gettext('month', 'calendar'), table: rcmail.gettext('agenda', 'calendar') }, listTexts: { until: rcmail.gettext('until', 'calendar'), past: rcmail.gettext('pastevents', 'calendar'), today: rcmail.gettext('today', 'calendar'), tomorrow: rcmail.gettext('tomorrow', 'calendar'), thisWeek: rcmail.gettext('thisweek', 'calendar'), nextWeek: rcmail.gettext('nextweek', 'calendar'), thisMonth: rcmail.gettext('thismonth', 'calendar'), nextMonth: rcmail.gettext('nextmonth', 'calendar'), future: rcmail.gettext('futureevents', 'calendar'), week: rcmail.gettext('weekofyear', 'calendar') }, selectable: true, selectHelper: false, currentTimeIndicator: settings.time_indicator, loading: function(isLoading) { me.is_loading = isLoading; this._rc_loading = rcmail.set_busy(isLoading, 'loading', this._rc_loading); // trigger callback if (!isLoading) me.events_loaded($(this).fullCalendar('clientEvents').length); }, // event rendering eventRender: fc_event_render, // render element indicating more (invisible) events overflowRender: function(data, element) { element.html(rcmail.gettext('andnmore', 'calendar').replace('$nr', data.count)) .click(function(e){ me.fisheye_view(data.date); }); }, // callback for date range selection select: function(start, end, allDay, e, view) { var range_select = (!allDay || start.getDate() != end.getDate()) if (dialog_check(e) && range_select) event_edit_dialog('new', { start:start, end:end, allDay:allDay, calendar:me.selected_calendar }); if (range_select || ignore_click) view.calendar.unselect(); }, // callback for clicks in all-day box dayClick: function(date, allDay, e, view) { var now = new Date().getTime(); if (now - day_clicked_ts < 400 && day_clicked == date.getTime()) { // emulate double-click on day var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); return event_edit_dialog('new', { start:date, end:enddate, allDay:allDay, calendar:me.selected_calendar }); } if (!ignore_click) { view.calendar.gotoDate(date); if (day_clicked && new Date(day_clicked).getMonth() != date.getMonth()) view.calendar.select(date, date, allDay); } day_clicked = date.getTime(); day_clicked_ts = now; }, // callback when a specific event is clicked eventClick: function(event) { if (!event.temp) event_show_dialog(event); }, // callback when an event was dragged and finally dropped eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) { if (event.end == null || event.end.getTime() < event.start.getTime()) { event.end = new Date(event.start.getTime() + (allDay ? DAY_MS : HOUR_MS)); } // moved to all-day section: set times to 12:00 - 13:00 if (allDay && !event.allDay) { event.start.setHours(12); event.start.setMinutes(0); event.start.setSeconds(0); event.end.setHours(13); event.end.setMinutes(0); event.end.setSeconds(0); } // moved from all-day section: set times to working hours else if (event.allDay && !allDay) { var newstart = event.start.getTime(); revertFunc(); // revert to get original duration var numdays = Math.max(1, Math.round((event.end.getTime() - event.start.getTime()) / DAY_MS)) - 1; event.start = new Date(newstart); event.end = new Date(newstart + numdays * DAY_MS); event.end.setHours(settings['work_end'] || 18); event.end.setMinutes(0); if (event.end.getTime() < event.start.getTime()) event.end = new Date(newstart + HOUR_MS); } // send move request to server var data = { id: event.id, calendar: event.calendar, start: date2servertime(event.start), end: date2servertime(event.end), allday: allDay?1:0 }; update_event_confirm('move', event, data); }, // callback for event resizing eventResize: function(event, delta) { // sanitize event dates if (event.allDay) event.start.setHours(12); if (!event.end || event.end.getTime() < event.start.getTime()) event.end = new Date(event.start.getTime() + HOUR_MS); // send resize request to server var data = { id: event.id, calendar: event.calendar, start: date2servertime(event.start), end: date2servertime(event.end) }; update_event_confirm('resize', event, data); }, viewDisplay: function(view) { $('#agendaoptions')[view.name == 'table' ? 'show' : 'hide'](); if (minical) { window.setTimeout(function(){ minical.datepicker('setDate', fc.fullCalendar('getDate')); }, exec_deferred); if (view.name != current_view) me.view_resize(); current_view = view.name; } }, viewRender: function(view) { if (fc && view.name == 'month') fc.fullCalendar('option', 'maxHeight', Math.floor((view.element.parent().height()-18) / 6) - 35); } }); // format time string var formattime = function(hour, minutes, start) { var time, diff, unit, duration = '', d = new Date(); d.setHours(hour); d.setMinutes(minutes); time = $.fullCalendar.formatDate(d, settings['time_format']); if (start) { diff = Math.floor((d.getTime() - start.getTime()) / 60000); if (diff > 0) { unit = 'm'; if (diff >= 60) { unit = 'h'; diff = Math.round(diff / 3) / 20; } duration = ' (' + diff + unit + ')'; } } return [time, duration]; }; var autocomplete_times = function(p, callback) { /* Time completions */ var result = []; var now = new Date(); var st, start = (String(this.element.attr('id')).indexOf('endtime') > 0 && (st = $('#edit-starttime').val()) && $('#edit-startdate').val() == $('#edit-enddate').val()) ? parse_datetime(st, '') : null; var full = p.term - 1 > 0 || p.term.length > 1; var hours = start ? start.getHours() : (full ? parse_datetime(p.term, '') : now).getHours(); var step = 15; var minutes = hours * 60 + (full ? 0 : now.getMinutes()); var min = Math.ceil(minutes / step) * step % 60; var hour = Math.floor(Math.ceil(minutes / step) * step / 60); // list hours from 0:00 till now for (var h = start ? start.getHours() : 0; h < hours; h++) result.push(formattime(h, 0, start)); // list 15min steps for the next two hours for (; h < hour + 2 && h < 24; h++) { while (min < 60) { result.push(formattime(h, min, start)); min += step; } min = 0; } // list the remaining hours till 23:00 while (h < 24) result.push(formattime((h++), 0, start)); return callback(result); }; var autocomplete_open = function(event, ui) { // scroll to current time var $this = $(this); var widget = $this.autocomplete('widget'); var menu = $this.data('autocomplete').menu; var amregex = /^(.+)(a[.m]*)/i; var pmregex = /^(.+)(a[.m]*)/i; var val = $(this).val().replace(amregex, '0:$1').replace(pmregex, '1:$1'); var li, html; widget.css('width', '10em'); widget.children().each(function(){ li = $(this); html = li.children().first().html().replace(/\s+\(.+\)$/, '').replace(amregex, '0:$1').replace(pmregex, '1:$1'); if (html.indexOf(val) == 0) menu._scrollIntoView(li); }); }; // if start date is changed, shift end date according to initial duration var shift_enddate = function(dateText) { var newstart = parse_datetime('0', dateText); var newend = new Date(newstart.getTime() + $('#edit-startdate').data('duration') * 1000); $('#edit-enddate').val($.fullCalendar.formatDate(newend, me.settings['date_format'])); event_times_changed(); }; // Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. // Uses the default $.datepicker.iso8601Week() function but takes firstDay setting into account. // This is a temporary fix until http://bugs.jqueryui.com/ticket/8420 is resolved. var iso8601Week = datepicker_settings.calculateWeek = function(date) { var mondayOffset = Math.abs(1 - datepicker_settings.firstDay); return $.datepicker.iso8601Week(new Date(date.getTime() + mondayOffset * 86400000)); }; var minical; var init_calendar_ui = function() { // initialize small calendar widget using jQuery UI datepicker minical = $('#datepicker').datepicker($.extend(datepicker_settings, { inline: true, showWeek: true, changeMonth: false, // maybe enable? changeYear: false, // maybe enable? onSelect: function(dateText, inst) { ignore_click = true; var d = minical.datepicker('getDate'); //parse_datetime('0:0', dateText); fc.fullCalendar('gotoDate', d).fullCalendar('select', d, d, true); }, onChangeMonthYear: function(year, month, inst) { minical.data('year', year).data('month', month); }, beforeShowDay: function(date) { var view = fc.fullCalendar('getView'); var active = view.visStart && date.getTime() >= view.visStart.getTime() && date.getTime() < view.visEnd.getTime(); return [ true, (active ? 'ui-datepicker-activerange ui-datepicker-active-' + view.name : ''), '']; } })) // set event handler for clicks on calendar week cell of the datepicker widget .click(function(e) { var cell = $(e.target); if (e.target.tagName == 'TD' && cell.hasClass('ui-datepicker-week-col')) { var base_date = minical.datepicker('getDate'); if (minical.data('month')) base_date.setMonth(minical.data('month')-1); if (minical.data('year')) base_date.setYear(minical.data('year')); base_date.setHours(12); base_date.setDate(base_date.getDate() - ((base_date.getDay() + 6) % 7) + datepicker_settings.firstDay); var day_off = base_date.getDay() - datepicker_settings.firstDay; var base_kw = iso8601Week(base_date); var target_kw = parseInt(cell.html()); var diff = (target_kw - base_kw) * 7 * DAY_MS; // select monday of the chosen calendar week var date = new Date(base_date.getTime() - day_off * DAY_MS + diff); fc.fullCalendar('gotoDate', date).fullCalendar('setDate', date).fullCalendar('changeView', 'agendaWeek'); minical.datepicker('setDate', date); } }); // init event dialog $('#eventtabs').tabs({ show: function(event, ui) { if (ui.panel.id == 'event-tab-3') { $('#edit-attendee-name').select(); // update free-busy status if needed if (freebusy_ui.needsupdate && me.selected_event) update_freebusy_status(me.selected_event); // add current user as organizer if non added yet if (!event_attendees.length) { add_attendee($.extend({ role:'ORGANIZER' }, settings.identity)); $('#edit-attendees-form .attendees-invitebox').show(); } } } }); $('#edit-enddate').datepicker(datepicker_settings); $('#edit-startdate').datepicker(datepicker_settings).datepicker('option', 'onSelect', shift_enddate).change(function(){ shift_enddate(this.value); }); $('#edit-enddate').datepicker('option', 'onSelect', event_times_changed).change(event_times_changed); $('#edit-allday').click(function(){ $('#edit-starttime, #edit-endtime')[(this.checked?'hide':'show')](); event_times_changed(); }); // configure drop-down menu on time input fields based on jquery UI autocomplete $('#edit-starttime, #edit-endtime, #eventedit input.edit-alarm-time') .attr('autocomplete', "off") .autocomplete({ delay: 100, minLength: 1, source: autocomplete_times, open: autocomplete_open, change: event_times_changed, select: function(event, ui) { $(this).val(ui.item[0]); return false; } }) .click(function() { // show drop-down upon clicks $(this).autocomplete('search', $(this).val() ? $(this).val().replace(/\D.*/, "") : " "); }).each(function(){ $(this).data('autocomplete')._renderItem = function(ul, item) { return $('<li>') .data('item.autocomplete', item) .append('<a>' + item[0] + item[1] + '</a>') .appendTo(ul); }; }); // register events on alarm fields init_alarms_edit('#eventedit'); // toggle recurrence frequency forms $('#edit-recurrence-frequency').change(function(e){ var freq = $(this).val().toLowerCase(); $('.recurrence-form').hide(); if (freq) $('#recurrence-form-'+freq+', #recurrence-form-until').show(); }); $('#edit-recurrence-enddate').datepicker(datepicker_settings).click(function(){ $("#edit-recurrence-repeat-until").prop('checked', true) }); $('#edit-recurrence-repeat-times').change(function(e){ $('#edit-recurrence-repeat-count').prop('checked', true); }); // init attendees autocompletion var ac_props; // parallel autocompletion if (rcmail.env.autocomplete_threads > 0) { ac_props = { threads: rcmail.env.autocomplete_threads, sources: rcmail.env.autocomplete_sources }; } rcmail.init_address_input_events($('#edit-attendee-name'), ac_props); rcmail.addEventListener('autocomplete_insert', function(e){ $('#edit-attendee-add').click(); }); $('#edit-attendee-add').click(function(){ var input = $('#edit-attendee-name'); rcmail.ksearch_blur(); if (add_attendees(input.val())) { input.val(''); } }); // keep these two checkboxes in sync $('#edit-attendees-donotify, #edit-attendees-invite').click(function(){ $('#edit-attendees-donotify, #edit-attendees-invite').prop('checked', this.checked); }); $('#edit-attendee-schedule').click(function(){ event_freebusy_dialog(); }); $('#shedule-freebusy-prev').html(bw.ie6 ? '&lt;&lt;' : '&#9668;').button().click(function(){ render_freebusy_grid(-1); }); $('#shedule-freebusy-next').html(bw.ie6 ? '&gt;&gt;' : '&#9658;').button().click(function(){ render_freebusy_grid(1); }).parent().buttonset(); $('#shedule-find-prev').button().click(function(){ freebusy_find_slot(-1); }); $('#shedule-find-next').button().click(function(){ freebusy_find_slot(1); }); $('#schedule-freebusy-workinghours').click(function(){ freebusy_ui.workinhoursonly = this.checked; $('#workinghourscss').remove(); if (this.checked) $('<style type="text/css" id="workinghourscss"> td.offhours { opacity:0.3; filter:alpha(opacity=30) } </style>').appendTo('head'); }); $('#event-rsvp input.button').click(function(){ event_rsvp($(this).attr('rel')) }); $('#agenda-listrange').change(function(e){ settings['agenda_range'] = parseInt($(this).val()); fc.fullCalendar('option', 'listRange', settings['agenda_range']).fullCalendar('render'); // TODO: save new settings in prefs }).val(settings['agenda_range']); $('#agenda-listsections').change(function(e){ settings['agenda_sections'] = $(this).val(); fc.fullCalendar('option', 'listSections', settings['agenda_sections']).fullCalendar('render'); // TODO: save new settings in prefs }).val(fc.fullCalendar('option', 'listSections')); // hide event dialog when clicking somewhere into document $(document).bind('mousedown', dialog_check); rcmail.set_busy(false, 'loading', ui_loading); } // initialize more UI elements (deferred) window.setTimeout(init_calendar_ui, exec_deferred); // add proprietary css styles if not IE if (!bw.ie) $('div.fc-content').addClass('rcube-fc-content'); // IE supresses 2nd click event when double-clicking if (bw.ie && bw.vendver < 9) { $('div.fc-content').bind('dblclick', function(e){ if (!$(this).hasClass('fc-widget-header') && fc.fullCalendar('getView').name != 'table') { var date = fc.fullCalendar('getDate'); var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); event_edit_dialog('new', { start:date, end:enddate, allDay:true, calendar:me.selected_calendar }); } }); } } // end rcube_calendar class /* calendar plugin initialization */ window.rcmail && rcmail.addEventListener('init', function(evt) { // configure toolbar buttons rcmail.register_command('addevent', function(){ cal.add_event(); }, true); rcmail.register_command('print', function(){ cal.print_calendars(); }, true); // configure list operations rcmail.register_command('calendar-create', function(){ cal.calendar_edit_dialog(null); }, true); rcmail.register_command('calendar-edit', function(){ cal.calendar_edit_dialog(cal.calendars[cal.selected_calendar]); }, false); rcmail.register_command('calendar-remove', function(){ cal.calendar_remove(cal.calendars[cal.selected_calendar]); }, false); rcmail.register_command('events-import', function(){ cal.import_events(cal.calendars[cal.selected_calendar]); }, true); rcmail.register_command('calendar-showurl', function(){ cal.showurl(cal.calendars[cal.selected_calendar]); }, false); // search and export events rcmail.register_command('export', function(){ rcmail.goto_url('export_events', { source:cal.selected_calendar }); }, true); rcmail.register_command('search', function(){ cal.quicksearch(); }, true); rcmail.register_command('reset-search', function(){ cal.reset_quicksearch(); }, true); // register callback commands rcmail.addEventListener('plugin.destroy_source', function(p){ cal.calendar_destroy_source(p.id); }); rcmail.addEventListener('plugin.unlock_saving', function(p){ cal.unlock_saving(); }); rcmail.addEventListener('plugin.refresh_calendar', function(p){ cal.refresh(p); }); rcmail.addEventListener('plugin.import_success', function(p){ cal.import_success(p); }); rcmail.addEventListener('plugin.import_error', function(p){ cal.import_error(p); }); rcmail.addEventListener('requestrefresh', function(q){ return cal.before_refresh(q); }); // let's go var cal = new rcube_calendar_ui($.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings)); $(window).resize(function(e) { // check target due to bugs in jquery // http://bugs.jqueryui.com/ticket/7514 // http://bugs.jquery.com/ticket/9841 if (e.target == window) { cal.view_resize(); } }).resize(); // show calendars list when ready $('#calendars').css('visibility', 'inherit'); // show toolbar $('#toolbar').show(); });
stephdl/roundcubemail_plugins
root/usr/share/roundcubemail/plugins/calendar/calendar_ui.js
JavaScript
gpl-2.0
114,423
describe('PastDateValidatorWidgetFactory', function() { var Mock = {}; var factory; var whoAmI; beforeEach(function() { angular.mock.module('studio'); mockElement(); inject(function(_$injector_) { mockWidgetScope(_$injector_); factory = _$injector_.get('PastDateValidatorWidgetFactory'); }); widget = factory.create(Mock.scope, Mock.element); }); describe('Start a PastDate Factory Object', function() { it('should return a PastDate Validator Object', function() { pending(); }); it('should start the data field as date', function() { expect(widget.data).toBeDefined(); expect(widget.data).toEqual(false); }); }); describe('updates on data', function() { xit('should model data value be equal to self value', function() { // expect(Mock.question.fillingRules.options['pastDate'].data.reference).toEqual(widget.data); }); it('should call updateFillingRules from parente widget', function() { spyOn(Mock.parentWidget, 'updateFillingRules'); widget.updateData(); expect(Mock.parentWidget.updateFillingRules).toHaveBeenCalled(); }); }); function mockElement() { Mock.element = {}; } function mockWidgetScope($injector) { Mock.scope = { class: '', $parent: { widget: mockParentWidget($injector) } }; return Mock.scope; } function mockParentWidget($injector) { mockQuestion($injector); Mock.parentWidget = { getItem: function() { return Mock.question; }, updateFillingRules: function() {} }; return Mock.parentWidget; } function mockQuestion($injector) { Mock.question = $injector.get('SurveyItemFactory').create('IntegerQuestion', 'Q1'); Mock.question.fillingRules.options.pastDate = $injector.get('RulesFactory').create('pastDate'); return Mock.question; } function mockAdd($injector) { Mock.add = $injector.get('FillingRulesEditorWidgetFactory').create(); } });
ccem-dev/studio
tests/unit/editor/ui/validation/require/past-date/past-date-validator-widget-factory-spec.js
JavaScript
gpl-2.0
2,268
'use strict'; var env = process.env.NODE_ENV || 'development', config = require('./config'), B = require('bluebird'), _ = require('underscore'), L = require('./logger'), S = require('underscore.string'), nodemailer = require('nodemailer'), smtpTransport = require('nodemailer-smtp-pool'); var Mailer = function (options) { var opts = _.extend({}, config.mail, options); this.transporter = B.promisifyAll(nodemailer.createTransport(smtpTransport(opts))); }; Mailer.prototype.send = function (options) { var that = this; return that.transporter.sendMailAsync(options); }; module.exports = Mailer;
zamamohammed/health-check
mailer.js
JavaScript
gpl-2.0
643
/*jshint strict: false */ /*global chrome */ var merge = require('./merge'); exports.extend = require('pouchdb-extend'); exports.ajax = require('./deps/ajax'); exports.createBlob = require('./deps/blob'); exports.uuid = require('./deps/uuid'); exports.getArguments = require('argsarray'); var buffer = require('./deps/buffer'); var errors = require('./deps/errors'); var EventEmitter = require('events').EventEmitter; var collections = require('./deps/collections'); exports.Map = collections.Map; exports.Set = collections.Set; if (typeof global.Promise === 'function') { exports.Promise = global.Promise; } else { exports.Promise = require('bluebird'); } var Promise = exports.Promise; function toObject(array) { var obj = {}; array.forEach(function (item) { obj[item] = true; }); return obj; } // List of top level reserved words for doc var reservedWords = toObject([ '_id', '_rev', '_attachments', '_deleted', '_revisions', '_revs_info', '_conflicts', '_deleted_conflicts', '_local_seq', '_rev_tree', //replication documents '_replication_id', '_replication_state', '_replication_state_time', '_replication_state_reason', '_replication_stats' ]); // List of reserved words that should end up the document var dataWords = toObject([ '_attachments', //replication documents '_replication_id', '_replication_state', '_replication_state_time', '_replication_state_reason', '_replication_stats' ]); exports.lastIndexOf = function (str, char) { for (var i = str.length - 1; i >= 0; i--) { if (str.charAt(i) === char) { return i; } } return -1; }; exports.clone = function (obj) { return exports.extend(true, {}, obj); }; exports.inherits = require('inherits'); // Determine id an ID is valid // - invalid IDs begin with an underescore that does not begin '_design' or // '_local' // - any other string value is a valid id // Returns the specific error object for each case exports.invalidIdError = function (id) { var err; if (!id) { err = new TypeError(errors.MISSING_ID.message); err.status = 412; } else if (typeof id !== 'string') { err = new TypeError(errors.INVALID_ID.message); err.status = 400; } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { err = new TypeError(errors.RESERVED_ID.message); err.status = 400; } if (err) { throw err; } }; function isChromeApp() { return (typeof chrome !== "undefined" && typeof chrome.storage !== "undefined" && typeof chrome.storage.local !== "undefined"); } // Pretty dumb name for a function, just wraps callback calls so we dont // to if (callback) callback() everywhere exports.call = exports.getArguments(function (args) { if (!args.length) { return; } var fun = args.shift(); if (typeof fun === 'function') { fun.apply(this, args); } }); exports.isLocalId = function (id) { return (/^_local/).test(id); }; // check if a specific revision of a doc has been deleted // - metadata: the metadata object from the doc store // - rev: (optional) the revision to check. defaults to winning revision exports.isDeleted = function (metadata, rev) { if (!rev) { rev = merge.winningRev(metadata); } var dashIndex = rev.indexOf('-'); if (dashIndex !== -1) { rev = rev.substring(dashIndex + 1); } var deleted = false; merge.traverseRevTree(metadata.rev_tree, function (isLeaf, pos, id, acc, opts) { if (id === rev) { deleted = !!opts.deleted; } }); return deleted; }; exports.revExists = function (metadata, rev) { var found = false; merge.traverseRevTree(metadata.rev_tree, function (leaf, pos, id, acc, opts) { if ((pos + '-' + id) === rev) { found = true; } }); return found; }; exports.filterChange = function (opts) { return function (change) { var req = {}; var hasFilter = opts.filter && typeof opts.filter === 'function'; req.query = opts.query_params; if (opts.filter && hasFilter && !opts.filter.call(this, change.doc, req)) { return false; } if (opts.doc_ids && opts.doc_ids.indexOf(change.id) === -1) { return false; } if (!opts.include_docs) { delete change.doc; } else { for (var att in change.doc._attachments) { if (change.doc._attachments.hasOwnProperty(att)) { change.doc._attachments[att].stub = true; } } } return true; }; }; // Preprocess documents, parse their revisions, assign an id and a // revision for new writes that are missing them, etc exports.parseDoc = function (doc, newEdits) { var nRevNum; var newRevId; var revInfo; var error; var opts = {status: 'available'}; if (doc._deleted) { opts.deleted = true; } if (newEdits) { if (!doc._id) { doc._id = exports.uuid(); } newRevId = exports.uuid(32, 16).toLowerCase(); if (doc._rev) { revInfo = /^(\d+)-(.+)$/.exec(doc._rev); if (!revInfo) { var err = new TypeError("invalid value for property '_rev'"); err.status = 400; } doc._rev_tree = [{ pos: parseInt(revInfo[1], 10), ids: [revInfo[2], {status: 'missing'}, [[newRevId, opts, []]]] }]; nRevNum = parseInt(revInfo[1], 10) + 1; } else { doc._rev_tree = [{ pos: 1, ids : [newRevId, opts, []] }]; nRevNum = 1; } } else { if (doc._revisions) { doc._rev_tree = [{ pos: doc._revisions.start - doc._revisions.ids.length + 1, ids: doc._revisions.ids.reduce(function (acc, x) { if (acc === null) { return [x, opts, []]; } else { return [x, {status: 'missing'}, [acc]]; } }, null) }]; nRevNum = doc._revisions.start; newRevId = doc._revisions.ids[0]; } if (!doc._rev_tree) { revInfo = /^(\d+)-(.+)$/.exec(doc._rev); if (!revInfo) { error = new TypeError(errors.BAD_ARG.message); error.status = errors.BAD_ARG.status; throw error; } nRevNum = parseInt(revInfo[1], 10); newRevId = revInfo[2]; doc._rev_tree = [{ pos: parseInt(revInfo[1], 10), ids: [revInfo[2], opts, []] }]; } } exports.invalidIdError(doc._id); doc._rev = [nRevNum, newRevId].join('-'); var result = {metadata : {}, data : {}}; for (var key in doc) { if (doc.hasOwnProperty(key)) { var specialKey = key[0] === '_'; if (specialKey && !reservedWords[key]) { error = new Error(errors.DOC_VALIDATION.message + ': ' + key); error.status = errors.DOC_VALIDATION.status; throw error; } else if (specialKey && !dataWords[key]) { result.metadata[key.slice(1)] = doc[key]; } else { result.data[key] = doc[key]; } } } return result; }; exports.isCordova = function () { return (typeof cordova !== "undefined" || typeof PhoneGap !== "undefined" || typeof phonegap !== "undefined"); }; exports.hasLocalStorage = function () { if (isChromeApp()) { return false; } try { return global.localStorage; } catch (e) { return false; } }; exports.Changes = Changes; exports.inherits(Changes, EventEmitter); function Changes() { if (!(this instanceof Changes)) { return new Changes(); } var self = this; EventEmitter.call(this); this.isChrome = isChromeApp(); this.listeners = {}; this.hasLocal = false; if (!this.isChrome) { this.hasLocal = exports.hasLocalStorage(); } if (this.isChrome) { chrome.storage.onChanged.addListener(function (e) { // make sure it's event addressed to us if (e.db_name != null) { //object only has oldValue, newValue members self.emit(e.dbName.newValue); } }); } else if (this.hasLocal) { if (global.addEventListener) { global.addEventListener("storage", function (e) { self.emit(e.key); }); } else { global.attachEvent("storage", function (e) { self.emit(e.key); }); } } } Changes.prototype.addListener = function (dbName, id, db, opts) { if (this.listeners[id]) { return; } function eventFunction() { db.changes({ include_docs: opts.include_docs, conflicts: opts.conflicts, continuous: false, descending: false, filter: opts.filter, view: opts.view, since: opts.since, query_params: opts.query_params, onChange: function (c) { if (c.seq > opts.since && !opts.cancelled) { opts.since = c.seq; exports.call(opts.onChange, c); } } }); } this.listeners[id] = eventFunction; this.on(dbName, eventFunction); }; Changes.prototype.removeListener = function (dbName, id) { if (!(id in this.listeners)) { return; } EventEmitter.prototype.removeListener.call(this, dbName, this.listeners[id]); }; Changes.prototype.notifyLocalWindows = function (dbName) { //do a useless change on a storage thing //in order to get other windows's listeners to activate if (this.isChrome) { chrome.storage.local.set({dbName: dbName}); } else if (this.hasLocal) { localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; } }; Changes.prototype.notify = function (dbName) { this.emit(dbName); this.notifyLocalWindows(dbName); }; if (!process.browser || !('atob' in global)) { exports.atob = function (str) { var base64 = new buffer(str, 'base64'); // Node.js will just skip the characters it can't encode instead of // throwing and exception if (base64.toString('base64') !== str) { throw ("Cannot base64 encode full string"); } return base64.toString('binary'); }; } else { exports.atob = function (str) { return atob(str); }; } if (!process.browser || !('btoa' in global)) { exports.btoa = function (str) { return new buffer(str, 'binary').toString('base64'); }; } else { exports.btoa = function (str) { return btoa(str); }; } // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) exports.fixBinary = function (bin) { if (!process.browser) { // don't need to do this in Node return bin; } var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; }; // shim for browsers that don't support it exports.readAsBinaryString = function (blob, callback) { var reader = new FileReader(); var hasBinaryString = typeof reader.readAsBinaryString === 'function'; reader.onloadend = function (e) { var result = e.target.result || ''; if (hasBinaryString) { return callback(result); } callback(exports.arrayBufferToBinaryString(result)); }; if (hasBinaryString) { reader.readAsBinaryString(blob); } else { reader.readAsArrayBuffer(blob); } }; exports.once = function (fun) { var called = false; return exports.getArguments(function (args) { if (called) { throw new Error('once called more than once'); } else { called = true; fun.apply(this, args); } }); }; exports.toPromise = function (func) { //create the function we will be returning return exports.getArguments(function (args) { var self = this; var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false; // if the last argument is a function, assume its a callback var usedCB; if (tempCB) { // if it was a callback, create a new callback which calls it, // but do so async so we don't trap any errors usedCB = function (err, resp) { process.nextTick(function () { tempCB(err, resp); }); }; } var promise = new Promise(function (fulfill, reject) { var resp; try { var callback = exports.once(function (err, mesg) { if (err) { reject(err); } else { fulfill(mesg); } }); // create a callback for this invocation // apply the function in the orig context args.push(callback); resp = func.apply(self, args); if (resp && typeof resp.then === 'function') { fulfill(resp); } } catch (e) { reject(e); } }); // if there is a callback, call it back if (usedCB) { promise.then(function (result) { usedCB(null, result); }, usedCB); } promise.cancel = function () { return this; }; return promise; }); }; exports.adapterFun = function (name, callback) { return exports.toPromise(exports.getArguments(function (args) { if (this._closed) { return Promise.reject(new Error('database is closed')); } var self = this; if (!this.taskqueue.isReady) { return new exports.Promise(function (fulfill, reject) { self.taskqueue.addTask(function (failed) { if (failed) { reject(failed); } else { fulfill(self[name].apply(self, args)); } }); }); } return callback.apply(this, args); })); }; //Can't find original post, but this is close //http://stackoverflow.com/questions/6965107/ (continues on next line) //converting-between-strings-and-arraybuffers exports.arrayBufferToBinaryString = function (buffer) { var binary = ""; var bytes = new Uint8Array(buffer); var length = bytes.byteLength; for (var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } return binary; }; exports.cancellableFun = function (fun, self, opts) { opts = opts ? exports.clone(true, {}, opts) : {}; var emitter = new EventEmitter(); var oldComplete = opts.complete || function () { }; var complete = opts.complete = exports.once(function (err, resp) { if (err) { oldComplete(err); } else { emitter.emit('end', resp); oldComplete(null, resp); } emitter.removeAllListeners(); }); var oldOnChange = opts.onChange || function () {}; var lastChange = 0; self.on('destroyed', function () { emitter.removeAllListeners(); }); opts.onChange = function (change) { oldOnChange(change); if (change.seq <= lastChange) { return; } lastChange = change.seq; emitter.emit('change', change); if (change.deleted) { emitter.emit('delete', change); } else if (change.changes.length === 1 && change.changes[0].rev.slice(0, 1) === '1-') { emitter.emit('create', change); } else { emitter.emit('update', change); } }; var promise = new Promise(function (fulfill, reject) { opts.complete = function (err, res) { if (err) { reject(err); } else { fulfill(res); } }; }); promise.then(function (result) { complete(null, result); }, complete); // this needs to be overwridden by caller, dont fire complete until // the task is ready promise.cancel = function () { promise.isCancelled = true; if (self.taskqueue.isReady) { opts.complete(null, {status: 'cancelled'}); } }; if (!self.taskqueue.isReady) { self.taskqueue.addTask(function () { if (promise.isCancelled) { opts.complete(null, {status: 'cancelled'}); } else { fun(self, opts, promise); } }); } else { fun(self, opts, promise); } promise.on = emitter.on.bind(emitter); promise.once = emitter.once.bind(emitter); promise.addListener = emitter.addListener.bind(emitter); promise.removeListener = emitter.removeListener.bind(emitter); promise.removeAllListeners = emitter.removeAllListeners.bind(emitter); promise.setMaxListeners = emitter.setMaxListeners.bind(emitter); promise.listeners = emitter.listeners.bind(emitter); promise.emit = emitter.emit.bind(emitter); return promise; }; exports.MD5 = exports.toPromise(require('./deps/md5')); // designed to give info to browser users, who are disturbed // when they see 404s in the console exports.explain404 = function (str) { if (process.browser && 'console' in global && 'info' in console) { console.info('The above 404 is totally normal. ' + str + '\n\u2665 the PouchDB team'); } }; exports.parseUri = require('./deps/parse-uri'); exports.compare = function (left, right) { return left < right ? -1 : left > right ? 1 : 0; };
mrded/wikijob
www/lib/pouchdb/lib/utils.js
JavaScript
gpl-2.0
16,505
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ var varienTabs = new Class.create(); varienTabs.prototype = { initialize : function(containerId, destElementId, activeTabId, shadowTabs){ this.containerId = containerId; this.destElementId = destElementId; this.activeTab = null; this.tabOnClick = this.tabMouseClick.bindAsEventListener(this); this.tabs = $$('#'+this.containerId+' li a.tab-item-link'); this.hideAllTabsContent(); for (var tab=0; tab<this.tabs.length; tab++) { Event.observe(this.tabs[tab],'click',this.tabOnClick); // move tab contents to destination element if($(this.destElementId)){ var tabContentElement = $(this.getTabContentElementId(this.tabs[tab])); if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){ $(this.destElementId).appendChild(tabContentElement); tabContentElement.container = this; tabContentElement.statusBar = this.tabs[tab]; tabContentElement.tabObject = this.tabs[tab]; this.tabs[tab].contentMoved = true; this.tabs[tab].container = this; this.tabs[tab].show = function(){ this.container.showTabContent(this); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]}); } } } /* // this code is pretty slow in IE, so lets do it in tabs*.phtml // mark ajax tabs as not loaded if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) { Element.addClassName($(this.tabs[tab].id), 'notloaded'); } */ // bind shadow tabs if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) { this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id]; } } this.displayFirst = activeTabId; Event.observe(window,'load',this.moveTabContentInDest.bind(this)); }, setSkipDisplayFirstTab : function(){ this.displayFirst = null; }, moveTabContentInDest : function(){ for(var tab=0; tab<this.tabs.length; tab++){ if($(this.destElementId) && !this.tabs[tab].contentMoved){ var tabContentElement = $(this.getTabContentElementId(this.tabs[tab])); if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){ $(this.destElementId).appendChild(tabContentElement); tabContentElement.container = this; tabContentElement.statusBar = this.tabs[tab]; tabContentElement.tabObject = this.tabs[tab]; this.tabs[tab].container = this; this.tabs[tab].show = function(){ this.container.showTabContent(this); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]}); } } } } if (this.displayFirst) { this.showTabContent($(this.displayFirst)); this.displayFirst = null; } }, getTabContentElementId : function(tab){ if(tab){ return tab.id+'_content'; } return false; }, tabMouseClick : function(event) { var tab = Event.findElement(event, 'a'); // go directly to specified url or switch tab if ((tab.href.indexOf('#') != tab.href.length-1) && !(Element.hasClassName(tab, 'ajax')) ) { location.href = tab.href; } else { this.showTabContent(tab); } Event.stop(event); }, hideAllTabsContent : function(){ for(var tab in this.tabs){ this.hideTabContent(this.tabs[tab]); } }, // show tab, ready or not showTabContentImmediately : function(tab) { this.hideAllTabsContent(); var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement) { Element.show(tabContentElement); Element.addClassName(tab, 'active'); // load shadow tabs, if any if (tab.shadowTabs && tab.shadowTabs.length) { for (var k in tab.shadowTabs) { this.loadShadowTab($(tab.shadowTabs[k])); } } if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } this.activeTab = tab; } if (varienGlobalEvents) { varienGlobalEvents.fireEvent('showTab', {tab:tab}); } }, // the lazy show tab method showTabContent : function(tab) { var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement) { if (this.activeTab != tab) { if (varienGlobalEvents) { if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) { return; }; } } // wait for ajax request, if defined var isAjax = Element.hasClassName(tab, 'ajax'); var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1; var isNotLoaded = Element.hasClassName(tab, 'notloaded'); if ( isAjax && (isEmpty || isNotLoaded) ) { new Ajax.Request(tab.href, { parameters: {form_key: FORM_KEY}, evalScripts: true, onSuccess: function(transport) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON() if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } } else { $(tabContentElement.id).update(transport.responseText); this.showTabContentImmediately(tab) } } catch (e) { $(tabContentElement.id).update(transport.responseText); this.showTabContentImmediately(tab) } }.bind(this) }); } else { this.showTabContentImmediately(tab); } } }, loadShadowTab : function(tab) { var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) { new Ajax.Request(tab.href, { parameters: {form_key: FORM_KEY}, evalScripts: true, onSuccess: function(transport) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON() if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } } else { $(tabContentElement.id).update(transport.responseText); if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } } } catch (e) { $(tabContentElement.id).update(transport.responseText); if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } } }.bind(this) }); } }, hideTabContent : function(tab){ var tabContentElement = $(this.getTabContentElementId(tab)); if($(this.destElementId) && tabContentElement){ Element.hide(tabContentElement); Element.removeClassName(tab, 'active'); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('hideTab', {tab:tab}); } } }
tonio-44/tikflak
shop/js/mage/adminhtml/tabs.js
JavaScript
gpl-2.0
9,985
Template.reassign_modal.helpers({ fields: function() { var userOptions = null; var showOrg = true; var instance = WorkflowManager.getInstance(); var space = db.spaces.findOne(instance.space); var flow = db.flows.findOne({ '_id': instance.flow }); var curSpaceUser = db.space_users.findOne({ space: instance.space, 'user': Meteor.userId() }); var organizations = db.organizations.find({ _id: { $in: curSpaceUser.organizations } }).fetch(); if (space.admins.contains(Meteor.userId())) { } else if (WorkflowManager.canAdmin(flow, curSpaceUser, organizations)) { var currentStep = InstanceManager.getCurrentStep() userOptions = ApproveManager.getNextStepUsers(instance, currentStep._id).getProperty("id").join(",") showOrg = Session.get("next_step_users_showOrg") } else { userOptions = "0" showOrg = false } var multi = false; var c = InstanceManager.getCurrentStep(); if (c && c.step_type == "counterSign") { multi = true; } return new SimpleSchema({ reassign_users: { autoform: { type: "selectuser", userOptions: userOptions, showOrg: showOrg, multiple: multi }, optional: true, type: String, label: TAPi18n.__("instance_reassign_user") } }); }, values: function() { return {}; }, current_step_name: function() { var s = InstanceManager.getCurrentStep(); var name; if (s) { name = s.name; } return name || ''; } }) Template.reassign_modal.events({ 'show.bs.modal #reassign_modal': function(event) { var reassign_users = $("input[name='reassign_users']")[0]; reassign_users.value = ""; reassign_users.dataset.values = ''; $(reassign_users).change(); }, 'click #reassign_help': function(event, template) { Steedos.openWindow(t("reassign_help")); }, 'click #reassign_modal_ok': function(event, template) { var val = AutoForm.getFieldValue("reassign_users", "reassign"); if (!val) { toastr.error(TAPi18n.__("instance_reassign_error_users_required")); return; } var reason = $("#reassign_modal_text").val(); var user_ids = val.split(","); InstanceManager.reassignIns(user_ids, reason); Modal.hide(template); }, })
steedos/apps
packages/steedos-workflow/client/views/instance/reassign_modal.js
JavaScript
gpl-2.0
2,218
/* Initialize */ var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; jQuery(document).ready(function ($) { // Bootstrap Init $("[rel=tooltip]").tooltip(); $('[data-toggle=tooltip]').tooltip(); $("[rel=popover]").popover(); $('#authorTab a').click(function (e) {e.preventDefault(); $(this).tab('show'); }); $('.sc_tabs a').click(function (e) {e.preventDefault(); $(this).tab('show'); }); $(".videofit").fitVids(); $(".embed-youtube").fitVids(); $('.kad-select').customSelect(); $('.woocommerce-ordering select').customSelect(); $('.collapse-next').click(function (e) { //e.preventDefault(); var $target = $(this).siblings('.sf-dropdown-menu'); if($target.hasClass('in') ) { $target.collapse('toggle'); $(this).removeClass('toggle-active'); } else { $target.collapse('toggle'); $(this).addClass('toggle-active'); } }); // Lightbox function kt_check_images( index, element ) { return /(png|jpg|jpeg|gif|tiff|bmp)$/.test( $( element ).attr( 'href' ).toLowerCase().split( '?' )[0].split( '#' )[0] ); } function kt_find_images() { $( 'a[href]' ).filter( kt_check_images ).attr( 'data-rel', 'lightbox' ); } kt_find_images(); $.extend(true, $.magnificPopup.defaults, { tClose: '', tLoading: light_load, // Text that is displayed during loading. Can contain %curr% and %total% keys gallery: { tPrev: '', // Alt text on left arrow tNext: '', // Alt text on right arrow tCounter: light_of // Markup for "1 of 7" counter }, image: { tError: light_error, // Error message when image could not be loaded titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); $("a[rel^='lightbox']").magnificPopup({type:'image'}); $("a[data-rel^='lightbox']").magnificPopup({type:'image'}); $('.kad-light-gallery').each(function(){ $(this).find('a[rel^="lightbox"]').magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: 'title' } }); }); $('.kad-light-gallery').each(function(){ $(this).find("a[data-rel^='lightbox']").magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: 'title' } }); }); $('.kad-light-wp-gallery').each(function(){ $(this).find('a[rel^="lightbox"]').magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); }); $('.kad-light-wp-gallery').each(function(){ $(this).find("a[data-rel^='lightbox']").magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); }); //Superfish Menu $('ul.sf-menu').superfish({ delay: 200, // one second delay on mouseout animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation speed: 'fast' // faster animation speed }); function kad_fullwidth_panel() { var margins = $(window).width() - $('#content').width(); $('.panel-row-style-wide-feature').each(function(){ $(this).css({'padding-left': margins/2 + 'px'}); $(this).css({'padding-right': margins/2 + 'px'}); $(this).css({'margin-left': '-' + margins/2 + 'px'}); $(this).css({'margin-right': '-' + margins/2 + 'px'}); $(this).css({'visibility': 'visible'}); }); } kad_fullwidth_panel(); $(window).on("debouncedresize", function( event ) {kad_fullwidth_panel();}); //init Flexslider $('.kt-flexslider').each(function(){ var flex_speed = $(this).data('flex-speed'), flex_animation = $(this).data('flex-animation'), flex_animation_speed = $(this).data('flex-anim-speed'), flex_auto = $(this).data('flex-auto'); $(this).flexslider({ animation:flex_animation, animationSpeed: flex_animation_speed, slideshow: flex_auto, slideshowSpeed: flex_speed, start: function ( slider ) { slider.removeClass( 'loading' ); } }); }); //init masonry $('.init-masonry').each(function(){ var masonrycontainer = $(this), masonry_selector = $(this).data('masonry-selector'); masonrycontainer.imagesLoadedn( function(){ masonrycontainer.masonry({itemSelector: masonry_selector}); }); }); //init carousel jQuery('.initcaroufedsel').each(function(){ var container = jQuery(this); var wcontainerclass = container.data('carousel-container'), cspeed = container.data('carousel-speed'), ctransition = container.data('carousel-transition'), cauto = container.data('carousel-auto'), carouselid = container.data('carousel-id'), ss = container.data('carousel-ss'), xs = container.data('carousel-xs'), sm = container.data('carousel-sm'), md = container.data('carousel-md'); var wcontainer = jQuery(wcontainerclass); function getUnitWidth() {var width; if(jQuery(window).width() <= 540) { width = wcontainer.width() / ss; } else if(jQuery(window).width() <= 768) { width = wcontainer.width() / xs; } else if(jQuery(window).width() <= 990) { width = wcontainer.width() / sm; } else { width = wcontainer.width() / md; } return width; } function setWidths() { var unitWidth = getUnitWidth() -1; container.children().css({ width: unitWidth }); } setWidths(); function initCarousel() { container.carouFredSel({ scroll: {items:1, easing: "swing", duration: ctransition, pauseOnHover : true}, auto: {play: cauto, timeoutDuration: cspeed}, prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, pagination: false, swipe: true, items: {visible: null} }); } container.imagesLoadedn( function(){ initCarousel(); }); wcontainer.animate({'opacity' : 1}); jQuery(window).on("debouncedresize", function( event ) { container.trigger("destroy"); setWidths(); initCarousel(); }); }); //init carouselslider jQuery('.initcarouselslider').each(function(){ var container = jQuery(this); var wcontainerclass = container.data('carousel-container'), cspeed = container.data('carousel-speed'), ctransition = container.data('carousel-transition'), cauto = container.data('carousel-auto'), carouselid = container.data('carousel-id'), carheight = container.data('carousel-height'), align = 'center'; var wcontainer = jQuery(wcontainerclass); function setWidths() { var unitWidth = container.width(); container.children().css({ width: unitWidth }); if(jQuery(window).width() <= 768) { carheight = null; container.children().css({ height: 'auto' }); } } setWidths(); function initCarouselslider() { container.carouFredSel({ width: '100%', height: carheight, align: align, auto: {play: cauto, timeoutDuration: cspeed}, scroll: {items : 1,easing: 'quadratic'}, items: {visible: 1,width: 'variable'}, prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, swipe: {onMouse: false,onTouch: true}, }); } container.imagesLoadedn( function(){ initCarouselslider(); wcontainer.animate({'opacity' : 1}); wcontainer.css({ height: 'auto' }); wcontainer.parent().removeClass('loading'); }); jQuery(window).on("debouncedresize", function( event ) { container.trigger("destroy"); setWidths(); initCarouselslider(); }); }); }); if( isMobile.any() ) { jQuery(document).ready(function ($) { $('.caroufedselclass').tswipe({ excludedElements:"button, input, select, textarea, .noSwipe", tswipeLeft: function() { $('.caroufedselclass').trigger('next', 1); }, tswipeRight: function() { $('.caroufedselclass').trigger('prev', 1); }, tap: function(event, target) { window.open(jQuery(target).closest('.grid_item').find('a').attr('href'), '_self'); } }); }); }
BellarmineBTDesigns/mashariki
wp-content/themes/pinnacle/assets/js/kt_main.js
JavaScript
gpl-2.0
9,445
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add("lang/dial",function(e){e.Intl.add("dial","",{label:"My label",resetStr:"Reset",tooltipHandle:"Drag to set value"})},"3.9.0pr1");
rochestb/Adventurly
node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dial/lang/dial.js
JavaScript
gpl-3.0
227
'use strict'; /** * Types of events * @readonly * @enum {number} */ var EventTypes = { // Channel Events /** * A channel got connected * @type {EventType} */ CONNECT: "connect", /** * A channel got disconnected */ DISCONNECT: "disconnect", /** * A channel got reconnected */ RECONNECT: "reconnect", /** * A channel is attempting to reconnect */ RECONNECTATTEMPT: "reconnect_attempt", /** * chatMode */ CHATMODE: "chatMode", /** * A list of current users in a channel */ CHANNELUSERS: "channelUsers", /** * A server message */ SERVERMESSAGE: "srvMsg", /** * A user message */ USERMESSAGE: "userMsg", /** * A /me message */ MEMESSAGE: "meMsg", /** * A /me message */ WHISPER: "whisper", /** * A global message */ GLOBALMESSAGE: "globalMsg", /** * An instruction/request to clear chat history */ CLEARCHAT: "clearChat", /** * A request for built-in command help */ COMMANDHELP: "commandHelp", /** * Whether or not mod tools should be visible */ MODTOOLSVISIBLE: "modToolsVisible", /** * A list of current mods in a channel */ MODLIST: "modList", /** * The color of the bot's name in chat */ COLOR: "color", /** * The online state of a stream */ ONLINESTATE: "onlineState", /** * A list of users included in a raffle */ RAFFLEUSERS: "raffleUsers", /** * The winner of a raffle */ WONRAFFLE: "wonRaffle", /** * runPoll */ RUNPOLL: "runPoll", /** * showPoll */ SHOWPOLL: "showPoll", /** * pollVotes */ POLLVOTES: "pollVotes", /** * voteResponse */ VOTERESPONSE: "voteResponse", /** * finishPoll */ FINISHPOLL: "finishPoll", /** * gameMode */ GAMEMODE: "gameMode", /** * adultMode */ ADULTMODE: "adultMode", /** * commissionsAvailable */ COMMISSIONSAVAILABLE: "commissionsAvailable", /** * clearUser */ CLEARUSER: "clearUser", /** * removeMsg */ REMOVEMESSAGE: "removeMsg", /** * A PTVAdmin? warning that a channel has adult content but is not in adult mode. */ WARNADULT: "warnAdult", /** * A PTVAdmin? warning that a channel has gaming content but is not in gaming mode. */ WARNGAMING: "warnGaming", /** * A PTVAdmin? warning that a channel has movie content. */ WARNMOVIES: "warnMovies", /** * The multistream status of a channel */ MULTISTATUS: "multiStatus", /** * Emitted after replaying chat history */ ENDHISTORY: "endHistory", /** * A list of people being ignored */ IGNORES: "ignores", // Bot Events /** * The bot threw an exception */ EXCEPTION: "exception", /** * A bot command */ CHATCOMMAND: "chatCommand", /** * A console command */ CONSOLECOMMAND: "consoleCommand", /** * A command needs completing */ COMMANDCOMPLETION: "commandCompletion", /** * A plugin was loaded */ PLUGINLOADED: "pluginLoaded", /** * A plugin was started */ PLUGINSTARTED: "pluginStarted", /** * A plugin was loaded */ PLUGINUNLOADED: "pluginUnloaded", /** * A plugin was started */ PLUGINSTOPPED: "pluginStopped", /** * Used to query plugins if they want to add a cli option/flag */ CLIOPTIONS: "CLIOptions" }; module.exports = EventTypes;
Tschrock/FezBot
modules/eventtypes.js
JavaScript
gpl-3.0
3,753
var translations = { 'es': { 'One moment while we<br>log you in': 'Espera un momento mientras<br>iniciamos tu sesión', 'You are now connected to the network': 'Ahora estás conectado a la red', 'Account signups/purchases are disabled in preview mode': 'La inscripciones de cuenta/compras están desactivadas en el modo de vista previa.', 'Notice': 'Aviso', 'Day': 'Día', 'Days': 'Días', 'Hour': 'Hora', 'Hours': 'Horas', 'Minutes': 'Minutos', 'Continue': 'Continuar', 'Thank You for Trying TWC WiFi': 'Gracias por probar TWC WiFi', 'Please purchase a TWC Access Pass to continue using WiFi': 'Adquiere un Pase de acceso (Access Pass) de TWC para continuar usando la red WiFi', 'Your TWC Access Pass has expired. Please select a new Access Pass Now.': 'Tu Access Pass (Pase de acceso) de TWC ha vencido. Selecciona un nuevo Access Pass (Pase de acceso) ahora.', 'Your account information has been pre-populated into the form. If you wish to change any information, you may edit the form before completing the order.': 'El formulario ha sido llenado con la información de tu cuenta. Si deseas modificar algún dato, puedes editar el formulario antes de completar la solicitud.', 'Your Password': 'Tu contraseña', 'Proceed to Login': 'Proceder con el inicio de sesión', 'Payment portal is not available at this moment': '', 'Redirecting to Payment portal...': '', 'Could not log you into the network': 'No se pudo iniciar sesión en la red' } } function translate(text, language) { if (language == 'en') return text; if (!translations[language]) return text; if (!translations[language][text]) return text; return translations[language][text] || text; }
kbeflo/evilportals
archive/optimumwifi/assets/js/xlate.js
JavaScript
gpl-3.0
2,089
var assert = require('assert'), path = require('path'), exec = require('child_process').exec, tmp = require('../lib/tmp'); // make sure that we do not test spam the global tmp tmp.TMP_DIR = './tmp'; function _spawnTestWithError(testFile, params, cb) { _spawnTest(true, testFile, params, cb); } function _spawnTestWithoutError(testFile, params, cb) { _spawnTest(false, testFile, params, cb); } function _spawnTest(passError, testFile, params, cb) { var node_path = process.argv[0], command = [ node_path, path.join(__dirname, testFile) ].concat(params).join(' '); exec(command, function _execDone(err, stdout, stderr) { if (passError) { if (err) { return cb(err); } else if (stderr.length > 0) { return cb(stderr.toString()); } } return cb(null, stdout.toString()); }); } function _testStat(stat, mode) { assert.equal(stat.uid, process.getuid(), 'should have the same UID'); assert.equal(stat.gid, process.getgid(), 'should have the same GUID'); assert.equal(stat.mode, mode); } function _testPrefix(prefix) { return function _testPrefixGenerated(err, name) { assert.equal(path.basename(name).slice(0, prefix.length), prefix, 'should have the provided prefix'); }; } function _testPrefixSync(prefix) { return function _testPrefixGeneratedSync(result) { if (result instanceof Error) { throw result; } _testPrefix(prefix)(null, result.name, result.fd); }; } function _testPostfix(postfix) { return function _testPostfixGenerated(err, name) { assert.equal(name.slice(name.length - postfix.length, name.length), postfix, 'should have the provided postfix'); }; } function _testPostfixSync(postfix) { return function _testPostfixGeneratedSync(result) { if (result instanceof Error) { throw result; } _testPostfix(postfix)(null, result.name, result.fd); }; } function _testKeep(type, keep, cb) { _spawnTestWithError('keep.js', [ type, keep ], cb); } function _testKeepSync(type, keep, cb) { _spawnTestWithError('keep-sync.js', [ type, keep ], cb); } function _testGraceful(type, graceful, cb) { _spawnTestWithoutError('graceful.js', [ type, graceful ], cb); } function _testGracefulSync(type, graceful, cb) { _spawnTestWithoutError('graceful-sync.js', [ type, graceful ], cb); } function _assertName(err, name) { assert.isString(name); assert.isNotZero(name.length, 'an empty string is not a valid name'); } function _assertNameSync(result) { if (result instanceof Error) { throw result; } var name = typeof(result) == 'string' ? result : result.name; _assertName(null, name); } function _testName(expected){ return function _testNameGenerated(err, name) { assert.equal(expected, name, 'should have the provided name'); }; } function _testNameSync(expected){ return function _testNameGeneratedSync(result) { if (result instanceof Error) { throw result; } _testName(expected)(null, result.name, result.fd); }; } function _testUnsafeCleanup(unsafe, cb) { _spawnTestWithoutError('unsafe.js', [ 'dir', unsafe ], cb); } function _testIssue62(cb) { _spawnTestWithoutError('issue62.js', [], cb); } function _testUnsafeCleanupSync(unsafe, cb) { _spawnTestWithoutError('unsafe-sync.js', [ 'dir', unsafe ], cb); } function _testIssue62Sync(cb) { _spawnTestWithoutError('issue62-sync.js', [], cb); } module.exports.testStat = _testStat; module.exports.testPrefix = _testPrefix; module.exports.testPrefixSync = _testPrefixSync; module.exports.testPostfix = _testPostfix; module.exports.testPostfixSync = _testPostfixSync; module.exports.testKeep = _testKeep; module.exports.testKeepSync = _testKeepSync; module.exports.testGraceful = _testGraceful; module.exports.testGracefulSync = _testGracefulSync; module.exports.assertName = _assertName; module.exports.assertNameSync = _assertNameSync; module.exports.testName = _testName; module.exports.testNameSync = _testNameSync; module.exports.testUnsafeCleanup = _testUnsafeCleanup; module.exports.testIssue62 = _testIssue62; module.exports.testUnsafeCleanupSync = _testUnsafeCleanupSync; module.exports.testIssue62Sync = _testIssue62Sync;
klhdy/im-indepartment
packORGAN/client/sealtalk-desktop-ent-src/node_modules/tmp/test/base.js
JavaScript
gpl-3.0
4,348
var searchData= [ ['gestionnaire_2ehpp',['Gestionnaire.hpp',['../Gestionnaire_8hpp.html',1,'']]], ['gestionnairemutex',['GestionnaireMutex',['../classGestionnaireMutex.html',1,'GestionnaireMutex'],['../classGestionnaireMutex.html#a16e149bb5c836f1ea2e7d6758422aca9',1,'GestionnaireMutex::GestionnaireMutex()']]], ['gestionnairemutex_2ecpp',['GestionnaireMutex.cpp',['../GestionnaireMutex_8cpp.html',1,'']]], ['gestionnairemutex_2ehpp',['GestionnaireMutex.hpp',['../GestionnaireMutex_8hpp.html',1,'']]], ['gestionnairepartie',['GestionnairePartie',['../classGestionnairePartie.html',1,'GestionnairePartie'],['../classGestionnairePartie.html#a83bcbead120fcdae027d9a3a6a7af83c',1,'GestionnairePartie::GestionnairePartie()']]], ['gestionnairepartie_2ecpp',['GestionnairePartie.cpp',['../GestionnairePartie_8cpp.html',1,'']]], ['gestionnairepartie_2ehpp',['GestionnairePartie.hpp',['../GestionnairePartie_8hpp.html',1,'']]], ['gestionnairerequete_2ecpp',['GestionnaireRequete.cpp',['../GestionnaireRequete_8cpp.html',1,'']]], ['gestionnairerequete_2ehpp',['GestionnaireRequete.hpp',['../GestionnaireRequete_8hpp.html',1,'']]], ['gestionnairesalon',['GestionnaireSalon',['../classGestionnaireSalon.html',1,'GestionnaireSalon'],['../classGestionnaireSalon.html#ae606439b050c0065db4a833a15d52f8b',1,'GestionnaireSalon::GestionnaireSalon()']]], ['gestionnairesalon_2ecpp',['GestionnaireSalon.cpp',['../GestionnaireSalon_8cpp.html',1,'']]], ['gestionnairesalon_2ehpp',['GestionnaireSalon.hpp',['../GestionnaireSalon_8hpp.html',1,'']]], ['gestionnairesocket',['GestionnaireSocket',['../classGestionnaireSocket.html',1,'GestionnaireSocket'],['../classGestionnaireSocket.html#aea6b223b8d0af0ec2688940a887fe17b',1,'GestionnaireSocket::GestionnaireSocket()']]], ['gestionnairesocket_2ecpp',['GestionnaireSocket.cpp',['../GestionnaireSocket_8cpp.html',1,'']]], ['gestionnairesocket_2ehpp',['GestionnaireSocket.hpp',['../GestionnaireSocket_8hpp.html',1,'']]], ['getdata',['getData',['../classDataPartieEnTete.html#aae81e6ebc709a0d6462c9a49afac6e6f',1,'DataPartieEnTete']]], ['gethote',['getHote',['../classSalon.html#a488ec3d4aea47aae26f7e33040d6db46',1,'Salon']]], ['getintervalletemporisation',['getIntervalleTemporisation',['../classMachineEtat.html#a05ba8f109b96a4c3eee40cc82da296e3',1,'MachineEtat']]], ['getlisteetat',['getListeEtat',['../classMachineEtat.html#abac1333e441143ac59f360ed3d950374',1,'MachineEtat']]], ['getmutex',['getMutex',['../classGestionnaireMutex.html#a4cd9287c0fc861296ead18746dbed30b',1,'GestionnaireMutex']]], ['getniveaumemoiretampon',['getNiveauMemoireTampon',['../classMachineEtat.html#a557ea7c575b72b0f2558c6ab9a1f121f',1,'MachineEtat']]], ['getnomjoueur',['getNomJoueur',['../classJoueur.html#a76413c6f6291c98784e3cb864db1311b',1,'Joueur']]], ['getnumeroclient',['getNumeroClient',['../classSocketTcp.html#a330cde24a46b5b945300402cd8f2495f',1,'SocketTcp']]], ['getnumerojoueur',['getNumeroJoueur',['../classJoueur.html#a28138f8a7705e6deea7802118072d1fe',1,'Joueur']]], ['getnumerosalon',['getNumeroSalon',['../classSalon.html#ab52889c156173dacca77b4a0188f742f',1,'Salon']]], ['getparam',['getParam',['../classConfiguration.html#a3d4b63d76baaad5a598402d9d0b2295e',1,'Configuration']]], ['getsocket',['getSocket',['../classGestionnaireSocket.html#ae54adc24a32a0e5db1bafff3564ebf8d',1,'GestionnaireSocket']]], ['getsockettcp',['getSocketTcp',['../classJoueur.html#a5971cb1e7bf96db7144e92e0d95de5bb',1,'Joueur']]], ['gettaillelistesocket',['getTailleListeSocket',['../classGestionnaireSocket.html#a95ee63ccc58d90538664af94559f66b7',1,'GestionnaireSocket']]], ['getvaleurlisteetat',['getValeurListeEtat',['../classMachineEtat.html#a63e8ed788501c5a22db4db813bd15d5e',1,'MachineEtat']]] ];
Aredhele/FreakyMonsters
serveur/doc/html/search/all_5.js
JavaScript
gpl-3.0
3,760
function assign(taskID, assignedTo) { $('.assign').width(150); $('.assign').height(40); $('.assign').load(createLink('user', 'ajaxGetUser', 'taskID=' + taskID + '&assignedTo=' + assignedTo)); } function setComment() { $('#comment').toggle(); }
isleon/zentao
module/task/js/view.js
JavaScript
gpl-3.0
252
(function() { 'use strict'; angular .module('editor.database', []) .config(function($indexedDBProvider) { $indexedDBProvider .connection('otus-studio') .upgradeDatabase(1, function(event, db, tx) { var store = db.createObjectStore('survey_template', { keyPath: 'template_oid'}); store.createIndex('contributor_idx', 'contributor', { unique: false }); }); }); }());
ccem-dev/otus-studio
source/app/editor/database/editor-database-module.js
JavaScript
gpl-3.0
499
/* Image.js * * copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers. * * This program 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. * * This program 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, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ /** * */ qx.Class.define('cv.parser.widgets.Image', { type: "static", /* ****************************************************** STATICS ****************************************************** */ statics: { /** * Parses the widgets XML configuration and extracts the given information * to a simple key/value map. * * @param xml {Element} XML-Element * @param path {String} internal path of the widget * @param flavour {String} Flavour of the widget * @param pageType {String} Page type (2d, 3d, ...) */ parse: function (xml, path, flavour, pageType) { var data = cv.parser.WidgetParser.parseElement(this, xml, path, flavour, pageType, this.getAttributeToPropertyMappings()); cv.parser.WidgetParser.parseRefresh(xml, path); return data; }, getAttributeToPropertyMappings: function () { return { 'width' : { "default": "100%" }, 'height' : {}, 'src' : {}, 'widthfit' : { target: 'widthFit', transform: function(value) { return value === "true"; }} }; } }, defer: function(statics) { // register the parser cv.parser.WidgetParser.addHandler("image", statics); } });
joltcoke/CometVisu
source/class/cv/parser/widgets/Image.js
JavaScript
gpl-3.0
2,083
/* * Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog, * Circulation and User's Management. It's written in Perl, and uses Apache2 * Web-Server, MySQL database and Sphinx 2 indexing. * Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP * * This file is part of Meran. * * Meran 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. * * Meran 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 Meran. If not, see <http://www.gnu.org/licenses/>. */ define([],function(){ 'use strict' /** * Implements unique() using the browser's sort(). * * @param a * The array to sort and strip of duplicate values. * Warning: this array will be modified in-place. * @param compFn * A custom comparison function that accepts two values a and * b from the given array and returns -1, 0, 1 depending on * whether a < b, a == b, a > b respectively. * * If no compFn is provided, the algorithm will use the * browsers default sort behaviour and loose comparison to * detect duplicates. * @return * The given array. */ function sortUnique(a, compFn){ var i; if (compFn) { a.sort(compFn); for (i = 1; i < a.length; i++) { if (0 === compFn(a[i], a[i - 1])) { a.splice(i--, 1); } } } else { a.sort(); for (i = 1; i < a.length; i++) { // Use loosely typed comparsion if no compFn is given // to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6] if (a[i] == a[i - 1]) { a.splice(i--, 1); } } } return a; } /** * Shallow comparison of two arrays. * * @param a, b * The arrays to compare. * @param equalFn * A custom comparison function that accepts two values a and * b from the given arrays and returns true or false for * equal and not equal respectively. * * If no equalFn is provided, the algorithm will use the strict * equals operator. * @return * True if all items in a and b are equal, false if not. */ function equal(a, b, equalFn) { var i = 0, len = a.length; if (len !== b.length) { return false; } if (equalFn) { for (; i < len; i++) { if (!equalFn(a[i], b[i])) { return false; } } } else { for (; i < len; i++) { if (a[i] !== b[i]) { return false; } } } return true; } /** * ECMAScript map replacement * See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map * And http://es5.github.com/#x15.4.4.19 * It's not exactly according to standard, but it does exactly what one expects. */ function map(a, fn) { var i, len, result = []; for (i = 0, len = a.length; i < len; i++) { result.push(fn(a[i])); } return result; } function mapNative(a, fn) { // Call map directly on the object instead of going through // Array.prototype.map. This avoids the problem that we may get // passed an array-like object (NodeList) which may cause an // error if the implementation of Array.prototype.map can only // deal with arrays (Array.prototype.map may be native or // provided by a javscript framework). return a.map(fn); } return { sortUnique: sortUnique, equal: equal, map: Array.prototype.map ? mapNative : map }; });
Desarrollo-CeSPI/meran
includes/aloha/util/arrays.js
JavaScript
gpl-3.0
3,812
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * The main class of Armature, it plays armature animation, manages and updates bones' state. * @class * @extends ccs.Node * * @property {ccs.Bone} parentBone - The parent bone of the armature node * @property {ccs.ArmatureAnimation} animation - The animation * @property {ccs.ArmatureData} armatureData - The armature data * @property {String} name - The name of the armature * @property {cc.SpriteBatchNode} batchNode - The batch node of the armature * @property {Number} version - The version * @property {Object} body - The body of the armature * @property {ccs.ColliderFilter} colliderFilter - <@writeonly> The collider filter of the armature */ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ animation: null, armatureData: null, batchNode: null, _parentBone: null, _boneDic: null, _topBoneList: null, _armatureIndexDic: null, _offsetPoint: null, version: 0, _armatureTransformDirty: true, _body: null, _blendFunc: null, _className: "Armature", /** * Create a armature node. * Constructor of ccs.Armature * @param {String} name * @param {ccs.Bone} parentBone * @example * var armature = new ccs.Armature(); */ ctor: function (name, parentBone) { cc.Node.prototype.ctor.call(this); this._name = ""; this._topBoneList = []; this._armatureIndexDic = {}; this._offsetPoint = cc.p(0, 0); this._armatureTransformDirty = true; this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; name && ccs.Armature.prototype.init.call(this, name, parentBone); // Hack way to avoid RendererWebGL from skipping Armature this._texture = {}; }, /** * Initializes a CCArmature with the specified name and CCBone * @param {String} [name] * @param {ccs.Bone} [parentBone] * @return {Boolean} */ init: function (name, parentBone) { if (parentBone) this._parentBone = parentBone; this.removeAllChildren(); this.animation = new ccs.ArmatureAnimation(); this.animation.init(this); this._boneDic = {}; this._topBoneList.length = 0; //this._name = name || ""; var armatureDataManager = ccs.armatureDataManager; var animationData; if (name !== "") { //animationData animationData = armatureDataManager.getAnimationData(name); cc.assert(animationData, "AnimationData not exist!"); this.animation.setAnimationData(animationData); //armatureData var armatureData = armatureDataManager.getArmatureData(name); cc.assert(armatureData, "ArmatureData not exist!"); this.armatureData = armatureData; //boneDataDic var boneDataDic = armatureData.getBoneDataDic(); for (var key in boneDataDic) { var bone = this.createBone(String(key)); //! init bone's Tween to 1st movement's 1st frame do { var movData = animationData.getMovement(animationData.movementNames[0]); if (!movData) break; var _movBoneData = movData.getMovementBoneData(bone.getName()); if (!_movBoneData || _movBoneData.frameList.length <= 0) break; var frameData = _movBoneData.getFrameData(0); if (!frameData) break; bone.getTweenData().copy(frameData); bone.changeDisplayWithIndex(frameData.displayIndex, false); } while (0); } this.update(0); this.updateOffsetPoint(); } else { name = "new_armature"; this.armatureData = new ccs.ArmatureData(); this.armatureData.name = name; animationData = new ccs.AnimationData(); animationData.name = name; armatureDataManager.addArmatureData(name, this.armatureData); armatureDataManager.addAnimationData(name, animationData); this.animation.setAnimationData(animationData); } this._renderCmd.initShaderCache(); this.setCascadeOpacityEnabled(true); this.setCascadeColorEnabled(true); return true; }, visit: function (parent) { var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; // quick return if not visible if (!this._visible) { cmd._propagateFlagsDown(parentCmd); return; } cmd.visit(parentCmd); cmd._dirtyFlag = 0; }, addChild: function (child, localZOrder, tag) { if (child instanceof ccui.Widget) { cc.log("Armature doesn't support to add Widget as its child, it will be fix soon."); return; } cc.Node.prototype.addChild.call(this, child, localZOrder, tag); }, /** * create a bone with name * @param {String} boneName * @return {ccs.Bone} */ createBone: function (boneName) { var existedBone = this.getBone(boneName); if (existedBone) return existedBone; var boneData = this.armatureData.getBoneData(boneName); var parentName = boneData.parentName; var bone = null; if (parentName) { this.createBone(parentName); bone = new ccs.Bone(boneName); this.addBone(bone, parentName); } else { bone = new ccs.Bone(boneName); this.addBone(bone, ""); } bone.setBoneData(boneData); bone.getDisplayManager().changeDisplayWithIndex(-1, false); return bone; }, /** * Add a Bone to this Armature * @param {ccs.Bone} bone The Bone you want to add to Armature * @param {String} parentName The parent Bone's name you want to add to. If it's null, then set Armature to its parent */ addBone: function (bone, parentName) { cc.assert(bone, "Argument must be non-nil"); var locBoneDic = this._boneDic; if (bone.getName()) cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again"); if (parentName) { var boneParent = locBoneDic[parentName]; if (boneParent) boneParent.addChildBone(bone); else this._topBoneList.push(bone); } else this._topBoneList.push(bone); bone.setArmature(this); locBoneDic[bone.getName()] = bone; this.addChild(bone); }, /** * Remove a bone with the specified name. If recursion it will also remove child Bone recursively. * @param {ccs.Bone} bone The bone you want to remove * @param {Boolean} recursion Determine whether remove the bone's child recursion. */ removeBone: function (bone, recursion) { cc.assert(bone, "bone must be added to the bone dictionary!"); bone.setArmature(null); bone.removeFromParent(recursion); cc.arrayRemoveObject(this._topBoneList, bone); delete this._boneDic[bone.getName()]; this.removeChild(bone, true); }, /** * Gets a bone with the specified name * @param {String} name The bone's name you want to get * @return {ccs.Bone} */ getBone: function (name) { return this._boneDic[name]; }, /** * Change a bone's parent with the specified parent name. * @param {ccs.Bone} bone The bone you want to change parent * @param {String} parentName The new parent's name */ changeBoneParent: function (bone, parentName) { cc.assert(bone, "bone must be added to the bone dictionary!"); var parentBone = bone.getParentBone(); if (parentBone) { cc.arrayRemoveObject(parentBone.getChildren(), bone); bone.setParentBone(null); } if (parentName) { var boneParent = this._boneDic[parentName]; if (boneParent) { boneParent.addChildBone(bone); cc.arrayRemoveObject(this._topBoneList, bone); } else this._topBoneList.push(bone); } }, /** * Get CCArmature's bone dictionary * @return {Object} Armature's bone dictionary */ getBoneDic: function () { return this._boneDic; }, /** * Set contentSize and Calculate anchor point. */ updateOffsetPoint: function () { // Set contentsize and Calculate anchor point. var rect = this.getBoundingBox(); this.setContentSize(rect); var locOffsetPoint = this._offsetPoint; locOffsetPoint.x = -rect.x; locOffsetPoint.y = -rect.y; if (rect.width !== 0 && rect.height !== 0) this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height); }, getOffsetPoints: function () { return {x: this._offsetPoint.x, y: this._offsetPoint.y}; }, /** * Sets animation to this Armature * @param {ccs.ArmatureAnimation} animation */ setAnimation: function (animation) { this.animation = animation; }, /** * Gets the animation of this Armature. * @return {ccs.ArmatureAnimation} */ getAnimation: function () { return this.animation; }, /** * armatureTransformDirty getter * @returns {Boolean} */ getArmatureTransformDirty: function () { return this._armatureTransformDirty; }, /** * The update callback of ccs.Armature, it updates animation's state and updates bone's state. * @override * @param {Number} dt */ update: function (dt) { this.animation.update(dt); var locTopBoneList = this._topBoneList; for (var i = 0; i < locTopBoneList.length; i++) locTopBoneList[i].update(dt); this._armatureTransformDirty = false; }, /** * The callback when ccs.Armature enter stage. * @override */ onEnter: function () { cc.Node.prototype.onEnter.call(this); this.scheduleUpdate(); }, /** * The callback when ccs.Armature exit stage. * @override */ onExit: function () { cc.Node.prototype.onExit.call(this); this.unscheduleUpdate(); }, /** * This boundingBox will calculate all bones' boundingBox every time * @returns {cc.Rect} */ getBoundingBox: function () { var minX, minY, maxX, maxY = 0; var first = true; var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children; var len = locChildren.length; for (var i = 0; i < len; i++) { var bone = locChildren[i]; if (bone) { var r = bone.getDisplayManager().getBoundingBox(); if (r.x === 0 && r.y === 0 && r.width === 0 && r.height === 0) continue; if (first) { minX = r.x; minY = r.y; maxX = r.x + r.width; maxY = r.y + r.height; first = false; } else { minX = r.x < boundingBox.x ? r.x : boundingBox.x; minY = r.y < boundingBox.y ? r.y : boundingBox.y; maxX = r.x + r.width > boundingBox.x + boundingBox.width ? r.x + r.width : boundingBox.x + boundingBox.width; maxY = r.y + r.height > boundingBox.y + boundingBox.height ? r.y + r.height : boundingBox.y + boundingBox.height; } boundingBox.x = minX; boundingBox.y = minY; boundingBox.width = maxX - minX; boundingBox.height = maxY - minY; } } return cc.rectApplyAffineTransform(boundingBox, this.getNodeToParentTransform()); }, /** * when bone contain the point ,then return it. * @param {Number} x * @param {Number} y * @returns {ccs.Bone} */ getBoneAtPoint: function (x, y) { var locChildren = this._children; for (var i = locChildren.length - 1; i >= 0; i--) { var child = locChildren[i]; if (child instanceof ccs.Bone && child.getDisplayManager().containPoint(x, y)) return child; } return null; }, /** * Sets parent bone of this Armature * @param {ccs.Bone} parentBone */ setParentBone: function (parentBone) { this._parentBone = parentBone; var locBoneDic = this._boneDic; for (var key in locBoneDic) { locBoneDic[key].setArmature(this); } }, /** * Return parent bone of ccs.Armature. * @returns {ccs.Bone} */ getParentBone: function () { return this._parentBone; }, /** * draw contour */ drawContour: function () { cc._drawingUtil.setDrawColor(255, 255, 255, 255); cc._drawingUtil.setLineWidth(1); var locBoneDic = this._boneDic; for (var key in locBoneDic) { var bone = locBoneDic[key]; var detector = bone.getColliderDetector(); if (!detector) continue; var bodyList = detector.getColliderBodyList(); for (var i = 0; i < bodyList.length; i++) { var body = bodyList[i]; var vertexList = body.getCalculatedVertexList(); cc._drawingUtil.drawPoly(vertexList, vertexList.length, true); } } }, setBody: function (body) { if (this._body === body) return; this._body = body; this._body.data = this; var child, displayObject, locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { child = locChildren[i]; if (child instanceof ccs.Bone) { var displayList = child.getDisplayManager().getDecorativeDisplayList(); for (var j = 0; j < displayList.length; j++) { displayObject = displayList[j]; var detector = displayObject.getColliderDetector(); if (detector) detector.setBody(this._body); } } } }, getShapeList: function () { if (this._body) return this._body.shapeList; return null; }, getBody: function () { return this._body; }, /** * Sets the blendFunc to ccs.Armature * @param {cc.BlendFunc|Number} blendFunc * @param {Number} [dst] */ setBlendFunc: function (blendFunc, dst) { if (dst === undefined) { this._blendFunc.src = blendFunc.src; this._blendFunc.dst = blendFunc.dst; } else { this._blendFunc.src = blendFunc; this._blendFunc.dst = dst; } }, /** * Returns the blendFunc of ccs.Armature * @returns {cc.BlendFunc} */ getBlendFunc: function () { return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); }, /** * set collider filter * @param {ccs.ColliderFilter} filter */ setColliderFilter: function (filter) { var locBoneDic = this._boneDic; for (var key in locBoneDic) locBoneDic[key].setColliderFilter(filter); }, /** * Returns the armatureData of ccs.Armature * @return {ccs.ArmatureData} */ getArmatureData: function () { return this.armatureData; }, /** * Sets armatureData to this Armature * @param {ccs.ArmatureData} armatureData */ setArmatureData: function (armatureData) { this.armatureData = armatureData; }, getBatchNode: function () { return this.batchNode; }, setBatchNode: function (batchNode) { this.batchNode = batchNode; }, /** * version getter * @returns {Number} */ getVersion: function () { return this.version; }, /** * version setter * @param {Number} version */ setVersion: function (version) { this.version = version; }, _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new ccs.Armature.CanvasRenderCmd(this); else return new ccs.Armature.WebGLRenderCmd(this); } }); var _p = ccs.Armature.prototype; /** @expose */ _p.parentBone; cc.defineGetterSetter(_p, "parentBone", _p.getParentBone, _p.setParentBone); /** @expose */ _p.body; cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody); /** @expose */ _p.colliderFilter; cc.defineGetterSetter(_p, "colliderFilter", null, _p.setColliderFilter); _p = null; /** * Allocates an armature, and use the ArmatureData named name in ArmatureDataManager to initializes the armature. * @param {String} [name] Bone name * @param {ccs.Bone} [parentBone] the parent bone * @return {ccs.Armature} * @deprecated since v3.1, please use new construction instead */ ccs.Armature.create = function (name, parentBone) { return new ccs.Armature(name, parentBone); };
corumcorp/redsentir
redsentir/static/juego/frameworks/cocos2d-html5/extensions/cocostudio/armature/CCArmature.js
JavaScript
gpl-3.0
18,849
/*global define*/ /*global test*/ /*global equal*/ define(['models/config'], function (Model) { 'use strict'; module('Config model'); test('Can be created with default values', function() { var note = new Model(); equal(note.get('name'), '', 'For default config name is empty'); equal(note.get('value'), '', 'For default config value is empty'); }); test('Update attributes', function(){ var note = new Model(); note.set('name', 'new-config'); equal(note.get('name'), 'new-config'); equal(note.get('value'), '', 'For default config value is empty'); }); });
elopio/laverna
test/spec/Models/config.js
JavaScript
gpl-3.0
641
var searchData= [ ['operator_2a',['operator*',['../class_complex.html#a789de21d72aa21414c26e0dd0966313a',1,'Complex']]], ['operator_2b',['operator+',['../class_complex.html#a5a7bc077499ace978055b0e6b9072ee9',1,'Complex']]], ['operator_5e',['operator^',['../class_complex.html#a952d42791b6b729c16406e21f9615f9f',1,'Complex']]] ];
philippeganz/mandelbrot
docs/search/functions_6.js
JavaScript
gpl-3.0
335
Bitrix 17.0.9 Business Demo = f37a7cf627b2ec3aa4045ed4678789ad
gohdan/DFC
known_files/hashes/bitrix/modules/iblock/install/components/bitrix/iblock.vote/templates/stars/script.min.js
JavaScript
gpl-3.0
63
define( "dojo/cldr/nls/nb/gregorian", //begin v1.x content { "dateFormatItem-Ehm": "E h.mm a", "days-standAlone-short": [ "sø.", "ma.", "ti.", "on.", "to.", "fr.", "lø." ], "months-format-narrow": [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], "field-second-relative+0": "nå", "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-weekday": "Ukedag", "dateFormatItem-yQQQ": "QQQ y", "dateFormatItem-yMEd": "E d.MM.y", "field-wed-relative+0": "onsdag denne uken", "dateFormatItem-GyMMMEd": "E d. MMM y G", "dateFormatItem-MMMEd": "E d. MMM", "field-wed-relative+1": "onsdag neste uke", "eraNarrow": [ "f.Kr.", "fvt.", "e.Kr.", "vt" ], "dateFormatItem-yMM": "MM.y", "field-tue-relative+-1": "tirsdag sist uke", "days-format-short": [ "sø.", "ma.", "ti.", "on.", "to.", "fr.", "lø." ], "dateFormat-long": "d. MMMM y", "field-fri-relative+-1": "fredag sist uke", "field-wed-relative+-1": "onsdag sist uke", "months-format-wide": [ "januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember" ], "dateTimeFormat-medium": "{1}, {0}", "dayPeriods-format-wide-pm": "p.m.", "dateFormat-full": "EEEE d. MMMM y", "field-thu-relative+-1": "torsdag sist uke", "dateFormatItem-Md": "d.M.", "dayPeriods-format-abbr-am": "a.m.", "dateFormatItem-yMd": "d.M.y", "dateFormatItem-yM": "M.y", "field-era": "Tidsalder", "months-standAlone-wide": [ "januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember" ], "timeFormat-short": "HH.mm", "quarters-format-wide": [ "1. kvartal", "2. kvartal", "3. kvartal", "4. kvartal" ], "timeFormat-long": "HH.mm.ss z", "dateFormatItem-yMMM": "MMM y", "dateFormatItem-yQQQQ": "QQQQ y", "field-year": "År", "dateFormatItem-MMdd": "d.M.", "field-hour": "Time", "months-format-abbr": [ "jan.", "feb.", "mar.", "apr.", "mai", "jun.", "jul.", "aug.", "sep.", "okt.", "nov.", "des." ], "field-sat-relative+0": "lørdag denne uken", "field-sat-relative+1": "lørdag neste uke", "timeFormat-full": "HH.mm.ss zzzz", "field-day-relative+0": "i dag", "field-day-relative+1": "i morgen", "field-thu-relative+0": "torsdag denne uken", "dateFormatItem-GyMMMd": "d. MMM y G", "field-day-relative+2": "i overmorgen", "field-thu-relative+1": "torsdag neste uke", "dateFormatItem-H": "HH", "months-standAlone-abbr": [ "jan", "feb", "mar", "apr", "mai", "jun", "jul", "aug", "sep", "okt", "nov", "des" ], "quarters-format-abbr": [ "K1", "K2", "K3", "K4" ], "quarters-standAlone-wide": [ "1. kvartal", "2. kvartal", "3. kvartal", "4. kvartal" ], "dateFormatItem-Gy": "y G", "dateFormatItem-M": "L.", "days-standAlone-wide": [ "søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag" ], "timeFormat-medium": "HH.mm.ss", "field-sun-relative+0": "søndag denne uken", "dateFormatItem-Hm": "HH.mm", "quarters-standAlone-abbr": [ "K1", "K2", "K3", "K4" ], "field-sun-relative+1": "søndag neste uke", "eraAbbr": [ "f.Kr.", "e.Kr." ], "field-minute": "Minutt", "field-dayperiod": "AM/PM", "days-standAlone-abbr": [ "sø.", "ma.", "ti.", "on.", "to.", "fr.", "lø." ], "dateFormatItem-d": "d.", "dateFormatItem-ms": "mm.ss", "quarters-format-narrow": [ "1", "2", "3", "4" ], "field-day-relative+-1": "i går", "dateFormatItem-h": "h a", "dateTimeFormat-long": "{1} 'kl.' {0}", "dayPeriods-format-narrow-am": "a", "field-day-relative+-2": "i forgårs", "dateFormatItem-MMMd": "d. MMM", "dateFormatItem-MEd": "E d.M", "dateTimeFormat-full": "{1} {0}", "field-fri-relative+0": "fredag denne uken", "dateFormatItem-yMMMM": "MMMM y", "field-fri-relative+1": "fredag neste uke", "field-day": "Dag", "days-format-wide": [ "søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag" ], "field-zone": "Tidssone", "dateFormatItem-y": "y", "months-standAlone-narrow": [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], "field-year-relative+-1": "i fjor", "field-month-relative+-1": "forrige måned", "dateFormatItem-hm": "h.mm a", "dayPeriods-format-abbr-pm": "p.m.", "days-format-abbr": [ "søn.", "man.", "tir.", "ons.", "tor.", "fre.", "lør." ], "eraNames": [ "f.Kr.", "e.Kr." ], "dateFormatItem-yMMMd": "d. MMM y", "days-format-narrow": [ "S", "M", "T", "O", "T", "F", "L" ], "days-standAlone-narrow": [ "S", "M", "T", "O", "T", "F", "L" ], "dateFormatItem-MMM": "LLL", "field-month": "Måned", "field-tue-relative+0": "tirsdag denne uken", "field-tue-relative+1": "tirsdag neste uke", "dayPeriods-format-wide-am": "a.m.", "dateFormatItem-EHm": "E HH.mm", "field-mon-relative+0": "mandag denne uken", "field-mon-relative+1": "mandag neste uke", "dateFormat-short": "dd.MM.y", "dateFormatItem-EHms": "E HH.mm.ss", "dateFormatItem-Ehms": "E h.mm.ss a", "field-second": "Sekund", "field-sat-relative+-1": "lørdag sist uke", "dateFormatItem-yMMMEd": "E d. MMM y", "field-sun-relative+-1": "søndag sist uke", "field-month-relative+0": "denne måneden", "field-month-relative+1": "neste måned", "dateFormatItem-Ed": "E d.", "dateTimeFormats-appendItem-Timezone": "{0} {1}", "field-week": "Uke", "dateFormat-medium": "d. MMM y", "field-year-relative+0": "i år", "field-week-relative+-1": "forrige uke", "field-year-relative+1": "neste år", "dayPeriods-format-narrow-pm": "p", "dateTimeFormat-short": "{1}, {0}", "dateFormatItem-Hms": "HH.mm.ss", "dateFormatItem-hms": "h.mm.ss a", "dateFormatItem-GyMMM": "MMM y G", "field-mon-relative+-1": "mandag sist uke", "field-week-relative+0": "denne uken", "field-week-relative+1": "neste uke" } //end v1.x content );
AnthonyARM/javascript
rowing/dojo-release-1.13.0/dojo/cldr/nls/nb/gregorian.js.uncompressed.js
JavaScript
gpl-3.0
5,993
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['button-content'], audio: Ember.inject.service(), soundName: null, rate: 1, preloadSounds: function() { this.get('audio'); }.on('init'), actions: { play() { this.get('audio').play(this.get('soundName'), this.get('rate')); } } });
hugoruscitti/huayra-procesing
app/components/p5-play-button.js
JavaScript
gpl-3.0
347
import {createBrowserHistory} from 'history'; import stringUtil from '@shared/util/stringUtil'; import ConfigStore from '../stores/ConfigStore'; const history = createBrowserHistory({basename: stringUtil.withoutTrailingSlash(ConfigStore.getBaseURI())}); export default history;
stephdewit/flood
client/src/javascript/util/history.js
JavaScript
gpl-3.0
281
asm(1000){ var a = 1; };
soliton4/promiseLand-website
release/client/promiseland/playground/asmsyntax.js
JavaScript
gpl-3.0
27
/*! @license Firebase v4.3.1 Build: rev-b4fe95f Terms: https://firebase.google.com/terms/ */ "use strict"; //# sourceMappingURL=requestmaker.js.map
chidelmun/Zikki
node_modules/firebase/storage/implementation/requestmaker.js
JavaScript
gpl-3.0
149
var searchData= [ ['save_5fcomments',['save_comments',['../useful__functions_8php.html#af56aec073a82606e9a7dac498de28d96',1,'useful_functions.php']]], ['save_5fexperiment_5flist',['save_experiment_list',['../choose__experiments_8php.html#a5d24f39ae6c336d7828523216bce6fae',1,'choose_experiments.php']]], ['save_5fsessions',['save_sessions',['../useful__functions_8php.html#a38a4632f417ceaa2f1c09c3ed0494d5e',1,'useful_functions.php']]], ['save_5fsignup_5fto_5fdb',['save_signup_to_db',['../useful__functions_8php.html#a0dca9d754b1a0d7b5401c446878844c5',1,'useful_functions.php']]], ['save_5fuser_5fexpt_5fchoices',['save_user_expt_choices',['../useful__functions_8php.html#a461a04526110df604708381a9eac7da8',1,'useful_functions.php']]], ['signup_5fexists',['signup_exists',['../useful__functions_8php.html#a7cf6d3ac90a6fca8c3f595e68b6e62cc',1,'useful_functions.php']]] ];
mnd22/chaos-signup
html/search/functions_7.js
JavaScript
gpl-3.0
884
'use strict'; var async = require('async'); var nconf = require('nconf'); var querystring = require('querystring'); var meta = require('../meta'); var pagination = require('../pagination'); var user = require('../user'); var topics = require('../topics'); var plugins = require('../plugins'); var helpers = require('./helpers'); var unreadController = module.exports; unreadController.get = function (req, res, next) { var page = parseInt(req.query.page, 10) || 1; var results; var cid = req.query.cid; var filter = req.query.filter || ''; var settings; async.waterfall([ function (next) { plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next); }, function (data, _next) { if (!data.filters[filter]) { return next(); } async.parallel({ watchedCategories: function (next) { helpers.getWatchedCategories(req.uid, cid, next); }, settings: function (next) { user.getSettings(req.uid, next); }, }, _next); }, function (_results, next) { results = _results; settings = results.settings; var start = Math.max(0, (page - 1) * settings.topicsPerPage); var stop = start + settings.topicsPerPage - 1; var cutoff = req.session.unreadCutoff ? req.session.unreadCutoff : topics.unreadCutoff(); topics.getUnreadTopics({ cid: cid, uid: req.uid, start: start, stop: stop, filter: filter, cutoff: cutoff, }, next); }, function (data, next) { user.blocks.filter(req.uid, data.topics, function (err, filtered) { data.topics = filtered; next(err, data); }); }, function (data) { data.title = meta.config.homePageTitle || '[[pages:home]]'; data.pageCount = Math.max(1, Math.ceil(data.topicCount / settings.topicsPerPage)); data.pagination = pagination.create(page, data.pageCount, req.query); if (settings.usePagination && (page < 1 || page > data.pageCount)) { req.query.page = Math.max(1, Math.min(data.pageCount, page)); return helpers.redirect(res, '/unread?' + querystring.stringify(req.query)); } data.categories = results.watchedCategories.categories; data.allCategoriesUrl = 'unread' + helpers.buildQueryString('', filter, ''); data.selectedCategory = results.watchedCategories.selectedCategory; data.selectedCids = results.watchedCategories.selectedCids; if (req.originalUrl.startsWith(nconf.get('relative_path') + '/api/unread') || req.originalUrl.startsWith(nconf.get('relative_path') + '/unread')) { data.title = '[[pages:unread]]'; data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]); } data.filters = helpers.buildFilters('unread', filter, req.query); data.selectedFilter = data.filters.find(function (filter) { return filter && filter.selected; }); res.render('unread', data); }, ], next); }; unreadController.unreadTotal = function (req, res, next) { var filter = req.query.filter || ''; async.waterfall([ function (next) { plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next); }, function (data, _next) { if (!data.filters[filter]) { return next(); } topics.getTotalUnread(req.uid, filter, _next); }, function (data) { res.json(data); }, ], next); };
An-dz/NodeBB
src/controllers/unread.js
JavaScript
gpl-3.0
3,327
(function () { 'use strict'; angular.module('driver.tools.export', [ 'ui.bootstrap', 'ui.router', 'driver.customReports', 'driver.resources', 'angular-spinkit', ]); })();
WorldBank-Transport/DRIVER
web/app/scripts/tools/export/module.js
JavaScript
gpl-3.0
225
"use strict"; exports.__esModule = true; var vueClient_1 = require("../../bibliotheque/vueClient"); console.log("* Chargement du script"); /* Test - déclaration d'une variable externe - Possible cf. declare */ function centreNoeud() { return JSON.parse(vueClient_1.contenuBalise(document, 'centre')); } function voisinsNoeud() { var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins')); var r = []; var id; for (id in v) { r.push(v[id]); } return r; } function adresseServeur() { return vueClient_1.contenuBalise(document, 'adresseServeur'); } /* type CanalChat = CanalClient<FormatMessageTchat>; // A initialiser var canal: CanalChat; var noeud: Noeud<FormatSommetTchat>; function envoyerMessage(texte: string, destinataire: Identifiant) { let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte); console.log("- Envoi du message brut : " + msg.brut()); console.log("- Envoi du message net : " + msg.net()); canal.envoyerMessage(msg); initialiserEntree('message_' + destinataire, ""); } // A exécuter après chargement de la page function initialisation(): void { console.log("* Initialisation après chargement du DOM ...") noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat); canal = new CanalClient<FormatMessageTchat>(adresseServeur()); canal.enregistrerTraitementAReception((m: FormatMessageTchat) => { let msg = new MessageTchat(m); console.log("- Réception du message brut : " + msg.brut()); console.log("- Réception du message net : " + msg.net()); posterNL('logChats', msg.net()); }); console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur()); // Gestion des événements pour les éléments du document. //document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true); let id: Identifiant; let v = noeud.voisins(); for (id in v) { console.log("id : " +id); let idVal = id; gererEvenementElement("boutonEnvoi_" + idVal, "click", e => { console.log("id message_" + idVal); console.log("entree : " + recupererEntree("message_" + idVal)); envoyerMessage(recupererEntree("message_" + idVal), idVal); }); } <form id="envoi"> <input type="text" id="message_id1"> <input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}." onClick="envoyerMessage(this.form.message.value, "id1")"> </form> console.log("* ... et des gestionnaires d'événements sur des éléments du document."); } // Gestion des événements pour le document console.log("* Enregistrement de l'initialisation"); gererEvenementDocument('DOMContentLoaded', initialisation); <script type="text/javascript"> document.addEventListener('DOMContentLoaded', initialisation()); </script> */ //# sourceMappingURL=clientChat.js.map
hgrall/merite
src/communication/v0/typeScript/build/tchat/client/clientChat.js
JavaScript
gpl-3.0
3,134