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
import Instruction from './Instruction'; function arcTo(x1, y1, x2, y2, r) { return new Instruction('call', { name: 'arcTo', args: [x1, y1, x2, y2, r], count: 5, }); } export default arcTo;
jtenner/e2d
src/arcTo.js
JavaScript
mit
207
'use strict'; exports.fixShould = function fixShould(str) { var segs = str.split('var should = require(\'should\');'); return segs.join('require(\'should\');'); };
jlinglue/vertexSDK
www/node_modules/update/lib/tests.js
JavaScript
mit
169
//// config/database.js module.exports = { url: 'mongodb://gaurav:gaurav@dogen.mongohq.com:10056/cmpe275' };
gauravshiralkar/Freedoor
config/database.js
JavaScript
mit
114
/* jslint node: true */ /*! * rinco - include templates * Copyright(c) 2014 Allan Esquina * MIT Licensed */ 'use strict'; var rinco = require('../rinco'); var it = require('../interpreter'); var Markdown = require('markdown').markdown; var md = require('markdown-it')({ html: true, linkify: true, typographer: true }); var config = require('../constants'); // Parse templates files rinco.render.middleware.register(function rinco_template(next, content) { [{ start:'<r-include', end:'/>'}].map(function (tag) { function r(content) { var has = false; content = it.parse(content, tag, function (prc) { var filename = prc.trim(); var tpl = rinco.fs.file.read(rinco.fs.path.join(config.INCLUDE_DIR, filename)); has = true; if(tpl) { if (rinco.fs.path.extname(filename) === ".md") { tpl = md.render(tpl.toString()); } return tpl; } else { return "File: " + rinco.fs.path.join(config.INCLUDE_DIR, filename); } }); return has ? r(content) : content; } content = r(content.toString()); }); next(content); });
rincojs/rinco-staticgen
lib/middleware/rinco-parse-template.js
JavaScript
mit
1,318
BASE.require(["Object"], function () { BASE.namespace("LG.core.dataModel.core"); var _globalObject = this; LG.core.dataModel.core.Credential = (function (Super) { var Credential = function () { var self = this; if (self === _globalObject) { throw new Error("Credential constructor invoked with global context. Say new."); } Super.call(self); self["authenticationFactors"] = []; self["authentications"] = []; self["personId"] = null; self["person"] = null; self["startDate"] = null; self["endDate"] = null; self["id"] = null; return self; }; BASE.extend(Credential, Super); return Credential; }(Object)); });
jaredjbarnes/WoodlandCreatures
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/LG/core/dataModel/core/Credential.js
JavaScript
mit
886
var events = require('events'); var request = require('request'); var zlib = require('zlib'); var iconv = require('iconv-lite'); var async = require('async'); var imagesize = require('imagesize'); var moment = require('moment'); var _ = require('underscore'); var cache = require('./cache'); var htmlUtils = require('./html-utils'); if (!GLOBAL.CONFIG) { GLOBAL.CONFIG = require('../config'); } /** * @private * Do HTTP GET request and handle redirects * @param url Request uri (parsed object or string) * @param {Object} options * @param {Number} [options.maxRedirects] * @param {Boolean} [options.fullResponse] True if need load full page response. Default: false. * @param {Function} [callback] The completion callback function or events.EventEmitter object * @returns {events.EventEmitter} The emitter object which emit error or response event */ var getUrl = exports.getUrl = function(url, options) { var req = new events.EventEmitter(); var options = options || {}; // Store cookies between redirects and requests. var jar = options.jar; if (!jar) { jar = request.jar(); } process.nextTick(function() { try { var supportGzip = !process.version.match(/^v0\.8/); var r = request({ uri: url, method: 'GET', headers: { 'User-Agent': CONFIG.USER_AGENT, 'Connection': 'close', 'Accept-Encoding': supportGzip ? 'gzip' : '' }, maxRedirects: options.maxRedirects || 3, timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT, followRedirect: options.followRedirect, jar: jar }) .on('error', function(error) { req.emit('error', error); }) .on('response', function(res) { if (supportGzip && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) > -1) { var gunzip = zlib.createUnzip(); gunzip.request = res.request; gunzip.statusCode = res.statusCode; gunzip.headers = res.headers; if (!options.asBuffer) { gunzip.setEncoding("binary"); } req.emit('response', gunzip); res.pipe(gunzip); } else { if (!options.asBuffer) { res.setEncoding("binary"); } req.emit('response', res); } }); req.emit('request', r); } catch (ex) { console.error('Error on getUrl for', url, '.\n Error:' + ex); req.emit('error', ex); } }); return req; }; var getHead = function(url, options) { var req = new events.EventEmitter(); var options = options || {}; // Store cookies between redirects and requests. var jar = options.jar; if (!jar) { jar = request.jar(); } process.nextTick(function() { try { var r = request({ uri: url, method: 'HEAD', headers: { 'User-Agent': CONFIG.USER_AGENT, 'Connection': 'close' }, maxRedirects: options.maxRedirects || 3, timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT, followRedirect: options.followRedirect, jar: jar }) .on('error', function(error) { req.emit('error', error); }) .on('response', function(res) { req.emit('response', res); }); req.emit('request', r); } catch (ex) { console.error('Error on getHead for', url, '.\n Error:' + ex); req.emit('error', ex); } }); return req; }; exports.getCharset = function(string, doNotParse) { var charset; if (doNotParse) { charset = string.toUpperCase(); } else if (string) { var m = string && string.match(/charset\s*=\s*([\w_-]+)/i); charset = m && m[1].toUpperCase(); } return charset; }; exports.encodeText = function(charset, text) { try { var b = iconv.encode(text, "ISO8859-1"); return iconv.decode(b, charset || "UTF-8"); } catch(e) { return text; } }; /** * @public * Get image size and type. * @param {String} uri Image uri. * @param {Object} [options] Options. * @param {Boolean} [options.cache] False to disable cache. Default: true. * @param {Function} callback Completion callback function. The callback gets two arguments (error, result) where result has: * - result.format * - result.width * - result.height * * error == 404 if not found. * */ exports.getImageMetadata = function(uri, options, callback){ if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; cache.withCache("image-meta:" + uri, function(callback) { var loadImageHead, imageResponseStarted, totalTime, timeout, contentLength; var requestInstance = null; function finish(error, data) { if (timeout) { clearTimeout(timeout); timeout = null; } else { return; } // We don't need more data. Abort causes error. timeout === null here so error will be skipped. requestInstance && requestInstance.abort(); if (!error && !data) { error = 404; } data = data || {}; if (options.debug) { data._time = { imageResponseStarted: imageResponseStarted || totalTime(), loadImageHead: loadImageHead && loadImageHead() || 0, total: totalTime() }; } if (error && error.message) { error = error.message; } if ((typeof error === 'string' && error.indexOf('ENOTFOUND') > -1) || error === 500) { error = 404; } if (error) { data.error = error; } callback(null, data); } timeout = setTimeout(function() { finish("timeout"); }, options.timeout || CONFIG.RESPONSE_TIMEOUT); if (options.debug) { totalTime = createTimer(); } async.waterfall([ function(cb){ getUrl(uri, { timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT, maxRedirects: 5, asBuffer: true }) .on('request', function(req) { requestInstance = req; }) .on('response', function(res) { var content_type = res.headers['content-type']; if (content_type && content_type !== 'application/octet-stream' && content_type !== 'binary/octet-stream') { if (content_type.indexOf('image/') === -1) { cb('invalid content type: ' + res.headers['content-type']); } } else { if (!uri.match(/\.(jpg|png|gif)(\?.*)?$/i)) { cb('invalid content type: no content-type header and file extension'); } } if (res.statusCode == 200) { if (options.debug) { imageResponseStarted = totalTime(); } contentLength = parseInt(res.headers['content-length'] || '0', 10); imagesize(res, cb); } else { cb(res.statusCode); } }) .on('error', function(error) { cb(error); }); }, function(data, cb){ if (options.debug) { loadImageHead = createTimer(); } if (contentLength) { data.content_length = contentLength; } cb(null, data); } ], finish); }, {disableCache: options.disableCache}, callback); }; exports.getUriStatus = function(uri, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; cache.withCache("status:" + uri, function(cb) { var time, timeout; function finish(error, data) { if (timeout) { clearTimeout(timeout); timeout = null; } else { return; } data = data || {}; if (error) { data.error = error; } if (options.debug) { data._time = time(); } cb(null, data); } timeout = setTimeout(function() { finish("timeout"); }, options.timeout || CONFIG.RESPONSE_TIMEOUT); if (options.debug) { time = createTimer(); } getUriStatus(uri, options, finish); }, {disableCache: options.disableCache}, callback); }; exports.getContentType = function(uriForCache, uriOriginal, options, cb) { cache.withCache("content-type:" + uriForCache, function(cb) { var timeout, requestInstance, totalTime; function finish(error, content_type) { if (timeout) { clearTimeout(timeout); timeout = null; } else { return; } // We don't need more data. Abort causes error. timeout === null here so error will be skipped. requestInstance && requestInstance.abort(); var data = {}; if (options.debug) { data._time = totalTime(); } if (error) { data.error = error; } if (!error && !data) { data.error = 404; } data.type = content_type; cb(null, data); } timeout = setTimeout(function() { finish("timeout"); }, options.timeout || CONFIG.RESPONSE_TIMEOUT); if (options.debug) { totalTime = createTimer(); } getHead(uriOriginal, { timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT, maxRedirects: 5 }) .on('request', function(req) { requestInstance = req; }) .on('response', function(res) { var content_type = res.headers['content-type']; if (content_type) { content_type = content_type.split(';')[0]; } finish(null, content_type); }) .on('error', function(error) { finish(error); }); }, {disableCache: options.disableCache}, cb); }; var NOW = new Date().getTime(); exports.unifyDate = function(date) { if (typeof date === "number") { if (date === 0) { return null; } // Check if date in seconds, not miliseconds. if (NOW / date > 100) { date = date * 1000; } var parsedDate = moment(date); if (parsedDate.isValid()) { return parsedDate.toJSON(); } } // TODO: time in format 'Mon, 29 October 2012 18:15:00' parsed as local timezone anyway. var parsedDate = moment.utc(date); if (parsedDate && parsedDate.isValid()) { return parsedDate.toJSON(); } return date; }; var lowerCaseKeys = exports.lowerCaseKeys = function(obj) { for (var k in obj) { var lowerCaseKey = k.toLowerCase(); if (lowerCaseKey != k) { obj[lowerCaseKey] = obj[k]; delete obj[k]; k = lowerCaseKey; } if (typeof obj[k] == "object") { lowerCaseKeys(obj[k]); } } }; exports.sendLogToWhitelist = function(uri, meta, oembed, whitelistRecord) { if (!CONFIG.WHITELIST_LOG_URL) { return } if (whitelistRecord && !whitelistRecord.isDefault) { // Skip whitelisted urls. return; } var data = getWhitelistLogData(meta, oembed); if (data) { data.uri = uri; request({ uri: CONFIG.WHITELIST_LOG_URL, method: 'GET', qs: data }) .on('error', function(error) { console.error('Error logging url:', uri, error); }) .on('response', function(res) { if (res.statusCode !== 200) { console.error('Error logging url:', uri, res.statusCode); } }); } }; exports.filterLinks = function(data, options) { var links = data.links; for(var i = 0; i < links.length;) { var link = links[i]; // SSL. var isImage = link.type.indexOf('image') === 0; var isHTML5Video = link.type.indexOf('video/') === 0; if (options.filterNonSSL) { var sslProtocol = link.href && link.href.match(/^(https:)?\/\//i); var hasSSL = link.rel.indexOf('ssl') > -1; if (sslProtocol || hasSSL || isImage || isHTML5Video) { // Good: has ssl. } else { // Filter non ssl if required. link.error = true; } } // HTML5. if (options.filterNonHTML5) { var hasHTML5 = link.rel.indexOf('html5') > -1; var isReader = link.rel.indexOf('reader') > -1; if (hasHTML5 || isImage || isHTML5Video || isReader) { // Good: is HTML5. } else { // Filter non HTML5 if required. link.error = true; } } // Max-width. if (options.maxWidth) { var isImage = link.type.indexOf('image') === 0; // TODO: force make html5 video responsive? var isHTML5Video = link.type.indexOf('video/') === 0; var m = link.media; if (m && !isImage && !isHTML5Video) { if (m.width && m.width > options.maxWidth) { link.error = true; } else if (m['min-width'] && m['min-width'] > options.maxWidth) { link.error = true; } } } if (link.error) { links.splice(i, 1); } else { i++; } } }; function iterateLinks(links, func) { if (links instanceof Array) { return links.forEach(func); } else if (typeof links === 'object') { for(var id in links) { var items = links[id]; if (items instanceof Array) { items.forEach(func); } } } } exports.generateLinksHtml = function(data, options) { // Links may be grouped. var links = data.links; iterateLinks(links, function(link) { if (!link.html && !link.type.match(/^image/)) { // Force make mp4 video to be autoplay in autoplayMode. if (options.autoplayMode && link.type.indexOf('video/') === 0 && link.rel.indexOf('autoplay') === -1) { link.rel.push('autoplay'); } var html = htmlUtils.generateLinkElementHtml(link, { iframelyData: data }); if (html) { link.html = html; } } }); if (!data.html) { var links_list = []; iterateLinks(links, function(link) { links_list.push(link); }); var plain_data = _.extend({}, data, {links:links_list}); // Prevent override main html field. var mainLink = htmlUtils.findMainLink(plain_data, options); if (mainLink) { if (mainLink.html) { data.rel = mainLink.rel; data.html = mainLink.html; } } } }; //==================================================================================== // Private //==================================================================================== var getUriStatus = function(uri, options, cb) { var r = request({ uri: uri, method: 'GET', headers: { 'User-Agent': CONFIG.USER_AGENT }, maxRedirects: 5, timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT, jar: request.jar() //Enable cookies, uses new jar }) .on('error', cb) .on('response', function(res) { r.abort(); cb(null, { code: res.statusCode, content_type: res.headers['content-type'] }); }); }; var createTimer = exports.createTimer = function() { var timer = new Date().getTime(); return function() { return new Date().getTime() - timer; }; }; var SHOPIFY_OEMBED_URLS = ['shopify.com', '/collections/', '/products/']; function isYoutube(meta) { var video; if (meta.og && (video = meta.og.video)) { if (!(video instanceof Array)) { video = [video]; } for(var i = 0; i < video.length; i++) { var v = video[i]; var url = v.url || v; if (url.indexOf && url.indexOf('youtube') > -1) { return true; } if (v.secure_url && v.secure_url.indexOf && v.secure_url.indexOf('youtube') > -1) { return true; } } } return false; } function getWhitelistLogData(meta, oembed) { var r = {}; if (meta) { var isJetpack = meta.twitter && meta.twitter.card === 'jetpack'; var isWordpress = meta.twitter && meta.twitter.generator === 'wordpress'; var isShopify = false; if (meta.alternate) { var alternate = meta.alternate instanceof Array ? meta.alternate : [meta.alternate]; var oembedLink; for(var i = 0; !oembedLink && i < alternate.length; i++) { var a = alternate[i]; if (a.type && a.href && a.type.indexOf('oembed') > -1) { oembedLink = a; } } if (oembedLink) { for(var i = 0; !isShopify && i < SHOPIFY_OEMBED_URLS.length; i++) { if (oembedLink.href.indexOf(SHOPIFY_OEMBED_URLS[i]) > -1) { isShopify = true; } } } } r.twitter_photo = (meta.twitter && meta.twitter.card === 'photo') && (meta.og && meta.og.type !== "article") && !isJetpack && !isWordpress && (meta.twitter && meta.twitter.site !== 'tumblr') && ( (meta.twitter && !!meta.twitter.image) || (meta.og && !!meta.og.image) ); r.twitter_player = meta.twitter && !!meta.twitter.player; r.twitter_stream = meta.twitter && meta.twitter.player && !!meta.twitter.player.stream; r.og_video = (meta.og && !!meta.og.video) && !isYoutube(meta); r.video_src = !!meta.video_src; r.sm4_video = !!(meta.sm4 && meta.sm4.video && meta.sm4.video.embed) } if (oembed && oembed.type !== 'link') { r['oembed_' + oembed.type] = true; } var hasTrue = false; var result = {}; for(var k in r) { if (r[k]) { result[k] = r[k]; hasTrue = true; } } // TODO: embedURL: getEl('[itemprop="embedURL"]') return hasTrue && result; }
aayusharora/loklak_webclient
iframely/lib/utils.js
JavaScript
mit
20,561
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue */ import CSSProperty from './CSSProperty' import warning from 'fbjs/lib/warning' let isUnitlessNumber = CSSProperty.isUnitlessNumber let styleWarnings = {} /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 let isEmpty = value == null || typeof value === 'boolean' || value === '' if (isEmpty) { return '' } let isNonNumeric = isNaN(value) if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value // cast to string } if (typeof value === 'string') { if (process.env.NODE_ENV !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { let owner = component._currentElement._owner let ownerName = owner ? owner.getName() : null if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {} } let warned = false if (ownerName) { let warnings = styleWarnings[ownerName] warned = warnings[name] if (!warned) { warnings[name] = true } } if (!warned) { process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0 } } } value = value.trim() } return value + 'px' } export default dangerousStyleValue
threepointone/glamor
src/CSSPropertyOperations/dangerousStyleValue.js
JavaScript
mit
3,021
function CScrollingBg(oSprite){ var _iLastObjIndex; var _aTiles; var _oSpriteTile; this._init = function(oSprite){ _oSpriteTile = oSprite; _aTiles = new Array(); var iYPos = -oSprite.height; while( iYPos < CANVAS_HEIGHT){ var oTile = new createjs.Bitmap(oSprite); oTile.y=iYPos; iYPos += oSprite.height; _aTiles.push(oTile); s_oStage.addChild(oTile); } _iLastObjIndex = 0; }; this.update = function(iSpeed){ for(var i=0;i<_aTiles.length;i++){ if(_aTiles[i].y > CANVAS_HEIGHT){ _aTiles[i].y = _aTiles[_iLastObjIndex].y - (_oSpriteTile.height); _iLastObjIndex = i; } _aTiles[i].y += iSpeed; } }; this._init(oSprite); }
igorlimasan/igorlimasan.github.io
js/CScrollingBg.js
JavaScript
mit
901
// generate a hash from string var crypto = require('crypto'), text = 'hello bob', key = 'mysecret key' // create hahs var hash = crypto.createHmac('sha512', key) hash.update(text) var value = hash.digest('hex') // print result console.log(value);
gartenfeld/node-crypto-examples
sha-text.js
JavaScript
mit
254
module.exports = function ({ serializers, $lookup }) { serializers.inc.object = function () { return function (object, $step = 0) { let $_, $bite return function $serialize ($buffer, $start, $end) { switch ($step) { case 0: $step = 1 $bite = 7n $_ = object.value case 1: while ($bite != -1n) { if ($start == $end) { return { start: $start, serialize: $serialize } } $buffer[$start++] = Number($_ >> $bite * 8n & 0xffn) $bite-- } $step = 2 case 2: break } return { start: $start, serialize: null } } } } () }
bigeasy/packet
test/generated/integer/be/word/long.serializer.inc.js
JavaScript
mit
938
import applicationActions from '../../constants/application'; import productActions from '../../constants/products'; export default function fetchProductAndCheckIfFound(context, payload, done) { context.dispatch(productActions.PRODUCTS_ITEM); context.api.products.get(payload).then(function successFn(result) { context.dispatch(productActions.PRODUCTS_ITEM_SUCCESS, result); done && done(); }, function errorFn(err) { context.dispatch(productActions.PRODUCTS_ITEM_ERROR, err.result); context.dispatch(applicationActions.APPLICATION_ROUTE_ERROR, err.status); done && done(); }); }
ESTEBANMURUZABAL/my-ecommerce-template
src/actions/Products/fetchProductAndCheckIfFound.js
JavaScript
mit
637
(function() { 'use strict'; angular.module('ionic.ui.service.sideMenuDelegate', []) .factory('$ionicSideMenuDelegate', ['$rootScope', '$timeout', '$q', function($rootScope, $timeout, $q) { return { getSideMenuController: function($scope) { return $scope.sideMenuController; }, close: function($scope) { if($scope.sideMenuController) { $scope.sideMenuController.close(); } }, toggleLeft: function($scope) { if($scope.sideMenuController) { $scope.sideMenuController.toggleLeft(); } }, toggleRight: function($scope) { if($scope.sideMenuController) { $scope.sideMenuController.toggleRight(); } }, openLeft: function($scope) { if($scope.sideMenuController) { $scope.sideMenuController.openPercentage(100); } }, openRight: function($scope) { if($scope.sideMenuController) { $scope.sideMenuController.openPercentage(-100); } } }; }]); })();
1900/ionic
js/ext/angular/src/service/delegates/ionicSideMenuDelegate.js
JavaScript
mit
995
/* */ "format global"; jasmine.HtmlReporterHelpers = {}; jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { var el = document.createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(document.createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == "className") { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; }; jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { var results = child.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.skipped) { status = 'skipped'; } return status; }; jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { var parentDiv = this.dom.summary; var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; var parent = child[parentSuite]; if (parent) { if (typeof this.views.suites[parent.id] == 'undefined') { this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); } parentDiv = this.views.suites[parent.id].element; } parentDiv.appendChild(childElement); }; jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { for(var fn in jasmine.HtmlReporterHelpers) { ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; } }; jasmine.HtmlReporter = function(_doc) { var self = this; var doc = _doc || window.document; var reporterView; var dom = {}; // Jasmine Reporter Public Interface self.logRunningSpecs = false; self.reportRunnerStarting = function(runner) { var specs = runner.specs() || []; if (specs.length == 0) { return; } createReporterDom(runner.env.versionString()); doc.body.appendChild(dom.reporter); reporterView = new jasmine.HtmlReporter.ReporterView(dom); reporterView.addSpecs(specs, self.specFilter); }; self.reportRunnerResults = function(runner) { reporterView && reporterView.complete(); }; self.reportSuiteResults = function(suite) { reporterView.suiteComplete(suite); }; self.reportSpecStarting = function(spec) { if (self.logRunningSpecs) { self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; self.reportSpecResults = function(spec) { reporterView.specComplete(spec); }; self.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; self.specFilter = function(spec) { if (!focusedSpecName()) { return true; } return spec.getFullName().indexOf(focusedSpecName()) === 0; }; return self; function focusedSpecName() { var specName; (function memoizeFocusedSpec() { if (specName) { return; } var paramMap = []; var params = doc.location.search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } specName = paramMap.spec; })(); return specName; } function createReporterDom(version) { dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, dom.banner = self.createDom('div', { className: 'banner' }, self.createDom('span', { className: 'title' }, "Jasmine "), self.createDom('span', { className: 'version' }, version)), dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), dom.alert = self.createDom('div', {className: 'alert'}), dom.results = self.createDom('div', {className: 'results'}, dom.summary = self.createDom('div', { className: 'summary' }), dom.details = self.createDom('div', { id: 'details' })) ); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporter.ReporterView = function(dom) { this.startedAt = new Date(); this.runningSpecCount = 0; this.completeSpecCount = 0; this.passedCount = 0; this.failedCount = 0; this.skippedCount = 0; this.createResultsMenu = function() { this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), ' | ', this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); this.summaryMenuItem.onclick = function() { dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); }; this.detailsMenuItem.onclick = function() { showDetails(); }; }; this.addSpecs = function(specs, specFilter) { this.totalSpecCount = specs.length; this.views = { specs: {}, suites: {} }; for (var i = 0; i < specs.length; i++) { var spec = specs[i]; this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); if (specFilter(spec)) { this.runningSpecCount++; } } }; this.specComplete = function(spec) { this.completeSpecCount++; if (isUndefined(this.views.specs[spec.id])) { this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); } var specView = this.views.specs[spec.id]; switch (specView.status()) { case 'passed': this.passedCount++; break; case 'failed': this.failedCount++; break; case 'skipped': this.skippedCount++; break; } specView.refresh(); this.refresh(); }; this.suiteComplete = function(suite) { var suiteView = this.views.suites[suite.id]; if (isUndefined(suiteView)) { return; } suiteView.refresh(); }; this.refresh = function() { if (isUndefined(this.resultsMenu)) { this.createResultsMenu(); } // currently running UI if (isUndefined(this.runningAlert)) { this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"}); dom.alert.appendChild(this.runningAlert); } this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); // skipped specs UI if (isUndefined(this.skippedAlert)) { this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"}); } this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; if (this.skippedCount === 1 && isDefined(dom.alert)) { dom.alert.appendChild(this.skippedAlert); } // passing specs UI if (isUndefined(this.passedAlert)) { this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"}); } this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); // failing specs UI if (isUndefined(this.failedAlert)) { this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); } this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); if (this.failedCount === 1 && isDefined(dom.alert)) { dom.alert.appendChild(this.failedAlert); dom.alert.appendChild(this.resultsMenu); } // summary info this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; }; this.complete = function() { dom.alert.removeChild(this.runningAlert); this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; if (this.failedCount === 0) { dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); } else { showDetails(); } dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); }; return this; function showDetails() { if (dom.reporter.className.search(/showDetails/) === -1) { dom.reporter.className += " showDetails"; } } function isUndefined(obj) { return typeof obj === 'undefined'; } function isDefined(obj) { return !isUndefined(obj); } function specPluralizedFor(count) { var str = count + " spec"; if (count > 1) { str += "s" } return str; } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); jasmine.HtmlReporter.SpecView = function(spec, dom, views) { this.spec = spec; this.dom = dom; this.views = views; this.symbol = this.createDom('li', { className: 'pending' }); this.dom.symbolSummary.appendChild(this.symbol); this.summary = this.createDom('div', { className: 'specSummary' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.spec.getFullName()), title: this.spec.getFullName() }, this.spec.description) ); this.detail = this.createDom('div', { className: 'specDetail' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.spec.getFullName()), title: this.spec.getFullName() }, this.spec.getFullName()) ); }; jasmine.HtmlReporter.SpecView.prototype.status = function() { return this.getSpecStatus(this.spec); }; jasmine.HtmlReporter.SpecView.prototype.refresh = function() { this.symbol.className = this.status(); switch (this.status()) { case 'skipped': break; case 'passed': this.appendSummaryToSuiteDiv(); break; case 'failed': this.appendSummaryToSuiteDiv(); this.appendFailureDetail(); break; } }; jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { this.summary.className += ' ' + this.status(); this.appendToSummary(this.spec, this.summary); }; jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { this.detail.className += ' ' + this.status(); var resultItems = this.spec.results().getItems(); var messagesDiv = this.createDom('div', { className: 'messages' }); for (var i = 0; i < resultItems.length; i++) { var result = resultItems[i]; if (result.type == 'log') { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); } else if (result.type == 'expect' && result.passed && !result.passed()) { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); if (result.trace.stack) { messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); } } } if (messagesDiv.childNodes.length > 0) { this.detail.appendChild(messagesDiv); this.dom.details.appendChild(this.detail); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { this.suite = suite; this.dom = dom; this.views = views; this.element = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description) ); this.appendToSummary(this.suite, this.element); }; jasmine.HtmlReporter.SuiteView.prototype.status = function() { return this.getSpecStatus(this.suite); }; jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { this.element.className += " " + this.status(); }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); /* @deprecated Use jasmine.HtmlReporter instead */ jasmine.TrivialReporter = function(doc) { this.document = doc || document; this.suiteDivs = {}; this.logRunningSpecs = false; }; jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { var el = document.createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(document.createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == "className") { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; }; jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { var showPassed, showSkipped; this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, this.createDom('div', { className: 'banner' }, this.createDom('div', { className: 'logo' }, this.createDom('span', { className: 'title' }, "Jasmine"), this.createDom('span', { className: 'version' }, runner.env.versionString())), this.createDom('div', { className: 'options' }, "Show ", showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") ) ), this.runnerDiv = this.createDom('div', { className: 'runner running' }, this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), this.runnerMessageSpan = this.createDom('span', {}, "Running..."), this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) ); this.document.body.appendChild(this.outerDiv); var suites = runner.suites(); for (var i = 0; i < suites.length; i++) { var suite = suites[i]; var suiteDiv = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); this.suiteDivs[suite.id] = suiteDiv; var parentDiv = this.outerDiv; if (suite.parentSuite) { parentDiv = this.suiteDivs[suite.parentSuite.id]; } parentDiv.appendChild(suiteDiv); } this.startedAt = new Date(); var self = this; showPassed.onclick = function(evt) { if (showPassed.checked) { self.outerDiv.className += ' show-passed'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); } }; showSkipped.onclick = function(evt) { if (showSkipped.checked) { self.outerDiv.className += ' show-skipped'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); } }; }; jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { var results = runner.results(); var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; this.runnerDiv.setAttribute("class", className); //do it twice for IE this.runnerDiv.setAttribute("className", className); var specs = runner.specs(); var specCount = 0; for (var i = 0; i < specs.length; i++) { if (this.specFilter(specs[i])) { specCount++; } } var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); }; jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { var results = suite.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.totalCount === 0) { // todo: change this to check results.skipped status = 'skipped'; } this.suiteDivs[suite.id].className += " " + status; }; jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { if (this.logRunningSpecs) { this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { var results = spec.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.skipped) { status = 'skipped'; } var specDiv = this.createDom('div', { className: 'spec ' + status }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(spec.getFullName()), title: spec.getFullName() }, spec.description)); var resultItems = results.getItems(); var messagesDiv = this.createDom('div', { className: 'messages' }); for (var i = 0; i < resultItems.length; i++) { var result = resultItems[i]; if (result.type == 'log') { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); } else if (result.type == 'expect' && result.passed && !result.passed()) { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); if (result.trace.stack) { messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); } } } if (messagesDiv.childNodes.length > 0) { specDiv.appendChild(messagesDiv); } this.suiteDivs[spec.suite.id].appendChild(specDiv); }; jasmine.TrivialReporter.prototype.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; jasmine.TrivialReporter.prototype.getLocation = function() { return this.document.location; }; jasmine.TrivialReporter.prototype.specFilter = function(spec) { var paramMap = {}; var params = this.getLocation().search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } if (!paramMap.spec) { return true; } return spec.getFullName().indexOf(paramMap.spec) === 0; };
lindanXmu/lindanxmu.github.io
projects/bayarea/jspm_packages/github/knockout/knockout@3.4.1/spec/lib/jasmine-1.2.0/jasmine-html.js
JavaScript
mit
19,089
"use strict"; const Channel = require("./Channel"); const Collection = require("../util/Collection"); const Endpoints = require("../rest/Endpoints"); const Message = require("./Message"); const OPCodes = require("../Constants").GatewayOPCodes; const User = require("./User"); /** * Represents a private channel * @extends Channel * @prop {String} id The ID of the channel * @prop {String} mention A string that mentions the channel * @prop {Number} type The type of the channel * @prop {String} lastMessageID The ID of the last message in this channel * @prop {User} recipient The recipient in this private channel (private channels only) * @prop {Collection<Message>} messages Collection of Messages in this channel */ class PrivateChannel extends Channel { constructor(data, client) { super(data); this._client = client; this.lastMessageID = data.last_message_id; this.call = this.lastCall = null; if(this.type === 1 || this.type === undefined) { this.recipient = new User(data.recipients[0], client); } this.messages = new Collection(Message, client.options.messageLimit); } /** * Ring fellow group channel recipient(s) * @arg {String[]} recipients The IDs of the recipients to ring */ ring(recipients) { this._client.requestHandler.request("POST", Endpoints.CHANNEL_CALL_RING(this.id), true, { recipients }); } /** * Check if the channel has an existing call */ syncCall() { this._client.shards.values().next().value.sendWS(OPCodes.SYNC_CALL, { channel_id: this.id }); } /** * Leave the channel * @returns {Promise} */ leave() { return this._client.deleteChannel.call(this._client, this.id); } /** * Send typing status in a text channel * @returns {Promise} */ sendTyping() { return (this._client || this.guild.shard.client).sendChannelTyping.call((this._client || this.guild.shard.client), this.id); } /** * Get a previous message in a text channel * @arg {String} messageID The ID of the message * @returns {Promise<Message>} */ getMessage(messageID) { return (this._client || this.guild.shard.client).getMessage.call((this._client || this.guild.shard.client), this.id, messageID); } /** * Get a previous message in a text channel * @arg {Number} [limit=50] The max number of messages to get * @arg {String} [before] Get messages before this message ID * @arg {String} [after] Get messages after this message ID * @arg {String} [around] Get messages around this message ID (does not work with limit > 100) * @returns {Promise<Message[]>} */ getMessages(limit, before, after, around) { return (this._client || this.guild.shard.client).getMessages.call((this._client || this.guild.shard.client), this.id, limit, before, after, around); } /** * Get all the pins in a text channel * @returns {Promise<Message[]>} */ getPins() { return (this._client || this.guild.shard.client).getPins.call((this._client || this.guild.shard.client), this.id); } /** * Create a message in a text channel * Note: If you want to DM someone, the user ID is **not** the DM channel ID. use Client.getDMChannel() to get the DM channel ID for a user * @arg {String | Object} content A string or object. If an object is passed: * @arg {String} content.content A content string * @arg {Boolean} [content.tts] Set the message TTS flag * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure * @arg {Object} [file] A file object * @arg {String} file.file A buffer containing file data * @arg {String} file.name What to name the file * @returns {Promise<Message>} */ createMessage(content, file) { return (this._client || this.guild.shard.client).createMessage.call((this._client || this.guild.shard.client), this.id, content, file); } /** * Edit a message * @arg {String} messageID The ID of the message * @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed: * @arg {String} content.content A content string * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default) * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure * @returns {Promise<Message>} */ editMessage(messageID, content) { return (this._client || this.guild.shard.client).editMessage.call((this._client || this.guild.shard.client), this.id, messageID, content); } /** * Pin a message * @arg {String} messageID The ID of the message * @returns {Promise} */ pinMessage(messageID) { return (this._client || this.guild.shard.client).pinMessage.call((this._client || this.guild.shard.client), this.id, messageID); } /** * Unpin a message * @arg {String} messageID The ID of the message * @returns {Promise} */ unpinMessage(messageID) { return (this._client || this.guild.shard.client).unpinMessage.call((this._client || this.guild.shard.client), this.id, messageID); } /** * Get a list of users who reacted with a specific reaction * @arg {String} messageID The ID of the message * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji) * @arg {Number} [limit=100] The maximum number of users to get * @arg {String} [before] Get users before this user ID * @arg {String} [after] Get users after this user ID * @returns {Promise<User[]>} */ getMessageReaction(messageID, reaction, limit, before, after) { return (this._client || this.guild.shard.client).getMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, limit, before, after); } /** * Add a reaction to a message * @arg {String} messageID The ID of the message * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji) * @arg {String} [userID="@me"] The ID of the user to react as * @returns {Promise} */ addMessageReaction(messageID, reaction, userID) { return (this._client || this.guild.shard.client).addMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID); } /** * Remove a reaction from a message * @arg {String} messageID The ID of the message * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji) * @arg {String} [userID="@me"] The ID of the user to remove the reaction for * @returns {Promise} */ removeMessageReaction(messageID, reaction, userID) { return (this._client || this.guild.shard.client).removeMessageReaction.call((this._client || this.guild.shard.client), this.id, messageID, reaction, userID); } /** * Remove all reactions from a message * @arg {String} messageID The ID of the message * @returns {Promise} */ removeMessageReactions(messageID) { return (this._client || this.guild.shard.client).removeMessageReactions.call((this._client || this.guild.shard.client), this.id, messageID); } /** * Delete a message * @arg {String} messageID The ID of the message * @arg {String} [reason] The reason to be displayed in audit logs * @returns {Promise} */ deleteMessage(messageID, reason) { return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID, reason); } /** * Un-send a message. You're welcome Programmix * @arg {String} messageID The ID of the message * @returns {Promise} */ unsendMessage(messageID) { return (this._client || this.guild.shard.client).deleteMessage.call((this._client || this.guild.shard.client), this.id, messageID); } toJSON() { var base = super.toJSON(true); for(var prop of ["call", "lastCall", "lastMessageID", "messages", "recipient"]) { base[prop] = this[prop] && this[prop].toJSON ? this[prop].toJSON() : this[prop]; } return base; } } module.exports = PrivateChannel;
briantanner/eris
lib/structures/PrivateChannel.js
JavaScript
mit
8,770
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require select2 //= require has_accounts_engine/accounting //= require has_accounts_engine/accounting-jquery //= require has_accounts_engine/bootstrap.datepicker //= require_tree . // Application specific behaviour function addAlternateTableBehaviour() { $("table.list tr:odd").addClass("odd"); } // Dirty Form function makeEditForm(form) { var buttons = form.find("fieldset.buttons"); buttons.animate({opacity: 1}, 1000); } function addDirtyForm() { $(".form-view form").dirty_form() .dirty(function(event, data){ makeEditForm($(this)); }) $(".form-view").focusin(function() {makeEditForm($(this))}); } function addNestedFormBehaviour() { $('body').on('click', '.delete-nested-form-item', function(event) { var item = $(this).parents('.nested-form-item'); // Hide item item.hide(); // Mark as ready to delete item.find("input[name$='[_destroy]']").val("1"); item.addClass('delete'); // Drop input fields to prevent browser validation problems item.find(":input").not("[name$='[_destroy]'], [name$='[id]']").remove(); // TODO: should be callbacks updatePositions($(this).parents('.nested-form-container')); updateLineItems(); // Don't follow link event.preventDefault(); }); } // Currency helpers function currencyRound(value) { if (isNaN(value)) { return 0.0; }; rounded = Math.round(value * 20) / 20; return rounded.toFixed(2); } // Line Item calculation function updateLineItemPrice(lineItem) { var list = lineItem.parent(); var reference_code = lineItem.find(":input[name$='[reference_code]']").val(); var quantity = lineItem.find(":input[name$='[quantity]']").val(); if (quantity == '%' || quantity == 'saldo_of') { var included_items; if (reference_code == '') { included_items = lineItem.prevAll('.line_item'); } else { // Should match using ~= but acts_as_taggable_adds_colons between tags included_items = list.find(":input[name$='[code]'][value='" + reference_code + "']").parents('.line_item, .saldo_line_item'); if (included_items.length == 0) { // Should match using ~= but acts_as_taggable_adds_colons between tags included_items = list.find(":input[name$='[include_in_saldo_list]'][value*='" + reference_code + "']").parents('.line_item, .saldo_line_item'); } } var price_input = lineItem.find(":input[name$='[price]']"); price_input.val(calculateTotalAmount(included_items)); } } function updateAllLineItemPrices() { $('.line_item, .saldo_line_item').each(function() { updateLineItemPrice($(this)); }); } function calculateLineItemTotalAmount(lineItem) { var times_input = lineItem.find(":input[name$='[times]']"); var times = accounting.parse(times_input.val()); if (isNaN(times)) { times = 1; }; var quantity_input = lineItem.find(":input[name$='[quantity]']"); var price_input = lineItem.find(":input[name$='[price]']"); var price = accounting.parse(price_input.val()); // For 'saldo_of' items, we don't take accounts into account if (quantity_input.val() == "saldo_of") { return currencyRound(price); }; var direct_account_id = $('#line_items').data('direct-account-id'); var direct_account_factor = $('#line_items').data('direct-account-factor'); var factor = 0; if (lineItem.find(":input[name$='[credit_account_id]']").val() == direct_account_id) { factor = 1; }; if (lineItem.find(":input[name$='[debit_account_id]']").val() == direct_account_id) { factor = -1; }; if (quantity_input.val() == '%') { times = times / 100; }; return currencyRound(times * price * factor * direct_account_factor); } function updateLineItemTotalAmount(lineItem) { var total_amount_input = lineItem.find(".total_amount"); var total_amount = accounting.formatNumber(calculateLineItemTotalAmount(lineItem)); // Update Element total_amount_input.text(total_amount); } function calculateTotalAmount(lineItems) { var total_amount = 0; $(lineItems).each(function() { total_amount += accounting.parse($(this).find(".total_amount").text()); }); return currencyRound(total_amount); } function updateLineItems() { if ($('#line_items').length > 0) { $('.line_item, .saldo_line_item').each(function() { updateLineItemPrice($(this)); updateLineItemTotalAmount($(this)); }); }; } // Recalculate after every key stroke function handleLineItemChange(event) { // If character is <return> if(event.keyCode == 13) { // ...trigger form action $(event.currentTarget).submit(); } else if(event.keyCode == 32) { // ...trigger form action $(event.currentTarget).submit(); } else { updateLineItems(); } } function addCalculateTotalAmountBehaviour() { $("#line_items").find(":input[name$='[times]'], :input[name$='[quantity]'], :input[name$='[price]'], input[name$='[reference_code]']").on('keyup', handleLineItemChange); $("#line_items").bind("sortstop", handleLineItemChange); } // Sorting function updatePositions(collection) { var items = collection.find('.nested-form-item').not('.delete'); items.each(function(index, element) { $(this).find("input[id$='_position']").val(index + 1) }); } function initAccounting() { // accounting.js // Settings object that controls default parameters for library methods: accounting.settings = { currency: { symbol : "", // default currency symbol is '$' format: "%v", // controls output: %s = symbol, %v = value/number (can be object: see below) decimal : ".", // decimal point separator thousand: "'", // thousands separator precision : 2 // decimal places }, number: { precision : 2, // default precision on numbers is 0 thousand: "'", decimal : "." } } } // Initialize behaviours function initializeBehaviours() { // Init settings initAccounting(); // from cyt.js addComboboxBehaviour(); addAutofocusBehaviour(); addDatePickerBehaviour(); addLinkifyContainersBehaviour(); addIconTooltipBehaviour(); addModalBehaviour(); // application addAlternateTableBehaviour(); addNestedFormBehaviour(); addCalculateTotalAmountBehaviour(); updateLineItems(); // twitter bootstrap $(function () { $(".alert").alert(); $("*[rel=popover]").popover({ offset: 10 }); $('.small-tooltip').tooltip({ placement: 'right' }); }) // select2 $('.select2').select2({ allowClear: true }); $('.select2-tags').each(function(index, element) { var tags = $(element).data('tags') || ''; $(element).select2({ tags: tags, tokenSeparators: [","] }) }) } // Loads functions after DOM is ready $(document).ready(initializeBehaviours);
hauledev/has_account_engine
app/assets/javascripts/has_accounts_engine/application.js
JavaScript
mit
7,364
/* * function Component with Hooks: Modify ./index.js to apply this file */ import React, { useState, useLayoutEffect } from 'react'; import './App.css'; import logo from './logo.svg'; import tplsrc from './views/showing-click-times.liquid'; import Parser from 'html-react-parser'; import { engine } from './engine'; import { Context } from './Context'; import { ClickButton } from './ClickButton'; const fetchTpl = engine.getTemplate(tplsrc.toString()) export function App() { const [state, setState] = useState({ logo: logo, name: 'alice', clickCount: 0, html: '' }); useLayoutEffect(() => { fetchTpl .then(tpl => engine.render(tpl, state)) .then(html => setState({...state, html})) }, [state.clickCount]) return ( <div className="App"> {Parser(`${state.html}`)} <Context.Provider value={{ count: () => setState({...state, clickCount: state.clickCount + 1}) }} > <ClickButton/> </Context.Provider> </div> ); }
harttle/shopify-liquid
demo/reactjs/src/AppWithHooks.js
JavaScript
mit
1,028
function tree(tasks) { return Object.keys(tasks) .reduce(function(prev, task) { prev.nodes.push({ label: task, nodes: Object.keys(tasks[task]).map(function(x){ return x; }) }); return prev; }, { nodes: [], }); } module.exports = tree;
Nafta7/toska
lib/treefy.js
JavaScript
mit
272
if (!Buffer.concat) { Buffer.concat = function(buffers) { const buffersCount = buffers.length; let length = 0; for (let i = 0; i < buffersCount; i++) { const buffer = buffers[i]; length += buffer.length; } const result = new Buffer(length); let position = 0; for (let i = 0; i < buffersCount; i++) { const buffer = buffers[i]; buffer.copy(result, position, 0); position += buffer.length; } return result; }; } Buffer.prototype.toByteArray = function() { return Array.prototype.slice.call(this, 0); }; Buffer.prototype.equals = function(other) { if (this.length !== other.length) { return false; } for (let i = 0, len = this.length; i < len; i++) { if (this[i] !== other[i]) { return false; } } return true; };
Sage-ERP-X3/tedious
src/buffertools.js
JavaScript
mit
817
import React, { Component, } from 'react'; import { StyleSheet, View, } from 'react-native'; export default class Col extends Component { render() { return ( <View style={[styles.col, { flex: parseInt(this.props.span) }, this.props.style]}>{this.props.children}</View> ) } } const styles = StyleSheet.create({ col: { } });
typesettin/manuscript
app/components/Grid/col.js
JavaScript
mit
341
module.exports = function(){ return 'd0' }
rjrodger/use-plugin
test/dotdot/d0.js
JavaScript
mit
45
/** * Created by IvanIsrael on 06/04/2017. */ 'use strict'; const express = require('express'); const router = express.Router(); const user_controller = require("../controllers/users"); const methods = user_controller.methods; const controllers = user_controller.controllers; const passport = require('passport'); /* GET users listing. */ router.post('/', passport.authenticate('local', { successRedirect: '/', failureRedirect: '../users', failureFlash: true })); router.get('/logout', function(req, res, next){ try { req.logOut(); console.log("Cerrando sesion..."); res.redirect('../users'); } catch (e) { console.log(e); res.redirect('../users'); } }); module.exports = router;
shotokan/tequila
routes/auth.js
JavaScript
mit
754
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></g></React.Fragment> , 'Battery20Rounded');
Kagami/material-ui
packages/material-ui-icons/src/Battery20Rounded.js
JavaScript
mit
434
import { createRenderer } from 'fela' import cssifyStaticStyle from '../cssifyStaticStyle' describe('Cssifying static css declarations', () => { it('should return the minified style string', () => { expect(cssifyStaticStyle('.foo{color:red}')).toEqual('.foo{color:red}') expect( cssifyStaticStyle( ` .foo { color: red } ` ) ).toEqual('.foo {color: red}') }) it('should cssify the static style', () => { expect( cssifyStaticStyle( { color: 'red', WebkitTransitionDuration: 3 }, createRenderer() ) ).toEqual('color:red;-webkit-transition-duration:3') }) })
derek-duncan/fela
packages/fela-utils/src/__tests__/cssifyStaticStyle-test.js
JavaScript
mit
687
define([ 'aeris/util', 'aeris/errors/invalidargumenterror', 'aeris/maps/layers/aeristile' ], function(_, InvalidArgumentError, AerisTile) { /** * Representation of an Aeris Modis layer. * * @constructor * @class aeris.maps.layers.ModisTile * @extends aeris.maps.layers.AerisTile */ var ModisTile = function(opt_attrs, opt_options) { var options = _.extend({ period: 14 }, opt_options); var attrs = _.extend({ autoUpdateInterval: AerisTile.updateIntervals.MODIS, /** * Hash of available tileType codes by period * Used to dynamically create layer's tileType * * @attribute modisPeriodTileTypes * @type {Object.<number, string>} */ modisPeriodTileTypes: { /* eg 1: "modis_tileType_1day", 3: "modis_tileType_3day" */ } }, opt_attrs); // Set initial tileType _.extend(attrs, { tileType: attrs.modisPeriodTileTypes[options.period] }); AerisTile.call(this, attrs, opt_options); this.setModisPeriod(options.period); }; // Inherit from AerisTile _.inherits(ModisTile, AerisTile); /** * @param {number} period * @throws {aeris.errors.InvalidArgumentError} If the layer does not support the given MODIS period. */ ModisTile.prototype.setModisPeriod = function(period) { var validPeriods = _.keys(this.get('modisPeriodTileTypes')); period = parseInt(period); // Validate period if (!period || period < 1) { throw new InvalidArgumentError('Invalid MODIS period: period must be a positive integer'); } if (!(period in this.get('modisPeriodTileTypes'))) { throw new InvalidArgumentError('Invalid MODIS periods: available periods are: ' + validPeriods.join(',')); } // Set new tile type this.set('tileType', this.get('modisPeriodTileTypes')[period], { validate: true }); }; return ModisTile; });
MikeLockz/exit-now-mobile
www/lib/aerisjs/src/maps/layers/modistile.js
JavaScript
mit
1,941
goo.V.attachToGlobal(); V.describe('GridRenderSystem Test'); var gooRunner = V.initGoo(); var world = gooRunner.world; var gridRenderSystem = new GridRenderSystem(); gooRunner.renderSystems.push(gridRenderSystem); world.setSystem(gridRenderSystem); V.addLights(); document.body.addEventListener('keypress', function (e) { switch (e.keyCode) { case 49: break; case 50: break; case 51: break; } }); // camera 1 - spinning // var cameraEntity = V.addOrbitCamera(new Vector3(25, 0, 0)); // cameraEntity.cameraComponent.camera.setFrustumPerspective(null, null, 1, 10000); // add camera var camera = new Camera(undefined, undefined, 1, 10000); var cameraEntity = gooRunner.world.createEntity(camera, 'CameraEntity', [0, 10, 20]).lookAt([0, 0, 0]).addToWorld(); // camera control set up var scripts = new ScriptComponent(); var wasdScript = Scripts.create('WASD', { domElement: gooRunner.renderer.domElement, walkSpeed: 1000, crawlSpeed: 20 }); // WASD control script to move around scripts.scripts.push(wasdScript); // the FPCam script itself that locks the pointer and moves the camera var fpScript = Scripts.create('MouseLookScript', { domElement: gooRunner.renderer.domElement }); scripts.scripts.push(fpScript); cameraEntity.setComponent(scripts); world.createEntity('Box', new Box(20, 0.1, 20), new Material(ShaderLib.simpleLit)).addToWorld(); world.createEntity('Sphere', new Sphere(8, 8, 1), new Material(ShaderLib.simpleLit)).addToWorld(); V.process();
GooTechnologies/goojs
visual-test/goo/entities/systems/GridRenderSystem-vtest.js
JavaScript
mit
1,529
window.React = require('react'); var App = require('./components/App.react'); var css = require('./../css/app.css'); require('../img/social_media.png'); React.initializeTouchEvents(true); // Render the app component (js/components/App.react.js) React.render( <App />, document.getElementById('app') );
mxstbr/sharingbuttons.io
js/app.js
JavaScript
mit
306
var gulp = require('gulp'); var config = require('./config'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); gulp.task('cover', function() { return gulp.src(config.tests.unit, { read: false }) .pipe(mocha({ reporter: 'dot', ui: 'mocha-given', require: ['coffee-script/register', 'should', 'should-sinon'] })) .pipe(istanbul.writeReports()); });
tandrewnichols/file-manifest
gulp/cover.js
JavaScript
mit
408
//>>built define({invalidMessage:"Angivet v\u00e4rde \u00e4r inte giltigt.",missingMessage:"V\u00e4rdet kr\u00e4vs.",rangeMessage:"V\u00e4rdet ligger utanf\u00f6r intervallet."});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/dijit/form/nls/sv/validate.js
JavaScript
mit
179
import React from 'react' import styles from './Toast.scss' export default ({ className, message, show }) => ( <div className={[ styles.container, 'animated', 'fadeIn', ].concat(className).join(' ')} style={{ display: show ? 'block' : 'none' }} > {message} </div> )
marsoln/temptation
web/components/Toast.js
JavaScript
mit
308
"use strict"; var $protobuf = require("../.."); module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require("../../google/protobuf/descriptor.json")).lookup(".google.protobuf"); var Namespace = $protobuf.Namespace, Root = $protobuf.Root, Enum = $protobuf.Enum, Type = $protobuf.Type, Field = $protobuf.Field, MapField = $protobuf.MapField, OneOf = $protobuf.OneOf, Service = $protobuf.Service, Method = $protobuf.Method; // --- Root --- /** * Properties of a FileDescriptorSet message. * @interface IFileDescriptorSet * @property {IFileDescriptorProto[]} file Files */ /** * Properties of a FileDescriptorProto message. * @interface IFileDescriptorProto * @property {string} [name] File name * @property {string} [package] Package * @property {*} [dependency] Not supported * @property {*} [publicDependency] Not supported * @property {*} [weakDependency] Not supported * @property {IDescriptorProto[]} [messageType] Nested message types * @property {IEnumDescriptorProto[]} [enumType] Nested enums * @property {IServiceDescriptorProto[]} [service] Nested services * @property {IFieldDescriptorProto[]} [extension] Nested extension fields * @property {IFileOptions} [options] Options * @property {*} [sourceCodeInfo] Not supported * @property {string} [syntax="proto2"] Syntax */ /** * Properties of a FileOptions message. * @interface IFileOptions * @property {string} [javaPackage] * @property {string} [javaOuterClassname] * @property {boolean} [javaMultipleFiles] * @property {boolean} [javaGenerateEqualsAndHash] * @property {boolean} [javaStringCheckUtf8] * @property {IFileOptionsOptimizeMode} [optimizeFor=1] * @property {string} [goPackage] * @property {boolean} [ccGenericServices] * @property {boolean} [javaGenericServices] * @property {boolean} [pyGenericServices] * @property {boolean} [deprecated] * @property {boolean} [ccEnableArenas] * @property {string} [objcClassPrefix] * @property {string} [csharpNamespace] */ /** * Values of he FileOptions.OptimizeMode enum. * @typedef IFileOptionsOptimizeMode * @type {number} * @property {number} SPEED=1 * @property {number} CODE_SIZE=2 * @property {number} LITE_RUNTIME=3 */ /** * Creates a root from a descriptor set. * @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor * @returns {Root} Root instance */ Root.fromDescriptor = function fromDescriptor(descriptor) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.FileDescriptorSet.decode(descriptor); var root = new Root(); if (descriptor.file) { var fileDescriptor, filePackage; for (var j = 0, i; j < descriptor.file.length; ++j) { filePackage = root; if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) filePackage = root.define(fileDescriptor["package"]); if (fileDescriptor.name && fileDescriptor.name.length) root.files.push(filePackage.filename = fileDescriptor.name); if (fileDescriptor.messageType) for (i = 0; i < fileDescriptor.messageType.length; ++i) filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], fileDescriptor.syntax)); if (fileDescriptor.enumType) for (i = 0; i < fileDescriptor.enumType.length; ++i) filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i])); if (fileDescriptor.extension) for (i = 0; i < fileDescriptor.extension.length; ++i) filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i])); if (fileDescriptor.service) for (i = 0; i < fileDescriptor.service.length; ++i) filePackage.add(Service.fromDescriptor(fileDescriptor.service[i])); var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); if (opts) { var ks = Object.keys(opts); for (i = 0; i < ks.length; ++i) filePackage.setOption(ks[i], opts[ks[i]]); } } } return root; }; /** * Converts a root to a descriptor set. * @returns {Message<IFileDescriptorSet>} Descriptor * @param {string} [syntax="proto2"] Syntax */ Root.prototype.toDescriptor = function toDescriptor(syntax) { var set = exports.FileDescriptorSet.create(); Root_toDescriptorRecursive(this, set.file, syntax); return set; }; // Traverses a namespace and assembles the descriptor set function Root_toDescriptorRecursive(ns, files, syntax) { // Create a new file var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); if (syntax) file.syntax = syntax; if (!(ns instanceof Root)) file["package"] = ns.fullName.substring(1); // Add nested types for (var i = 0, nested; i < ns.nestedArray.length; ++i) if ((nested = ns._nestedArray[i]) instanceof Type) file.messageType.push(nested.toDescriptor(syntax)); else if (nested instanceof Enum) file.enumType.push(nested.toDescriptor()); else if (nested instanceof Field) file.extension.push(nested.toDescriptor(syntax)); else if (nested instanceof Service) file.service.push(nested.toDescriptor()); else if (nested instanceof /* plain */ Namespace) Root_toDescriptorRecursive(nested, files, syntax); // requires new file // Keep package-level options file.options = toDescriptorOptions(ns.options, exports.FileOptions); // And keep the file only if there is at least one nested object if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) files.push(file); } // --- Type --- /** * Properties of a DescriptorProto message. * @interface IDescriptorProto * @property {string} [name] Message type name * @property {IFieldDescriptorProto[]} [field] Fields * @property {IFieldDescriptorProto[]} [extension] Extension fields * @property {IDescriptorProto[]} [nestedType] Nested message types * @property {IEnumDescriptorProto[]} [enumType] Nested enums * @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges * @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs * @property {IMessageOptions} [options] Not supported * @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges * @property {string[]} [reservedName] Reserved names */ /** * Properties of a MessageOptions message. * @interface IMessageOptions * @property {boolean} [mapEntry=false] Whether this message is a map entry */ /** * Properties of an ExtensionRange message. * @interface IDescriptorProtoExtensionRange * @property {number} [start] Start field id * @property {number} [end] End field id */ /** * Properties of a ReservedRange message. * @interface IDescriptorProtoReservedRange * @property {number} [start] Start field id * @property {number} [end] End field id */ var unnamedMessageIndex = 0; /** * Creates a type from a descriptor. * @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @param {string} [syntax="proto2"] Syntax * @returns {Type} Type instance */ Type.fromDescriptor = function fromDescriptor(descriptor, syntax) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.DescriptorProto.decode(descriptor); // Create the message type var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), i; /* Oneofs */ if (descriptor.oneofDecl) for (i = 0; i < descriptor.oneofDecl.length; ++i) type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); /* Fields */ if (descriptor.field) for (i = 0; i < descriptor.field.length; ++i) { var field = Field.fromDescriptor(descriptor.field[i], syntax); type.add(field); if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins type.oneofsArray[descriptor.field[i].oneofIndex].add(field); } /* Extension fields */ if (descriptor.extension) for (i = 0; i < descriptor.extension.length; ++i) type.add(Field.fromDescriptor(descriptor.extension[i], syntax)); /* Nested types */ if (descriptor.nestedType) for (i = 0; i < descriptor.nestedType.length; ++i) { type.add(Type.fromDescriptor(descriptor.nestedType[i], syntax)); if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) type.setOption("map_entry", true); } /* Nested enums */ if (descriptor.enumType) for (i = 0; i < descriptor.enumType.length; ++i) type.add(Enum.fromDescriptor(descriptor.enumType[i])); /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { type.extensions = []; for (i = 0; i < descriptor.extensionRange.length; ++i) type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]); } /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { type.reserved = []; /* Ranges */ if (descriptor.reservedRange) for (i = 0; i < descriptor.reservedRange.length; ++i) type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]); /* Names */ if (descriptor.reservedName) for (i = 0; i < descriptor.reservedName.length; ++i) type.reserved.push(descriptor.reservedName[i]); } return type; }; /** * Converts a type to a descriptor. * @returns {Message<IDescriptorProto>} Descriptor * @param {string} [syntax="proto2"] Syntax */ Type.prototype.toDescriptor = function toDescriptor(syntax) { var descriptor = exports.DescriptorProto.create({ name: this.name }), i; /* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) { var fieldDescriptor; descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(syntax)); if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType), valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : undefined; descriptor.nestedType.push(exports.DescriptorProto.create({ name: fieldDescriptor.typeName, field: [ exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) ], options: exports.MessageOptions.create({ mapEntry: true }) })); } } /* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i) descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); /* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) { /* Extension fields */ if (this._nestedArray[i] instanceof Field) descriptor.field.push(this._nestedArray[i].toDescriptor(syntax)); /* Types */ else if (this._nestedArray[i] instanceof Type) descriptor.nestedType.push(this._nestedArray[i].toDescriptor(syntax)); /* Enums */ else if (this._nestedArray[i] instanceof Enum) descriptor.enumType.push(this._nestedArray[i].toDescriptor()); // plain nested namespaces become packages instead in Root#toDescriptor } /* Extension ranges */ if (this.extensions) for (i = 0; i < this.extensions.length; ++i) descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); /* Reserved... */ if (this.reserved) for (i = 0; i < this.reserved.length; ++i) /* Names */ if (typeof this.reserved[i] === "string") descriptor.reservedName.push(this.reserved[i]); /* Ranges */ else descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); return descriptor; }; // --- Field --- /** * Properties of a FieldDescriptorProto message. * @interface IFieldDescriptorProto * @property {string} [name] Field name * @property {number} [number] Field id * @property {IFieldDescriptorProtoLabel} [label] Field rule * @property {IFieldDescriptorProtoType} [type] Field basic type * @property {string} [typeName] Field type name * @property {string} [extendee] Extended type name * @property {string} [defaultValue] Literal default value * @property {number} [oneofIndex] Oneof index if part of a oneof * @property {*} [jsonName] Not supported * @property {IFieldOptions} [options] Field options */ /** * Values of the FieldDescriptorProto.Label enum. * @typedef IFieldDescriptorProtoLabel * @type {number} * @property {number} LABEL_OPTIONAL=1 * @property {number} LABEL_REQUIRED=2 * @property {number} LABEL_REPEATED=3 */ /** * Values of the FieldDescriptorProto.Type enum. * @typedef IFieldDescriptorProtoType * @type {number} * @property {number} TYPE_DOUBLE=1 * @property {number} TYPE_FLOAT=2 * @property {number} TYPE_INT64=3 * @property {number} TYPE_UINT64=4 * @property {number} TYPE_INT32=5 * @property {number} TYPE_FIXED64=6 * @property {number} TYPE_FIXED32=7 * @property {number} TYPE_BOOL=8 * @property {number} TYPE_STRING=9 * @property {number} TYPE_GROUP=10 * @property {number} TYPE_MESSAGE=11 * @property {number} TYPE_BYTES=12 * @property {number} TYPE_UINT32=13 * @property {number} TYPE_ENUM=14 * @property {number} TYPE_SFIXED32=15 * @property {number} TYPE_SFIXED64=16 * @property {number} TYPE_SINT32=17 * @property {number} TYPE_SINT64=18 */ /** * Properties of a FieldOptions message. * @interface IFieldOptions * @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3) * @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js) */ /** * Values of the FieldOptions.JSType enum. * @typedef IFieldOptionsJSType * @type {number} * @property {number} JS_NORMAL=0 * @property {number} JS_STRING=1 * @property {number} JS_NUMBER=2 */ // copied here from parse.js var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; /** * Creates a field from a descriptor. * @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @param {string} [syntax="proto2"] Syntax * @returns {Field} Field instance */ Field.fromDescriptor = function fromDescriptor(descriptor, syntax) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.DescriptorProto.decode(descriptor); if (typeof descriptor.number !== "number") throw Error("missing field id"); // Rewire field type var fieldType; if (descriptor.typeName && descriptor.typeName.length) fieldType = descriptor.typeName; else fieldType = fromDescriptorType(descriptor.type); // Rewire field rule var fieldRule; switch (descriptor.label) { // 0 is reserved for errors case 1: fieldRule = undefined; break; case 2: fieldRule = "required"; break; case 3: fieldRule = "repeated"; break; default: throw Error("illegal label: " + descriptor.label); } var extendee = descriptor.extendee; if (descriptor.extendee !== undefined) { extendee = extendee.length ? extendee : undefined; } var field = new Field( descriptor.name.length ? descriptor.name : "field" + descriptor.number, descriptor.number, fieldType, fieldRule, extendee ); field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); if (descriptor.defaultValue && descriptor.defaultValue.length) { var defaultValue = descriptor.defaultValue; switch (defaultValue) { case "true": case "TRUE": defaultValue = true; break; case "false": case "FALSE": defaultValue = false; break; default: var match = numberRe.exec(defaultValue); if (match) defaultValue = parseInt(defaultValue); // eslint-disable-line radix break; } field.setOption("default", defaultValue); } if (packableDescriptorType(descriptor.type)) { if (syntax === "proto3") { // defaults to packed=true (internal preset is packed=true) if (descriptor.options && !descriptor.options.packed) field.setOption("packed", false); } else if (!(descriptor.options && descriptor.options.packed)) // defaults to packed=false field.setOption("packed", false); } return field; }; /** * Converts a field to a descriptor. * @returns {Message<IFieldDescriptorProto>} Descriptor * @param {string} [syntax="proto2"] Syntax */ Field.prototype.toDescriptor = function toDescriptor(syntax) { var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); if (this.map) { descriptor.type = 11; // message descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor) descriptor.label = 3; // repeated } else { // Rewire field type switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType)) { case 10: // group case 11: // type case 14: // enum descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; break; } // Rewire field rule switch (this.rule) { case "repeated": descriptor.label = 3; break; case "required": descriptor.label = 2; break; default: descriptor.label = 1; break; } } // Handle extension field descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; // Handle part of oneof if (this.partOf) if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) throw Error("missing oneof"); if (this.options) { descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); if (this.options["default"] != null) descriptor.defaultValue = String(this.options["default"]); } if (syntax === "proto3") { // defaults to packed=true if (!this.packed) (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; } else if (this.packed) // defaults to packed=false (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; return descriptor; }; // --- Enum --- /** * Properties of an EnumDescriptorProto message. * @interface IEnumDescriptorProto * @property {string} [name] Enum name * @property {IEnumValueDescriptorProto[]} [value] Enum values * @property {IEnumOptions} [options] Enum options */ /** * Properties of an EnumValueDescriptorProto message. * @interface IEnumValueDescriptorProto * @property {string} [name] Name * @property {number} [number] Value * @property {*} [options] Not supported */ /** * Properties of an EnumOptions message. * @interface IEnumOptions * @property {boolean} [allowAlias] Whether aliases are allowed * @property {boolean} [deprecated] */ var unnamedEnumIndex = 0; /** * Creates an enum from a descriptor. * @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @returns {Enum} Enum instance */ Enum.fromDescriptor = function fromDescriptor(descriptor) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.EnumDescriptorProto.decode(descriptor); // Construct values object var values = {}; if (descriptor.value) for (var i = 0; i < descriptor.value.length; ++i) { var name = descriptor.value[i].name, value = descriptor.value[i].number || 0; values[name && name.length ? name : "NAME" + value] = value; } return new Enum( descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, values, fromDescriptorOptions(descriptor.options, exports.EnumOptions) ); }; /** * Converts an enum to a descriptor. * @returns {Message<IEnumDescriptorProto>} Descriptor */ Enum.prototype.toDescriptor = function toDescriptor() { // Values var values = []; for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); return exports.EnumDescriptorProto.create({ name: this.name, value: values, options: toDescriptorOptions(this.options, exports.EnumOptions) }); }; // --- OneOf --- /** * Properties of a OneofDescriptorProto message. * @interface IOneofDescriptorProto * @property {string} [name] Oneof name * @property {*} [options] Not supported */ var unnamedOneofIndex = 0; /** * Creates a oneof from a descriptor. * @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @returns {OneOf} OneOf instance */ OneOf.fromDescriptor = function fromDescriptor(descriptor) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.OneofDescriptorProto.decode(descriptor); return new OneOf( // unnamedOneOfIndex is global, not per type, because we have no ref to a type here descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option ); }; /** * Converts a oneof to a descriptor. * @returns {Message<IOneofDescriptorProto>} Descriptor */ OneOf.prototype.toDescriptor = function toDescriptor() { return exports.OneofDescriptorProto.create({ name: this.name // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option }); }; // --- Service --- /** * Properties of a ServiceDescriptorProto message. * @interface IServiceDescriptorProto * @property {string} [name] Service name * @property {IMethodDescriptorProto[]} [method] Methods * @property {IServiceOptions} [options] Options */ /** * Properties of a ServiceOptions message. * @interface IServiceOptions * @property {boolean} [deprecated] */ var unnamedServiceIndex = 0; /** * Creates a service from a descriptor. * @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @returns {Service} Service instance */ Service.fromDescriptor = function fromDescriptor(descriptor) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.ServiceDescriptorProto.decode(descriptor); var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); if (descriptor.method) for (var i = 0; i < descriptor.method.length; ++i) service.add(Method.fromDescriptor(descriptor.method[i])); return service; }; /** * Converts a service to a descriptor. * @returns {Message<IServiceDescriptorProto>} Descriptor */ Service.prototype.toDescriptor = function toDescriptor() { // Methods var methods = []; for (var i = 0; i < this.methodsArray; ++i) methods.push(this._methodsArray[i].toDescriptor()); return exports.ServiceDescriptorProto.create({ name: this.name, methods: methods, options: toDescriptorOptions(this.options, exports.ServiceOptions) }); }; // --- Method --- /** * Properties of a MethodDescriptorProto message. * @interface IMethodDescriptorProto * @property {string} [name] Method name * @property {string} [inputType] Request type name * @property {string} [outputType] Response type name * @property {IMethodOptions} [options] Not supported * @property {boolean} [clientStreaming=false] Whether requests are streamed * @property {boolean} [serverStreaming=false] Whether responses are streamed */ /** * Properties of a MethodOptions message. * @interface IMethodOptions * @property {boolean} [deprecated] */ var unnamedMethodIndex = 0; /** * Creates a method from a descriptor. * @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor * @returns {Method} Reflected method instance */ Method.fromDescriptor = function fromDescriptor(descriptor) { // Decode the descriptor message if specified as a buffer: if (typeof descriptor.length === "number") descriptor = exports.MethodDescriptorProto.decode(descriptor); return new Method( // unnamedMethodIndex is global, not per service, because we have no ref to a service here descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, "rpc", descriptor.inputType, descriptor.outputType, Boolean(descriptor.clientStreaming), Boolean(descriptor.serverStreaming), fromDescriptorOptions(descriptor.options, exports.MethodOptions) ); }; /** * Converts a method to a descriptor. * @returns {Message<IMethodDescriptorProto>} Descriptor */ Method.prototype.toDescriptor = function toDescriptor() { return exports.MethodDescriptorProto.create({ name: this.name, inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, clientStreaming: this.requestStream, serverStreaming: this.responseStream, options: toDescriptorOptions(this.options, exports.MethodOptions) }); }; // --- utility --- // Converts a descriptor type to a protobuf.js basic type function fromDescriptorType(type) { switch (type) { // 0 is reserved for errors case 1: return "double"; case 2: return "float"; case 3: return "int64"; case 4: return "uint64"; case 5: return "int32"; case 6: return "fixed64"; case 7: return "fixed32"; case 8: return "bool"; case 9: return "string"; case 12: return "bytes"; case 13: return "uint32"; case 15: return "sfixed32"; case 16: return "sfixed64"; case 17: return "sint32"; case 18: return "sint64"; } throw Error("illegal type: " + type); } // Tests if a descriptor type is packable function packableDescriptorType(type) { switch (type) { case 1: // double case 2: // float case 3: // int64 case 4: // uint64 case 5: // int32 case 6: // fixed64 case 7: // fixed32 case 8: // bool case 13: // uint32 case 14: // enum (!) case 15: // sfixed32 case 16: // sfixed64 case 17: // sint32 case 18: // sint64 return true; } return false; } // Converts a protobuf.js basic type to a descriptor type function toDescriptorType(type, resolvedType) { switch (type) { // 0 is reserved for errors case "double": return 1; case "float": return 2; case "int64": return 3; case "uint64": return 4; case "int32": return 5; case "fixed64": return 6; case "fixed32": return 7; case "bool": return 8; case "string": return 9; case "bytes": return 12; case "uint32": return 13; case "sfixed32": return 15; case "sfixed64": return 16; case "sint32": return 17; case "sint64": return 18; } if (resolvedType instanceof Enum) return 14; if (resolvedType instanceof Type) return resolvedType.group ? 10 : 11; throw Error("illegal type: " + type); } // Converts descriptor options to an options object function fromDescriptorOptions(options, type) { if (!options) return undefined; var out = []; for (var i = 0, field, key, val; i < type.fieldsArray.length; ++i) if ((key = (field = type._fieldsArray[i]).name) !== "uninterpretedOption") if (options.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins val = options[key]; if (field.resolvedType instanceof Enum && typeof val === "number" && field.resolvedType.valuesById[val] !== undefined) val = field.resolvedType.valuesById[val]; out.push(underScore(key), val); } return out.length ? $protobuf.util.toObject(out) : undefined; } // Converts an options object to descriptor options function toDescriptorOptions(options, type) { if (!options) return undefined; var out = []; for (var i = 0, ks = Object.keys(options), key, val; i < ks.length; ++i) { val = options[key = ks[i]]; if (key === "default") continue; var field = type.fields[key]; if (!field && !(field = type.fields[key = $protobuf.util.camelCase(key)])) continue; out.push(key, val); } return out.length ? type.fromObject($protobuf.util.toObject(out)) : undefined; } // Calculates the shortest relative path from `from` to `to`. function shortname(from, to) { var fromPath = from.fullName.split("."), toPath = to.fullName.split("."), i = 0, j = 0, k = toPath.length - 1; if (!(from instanceof Root) && to instanceof Namespace) while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { var other = to.lookup(fromPath[i++], true); if (other !== null && other !== to) break; ++j; } else for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j); return toPath.slice(j).join("."); } // copied here from cli/targets/proto.js function underScore(str) { return str.substring(0,1) + str.substring(1) .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); }); } // --- exports --- /** * Reflected file descriptor set. * @name FileDescriptorSet * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected file descriptor proto. * @name FileDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected descriptor proto. * @name DescriptorProto * @type {Type} * @property {Type} ExtensionRange * @property {Type} ReservedRange * @const * @tstype $protobuf.Type & { * ExtensionRange: $protobuf.Type, * ReservedRange: $protobuf.Type * } */ /** * Reflected field descriptor proto. * @name FieldDescriptorProto * @type {Type} * @property {Enum} Label * @property {Enum} Type * @const * @tstype $protobuf.Type & { * Label: $protobuf.Enum, * Type: $protobuf.Enum * } */ /** * Reflected oneof descriptor proto. * @name OneofDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected enum descriptor proto. * @name EnumDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected service descriptor proto. * @name ServiceDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected enum value descriptor proto. * @name EnumValueDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected method descriptor proto. * @name MethodDescriptorProto * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected file options. * @name FileOptions * @type {Type} * @property {Enum} OptimizeMode * @const * @tstype $protobuf.Type & { * OptimizeMode: $protobuf.Enum * } */ /** * Reflected message options. * @name MessageOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected field options. * @name FieldOptions * @type {Type} * @property {Enum} CType * @property {Enum} JSType * @const * @tstype $protobuf.Type & { * CType: $protobuf.Enum, * JSType: $protobuf.Enum * } */ /** * Reflected oneof options. * @name OneofOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected enum options. * @name EnumOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected enum value options. * @name EnumValueOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected service options. * @name ServiceOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected method options. * @name MethodOptions * @type {Type} * @const * @tstype $protobuf.Type */ /** * Reflected uninterpretet option. * @name UninterpretedOption * @type {Type} * @property {Type} NamePart * @const * @tstype $protobuf.Type & { * NamePart: $protobuf.Type * } */ /** * Reflected source code info. * @name SourceCodeInfo * @type {Type} * @property {Type} Location * @const * @tstype $protobuf.Type & { * Location: $protobuf.Type * } */ /** * Reflected generated code info. * @name GeneratedCodeInfo * @type {Type} * @property {Type} Annotation * @const * @tstype $protobuf.Type & { * Annotation: $protobuf.Type * } */
AntonyThorpe/knockout-apollo
tests/node_modules/protobufjs/ext/descriptor/index.js
JavaScript
mit
35,922
var React = require('react'); var AltContainer = require('../libraries/alt/AltContainer'); var LocationStore = require('../stores/LocationStore'); var FavoritesStore = require('../stores/FavoritesStore'); var LocationActions = require('../actions/LocationActions'); var Favorites = React.createClass({ render() { return ( <ul> {this.props.locations.map((location, i) => { return ( <li key={i}>{location.name}</li> ); })} </ul> ); } }); var AllLocations = React.createClass({ addFave(ev) { var location = LocationStore.getLocation( Number(ev.target.getAttribute('data-id')) ); LocationActions.favoriteLocation(location); }, render() { if (this.props.errorMessage) { return ( <div>{this.props.errorMessage}</div> ); } if (LocationStore.isLoading()) { return ( <div> <img src="ajax-loader.gif" /> </div> ) } return ( <ul> {this.props.locations.map((location, i) => { var faveButton = ( <button onClick={this.addFave} data-id={location.id}> Favorite </button> ); return ( <li key={i}> {location.name} {location.has_favorite ? '<3' : faveButton} </li> ); })} </ul> ); } }); var Locations = React.createClass({ componentDidMount() { LocationStore.fetchLocations(); }, render() { return ( <div> <h1>Locations</h1> <AltContainer store={LocationStore}> <AllLocations /> </AltContainer> <h1>Favorites</h1> <AltContainer store={FavoritesStore}> <Favorites /> </AltContainer> </div> ); } }); module.exports = Locations;
vanHeemstraSystems/components
src/locations/locations.js
JavaScript
mit
1,842
var util = require('hexo-util'); var code = [ 'if tired && night:', ' sleep()' ].join('\n'); var content = [ '# Title', '``` python', code, '```', 'some content', '', '## Another title', '{% blockquote %}', 'quote content', '{% endblockquote %}', '', '{% quote Hello World %}', 'quote content', '{% endquote %}' ].join('\n'); exports.content = content; exports.expected = [ '<h1 id="Title"><a href="#Title" class="headerlink" title="Title"></a>Title</h1>', util.highlight(code, {lang: 'python'}), '\n<p>some content</p>\n', '<h2 id="Another-title"><a href="#Another-title" class="headerlink" title="Another title"></a>Another title</h2>', '<blockquote>', '<p>quote content</p>\n', '</blockquote>\n', '<blockquote><p>quote content</p>\n', '<footer><strong>Hello World</strong></footer></blockquote>' ].join('');
wangjordy/wangjordy.github.io
test/fixtures/post_render.js
JavaScript
mit
866
import { Class } from '../mixin/index'; export default function (UIkit) { UIkit.component('icon', UIkit.components.svg.extend({ mixins: [Class], name: 'icon', args: 'icon', props: ['icon'], defaults: {exclude: ['id', 'style', 'class', 'src']}, init() { this.$el.addClass('uk-icon'); } })); [ 'close', 'navbar-toggle-icon', 'overlay-icon', 'pagination-previous', 'pagination-next', 'slidenav', 'search-icon', 'totop' ].forEach(name => UIkit.component(name, UIkit.components.icon.extend({name}))); }
Al-nimr-Studio/pos-team
distribution/scripts/uikit/src/js/core/icon.js
JavaScript
mit
691
var rowIdSequence = 100; var rowClassRules = { "red-row": 'data.color == "Red"', "green-row": 'data.color == "Green"', "blue-row": 'data.color == "Blue"', }; var gridOptions = { defaultColDef: { width: 80, sortable: true, filter: true, resizable: true }, rowClassRules: rowClassRules, rowData: createRowData(), rowDragManaged: true, columnDefs: [ {cellRenderer: 'dragSourceCellRenderer'}, {field: "id"}, {field: "color"}, {field: "value1"}, {field: "value2"} ], components: { dragSourceCellRenderer: DragSourceRenderer, }, animateRows: true }; function createRowData() { var data = []; ['Red', 'Green', 'Blue', 'Red', 'Green', 'Blue', 'Red', 'Green', 'Blue'].forEach(function (color) { var newDataItem = { id: rowIdSequence++, color: color, value1: Math.floor(Math.random() * 100), value2: Math.floor(Math.random() * 100) }; data.push(newDataItem); }); return data; } function onDragOver(event) { var types = event.dataTransfer.types; var dragSupported = types.length; if (dragSupported) { event.dataTransfer.dropEffect = "move"; } event.preventDefault(); } function onDrop(event) { event.preventDefault(); var userAgent = window.navigator.userAgent; var isIE = userAgent.indexOf("Trident/") >= 0; var textData = event.dataTransfer.getData(isIE ? 'text' : 'text/plain'); var eJsonRow = document.createElement('div'); eJsonRow.classList.add('json-row'); eJsonRow.innerText = textData; var eJsonDisplay = document.querySelector('#eJsonDisplay'); eJsonDisplay.appendChild(eJsonRow); } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function () { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); });
ceolter/angular-grid
grid-packages/ag-grid-docs/documentation/src/pages/drag-and-drop/examples/custom-drag-comp/main.js
JavaScript
mit
1,992
hello[''] = true;
pgilad/esformatter-dot-notation
tests/fixtures/empty.js
JavaScript
mit
18
var get = Ember.get, set = Ember.set; var Post, post, Comment, comment, env; module("integration/serializer/json - JSONSerializer", { setup: function() { Post = DS.Model.extend({ title: DS.attr('string'), comments: DS.hasMany('comment', {inverse:null}) }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); env = setupStore({ post: Post, comment: Comment }); env.store.modelFor('post'); env.store.modelFor('comment'); }, teardown: function() { env.store.destroy(); } }); test("serializeAttribute", function() { post = env.store.createRecord("post", { title: "Rails is omakase"}); var json = {}; env.serializer.serializeAttribute(post, json, "title", {type: "string"}); deepEqual(json, { title: "Rails is omakase" }); }); test("serializeAttribute respects keyForAttribute", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ keyForAttribute: function(key) { return key.toUpperCase(); } })); post = env.store.createRecord("post", { title: "Rails is omakase"}); var json = {}; env.container.lookup("serializer:post").serializeAttribute(post, json, "title", {type: "string"}); deepEqual(json, { TITLE: "Rails is omakase" }); }); test("serializeBelongsTo", function() { post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post}); var json = {}; env.serializer.serializeBelongsTo(comment, json, {key: "post", options: {}}); deepEqual(json, { post: "1" }); }); test("serializeBelongsTo with null", function() { comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: null}); var json = {}; env.serializer.serializeBelongsTo(comment, json, {key: "post", options: {}}); deepEqual(json, { post: null }, "Can set a belongsTo to a null value"); }); test("serializeBelongsTo respects keyForRelationship", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship: function(key, type) { return key.toUpperCase(); } })); post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post}); var json = {}; env.container.lookup("serializer:post").serializeBelongsTo(comment, json, {key: "post", options: {}}); deepEqual(json, { POST: "1" }); }); test("serializeHasMany respects keyForRelationship", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship: function(key, type) { return key.toUpperCase(); } })); post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post, id: "1"}); var json = {}; env.container.lookup("serializer:post").serializeHasMany(post, json, {key: "comments", options: {}}); deepEqual(json, { COMMENTS: ["1"] }); }); test("serializeIntoHash", function() { post = env.store.createRecord("post", { title: "Rails is omakase"}); var json = {}; env.serializer.serializeIntoHash(json, Post, post); deepEqual(json, { title: "Rails is omakase", comments: [] }); }); test("serializePolymorphicType", function() { env.container.register('serializer:comment', DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); json[relationship.key + "TYPE"] = belongsTo.constructor.typeKey; } })); post = env.store.createRecord(Post, { title: "Rails is omakase", id: "1"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post}); var json = {}; env.container.lookup("serializer:comment").serializeBelongsTo(comment, json, {key: "post", options: { polymorphic: true}}); deepEqual(json, { post: "1", postTYPE: "post" }); }); test("extractArray normalizes each record in the array", function() { var postNormalizeCount = 0; var posts = [ { title: "Rails is omakase"}, { title: "Another Post"} ]; env.container.register('serializer:post', DS.JSONSerializer.extend({ normalize: function () { postNormalizeCount++; return this._super.apply(this, arguments); } })); env.container.lookup("serializer:post").extractArray(env.store, Post, posts); equal(postNormalizeCount, 2, "two posts are normalized"); }); test('Serializer should respect the attrs hash when extracting records', function(){ env.container.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", comments: { key: 'my_comments' } } })); var jsonHash = { title_payload_key: "Rails is omakase", my_comments: [1, 2] }; var post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash); equal(post.title, "Rails is omakase"); deepEqual(post.comments, [1,2]); }); test('Serializer should respect the attrs hash when serializing records', function(){ Post.reopen({ parentPost: DS.belongsTo('post') }); env.container.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", parentPost: {key: 'my_parent'} } })); var parentPost = env.store.push("post", { id:2, title: "Rails is omakase"}); post = env.store.createRecord("post", { title: "Rails is omakase", parentPost: parentPost}); var payload = env.container.lookup("serializer:post").serialize(post); equal(payload.title_payload_key, "Rails is omakase"); equal(payload.my_parent, '2'); }); test('Serializer respects `serialize: false` on the attrs hash', function(){ expect(2); env.container.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: {serialize: false} } })); post = env.store.createRecord("post", { title: "Rails is omakase"}); var payload = env.container.lookup("serializer:post").serialize(post); ok(!payload.hasOwnProperty('title'), "Does not add the key to instance"); ok(!payload.hasOwnProperty('[object Object]'),"Does not add some random key like [object Object]"); }); test('Serializer respects `serialize: false` on the attrs hash for a `hasMany` property', function(){ expect(1); env.container.register("serializer:post", DS.JSONSerializer.extend({ attrs: { comments: {serialize: false} } })); post = env.store.createRecord("post", { title: "Rails is omakase"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post}); var serializer = env.container.lookup("serializer:post"); var serializedProperty = serializer.keyForRelationship('comments', 'hasMany'); var payload = serializer.serialize(post); ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test('Serializer respects `serialize: false` on the attrs hash for a `belongsTo` property', function(){ expect(1); env.container.register("serializer:comment", DS.JSONSerializer.extend({ attrs: { post: {serialize: false} } })); post = env.store.createRecord("post", { title: "Rails is omakase"}); comment = env.store.createRecord(Comment, { body: "Omakase is delicious", post: post}); var serializer = env.container.lookup("serializer:comment"); var serializedProperty = serializer.keyForRelationship('post', 'belongsTo'); var payload = serializer.serialize(comment); ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test("Serializer should respect the primaryKey attribute when extracting records", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ primaryKey: '_ID_' })); var jsonHash = { "_ID_": 1, title: "Rails is omakase"}; post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash); equal(post.id, "1"); equal(post.title, "Rails is omakase"); }); test("Serializer should respect the primaryKey attribute when serializing records", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ primaryKey: '_ID_' })); post = env.store.createRecord("post", { id: "1", title: "Rails is omakase"}); var payload = env.container.lookup("serializer:post").serialize(post, {includeId: true}); equal(payload._ID_, "1"); }); test("Serializer should respect keyForAttribute when extracting records", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ keyForAttribute: function(key) { return key.toUpperCase(); } })); var jsonHash = {id: 1, TITLE: 'Rails is omakase'}; post = env.container.lookup("serializer:post").normalize(Post, jsonHash); equal(post.id, "1"); equal(post.title, "Rails is omakase"); }); test("Serializer should respect keyForRelationship when extracting records", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship: function(key, type) { return key.toUpperCase(); } })); var jsonHash = {id: 1, title: 'Rails is omakase', COMMENTS: ['1']}; post = env.container.lookup("serializer:post").normalize(Post, jsonHash); deepEqual(post.comments, ['1']); }); test("normalizePayload is called during extractSingle", function() { env.container.register('serializer:post', DS.JSONSerializer.extend({ normalizePayload: function(payload) { return payload.response; } })); var jsonHash = { response: { id: 1, title: "Rails is omakase" } }; post = env.container.lookup("serializer:post").extractSingle(env.store, Post, jsonHash); equal(post.id, "1"); equal(post.title, "Rails is omakase"); }); test("Calling normalize should normalize the payload (only the passed keys)", function () { expect(1); var Person = DS.Model.extend({ posts: DS.hasMany('post') }); env.container.register('serializer:post', DS.JSONSerializer.extend({ attrs: { notInHash: 'aCustomAttrNotInHash', inHash: 'aCustomAttrInHash' } })); env.container.register('model:person', Person); Post.reopen({ content: DS.attr('string'), author: DS.belongsTo('person'), notInHash: DS.attr('string'), inHash: DS.attr('string') }); var normalizedPayload = env.container.lookup("serializer:post").normalize(Post, { id: '1', title: 'Ember rocks', author: 1, aCustomAttrInHash: 'blah' }); deepEqual(normalizedPayload, { id: '1', title: 'Ember rocks', author: 1, inHash: 'blah' }); });
chadhietala/data
packages/ember-data/tests/integration/serializers/json_serializer_test.js
JavaScript
mit
10,807
//-------------------------------------------------------------------------------------------------- $.SocketClient = $.CT.extend( /*-------------------------------------------------------------------------------------------------- | | -> Конструктор | |-------------------------------------------------------------------------------------------------*/ {private: {constructor: function(id, ws) { this.id = id;// ID соединения this.ws = ws;// Экземпляр соединения }}}, /*-------------------------------------------------------------------------------------------------- | | -> Возвращает UserID | |-------------------------------------------------------------------------------------------------*/ {public: {getUserID: function() { return this.userid; }}}, /*-------------------------------------------------------------------------------------------------- | | -> Задает UserID | |-------------------------------------------------------------------------------------------------*/ {public: {setUserID: function(userid) { this.userid = userid; }}}, /*-------------------------------------------------------------------------------------------------- | | -> Возвращает информацию о юзере | |-------------------------------------------------------------------------------------------------*/ {public: {getData: function() { return this.data; }}}, /*-------------------------------------------------------------------------------------------------- | | -> Задает информацию о юзере | |-------------------------------------------------------------------------------------------------*/ {public: {setData: function(data) { this.data = data; }}}, /*-------------------------------------------------------------------------------------------------- | | -> Отправляет сообщение об ошибке и закрывает соединение | |-------------------------------------------------------------------------------------------------*/ {public: {error: function(error_msg) { // Отправляем сообщение this.send('Error', {'error_msg': error_msg}); // Закрываем соединение this.close(); }}}, /*-------------------------------------------------------------------------------------------------- | | -> Отправляет сообщение | |-------------------------------------------------------------------------------------------------*/ {public: {send: function() { // Создаем запрос var r = []; // Переводим аргументы в массив var args = Array.prototype.slice.call(arguments, 0); // Удаляем первый элемент args.shift(); // Добавляем заголовок r.push(arguments[0]); // Добавляем тело запроса (по умолчанию пустой массив) r.push(args); // Конвертируем в JSON var json = JSON.stringify(r); // Отправляем сообщение try { this.ws.send(json); } catch(e) { } // Записываем в консоль $.SocketConsole['<-'](arguments[0], ($.Socket.isConsole == 'body' ? JSON.stringify(r[1]) : json)); }}}, /*-------------------------------------------------------------------------------------------------- | | -> Закрывает соединение | |-------------------------------------------------------------------------------------------------*/ {public: {close: function() { // Закрываем соединение try { this.ws.close(); } catch(e) { } }}} ); //--------------------------------------------------------------------------------------------------
classtype/wordstat-server
WordStat/Modules/Socket/SocketClient.js
JavaScript
mit
4,102
import journey from "lib/journey/journey.js"; import template from "./home.html"; import Ractive from "Ractive.js"; var home = { // this function is called when we enter the route enter: function ( route, prevRoute, options ) { /*%injectPath%*/ // Create our view, and assign it to the route under the property 'view'. route.view = new Ractive( { el: options.target, template: template, onrender: function() { // We want a funky intro for our text, so after 500ms we display the node with id='home-demo' // and add the class rollIn. setTimeout(function() { $('#home-demo').removeClass('invisible').addClass("rollIn"); }, 500); } } ); }, // this function is called when we leave the route leave: function ( route, nextRoute, options ) { // Remove the view from the DOM route.view.teardown(); } }; export default home;
journey-js/journey-examples
src/js/app/views/home/home.js
JavaScript
mit
877
'use strict'; var digdugAdapter = require('../digdug.js'); var DigdugSauceLabsTunnel = require('digdug/SauceLabsTunnel'); module.exports = function(options) { return digdugAdapter('SauceLabs', DigdugSauceLabsTunnel, options); };
uxebu/kommando
src/driver/sauce-labs.js
JavaScript
mit
233
version https://git-lfs.github.com/spec/v1 oid sha256:723a8517e1cf6d7394b64767b5361ca7f77278fc4d699827b5994af7b1be1714 size 183710
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.14.1/charts-legend/charts-legend-coverage.js
JavaScript
mit
131
/*! * Copyright © 2008 Fair Oaks Labs, Inc. * All rights reserved. */ // Utility object: Encode/Decode C-style binary primitives to/from octet arrays function JSPack() { // Module-level (private) variables var el, bBE = false, m = this; // Raw byte arrays m._DeArray = function (a, p, l) { return [a.slice(p,p+l)]; }; m._EnArray = function (a, p, l, v) { for (var i = 0; i < l; a[p+i] = v[i]?v[i]:0, i++); }; // ASCII characters m._DeChar = function (a, p) { return String.fromCharCode(a[p]); }; m._EnChar = function (a, p, v) { a[p] = v.charCodeAt(0); }; // Little-endian (un)signed N-byte integers m._DeInt = function (a, p) { var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, rv, i, f; for (rv = 0, i = lsb, f = 1; i != stop; rv+=(a[p+i]*f), i+=nsb, f*=256); if (el.bSigned && (rv & Math.pow(2, el.len*8-1))) { rv -= Math.pow(2, el.len*8); } return rv; }; m._EnInt = function (a, p, v) { var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, i; v = (v<el.min)?el.min:(v>el.max)?el.max:v; for (i = lsb; i != stop; a[p+i]=v&0xff, i+=nsb, v>>=8); }; // ASCII character strings m._DeString = function (a, p, l) { for (var rv = new Array(l), i = 0; i < l; rv[i] = String.fromCharCode(a[p+i]), i++); return rv.join(''); }; m._EnString = function (a, p, l, v) { for (var t, i = 0; i < l; a[p+i] = (t=v.charCodeAt(i))?t:0, i++); }; // Little-endian N-bit IEEE 754 floating point m._De754 = function (a, p) { var s, e, m, i, d, nBits, mLen, eLen, eBias, eMax; mLen = el.mLen, eLen = el.len*8-el.mLen-1, eMax = (1<<eLen)-1, eBias = eMax>>1; i = bBE?0:(el.len-1); d = bBE?1:-1; s = a[p+i]; i+=d; nBits = -7; for (e = s&((1<<(-nBits))-1), s>>=(-nBits), nBits += eLen; nBits > 0; e=e*256+a[p+i], i+=d, nBits-=8); for (m = e&((1<<(-nBits))-1), e>>=(-nBits), nBits += mLen; nBits > 0; m=m*256+a[p+i], i+=d, nBits-=8); switch (e) { case 0: // Zero, or denormalized number e = 1-eBias; break; case eMax: // NaN, or +/-Infinity return m?NaN:((s?-1:1)*Infinity); default: // Normalized number m = m + Math.pow(2, mLen); e = e - eBias; break; } return (s?-1:1) * m * Math.pow(2, e-mLen); }; m._En754 = function (a, p, v) { var s, e, m, i, d, c, mLen, eLen, eBias, eMax; mLen = el.mLen, eLen = el.len*8-el.mLen-1, eMax = (1<<eLen)-1, eBias = eMax>>1; s = v<0?1:0; v = Math.abs(v); if (isNaN(v) || (v == Infinity)) { m = isNaN(v)?1:0; e = eMax; } else { e = Math.floor(Math.log(v)/Math.LN2); // Calculate log2 of the value if (v*(c = Math.pow(2, -e)) < 1) { e--; c*=2; } // Math.log() isn't 100% reliable // Round by adding 1/2 the significand's LSD if (e+eBias >= 1) { v += el.rt/c; } // Normalized: mLen significand digits else { v += el.rt*Math.pow(2, 1-eBias); } // Denormalized: <= mLen significand digits if (v*c >= 2) { e++; c/=2; } // Rounding can increment the exponent if (e+eBias >= eMax) { // Overflow m = 0; e = eMax; } else if (e+eBias >= 1) { // Normalized - term order matters, as Math.pow(2, 52-e) and v*Math.pow(2, 52) can overflow m = (v*c-1)*Math.pow(2, mLen); e = e + eBias; } else { // Denormalized - also catches the '0' case, somewhat by chance m = v*Math.pow(2, eBias-1)*Math.pow(2, mLen); e = 0; } } for (i = bBE?(el.len-1):0, d=bBE?-1:1; mLen >= 8; a[p+i]=m&0xff, i+=d, m/=256, mLen-=8); for (e=(e<<mLen)|m, eLen+=mLen; eLen > 0; a[p+i]=e&0xff, i+=d, e/=256, eLen-=8); a[p+i-d] |= s*128; }; // Class data m._sPattern = '(\\d+)?([AxcbBhHsfdiIlLqQ])'; m._lenLut = {'A':1, 'x':1, 'c':1, 'b':1, 'B':1, 'h':2, 'H':2, 's':1, 'f':4, 'd':8, 'i':4, 'I':4, 'l':4, 'L':4, 'q':8, 'Q':8}; m._elLut = { 'A': {en:m._EnArray, de:m._DeArray}, 's': {en:m._EnString, de:m._DeString}, 'c': {en:m._EnChar, de:m._DeChar}, 'b': {en:m._EnInt, de:m._DeInt, len:1, bSigned:true, min:-Math.pow(2, 7), max:Math.pow(2, 7)-1}, 'B': {en:m._EnInt, de:m._DeInt, len:1, bSigned:false, min:0, max:Math.pow(2, 8)-1}, 'h': {en:m._EnInt, de:m._DeInt, len:2, bSigned:true, min:-Math.pow(2, 15), max:Math.pow(2, 15)-1}, 'H': {en:m._EnInt, de:m._DeInt, len:2, bSigned:false, min:0, max:Math.pow(2, 16)-1}, 'i': {en:m._EnInt, de:m._DeInt, len:4, bSigned:true, min:-Math.pow(2, 31), max:Math.pow(2, 31)-1}, 'I': {en:m._EnInt, de:m._DeInt, len:4, bSigned:false, min:0, max:Math.pow(2, 32)-1}, 'l': {en:m._EnInt, de:m._DeInt, len:4, bSigned:true, min:-Math.pow(2, 31), max:Math.pow(2, 31)-1}, 'L': {en:m._EnInt, de:m._DeInt, len:4, bSigned:false, min:0, max:Math.pow(2, 32)-1}, 'f': {en:m._En754, de:m._De754, len:4, mLen:23, rt:Math.pow(2, -24)-Math.pow(2, -77)}, 'd': {en:m._En754, de:m._De754, len:8, mLen:52, rt:0}, 'q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:true, min:-Math.pow(2, 63), max:Math.pow(2, 63)-1}, 'Q': {en:m._EnInt, de:m._DeInt, len:8, bSigned:false, min:0, max:Math.pow(2, 64)-1}}; // Unpack a series of n elements of size s from array a at offset p with fxn m._UnpackSeries = function (n, s, a, p) { for (var fxn = el.de, rv = [], i = 0; i < n; rv.push(fxn(a, p+i*s)), i++); return rv; }; // Pack a series of n elements of size s from array v at offset i to array a at offset p with fxn m._PackSeries = function (n, s, a, p, v, i) { for (var fxn = el.en, o = 0; o < n; fxn(a, p+o*s, v[i+o]), o++); }; // Unpack the octet array a, beginning at offset p, according to the fmt string m.Unpack = function (fmt, a, p) { // Set the private bBE flag based on the format string - assume big-endianness bBE = (fmt.charAt(0) != '<'); p = p?p:0; var re = new RegExp(this._sPattern, 'g'), m, n, s, rv = []; while (m = re.exec(fmt)) { n = ((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1]); s = this._lenLut[m[2]]; if ((p + n*s) > a.length) { return undefined; } switch (m[2]) { case 'A': case 's': rv.push(this._elLut[m[2]].de(a, p, n)); break; case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'f': case 'd': case 'q': case 'Q': el = this._elLut[m[2]]; rv.push(this._UnpackSeries(n, s, a, p)); break; } p += n*s; } return Array.prototype.concat.apply([], rv); }; // Pack the supplied values into the octet array a, beginning at offset p, according to the fmt string m.PackTo = function (fmt, a, p, values) { // Set the private bBE flag based on the format string - assume big-endianness bBE = (fmt.charAt(0) != '<'); var re = new RegExp(this._sPattern, 'g'), m, n, s, i = 0, j; while (m = re.exec(fmt)) { n = ((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1]); s = this._lenLut[m[2]]; if ((p + n*s) > a.length) { return false; } switch (m[2]) { case 'A': case 's': if ((i + 1) > values.length) { return false; } this._elLut[m[2]].en(a, p, n, values[i]); i += 1; break; case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'f': case 'd': case 'q': case 'Q': el = this._elLut[m[2]]; if ((i + n) > values.length) { return false; } this._PackSeries(n, s, a, p, values, i); i += n; break; case 'x': for (j = 0; j < n; j++) { a[p+j] = 0; } break; } p += n*s; } return a; }; // Pack the supplied values into a new octet array, according to the fmt string m.Pack = function (fmt, values) { return this.PackTo(fmt, new Array(this.CalcLength(fmt)), 0, values); }; // Determine the number of bytes represented by the format string m.CalcLength = function (fmt) { var re = new RegExp(this._sPattern, 'g'), m, sum = 0; while (m = re.exec(fmt)) { sum += (((m[1]==undefined)||(m[1]==''))?1:parseInt(m[1])) * this._lenLut[m[2]]; } return sum; }; };
chancecoin/chancecoinj
resources/static/js/jspack.js
JavaScript
mit
7,911
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A WebGLBatch Enables a group of sprites to be drawn using the same settings. * if a group of sprites all have the same baseTexture and blendMode then they can be * grouped into a batch. All the sprites in a batch can then be drawn in one go by the * GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch * even if the batch only contains one sprite. Batching is handled automatically by the * webGL renderer. A good tip is: the smaller the number of batchs there are, the faster * the webGL renderer will run. * * @class WebGLBatch * @contructor * @param gl {WebGLContext} An instance of the webGL context */ PIXI.WebGLRenderGroup = function(gl, transparent) { this.gl = gl; this.root; this.backgroundColor; this.transparent = transparent == undefined ? true : transparent; this.batchs = []; this.toRemove = []; // console.log(this.transparent) this.filterManager = new PIXI.WebGLFilterManager(this.transparent); } // constructor PIXI.WebGLRenderGroup.prototype.constructor = PIXI.WebGLRenderGroup; /** * Add a display object to the webgl renderer * * @method setRenderable * @param displayObject {DisplayObject} * @private */ PIXI.WebGLRenderGroup.prototype.setRenderable = function(displayObject) { // has this changed?? if(this.root)this.removeDisplayObjectAndChildren(this.root); displayObject.worldVisible = displayObject.visible; // soooooo // // to check if any batchs exist already?? // TODO what if its already has an object? should remove it this.root = displayObject; this.addDisplayObjectAndChildren(displayObject); } /** * Renders the stage to its webgl view * * @method render * @param projection {Object} */ PIXI.WebGLRenderGroup.prototype.render = function(projection, buffer) { PIXI.WebGLRenderer.updateTextures(); var gl = this.gl; gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y); this.filterManager.begin(projection, buffer); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // will render all the elements in the group var renderable; for (var i=0; i < this.batchs.length; i++) { renderable = this.batchs[i]; if(renderable instanceof PIXI.WebGLBatch) { this.batchs[i].render(); continue; } // render special this.renderSpecial(renderable, projection); } } /** * Renders a specific displayObject * * @method renderSpecific * @param displayObject {DisplayObject} * @param projection {Object} * @private */ PIXI.WebGLRenderGroup.prototype.renderSpecific = function(displayObject, projection, buffer) { PIXI.WebGLRenderer.updateTextures(); var gl = this.gl; gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y); this.filterManager.begin(projection, buffer); // to do! // render part of the scene... var startIndex; var startBatchIndex; var endIndex; var endBatchIndex; /* * LOOK FOR THE NEXT SPRITE * This part looks for the closest next sprite that can go into a batch * it keeps looking until it finds a sprite or gets to the end of the display * scene graph */ var nextRenderable = displayObject.first; while(nextRenderable._iNext) { if(nextRenderable.renderable && nextRenderable.__renderGroup)break; nextRenderable = nextRenderable._iNext; } var startBatch = nextRenderable.batch; //console.log(nextRenderable); //console.log(renderable) if(nextRenderable instanceof PIXI.Sprite) { startBatch = nextRenderable.batch; var head = startBatch.head; var next = head; // ok now we have the batch.. need to find the start index! if(head == nextRenderable) { startIndex = 0; } else { startIndex = 1; while(head.__next != nextRenderable) { startIndex++; head = head.__next; } } } else { startBatch = nextRenderable; } // Get the LAST renderable object var lastRenderable = displayObject.last; while(lastRenderable._iPrev) { if(lastRenderable.renderable && lastRenderable.__renderGroup)break; lastRenderable = lastRenderable._iNext; } if(lastRenderable instanceof PIXI.Sprite) { endBatch = lastRenderable.batch; var head = endBatch.head; if(head == lastRenderable) { endIndex = 0; } else { endIndex = 1; while(head.__next != lastRenderable) { endIndex++; head = head.__next; } } } else { endBatch = lastRenderable; } if(startBatch == endBatch) { if(startBatch instanceof PIXI.WebGLBatch) { startBatch.render(startIndex, endIndex+1); } else { this.renderSpecial(startBatch, projection); } return; } // now we have first and last! startBatchIndex = this.batchs.indexOf(startBatch); endBatchIndex = this.batchs.indexOf(endBatch); // DO the first batch if(startBatch instanceof PIXI.WebGLBatch) { startBatch.render(startIndex); } else { this.renderSpecial(startBatch, projection); } // DO the middle batchs.. for (var i=startBatchIndex+1; i < endBatchIndex; i++) { renderable = this.batchs[i]; if(renderable instanceof PIXI.WebGLBatch) { this.batchs[i].render(); } else { this.renderSpecial(renderable, projection); } } // DO the last batch.. if(endBatch instanceof PIXI.WebGLBatch) { endBatch.render(0, endIndex+1); } else { this.renderSpecial(endBatch, projection); } } /** * Renders a specific renderable * * @method renderSpecial * @param renderable {DisplayObject} * @param projection {Object} * @private */ PIXI.WebGLRenderGroup.prototype.renderSpecial = function(renderable, projection) { var worldVisible = renderable.vcount === PIXI.visibleCount if(renderable instanceof PIXI.TilingSprite) { if(worldVisible)this.renderTilingSprite(renderable, projection); } else if(renderable instanceof PIXI.Strip) { if(worldVisible)this.renderStrip(renderable, projection); } else if(renderable instanceof PIXI.CustomRenderable) { if(worldVisible) renderable.renderWebGL(this, projection); } else if(renderable instanceof PIXI.Graphics) { if(worldVisible && renderable.renderable) PIXI.WebGLGraphics.renderGraphics(renderable, projection); } else if(renderable instanceof PIXI.FilterBlock) { this.handleFilterBlock(renderable, projection); } } flip = false; var maskStack = []; var maskPosition = 0; //var usedMaskStack = []; PIXI.WebGLRenderGroup.prototype.handleFilterBlock = function(filterBlock, projection) { /* * for now only masks are supported.. */ var gl = PIXI.gl; if(filterBlock.open) { if(filterBlock.data instanceof Array) { this.filterManager.pushFilter(filterBlock); // ok so.. } else { maskPosition++; maskStack.push(filterBlock) gl.enable(gl.STENCIL_TEST); gl.colorMask(false, false, false, false); gl.stencilFunc(gl.ALWAYS,1,1); gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); PIXI.WebGLGraphics.renderGraphics(filterBlock.data, projection); gl.colorMask(true, true, true, true); gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length); gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); } } else { if(filterBlock.data instanceof Array) { this.filterManager.popFilter(); } else { var maskData = maskStack.pop(filterBlock) if(maskData) { gl.colorMask(false, false, false, false); gl.stencilFunc(gl.ALWAYS,1,1); gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); PIXI.WebGLGraphics.renderGraphics(maskData.data, projection); gl.colorMask(true, true, true, true); gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length); gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); }; gl.disable(gl.STENCIL_TEST); } } } /** * Updates a webgl texture * * @method updateTexture * @param displayObject {DisplayObject} * @private */ PIXI.WebGLRenderGroup.prototype.updateTexture = function(displayObject) { // TODO definitely can optimse this function.. this.removeObject(displayObject); /* * LOOK FOR THE PREVIOUS RENDERABLE * This part looks for the closest previous sprite that can go into a batch * It keeps going back until it finds a sprite or the stage */ var previousRenderable = displayObject.first; while(previousRenderable != this.root) { previousRenderable = previousRenderable._iPrev; if(previousRenderable.renderable && previousRenderable.__renderGroup)break; } /* * LOOK FOR THE NEXT SPRITE * This part looks for the closest next sprite that can go into a batch * it keeps looking until it finds a sprite or gets to the end of the display * scene graph */ var nextRenderable = displayObject.last; while(nextRenderable._iNext) { nextRenderable = nextRenderable._iNext; if(nextRenderable.renderable && nextRenderable.__renderGroup)break; } this.insertObject(displayObject, previousRenderable, nextRenderable); } /** * Adds filter blocks * * @method addFilterBlocks * @param start {FilterBlock} * @param end {FilterBlock} * @private */ PIXI.WebGLRenderGroup.prototype.addFilterBlocks = function(start, end) { start.__renderGroup = this; end.__renderGroup = this; /* * LOOK FOR THE PREVIOUS RENDERABLE * This part looks for the closest previous sprite that can go into a batch * It keeps going back until it finds a sprite or the stage */ var previousRenderable = start; while(previousRenderable != this.root.first) { previousRenderable = previousRenderable._iPrev; if(previousRenderable.renderable && previousRenderable.__renderGroup)break; } this.insertAfter(start, previousRenderable); /* * LOOK FOR THE NEXT SPRITE * This part looks for the closest next sprite that can go into a batch * it keeps looking until it finds a sprite or gets to the end of the display * scene graph */ var previousRenderable2 = end; while(previousRenderable2 != this.root.first) { previousRenderable2 = previousRenderable2._iPrev; if(previousRenderable2.renderable && previousRenderable2.__renderGroup)break; } this.insertAfter(end, previousRenderable2); } /** * Remove filter blocks * * @method removeFilterBlocks * @param start {FilterBlock} * @param end {FilterBlock} * @private */ PIXI.WebGLRenderGroup.prototype.removeFilterBlocks = function(start, end) { this.removeObject(start); this.removeObject(end); } /** * Adds a display object and children to the webgl context * * @method addDisplayObjectAndChildren * @param displayObject {DisplayObject} * @private */ PIXI.WebGLRenderGroup.prototype.addDisplayObjectAndChildren = function(displayObject) { if(displayObject.__renderGroup)displayObject.__renderGroup.removeDisplayObjectAndChildren(displayObject); /* * LOOK FOR THE PREVIOUS RENDERABLE * This part looks for the closest previous sprite that can go into a batch * It keeps going back until it finds a sprite or the stage */ var previousRenderable = displayObject.first; while(previousRenderable != this.root.first) { previousRenderable = previousRenderable._iPrev; if(previousRenderable.renderable && previousRenderable.__renderGroup)break; } /* * LOOK FOR THE NEXT SPRITE * This part looks for the closest next sprite that can go into a batch * it keeps looking until it finds a sprite or gets to the end of the display * scene graph */ var nextRenderable = displayObject.last; while(nextRenderable._iNext) { nextRenderable = nextRenderable._iNext; if(nextRenderable.renderable && nextRenderable.__renderGroup)break; } // one the display object hits this. we can break the loop var tempObject = displayObject.first; var testObject = displayObject.last._iNext; do { tempObject.__renderGroup = this; if(tempObject.renderable) { this.insertObject(tempObject, previousRenderable, nextRenderable); previousRenderable = tempObject; } tempObject = tempObject._iNext; } while(tempObject != testObject) } /** * Removes a display object and children to the webgl context * * @method removeDisplayObjectAndChildren * @param displayObject {DisplayObject} * @private */ PIXI.WebGLRenderGroup.prototype.removeDisplayObjectAndChildren = function(displayObject) { if(displayObject.__renderGroup != this)return; // var displayObject = displayObject.first; var lastObject = displayObject.last; do { displayObject.__renderGroup = null; if(displayObject.renderable)this.removeObject(displayObject); displayObject = displayObject._iNext; } while(displayObject) } /** * Inserts a displayObject into the linked list * * @method insertObject * @param displayObject {DisplayObject} * @param previousObject {DisplayObject} * @param nextObject {DisplayObject} * @private */ PIXI.WebGLRenderGroup.prototype.insertObject = function(displayObject, previousObject, nextObject) { // while looping below THE OBJECT MAY NOT HAVE BEEN ADDED var previousSprite = previousObject; var nextSprite = nextObject; /* * so now we have the next renderable and the previous renderable * */ if(displayObject instanceof PIXI.Sprite) { var previousBatch var nextBatch if(previousSprite instanceof PIXI.Sprite) { previousBatch = previousSprite.batch; if(previousBatch) { if(previousBatch.texture == displayObject.texture.baseTexture && previousBatch.blendMode == displayObject.blendMode) { previousBatch.insertAfter(displayObject, previousSprite); return; } } } else { // TODO reword! previousBatch = previousSprite; } if(nextSprite) { if(nextSprite instanceof PIXI.Sprite) { nextBatch = nextSprite.batch; //batch may not exist if item was added to the display list but not to the webGL if(nextBatch) { if(nextBatch.texture == displayObject.texture.baseTexture && nextBatch.blendMode == displayObject.blendMode) { nextBatch.insertBefore(displayObject, nextSprite); return; } else { if(nextBatch == previousBatch) { // THERE IS A SPLIT IN THIS BATCH! // var splitBatch = previousBatch.split(nextSprite); // COOL! // add it back into the array /* * OOPS! * seems the new sprite is in the middle of a batch * lets split it.. */ var batch = PIXI.WebGLRenderer.getBatch(); var index = this.batchs.indexOf( previousBatch ); batch.init(displayObject); this.batchs.splice(index+1, 0, batch, splitBatch); return; } } } } else { // TODO re-word! nextBatch = nextSprite; } } /* * looks like it does not belong to any batch! * but is also not intersecting one.. * time to create anew one! */ var batch = PIXI.WebGLRenderer.getBatch(); batch.init(displayObject); if(previousBatch) // if this is invalid it means { var index = this.batchs.indexOf( previousBatch ); this.batchs.splice(index+1, 0, batch); } else { this.batchs.push(batch); } return; } else if(displayObject instanceof PIXI.TilingSprite) { // add to a batch!! this.initTilingSprite(displayObject); // this.batchs.push(displayObject); } else if(displayObject instanceof PIXI.Strip) { // add to a batch!! this.initStrip(displayObject); // this.batchs.push(displayObject); } else if(displayObject)// instanceof PIXI.Graphics) { //displayObject.initWebGL(this); // add to a batch!! //this.initStrip(displayObject); //this.batchs.push(displayObject); } this.insertAfter(displayObject, previousSprite); // insert and SPLIT! } /** * Inserts a displayObject into the linked list * * @method insertAfter * @param item {DisplayObject} * @param displayObject {DisplayObject} The object to insert * @private */ PIXI.WebGLRenderGroup.prototype.insertAfter = function(item, displayObject) { if(displayObject instanceof PIXI.Sprite) { var previousBatch = displayObject.batch; if(previousBatch) { // so this object is in a batch! // is it not? need to split the batch if(previousBatch.tail == displayObject) { // is it tail? insert in to batchs var index = this.batchs.indexOf( previousBatch ); this.batchs.splice(index+1, 0, item); } else { // TODO MODIFY ADD / REMOVE CHILD TO ACCOUNT FOR FILTERS (also get prev and next) // // THERE IS A SPLIT IN THIS BATCH! // var splitBatch = previousBatch.split(displayObject.__next); // COOL! // add it back into the array /* * OOPS! * seems the new sprite is in the middle of a batch * lets split it.. */ var index = this.batchs.indexOf( previousBatch ); this.batchs.splice(index+1, 0, item, splitBatch); } } else { this.batchs.push(item); } } else { var index = this.batchs.indexOf( displayObject ); this.batchs.splice(index+1, 0, item); } } /** * Removes a displayObject from the linked list * * @method removeObject * @param displayObject {DisplayObject} The object to remove * @private */ PIXI.WebGLRenderGroup.prototype.removeObject = function(displayObject) { // loop through children.. // display object // // add a child from the render group.. // remove it and all its children! //displayObject.cacheVisible = false;//displayObject.visible; /* * removing is a lot quicker.. * */ var batchToRemove; if(displayObject instanceof PIXI.Sprite) { // should always have a batch! var batch = displayObject.batch; if(!batch)return; // this means the display list has been altered befre rendering batch.remove(displayObject); if(batch.size==0) { batchToRemove = batch; } } else { batchToRemove = displayObject; } /* * Looks like there is somthing that needs removing! */ if(batchToRemove) { var index = this.batchs.indexOf( batchToRemove ); if(index == -1)return;// this means it was added then removed before rendered // ok so.. check to see if you adjacent batchs should be joined. // TODO may optimise? if(index == 0 || index == this.batchs.length-1) { // wha - eva! just get of the empty batch! this.batchs.splice(index, 1); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); return; } if(this.batchs[index-1] instanceof PIXI.WebGLBatch && this.batchs[index+1] instanceof PIXI.WebGLBatch) { if(this.batchs[index-1].texture == this.batchs[index+1].texture && this.batchs[index-1].blendMode == this.batchs[index+1].blendMode) { //console.log("MERGE") this.batchs[index-1].merge(this.batchs[index+1]); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); PIXI.WebGLRenderer.returnBatch(this.batchs[index+1]); this.batchs.splice(index, 2); return; } } this.batchs.splice(index, 1); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); } } /** * Initializes a tiling sprite * * @method initTilingSprite * @param sprite {TilingSprite} The tiling sprite to initialize * @private */ PIXI.WebGLRenderGroup.prototype.initTilingSprite = function(sprite) { var gl = this.gl; // make the texture tilable.. sprite.verticies = new Float32Array([0, 0, sprite.width, 0, sprite.width, sprite.height, 0, sprite.height]); sprite.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); sprite.colors = new Float32Array([1,1,1,1]); sprite.indices = new Uint16Array([0, 1, 3,2])//, 2]); sprite._vertexBuffer = gl.createBuffer(); sprite._indexBuffer = gl.createBuffer(); sprite._uvBuffer = gl.createBuffer(); sprite._colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, sprite._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, sprite.verticies, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, sprite.uvs, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, sprite._colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, sprite.colors, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sprite._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sprite.indices, gl.STATIC_DRAW); // return ( (x > 0) && ((x & (x - 1)) == 0) ); if(sprite.texture.baseTexture._glTexture) { gl.bindTexture(gl.TEXTURE_2D, sprite.texture.baseTexture._glTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); sprite.texture.baseTexture._powerOf2 = true; } else { sprite.texture.baseTexture._powerOf2 = true; } } /** * Renders a Strip * * @method renderStrip * @param strip {Strip} The strip to render * @param projection {Object} * @private */ PIXI.WebGLRenderGroup.prototype.renderStrip = function(strip, projection) { var gl = this.gl; PIXI.activateStripShader(); var shader = PIXI.stripShader; var program = shader.program; var m = PIXI.mat3.clone(strip.worldTransform); PIXI.mat3.transpose(m); // console.log(projection) // set the matrix transform for the gl.uniformMatrix3fv(shader.translationMatrix, false, m); gl.uniform2f(shader.projectionVector, projection.x, projection.y); gl.uniform2f(shader.offsetVector, -PIXI.offset.x, -PIXI.offset.y); gl.uniform1f(shader.alpha, strip.worldAlpha); /* if(strip.blendMode == PIXI.blendModes.NORMAL) { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } else { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); } */ //console.log("!!") if(!strip.dirty) { gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, strip.verticies) gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); // update the uvs gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0); // dont need to upload! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); } else { strip.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.STATIC_DRAW) gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); // update the uvs gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW) gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); // console.log(strip.texture.baseTexture._glTexture) gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW) gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0); // dont need to upload! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); } gl.drawElements(gl.TRIANGLE_STRIP, strip.indices.length, gl.UNSIGNED_SHORT, 0); PIXI.deactivateStripShader(); //gl.useProgram(PIXI.currentProgram); } /** * Renders a TilingSprite * * @method renderTilingSprite * @param sprite {TilingSprite} The tiling sprite to render * @param projectionMatrix {Object} * @private */ PIXI.WebGLRenderGroup.prototype.renderTilingSprite = function(sprite, projectionMatrix) { var gl = this.gl; var shaderProgram = PIXI.shaderProgram; var tilePosition = sprite.tilePosition; var tileScale = sprite.tileScale; var offsetX = tilePosition.x/sprite.texture.baseTexture.width; var offsetY = tilePosition.y/sprite.texture.baseTexture.height; var scaleX = (sprite.width / sprite.texture.baseTexture.width) / tileScale.x; var scaleY = (sprite.height / sprite.texture.baseTexture.height) / tileScale.y; sprite.uvs[0] = 0 - offsetX; sprite.uvs[1] = 0 - offsetY; sprite.uvs[2] = (1 * scaleX) -offsetX; sprite.uvs[3] = 0 - offsetY; sprite.uvs[4] = (1 *scaleX) - offsetX; sprite.uvs[5] = (1 *scaleY) - offsetY; sprite.uvs[6] = 0 - offsetX; sprite.uvs[7] = (1 *scaleY) - offsetY; gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, sprite.uvs) this.renderStrip(sprite, projectionMatrix); } /** * Initializes a strip to be rendered * * @method initStrip * @param strip {Strip} The strip to initialize * @private */ PIXI.WebGLRenderGroup.prototype.initStrip = function(strip) { // build the strip! var gl = this.gl; var shaderProgram = this.shaderProgram; strip._vertexBuffer = gl.createBuffer(); strip._indexBuffer = gl.createBuffer(); strip._uvBuffer = gl.createBuffer(); strip._colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); }
2016rshah/phaser
src/pixi/renderers/webgl/WebGLRenderGroup.js
JavaScript
mit
25,493
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FaUserMd = function FaUserMd(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z' }) ) ); }; exports.default = FaUserMd; module.exports = exports['default'];
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/lib/fa/user-md.js
JavaScript
mit
1,722
module.exports = function(grunt) { "use strict"; var jsFiles = ["Gruntfile.js", "src/**/*.js"]; var htmlfiles = ["src/view/todoList.html", "src/view/todoFooter.html", "src/view/todoCreater.html"]; grunt.initConfig({ jshint: { all: jsFiles, options: { jshintrc: ".jshintrc", jshintignore: ".jshintignore" } }, watch: { css: { options: { livereload: true }, files: ["src/**/*.css"] }, js: { options: { livereload: true }, files: ["src/**/*.js"] }, html: { options: { livereload: true }, files: ["src/**/*.html"], tasks: ["template"] } }, jsbeautifier: { js: { src: jsFiles, options: { config: "jsbeautifier.json" } }, json: { fileTypes: [".json"], src: ["bower.json", "package.json", "jsbeautifier.json"], options: { config: "jsbeautifier.json" } } } }); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-jsbeautifier"); grunt.loadNpmTasks("grunt-contrib-watch"); /* grunt.loadTasks = "tasks"; require("matchdep").filterAll("grunt-*").forEach(grunt.loadNpmTasks); */ grunt.registerTask("template", "Converting HTML templates into JSON", function() { var _ = require("underscore"); var src = ""; htmlfiles.forEach(function(file) { var filetext = grunt.file.read(file).split("\t").join("") .split("\n").join("") .split(">").map(function(v) { return v.trim(); }).join(">"); src = src + "templates[\"" + file.split("/").pop() + "\"] = " + _.template(filetext).source + ";\n"; }); grunt.file.write("src/template.js", "templates = {};" + src); console.log("src/template.js Generated"); }); grunt.registerTask("default", ["jsbeautifier", "jshint"]); };
deepaksisodiya/polymer.js
Gruntfile.js
JavaScript
mit
1,975
'use strict'; var config = browser.params; var UserModel = require(config.serverConfig.root + '/server/api/user/user.model'); describe('Logout View', function() { var login = function(user) { let promise = browser.get(config.baseUrl + '/login'); require('../login/login.po').login(user); return promise; }; var testUser = { name: 'Test User', email: 'test@example.com', password: 'test' }; beforeEach(function() { return UserModel .removeAsync() .then(function() { return UserModel.createAsync(testUser); }) .then(function() { return login(testUser); }); }); after(function() { return UserModel.removeAsync(); }) describe('with local auth', function() { it('should logout a user and redirecting to "/"', function() { var navbar = require('../../components/navbar/navbar.po'); browser.getCurrentUrl().should.eventually.equal(config.baseUrl + '/'); navbar.navbarAccountGreeting.getText().should.eventually.equal('Hello ' + testUser.name); browser.get(config.baseUrl + '/logout'); navbar = require('../../components/navbar/navbar.po'); browser.getCurrentUrl().should.eventually.equal(config.baseUrl + '/'); navbar.navbarAccountGreeting.isDisplayed().should.eventually.equal(false); }); }); });
omarjmh/angularFullStack
e2e/account/logout/logout.spec.js
JavaScript
mit
1,351
var gridOptions = { columnDefs: [ { field: 'country', rowGroup: true, hide: true }, { field: 'athlete', minWidth: 180 }, { field: 'age' }, { field: 'year' }, { field: 'date', minWidth: 150 }, { field: 'sport', minWidth: 150 }, { field: 'gold' }, { field: 'silver' }, { field: 'bronze' }, { field: 'total' } ], defaultColDef: { flex: 1, minWidth: 100, sortable: true, filter: true }, autoGroupColumnDef: { minWidth: 200 }, groupDefaultExpanded: 1, }; function onBtForEachNode() { console.log('### api.forEachNode() ###'); gridOptions.api.forEachNode(this.printNode); } function onBtForEachNodeAfterFilter() { console.log('### api.forEachNodeAfterFilter() ###'); gridOptions.api.forEachNodeAfterFilter(this.printNode); } function onBtForEachNodeAfterFilterAndSort() { console.log('### api.forEachNodeAfterFilterAndSort() ###'); gridOptions.api.forEachNodeAfterFilterAndSort(this.printNode); } function onBtForEachLeafNode() { console.log('### api.forEachLeafNode() ###'); gridOptions.api.forEachLeafNode(this.printNode); } // inScope[printNode] function printNode(node, index) { if (node.group) { console.log(index + ' -> group: ' + node.key); } else { console.log(index + ' -> data: ' + node.data.country + ', ' + node.data.athlete); } } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' }) .then(function(data) { gridOptions.api.setRowData(data.slice(0, 50)); }); });
ceolter/angular-grid
grid-packages/ag-grid-docs/documentation/src/pages/accessing-data/examples/using-for-each/main.js
JavaScript
mit
1,868
define( //begin v1.x content { "dateFormatItem-Ehm": "E h:mm a", "days-standAlone-short": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "months-format-narrow": [ "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." ], "field-second-relative+0": "ขณะนี้", "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-weekday": "วันในสัปดาห์", "dateFormatItem-yQQQ": "QQQ y", "dateFormatItem-yMEd": "E d/M/y", "field-wed-relative+0": "พุธนี้", "field-wed-relative+1": "พุธหน้า", "dateFormatItem-GyMMMEd": "E d MMM G y", "dateFormatItem-MMMEd": "E d MMM", "eraNarrow": [ "ก่อน ค.ศ.", "ก.ส.ศ.", "ค.ศ.", "ส.ศ." ], "field-tue-relative+-1": "อังคารที่แล้ว", "days-format-short": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "dateFormat-long": "d MMMM G y", "field-fri-relative+-1": "ศุกร์ที่แล้ว", "field-wed-relative+-1": "พุธที่แล้ว", "months-format-wide": [ "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" ], "dateTimeFormat-medium": "{1} {0}", "dayPeriods-format-wide-pm": "หลังเที่ยง", "dateFormat-full": "EEEEที่ d MMMM G y", "field-thu-relative+-1": "พฤหัสที่แล้ว", "dateFormatItem-Md": "d/M", "dateFormatItem-yMd": "d/M/y", "field-era": "สมัย", "dateFormatItem-yM": "M/y", "months-standAlone-wide": [ "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" ], "timeFormat-short": "HH:mm", "quarters-format-wide": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "dateFormatItem-yQQQQ": "QQQQ G y", "timeFormat-long": "H นาฬิกา mm นาที ss วินาที z", "field-year": "ปี", "dateFormatItem-yMMM": "MMM y", "field-hour": "ชั่วโมง", "months-format-abbr": [ "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." ], "field-sat-relative+0": "เสาร์นี้", "field-sat-relative+1": "เสาร์หน้า", "timeFormat-full": "H นาฬิกา mm นาที ss วินาที zzzz", "field-day-relative+0": "วันนี้", "field-thu-relative+0": "พฤหัสนี้", "field-day-relative+1": "พรุ่งนี้", "field-thu-relative+1": "พฤหัสหน้า", "dateFormatItem-GyMMMd": "d MMM G y", "field-day-relative+2": "มะรืนนี้", "dateFormatItem-H": "HH", "months-standAlone-abbr": [ "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." ], "quarters-format-abbr": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "quarters-standAlone-wide": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "dateFormatItem-Gy": "G y", "dateFormatItem-M": "L", "days-standAlone-wide": [ "วันอาทิตย์", "วันจันทร์", "วันอังคาร", "วันพุธ", "วันพฤหัสบดี", "วันศุกร์", "วันเสาร์" ], "dateFormatItem-MMMMd": "d MMMM", "timeFormat-medium": "HH:mm:ss", "field-sun-relative+0": "อาทิตย์นี้", "dateFormatItem-Hm": "HH:mm", "field-sun-relative+1": "อาทิตย์หน้า", "quarters-standAlone-abbr": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "eraAbbr": [ "ปีก่อน ค.ศ.", "ค.ศ." ], "field-minute": "นาที", "field-dayperiod": "ช่วงวัน", "days-standAlone-abbr": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "dateFormatItem-d": "d", "dateFormatItem-ms": "mm:ss", "quarters-format-narrow": [ "1", "2", "3", "4" ], "field-day-relative+-1": "เมื่อวาน", "dateFormatItem-h": "h a", "dateTimeFormat-long": "{1} {0}", "field-day-relative+-2": "เมื่อวานซืน", "dateFormatItem-MMMd": "d MMM", "dateFormatItem-MEd": "E d/M", "dateTimeFormat-full": "{1} {0}", "field-fri-relative+0": "ศุกร์นี้", "dateFormatItem-yMMMM": "MMMM G y", "field-fri-relative+1": "ศุกร์หน้า", "field-day": "วัน", "days-format-wide": [ "วันอาทิตย์", "วันจันทร์", "วันอังคาร", "วันพุธ", "วันพฤหัสบดี", "วันศุกร์", "วันเสาร์" ], "field-zone": "เขตเวลา", "dateFormatItem-y": "y", "months-standAlone-narrow": [ "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." ], "field-year-relative+-1": "ปีที่แล้ว", "field-month-relative+-1": "เดือนที่แล้ว", "dateFormatItem-hm": "h:mm a", "days-format-abbr": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "dateFormatItem-yMMMd": "d MMM y", "eraNames": [ "ปีก่อนคริสต์ศักราช", "คริสต์ศักราช" ], "days-format-narrow": [ "อา", "จ", "อ", "พ", "พฤ", "ศ", "ส" ], "days-standAlone-narrow": [ "อา", "จ", "อ", "พ", "พฤ", "ศ", "ส" ], "dateFormatItem-MMM": "LLL", "field-month": "เดือน", "field-tue-relative+0": "อังคารนี้", "field-tue-relative+1": "อังคารหน้า", "dayPeriods-format-wide-am": "ก่อนเที่ยง", "dateFormatItem-MMMMEd": "E d MMMM", "dateFormatItem-EHm": "E HH:mm", "field-mon-relative+0": "จันทร์นี้", "field-mon-relative+1": "จันทร์หน้า", "dateFormat-short": "d/M/yy", "dateFormatItem-EHms": "E HH:mm:ss", "dateFormatItem-Ehms": "E h:mm:ss a", "field-second": "วินาที", "field-sat-relative+-1": "เสาร์ที่แล้ว", "dateFormatItem-yMMMEd": "E d MMM y", "field-sun-relative+-1": "อาทิตย์ที่แล้ว", "field-month-relative+0": "เดือนนี้", "field-month-relative+1": "เดือนหน้า", "dateFormatItem-Ed": "E d", "dateTimeFormats-appendItem-Timezone": "{0} {1}", "field-week": "สัปดาห์", "dateFormat-medium": "d MMM y", "field-year-relative+0": "ปีนี้", "field-week-relative+-1": "สัปดาห์ที่แล้ว", "field-year-relative+1": "ปีหน้า", "dateFormatItem-mmss": "mm:ss", "dateTimeFormat-short": "{1} {0}", "dateFormatItem-Hms": "HH:mm:ss", "dateFormatItem-hms": "h:mm:ss a", "dateFormatItem-GyMMM": "MMM G y", "field-mon-relative+-1": "จันทร์ที่แล้ว", "field-week-relative+0": "สัปดาห์นี้", "field-week-relative+1": "สัปดาห์หน้า" } //end v1.x content );
cdnjs/cdnjs
ajax/libs/dojo/1.16.2/cldr/nls/th/gregorian.js
JavaScript
mit
8,073
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidationRendererCustomAttribute = undefined; var _validationController = require('./validation-controller'); var ValidationRendererCustomAttribute = exports.ValidationRendererCustomAttribute = function () { function ValidationRendererCustomAttribute() { } ValidationRendererCustomAttribute.prototype.created = function created(view) { this.container = view.container; }; ValidationRendererCustomAttribute.prototype.bind = function bind() { this.controller = this.container.get(_validationController.ValidationController); this.renderer = this.container.get(this.value); this.controller.addRenderer(this.renderer); }; ValidationRendererCustomAttribute.prototype.unbind = function unbind() { this.controller.removeRenderer(this.renderer); this.controller = null; this.renderer = null; }; return ValidationRendererCustomAttribute; }();
Zensavona/validation
dist/commonjs/validation-renderer-custom-attribute.js
JavaScript
cc0-1.0
981
var chai = require('chai'); var expect = chai.expect; //var should = chai.should(); var Schema2Msgs = require('./Schema2Msgs'); describe('schema2msgs', function () { it.only('should extract messages from a simple schema', function () { var schema = { schema: { "hello": "World", "test": { title: "me", help: "you" }, "more": { title: "me", help: "you", "validators": "required phone" }, "more": { title: "me", help: "you", validators: ["required", {type: "phone"}, { "type": "required", message: "This field is super required" }] } } } var s2m = new Schema2Msgs(schema, 'schema2msgs'); var result = s2m.messages(); console.log(JSON.stringify((result), null, 3)); console.log(JSON.stringify((schema), null, 3)); expect(result).to.deep.equal({ "schema2msgs.hello.title": "Hello", "schema2msgs.test.title": "me", "schema2msgs.test.help": "you", "schema2msgs.more.title": "me", "schema2msgs.more.help": "you", "validators.required.message": "required", "validators.phone.message": "phone", "schema2msgs.more.validators.required.message": "This field is super required" }); expect(schema).to.deep.equal({ "schema": { "hello": { "type": "World", "title": { "content":"Hello", "g10n": "schema2msgs.hello.title" } }, "test": { "title": { "content": "me", "g10n": "schema2msgs.test.title" }, "help": { "content": "you", "g10n": "schema2msgs.test.help" } }, "more": { "title": { "content": "me", "g10n": "schema2msgs.more.title" }, "help": { "content": "you", "g10n": "schema2msgs.more.help" }, "validators": [ { "type": "required", "g10n": "validators.required.message" }, { "type": "phone", "g10n": "validators.phone.message" }, { "type": "required", "message": { "content": "This field is super required", "g10n": "schema2msgs.more.validators.required.message" } } ] } }}); }); it('should extract messages from a schema with content', function () { var schema = { "test": { "title": [ "{name} took {numPhotos, plural,\n =0 {no photos}\n =1 {one photo}\n other {# photos}\n} on {takenDate, date, long}.\n", { content: false }, { content: [ { content: "All good?" }, "Is good {stuff}?" ] } ], "help": { "content": "Do you like my help?" }, "validators": [{ "type": "supd", "message": { content: "A very custom {..stuff.valid} message" } }, "required"] } } var s2m = new Schema2Msgs(schema, 'schema2msgs'); var result = s2m.messages(); console.log(JSON.stringify((result), null, 3)); console.log(JSON.stringify((schema), null, 3)); expect(result).to.deep.equal({ "schema2msgs.test.title[0]": "{name} took {numPhotos, plural,\n =0 {no photos}\n =1 {one photo}\n other {# photos}\n} on {takenDate, date, long}.\n", "schema2msgs.test.title[2][0]": "All good?", "schema2msgs.test.title[2][1]": "Is good {stuff}?", "schema2msgs.test.help": "Do you like my help?", "schema2msgs.test.validators.supd.message": "A very custom {..stuff.valid} message", "validators.required.message": "required" }); expect(schema).to.deep.equal({ "test": { "title": [ { "content": "{name} took {numPhotos, plural,\n =0 {no photos}\n =1 {one photo}\n other {# photos}\n} on {takenDate, date, long}.\n", "g10n": { "key": "schema2msgs.test.title[0]", "listen": [ "name", "numPhotos", "takenDate" ] } }, { "content": false }, { "content": [ { "content": { "content": "All good?", "g10n": "schema2msgs.test.title[2][0]" } }, { "content": "Is good {stuff}?", "g10n": { "key": "schema2msgs.test.title[2][1]", "listen": [ "stuff" ] } } ] } ], "help": { "content": { "content": "Do you like my help?", "g10n": "schema2msgs.test.help" } }, "validators": [ { "type": "supd", "message": { "content": { "content": "A very custom {..stuff.valid} message", "g10n": { "key": "schema2msgs.test.validators.supd.message", "listen": [ "::stuff:valid" ] } } } }, { "type": "required", "g10n": "validators.required.message" } ] } }); }); it('should extrac messages from subSchema', function () { var schema = { "top": { "type": "Object", "subSchema": { "sub": { "type": "Object", "subSchema": { "sub1": { title: "Hello" } } } } } } var s2m = new Schema2Msgs(schema, 'schema2msgs'); var result = s2m.messages(); console.log(JSON.stringify((result), null, 3)); console.log(JSON.stringify((schema), null, 3)); expect(result).to.deep.equal({ "schema2msgs.top.title": "Top", "schema2msgs.top.sub.title": "Sub", "schema2msgs.top.sub.sub1.title": "Hello" }); expect(schema).to.deep.equal({ "top": { "type": "Object", "subSchema": { "sub": { "type": "Object", "subSchema": { "sub1": { "title": { "content": "Hello", "g10n": "schema2msgs.top.sub.sub1.title" } } }, "title": { "content": "Sub", "g10n": "schema2msgs.top.sub.title" } } }, "title": { "content": "Top", "g10n": "schema2msgs.top.title" } } }); }) });
jspears/subschema-g10n
schema2msgs-test.js
JavaScript
cc0-1.0
9,491
class GalmaCluster extends Cluster{ constructor(params){ super(params); var self = this; //---------------------------------- this.children = []; Loader.objLoader.load('assets/models/clusters/galma-cluster.obj', function(object){ //console.log(object); for(var i = 0; i < object.children.length; i++){ self.children.push(object.children[i]); } self.children[0].material = Materials.m4; self.children[1].material = Materials.m5; self.children[2].material = Materials.m4; self.children[3].material = Materials.m5; object.scale.set(20, 20, 20); self.container.add(object); }); } render(t){ super.render(t); //-------------------------------------------------- } }
zuunduun/demarajdewindoz8
public/js/app/3d-objects/clusters/galma-cluster.js
JavaScript
cc0-1.0
874
import expect from 'expect' import colorsCSS from 'colors.css' import Color from '../src/with-better-colors' describe('colors.css support', () => { it('works as expected', () => { for (const name in colorsCSS) { if (colorsCSS.hasOwnProperty(name)) { expect(Color(name).toString()) .toBe(Color(colorsCSS[name]).toString()) } } }) })
philpl/goethe
test/with-better-colors.js
JavaScript
cc0-1.0
376
var Action = require('./../actions/action.create.js'); var RouteConfig = require('./route.create.config'); var RouteCreate = require('./route.default.js')(Action, RouteConfig);
douglaszuqueto/be-mean-instagram
sistema-mongoose-atomico-promises-events/server/modules/users/routes/index.js
JavaScript
cc0-1.0
178
'use strict'; describe('Controller: EditprefixersCtrl', function () { // load the controller's module beforeEach(module('grafterizerApp')); var EditprefixersCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); EditprefixersCtrl = $controller('EditprefixersCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
dapaas/grafterizer
test/spec/controllers/editprefixers.js
JavaScript
epl-1.0
546
!function(a){var b=a("#upload-button"),c=a("#upload-version-form"),d=c.length&&c.find('input[name="file"]'),e=b.length&&c.length&&d.length;e&&(b.click(function(a){a.preventDefault(),d.click()}),d.on("change",function(){a("body").presideLoadingSheen(!0),c.submit()}))}(presideJQuery),function(a){var b,c,d=a("#version-carousel");d.length&&(c=d.find(".current-version").index(),d.owlCarousel({navigation:!1,slideSpeed:300,paginationSpeed:400,singleItem:!0}),b=d.data("owlCarousel"),b.jumpTo(c))}(presideJQuery); //# sourceMappingURL=_editAsset.min.map
josephpbuarao/Preside-CMS
system/assets/js/admin/specific/assetmanager/editAsset/_81dabbe8.editAsset.min.js
JavaScript
gpl-2.0
549
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (Buffer){ var pbkdf2Sync = require('pbkdf2').pbkdf2Sync var MAX_VALUE = 0x7fffffff // N = Cpu cost, r = Memory cost, p = parallelization cost function scrypt (key, salt, N, r, p, dkLen, progressCallback) { if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2') if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large') if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large') var XY = new Buffer(256 * r) var V = new Buffer(128 * r * N) // pseudo global var B32 = new Int32Array(16) // salsa20_8 var x = new Int32Array(16) // salsa20_8 var _X = new Buffer(64) // blockmix_salsa8 // pseudo global var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256') var tickCallback if (progressCallback) { var totalOps = p * N * 2 var currentOp = 0 tickCallback = function () { ++currentOp // send progress notifications once every 1,000 ops if (currentOp % 1000 === 0) { progressCallback({ current: currentOp, total: totalOps, percent: (currentOp / totalOps) * 100.0 }) } } } for (var i = 0; i < p; i++) { smix(B, i * 128 * r, r, N, V, XY) } return pbkdf2Sync(key, B, 1, dkLen, 'sha256') // all of these functions are actually moved to the top // due to function hoisting function smix (B, Bi, r, N, V, XY) { var Xi = 0 var Yi = 128 * r var i B.copy(XY, Xi, Bi, Bi + Yi) for (i = 0; i < N; i++) { XY.copy(V, i * Yi, Xi, Xi + Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } for (i = 0; i < N; i++) { var offset = Xi + (2 * r - 1) * 64 var j = XY.readUInt32LE(offset) & (N - 1) blockxor(V, j * Yi, XY, Xi, Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } XY.copy(B, Bi, Xi, Xi + Yi) } function blockmix_salsa8 (BY, Bi, Yi, r) { var i arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64) for (i = 0; i < 2 * r; i++) { blockxor(BY, i * 64, _X, 0, 64) salsa20_8(_X) arraycopy(_X, 0, BY, Yi + (i * 64), 64) } for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64) } for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64) } } function R (a, b) { return (a << b) | (a >>> (32 - b)) } function salsa20_8 (B) { var i for (i = 0; i < 16; i++) { B32[i] = (B[i * 4 + 0] & 0xff) << 0 B32[i] |= (B[i * 4 + 1] & 0xff) << 8 B32[i] |= (B[i * 4 + 2] & 0xff) << 16 B32[i] |= (B[i * 4 + 3] & 0xff) << 24 // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js } arraycopy(B32, 0, x, 0, 16) for (i = 8; i > 0; i -= 2) { x[ 4] ^= R(x[ 0] + x[12], 7) x[ 8] ^= R(x[ 4] + x[ 0], 9) x[12] ^= R(x[ 8] + x[ 4], 13) x[ 0] ^= R(x[12] + x[ 8], 18) x[ 9] ^= R(x[ 5] + x[ 1], 7) x[13] ^= R(x[ 9] + x[ 5], 9) x[ 1] ^= R(x[13] + x[ 9], 13) x[ 5] ^= R(x[ 1] + x[13], 18) x[14] ^= R(x[10] + x[ 6], 7) x[ 2] ^= R(x[14] + x[10], 9) x[ 6] ^= R(x[ 2] + x[14], 13) x[10] ^= R(x[ 6] + x[ 2], 18) x[ 3] ^= R(x[15] + x[11], 7) x[ 7] ^= R(x[ 3] + x[15], 9) x[11] ^= R(x[ 7] + x[ 3], 13) x[15] ^= R(x[11] + x[ 7], 18) x[ 1] ^= R(x[ 0] + x[ 3], 7) x[ 2] ^= R(x[ 1] + x[ 0], 9) x[ 3] ^= R(x[ 2] + x[ 1], 13) x[ 0] ^= R(x[ 3] + x[ 2], 18) x[ 6] ^= R(x[ 5] + x[ 4], 7) x[ 7] ^= R(x[ 6] + x[ 5], 9) x[ 4] ^= R(x[ 7] + x[ 6], 13) x[ 5] ^= R(x[ 4] + x[ 7], 18) x[11] ^= R(x[10] + x[ 9], 7) x[ 8] ^= R(x[11] + x[10], 9) x[ 9] ^= R(x[ 8] + x[11], 13) x[10] ^= R(x[ 9] + x[ 8], 18) x[12] ^= R(x[15] + x[14], 7) x[13] ^= R(x[12] + x[15], 9) x[14] ^= R(x[13] + x[12], 13) x[15] ^= R(x[14] + x[13], 18) } for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i] for (i = 0; i < 16; i++) { var bi = i * 4 B[bi + 0] = (B32[i] >> 0 & 0xff) B[bi + 1] = (B32[i] >> 8 & 0xff) B[bi + 2] = (B32[i] >> 16 & 0xff) B[bi + 3] = (B32[i] >> 24 & 0xff) // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js } } // naive approach... going back to loop unrolling may yield additional performance function blockxor (S, Si, D, Di, len) { for (var i = 0; i < len; i++) { D[Di + i] ^= S[Si + i] } } } function arraycopy (src, srcPos, dest, destPos, length) { if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { src.copy(dest, destPos, srcPos, srcPos + length) } else { while (length--) { dest[destPos++] = src[srcPos++] } } } module.exports = scrypt }).call(this,require("buffer").Buffer) },{"buffer":18,"pbkdf2":2}],2:[function(require,module,exports){ (function (Buffer){ var createHmac = require('create-hmac') var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs exports.pbkdf2 = pbkdf2 function pbkdf2 (password, salt, iterations, keylen, digest, callback) { if (typeof digest === 'function') { callback = digest digest = undefined } if (typeof callback !== 'function') { throw new Error('No callback provided to pbkdf2') } var result = pbkdf2Sync(password, salt, iterations, keylen, digest) setTimeout(function () { callback(undefined, result) }) } exports.pbkdf2Sync = pbkdf2Sync function pbkdf2Sync (password, salt, iterations, keylen, digest) { if (typeof iterations !== 'number') { throw new TypeError('Iterations not a number') } if (iterations < 0) { throw new TypeError('Bad iterations') } if (typeof keylen !== 'number') { throw new TypeError('Key length not a number') } if (keylen < 0 || keylen > MAX_ALLOC) { throw new TypeError('Bad key length') } digest = digest || 'sha1' if (!Buffer.isBuffer(password)) password = new Buffer(password, 'binary') if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, 'binary') var hLen var l = 1 var DK = new Buffer(keylen) var block1 = new Buffer(salt.length + 4) salt.copy(block1, 0, 0, salt.length) var r var T for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length) var U = createHmac(digest, password).update(block1).digest() if (!hLen) { hLen = U.length T = new Buffer(hLen) l = Math.ceil(keylen / hLen) r = keylen - (l - 1) * hLen } U.copy(T, 0, 0, hLen) for (var j = 1; j < iterations; j++) { U = createHmac(digest, password).update(U).digest() for (var k = 0; k < hLen; k++) { T[k] ^= U[k] } } var destPos = (i - 1) * hLen var len = (i === l ? r : hLen) T.copy(DK, destPos, 0, len) } return DK } }).call(this,require("buffer").Buffer) },{"buffer":18,"create-hmac":3}],3:[function(require,module,exports){ (function (Buffer){ 'use strict'; var createHash = require('create-hash/browser'); var inherits = require('inherits') var Transform = require('stream').Transform var ZEROS = new Buffer(128) ZEROS.fill(0) function Hmac(alg, key) { Transform.call(this) if (typeof key === 'string') { key = new Buffer(key) } var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 this._alg = alg this._key = key if (key.length > blocksize) { key = createHash(alg).update(key).digest() } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = this._ipad = new Buffer(blocksize) var opad = this._opad = new Buffer(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } this._hash = createHash(alg).update(ipad) } inherits(Hmac, Transform) Hmac.prototype.update = function (data, enc) { this._hash.update(data, enc) return this } Hmac.prototype._transform = function (data, _, next) { this._hash.update(data) next() } Hmac.prototype._flush = function (next) { this.push(this.digest()) next() } Hmac.prototype.digest = function (enc) { var h = this._hash.digest() return createHash(this._alg).update(this._opad).update(h).digest(enc) } module.exports = function createHmac(alg, key) { return new Hmac(alg, key) } }).call(this,require("buffer").Buffer) },{"buffer":18,"create-hash/browser":4,"inherits":16,"stream":37}],4:[function(require,module,exports){ (function (Buffer){ 'use strict'; var inherits = require('inherits') var md5 = require('./md5') var rmd160 = require('ripemd160') var sha = require('sha.js') var Transform = require('stream').Transform function HashNoConstructor(hash) { Transform.call(this) this._hash = hash this.buffers = [] } inherits(HashNoConstructor, Transform) HashNoConstructor.prototype._transform = function (data, _, next) { this.buffers.push(data) next() } HashNoConstructor.prototype._flush = function (next) { this.push(this.digest()) next() } HashNoConstructor.prototype.update = function (data, enc) { if (typeof data === 'string') { data = new Buffer(data, enc) } this.buffers.push(data) return this } HashNoConstructor.prototype.digest = function (enc) { var buf = Buffer.concat(this.buffers) var r = this._hash(buf) this.buffers = null return enc ? r.toString(enc) : r } function Hash(hash) { Transform.call(this) this._hash = hash } inherits(Hash, Transform) Hash.prototype._transform = function (data, enc, next) { if (enc) data = new Buffer(data, enc) this._hash.update(data) next() } Hash.prototype._flush = function (next) { this.push(this._hash.digest()) this._hash = null next() } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { data = new Buffer(data, enc) } this._hash.update(data) return this } Hash.prototype.digest = function (enc) { var outData = this._hash.digest() return enc ? outData.toString(enc) : outData } module.exports = function createHash (alg) { if ('md5' === alg) return new HashNoConstructor(md5) if ('rmd160' === alg) return new HashNoConstructor(rmd160) return new Hash(sha(alg)) } }).call(this,require("buffer").Buffer) },{"./md5":6,"buffer":18,"inherits":16,"ripemd160":7,"sha.js":9,"stream":37}],5:[function(require,module,exports){ (function (Buffer){ 'use strict'; var intSize = 4; var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); var chrsz = 8; function toArray(buf, bigEndian) { if ((buf.length % intSize) !== 0) { var len = buf.length + (intSize - (buf.length % intSize)); buf = Buffer.concat([buf, zeroBuffer], len); } var arr = []; var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; for (var i = 0; i < buf.length; i += intSize) { arr.push(fn.call(buf, i)); } return arr; } function toBuffer(arr, size, bigEndian) { var buf = new Buffer(size); var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; for (var i = 0; i < arr.length; i++) { fn.call(buf, arr[i], i * 4, true); } return buf; } function hash(buf, fn, hashSize, bigEndian) { if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); return toBuffer(arr, hashSize, bigEndian); } exports.hash = hash; }).call(this,require("buffer").Buffer) },{"buffer":18}],6:[function(require,module,exports){ 'use strict'; /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ var helpers = require('./helpers'); /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } module.exports = function md5(buf) { return helpers.hash(buf, core_md5, 16); }; },{"./helpers":5}],7:[function(require,module,exports){ (function (Buffer){ /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // constants table var zl = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ] var zr = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ] var sl = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ] var sr = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ] var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] function bytesToWords (bytes) { var words = [] for (var i = 0, b = 0; i < bytes.length; i++, b += 8) { words[b >>> 5] |= bytes[i] << (24 - b % 32) } return words } function wordsToBytes (words) { var bytes = [] for (var b = 0; b < words.length * 32; b += 8) { bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) } return bytes } function processBlock (H, M, offset) { // swap endian for (var i = 0; i < 16; i++) { var offset_i = offset + i var M_offset_i = M[offset_i] // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ) } // Working variables var al, bl, cl, dl, el var ar, br, cr, dr, er ar = al = H[0] br = bl = H[1] cr = cl = H[2] dr = dl = H[3] er = el = H[4] // computation var t for (i = 0; i < 80; i += 1) { t = (al + M[offset + zl[i]]) | 0 if (i < 16) { t += f1(bl, cl, dl) + hl[0] } else if (i < 32) { t += f2(bl, cl, dl) + hl[1] } else if (i < 48) { t += f3(bl, cl, dl) + hl[2] } else if (i < 64) { t += f4(bl, cl, dl) + hl[3] } else {// if (i<80) { t += f5(bl, cl, dl) + hl[4] } t = t | 0 t = rotl(t, sl[i]) t = (t + el) | 0 al = el el = dl dl = rotl(cl, 10) cl = bl bl = t t = (ar + M[offset + zr[i]]) | 0 if (i < 16) { t += f5(br, cr, dr) + hr[0] } else if (i < 32) { t += f4(br, cr, dr) + hr[1] } else if (i < 48) { t += f3(br, cr, dr) + hr[2] } else if (i < 64) { t += f2(br, cr, dr) + hr[3] } else {// if (i<80) { t += f1(br, cr, dr) + hr[4] } t = t | 0 t = rotl(t, sr[i]) t = (t + er) | 0 ar = er er = dr dr = rotl(cr, 10) cr = br br = t } // intermediate hash value t = (H[1] + cl + dr) | 0 H[1] = (H[2] + dl + er) | 0 H[2] = (H[3] + el + ar) | 0 H[3] = (H[4] + al + br) | 0 H[4] = (H[0] + bl + cr) | 0 H[0] = t } function f1 (x, y, z) { return ((x) ^ (y) ^ (z)) } function f2 (x, y, z) { return (((x) & (y)) | ((~x) & (z))) } function f3 (x, y, z) { return (((x) | (~(y))) ^ (z)) } function f4 (x, y, z) { return (((x) & (z)) | ((y) & (~(z)))) } function f5 (x, y, z) { return ((x) ^ ((y) | (~(z)))) } function rotl (x, n) { return (x << n) | (x >>> (32 - n)) } function ripemd160 (message) { var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] if (typeof message === 'string') { message = new Buffer(message, 'utf8') } var m = bytesToWords(message) var nBitsLeft = message.length * 8 var nBitsTotal = message.length * 8 // Add padding m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32) m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ) for (var i = 0; i < m.length; i += 16) { processBlock(H, m, i) } // swap endian for (i = 0; i < 5; i++) { // shortcut var H_i = H[i] // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00) } var digestbytes = wordsToBytes(H) return new Buffer(digestbytes) } module.exports = ripemd160 }).call(this,require("buffer").Buffer) },{"buffer":18}],8:[function(require,module,exports){ (function (Buffer){ // prototype class for hash functions function Hash (blockSize, finalSize) { this._block = new Buffer(blockSize) this._finalSize = finalSize this._blockSize = blockSize this._len = 0 this._s = 0 } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8' data = new Buffer(data, enc) } var l = this._len += data.length var s = this._s || 0 var f = 0 var buffer = this._block while (s < l) { var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) var ch = (t - f) for (var i = 0; i < ch; i++) { buffer[(s % this._blockSize) + i] = data[i + f] } s += ch f += ch if ((s % this._blockSize) === 0) { this._update(buffer) } } this._s = s return this } Hash.prototype.digest = function (enc) { // Suppose the length of the message M, in bits, is l var l = this._len * 8 // Append the bit 1 to the end of the message this._block[this._len % this._blockSize] = 0x80 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize this._block.fill(0, this._len % this._blockSize + 1) if (l % (this._blockSize * 8) >= this._finalSize * 8) { this._update(this._block) this._block.fill(0) } // to this append the block which is equal to the number l written in binary // TODO: handle case where l is > Math.pow(2, 29) this._block.writeInt32BE(l, this._blockSize - 4) var hash = this._update(this._block) || this._hash() return enc ? hash.toString(enc) : hash } Hash.prototype._update = function () { throw new Error('_update must be implemented by subclass') } module.exports = Hash }).call(this,require("buffer").Buffer) },{"buffer":18}],9:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() var Algorithm = exports[algorithm] if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') return new Algorithm() } exports.sha = require('./sha') exports.sha1 = require('./sha1') exports.sha224 = require('./sha224') exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') },{"./sha":10,"./sha1":11,"./sha224":12,"./sha256":13,"./sha384":14,"./sha512":15}],10:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined * in FIPS PUB 180-1 * This source code is derived from sha1.js of the same repository. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left * operation was added. */ var inherits = require('inherits') var Hash = require('./hash') var W = new Array(80) function Sha () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha, Hash) Sha.prototype.init = function () { this._a = 0x67452301 | 0 this._b = 0xefcdab89 | 0 this._c = 0x98badcfe | 0 this._d = 0x10325476 | 0 this._e = 0xc3d2e1f0 | 0 return this } /* * Bitwise rotate a 32-bit number to the left. */ function rol (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } Sha.prototype._update = function (M) { var W = this._w var a = this._a var b = this._b var c = this._c var d = this._d var e = this._e var j = 0, k /* * SHA-1 has a bitwise rotate left operation. But, SHA is not * function calcW() { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) } */ function calcW () { return W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16] } function loop (w, f) { W[j] = w var t = rol(a, 5) + f + e + w + k e = d d = c c = rol(b, 30) b = a a = t j++ } k = 1518500249 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d)) while (j < 20) loop(calcW(), (b & c) | ((~b) & d)) k = 1859775393 while (j < 40) loop(calcW(), b ^ c ^ d) k = -1894007588 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d)) k = -899497514 while (j < 80) loop(calcW(), b ^ c ^ d) this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha.prototype._hash = function () { var H = new Buffer(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha }).call(this,require("buffer").Buffer) },{"./hash":8,"buffer":18,"inherits":16}],11:[function(require,module,exports){ (function (Buffer){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ var inherits = require('inherits') var Hash = require('./hash') var W = new Array(80) function Sha1 () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha1, Hash) Sha1.prototype.init = function () { this._a = 0x67452301 | 0 this._b = 0xefcdab89 | 0 this._c = 0x98badcfe | 0 this._d = 0x10325476 | 0 this._e = 0xc3d2e1f0 | 0 return this } /* * Bitwise rotate a 32-bit number to the left. */ function rol (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } Sha1.prototype._update = function (M) { var W = this._w var a = this._a var b = this._b var c = this._c var d = this._d var e = this._e var j = 0, k function calcW () { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) } function loop (w, f) { W[j] = w var t = rol(a, 5) + f + e + w + k e = d d = c c = rol(b, 30) b = a a = t j++ } k = 1518500249 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d)) while (j < 20) loop(calcW(), (b & c) | ((~b) & d)) k = 1859775393 while (j < 40) loop(calcW(), b ^ c ^ d) k = -1894007588 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d)) k = -899497514 while (j < 80) loop(calcW(), b ^ c ^ d) this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha1.prototype._hash = function () { var H = new Buffer(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha1 }).call(this,require("buffer").Buffer) },{"./hash":8,"buffer":18,"inherits":16}],12:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Sha256 = require('./sha256') var Hash = require('./hash') var W = new Array(64) function Sha224 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha224, Sha256) Sha224.prototype.init = function () { this._a = 0xc1059ed8 | 0 this._b = 0x367cd507 | 0 this._c = 0x3070dd17 | 0 this._d = 0xf70e5939 | 0 this._e = 0xffc00b31 | 0 this._f = 0x68581511 | 0 this._g = 0x64f98fa7 | 0 this._h = 0xbefa4fa4 | 0 return this } Sha224.prototype._hash = function () { var H = new Buffer(28) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) return H } module.exports = Sha224 }).call(this,require("buffer").Buffer) },{"./hash":8,"./sha256":13,"buffer":18,"inherits":16}],13:[function(require,module,exports){ (function (Buffer){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Hash = require('./hash') var K = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 ] var W = new Array(64) function Sha256 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha256, Hash) Sha256.prototype.init = function () { this._a = 0x6a09e667 | 0 this._b = 0xbb67ae85 | 0 this._c = 0x3c6ef372 | 0 this._d = 0xa54ff53a | 0 this._e = 0x510e527f | 0 this._f = 0x9b05688c | 0 this._g = 0x1f83d9ab | 0 this._h = 0x5be0cd19 | 0 return this } function S (X, n) { return (X >>> n) | (X << (32 - n)) } function R (X, n) { return (X >>> n) } function Ch (x, y, z) { return ((x & y) ^ ((~x) & z)) } function Maj (x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)) } function Sigma0256 (x) { return (S(x, 2) ^ S(x, 13) ^ S(x, 22)) } function Sigma1256 (x) { return (S(x, 6) ^ S(x, 11) ^ S(x, 25)) } function Gamma0256 (x) { return (S(x, 7) ^ S(x, 18) ^ R(x, 3)) } function Gamma1256 (x) { return (S(x, 17) ^ S(x, 19) ^ R(x, 10)) } Sha256.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 var f = this._f | 0 var g = this._g | 0 var h = this._h | 0 var j = 0 function calcW () { return Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16] } function loop (w) { W[j] = w var T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w var T2 = Sigma0256(a) + Maj(a, b, c) h = g g = f f = e e = d + T1 d = c c = b b = a a = T1 + T2 j++ } while (j < 16) loop(M.readInt32BE(j * 4)) while (j < 64) loop(calcW()) this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 this._f = (f + this._f) | 0 this._g = (g + this._g) | 0 this._h = (h + this._h) | 0 } Sha256.prototype._hash = function () { var H = new Buffer(32) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) H.writeInt32BE(this._h, 28) return H } module.exports = Sha256 }).call(this,require("buffer").Buffer) },{"./hash":8,"buffer":18,"inherits":16}],14:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var SHA512 = require('./sha512') var Hash = require('./hash') var W = new Array(160) function Sha384 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha384, SHA512) Sha384.prototype.init = function () { this._a = 0xcbbb9d5d | 0 this._b = 0x629a292a | 0 this._c = 0x9159015a | 0 this._d = 0x152fecd8 | 0 this._e = 0x67332667 | 0 this._f = 0x8eb44a87 | 0 this._g = 0xdb0c2e0d | 0 this._h = 0x47b5481d | 0 this._al = 0xc1059ed8 | 0 this._bl = 0x367cd507 | 0 this._cl = 0x3070dd17 | 0 this._dl = 0xf70e5939 | 0 this._el = 0xffc00b31 | 0 this._fl = 0x68581511 | 0 this._gl = 0x64f98fa7 | 0 this._hl = 0xbefa4fa4 | 0 return this } Sha384.prototype._hash = function () { var H = new Buffer(48) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._a, this._al, 0) writeInt64BE(this._b, this._bl, 8) writeInt64BE(this._c, this._cl, 16) writeInt64BE(this._d, this._dl, 24) writeInt64BE(this._e, this._el, 32) writeInt64BE(this._f, this._fl, 40) return H } module.exports = Sha384 }).call(this,require("buffer").Buffer) },{"./hash":8,"./sha512":15,"buffer":18,"inherits":16}],15:[function(require,module,exports){ (function (Buffer){ var inherits = require('inherits') var Hash = require('./hash') var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] var W = new Array(160) function Sha512 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha512, Hash) Sha512.prototype.init = function () { this._a = 0x6a09e667 | 0 this._b = 0xbb67ae85 | 0 this._c = 0x3c6ef372 | 0 this._d = 0xa54ff53a | 0 this._e = 0x510e527f | 0 this._f = 0x9b05688c | 0 this._g = 0x1f83d9ab | 0 this._h = 0x5be0cd19 | 0 this._al = 0xf3bcc908 | 0 this._bl = 0x84caa73b | 0 this._cl = 0xfe94f82b | 0 this._dl = 0x5f1d36f1 | 0 this._el = 0xade682d1 | 0 this._fl = 0x2b3e6c1f | 0 this._gl = 0xfb41bd6b | 0 this._hl = 0x137e2179 | 0 return this } function S (X, Xl, n) { return (X >>> n) | (Xl << (32 - n)) } function Ch (x, y, z) { return ((x & y) ^ ((~x) & z)) } function Maj (x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)) } Sha512.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 var f = this._f | 0 var g = this._g | 0 var h = this._h | 0 var al = this._al | 0 var bl = this._bl | 0 var cl = this._cl | 0 var dl = this._dl | 0 var el = this._el | 0 var fl = this._fl | 0 var gl = this._gl | 0 var hl = this._hl | 0 var i = 0, j = 0 var Wi, Wil function calcW () { var x = W[j - 15 * 2] var xl = W[j - 15 * 2 + 1] var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7) var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7) x = W[j - 2 * 2] xl = W[j - 2 * 2 + 1] var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6) var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6) // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[j - 7 * 2] var Wi7l = W[j - 7 * 2 + 1] var Wi16 = W[j - 16 * 2] var Wi16l = W[j - 16 * 2 + 1] Wil = gamma0l + Wi7l Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0) Wil = Wil + gamma1l Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0) Wil = Wil + Wi16l Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0) } function loop () { W[j] = Wi W[j + 1] = Wil var maj = Maj(a, b, c) var majl = Maj(al, bl, cl) var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7) var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7) var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9) var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9) // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[j] var Kil = K[j + 1] var ch = Ch(e, f, g) var chl = Ch(el, fl, gl) var t1l = hl + sigma1l var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0) t1l = t1l + chl t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0) t1l = t1l + Kil t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0) t1l = t1l + Wil t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0) // t2 = sigma0 + maj var t2l = sigma0l + majl var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0) h = g hl = gl g = f gl = fl f = e fl = el el = (dl + t1l) | 0 e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0 d = c dl = cl c = b cl = bl b = a bl = al al = (t1l + t2l) | 0 a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0 i++ j += 2 } while (i < 16) { Wi = M.readInt32BE(j * 4) Wil = M.readInt32BE(j * 4 + 4) loop() } while (i < 80) { calcW() loop() } this._al = (this._al + al) | 0 this._bl = (this._bl + bl) | 0 this._cl = (this._cl + cl) | 0 this._dl = (this._dl + dl) | 0 this._el = (this._el + el) | 0 this._fl = (this._fl + fl) | 0 this._gl = (this._gl + gl) | 0 this._hl = (this._hl + hl) | 0 this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0 this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0 this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0 this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0 this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0 this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0 this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0 this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0 } Sha512.prototype._hash = function () { var H = new Buffer(64) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._a, this._al, 0) writeInt64BE(this._b, this._bl, 8) writeInt64BE(this._c, this._cl, 16) writeInt64BE(this._d, this._dl, 24) writeInt64BE(this._e, this._el, 32) writeInt64BE(this._f, this._fl, 40) writeInt64BE(this._g, this._gl, 48) writeInt64BE(this._h, this._hl, 56) return H } module.exports = Sha512 }).call(this,require("buffer").Buffer) },{"./hash":8,"buffer":18,"inherits":16}],16:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],17:[function(require,module,exports){ },{}],18:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('is-array') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } this.length = 0 this.parent = undefined // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined' && object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = String(string) if (string.length === 0) return 0 switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': return string.length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return string.length * 2 case 'hex': return string.length >>> 1 case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'base64': return base64ToBytes(string).length default: return string.length } } Buffer.byteLength = byteLength // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function toString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = value return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = value } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = value return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + targetStart] = this[i + start] } } else { target._set(this.subarray(start, start + len), targetStart) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function toArrayBuffer () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function _augment (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array set method before overwriting arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.indexOf = BP.indexOf arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] var i = 0 for (; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (leadSurrogate) { // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } else { // valid surrogate pair codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 leadSurrogate = null } } else { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else { // valid lead leadSurrogate = codePoint continue } } } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = null } // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x200000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } },{"base64-js":19,"ieee754":20,"is-array":21}],19:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],20:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],21:[function(require,module,exports){ /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; },{}],22:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],23:[function(require,module,exports){ arguments[4][16][0].apply(exports,arguments) },{"dup":16}],24:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],25:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],26:[function(require,module,exports){ module.exports = require("./lib/_stream_duplex.js") },{"./lib/_stream_duplex.js":27}],27:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. module.exports = Duplex; /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } /*</replacement>*/ /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); forEach(objectKeys(Writable.prototype), function(method) { if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; }); function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(this.end.bind(this)); } function forEach (xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } }).call(this,require('_process')) },{"./_stream_readable":29,"./_stream_writable":31,"_process":25,"core-util-is":32,"inherits":23}],28:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":30,"core-util-is":32,"inherits":23}],29:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // 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. module.exports = Readable; /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('buffer').Buffer; /*</replacement>*/ Readable.ReadableState = ReadableState; var EE = require('events').EventEmitter; /*<replacement>*/ if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ var Stream = require('stream'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var StringDecoder; /*<replacement>*/ var debug = require('util'); if (debug && debug.debuglog) { debug = debug.debuglog('stream'); } else { debug = function () {}; } /*</replacement>*/ util.inherits(Readable, Stream); function ReadableState(options, stream) { var Duplex = require('./_stream_duplex'); options = options || {}; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var defaultHwm = options.objectMode ? 16 : 16 * 1024; this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; // cast to ints. this.highWaterMark = ~~this.highWaterMark; this.buffer = []; this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen // after read()ing all the bytes and not getting any pushback. this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { var Duplex = require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; Stream.call(this); } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; if (util.isString(chunk) && !state.objectMode) { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); encoding = ''; } } return readableAddChunk(this, state, chunk, encoding, false); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function(chunk) { var state = this._readableState; return readableAddChunk(this, state, chunk, '', true); }; function readableAddChunk(stream, state, chunk, encoding, addToFront) { var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (util.isNullOrUndefined(chunk)) { state.reading = false; if (!state.ended) onEofChunk(stream, state); } else if (state.objectMode || chunk && chunk.length > 0) { if (state.ended && !addToFront) { var e = new Error('stream.push() after EOF'); stream.emit('error', e); } else if (state.endEmitted && addToFront) { var e = new Error('stream.unshift() after end event'); stream.emit('error', e); } else { if (state.decoder && !addToFront && !encoding) chunk = state.decoder.write(chunk); if (!addToFront) state.reading = false; // if we want the data now, just emit it. if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk); else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } } else if (!addToFront) { state.reading = false; } return needMoreData(state); } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } // backwards compatibility. Readable.prototype.setEncoding = function(enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 128MB var MAX_HWM = 0x800000; function roundUpToNextPowerOf2(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 n--; for (var p = 1; p < 32; p <<= 1) n |= n >> p; n++; } return n; } function howMuchToRead(n, state) { if (state.length === 0 && state.ended) return 0; if (state.objectMode) return n === 0 ? 0 : 1; if (isNaN(n) || util.isNull(n)) { // only flow one buffer at a time if (state.flowing && state.buffer.length) return state.buffer[0].length; else return state.length; } if (n <= 0) return 0; // If we're asking for more than the target buffer level, // then raise the water mark. Bump up to the next highest // power of 2, to prevent increasing it excessively in tiny // amounts. if (n > state.highWaterMark) state.highWaterMark = roundUpToNextPowerOf2(n); // don't have that much. return null, unless we've ended. if (n > state.length) { if (!state.ended) { state.needReadable = true; return 0; } else return state.length; } return n; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function(n) { debug('read', n); var state = this._readableState; var nOrig = n; if (!util.isNumber(n) || n > 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this); else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; } // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (doRead && !state.reading) n = howMuchToRead(nOrig, state); var ret; if (n > 0) ret = fromList(n, state); else ret = null; if (util.isNull(ret)) { state.needReadable = true; n = 0; } state.length -= n; // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (state.length === 0 && !state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended && state.length === 0) endReadable(this); if (!util.isNull(ret)) this.emit('data', ret); return ret; }; function chunkInvalid(state, chunk) { var er = null; if (!util.isBuffer(chunk) && !util.isString(chunk) && !util.isNullOrUndefined(chunk) && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } function onEofChunk(stream, state) { if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) process.nextTick(function() { emitReadable_(stream); }); else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(function() { maybeReadMore_(stream, state); }); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function(n) { this.emit('error', new Error('not implemented')); }; Readable.prototype.pipe = function(dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : cleanup; if (state.endEmitted) process.nextTick(endFn); else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable) { debug('onunpipe'); if (readable === src) { cleanup(); } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', cleanup); src.removeListener('data', ondata); // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } src.on('data', ondata); function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); if (false === ret) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EE.listenerCount(dest, 'error') === 0) dest.emit('error', er); } // This is a brutally ugly hack to make sure that our error handler // is attached before any userland ones. NEVER DO THIS. if (!dest._events || !dest._events.error) dest.on('error', onerror); else if (isArray(dest._events.error)) dest._events.error.unshift(onerror); else dest._events.error = [onerror, dest._events.error]; // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function(dest) { var state = this._readableState; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) dests[i].emit('unpipe', this); return this; } // try to find the right one. var i = indexOf(state.pipes, dest); if (i === -1) return this; state.pipes.splice(i, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function(ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); // If listening to data, and it has not explicitly been paused, // then call resume to start the flow of data on the next tick. if (ev === 'data' && false !== this._readableState.flowing) { this.resume(); } if (ev === 'readable' && this.readable) { var state = this._readableState; if (!state.readableListening) { state.readableListening = true; state.emittedReadable = false; state.needReadable = true; if (!state.reading) { var self = this; process.nextTick(function() { debug('readable nexttick read 0'); self.read(0); }); } else if (state.length) { emitReadable(this, state); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function() { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; if (!state.reading) { debug('resume read 0'); this.read(0); } resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; process.nextTick(function() { resume_(stream, state); }); } } function resume_(stream, state) { state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function() { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); if (state.flowing) { do { var chunk = stream.read(); } while (null !== chunk && state.flowing); } } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function(stream) { var state = this._readableState; var paused = false; var self = this; stream.on('end', function() { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); } self.push(null); }); stream.on('data', function(chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); if (!chunk || !state.objectMode && !chunk.length) return; var ret = self.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { this[i] = function(method) { return function() { return stream[method].apply(stream, arguments); }}(i); } } // proxy certain important events. var events = ['error', 'close', 'destroy', 'pause', 'resume']; forEach(events, function(ev) { stream.on(ev, self.emit.bind(self, ev)); }); // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function(n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return self; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. function fromList(n, state) { var list = state.buffer; var length = state.length; var stringMode = !!state.decoder; var objectMode = !!state.objectMode; var ret; // nothing in the list, definitely empty. if (list.length === 0) return null; if (length === 0) ret = null; else if (objectMode) ret = list.shift(); else if (!n || n >= length) { // read it all, truncate the array. if (stringMode) ret = list.join(''); else ret = Buffer.concat(list, length); list.length = 0; } else { // read just some of it. if (n < list[0].length) { // just take a part of the first list item. // slice is the same for buffers and strings. var buf = list[0]; ret = buf.slice(0, n); list[0] = buf.slice(n); } else if (n === list[0].length) { // first list is a perfect match ret = list.shift(); } else { // complex case. // we have enough to cover it, but it spans past the first buffer. if (stringMode) ret = ''; else ret = new Buffer(n); var c = 0; for (var i = 0, l = list.length; i < l && c < n; i++) { var buf = list[0]; var cpy = Math.min(n - c, buf.length); if (stringMode) ret += buf.slice(0, cpy); else buf.copy(ret, c, 0, cpy); if (cpy < buf.length) list[0] = buf.slice(cpy); else list.shift(); c += cpy; } } } return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('endReadable called on non-empty stream'); if (!state.endEmitted) { state.ended = true; process.nextTick(function() { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } }); } } function forEach (xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf (xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process')) },{"./_stream_duplex":27,"_process":25,"buffer":18,"core-util-is":32,"events":22,"inherits":23,"isarray":24,"stream":37,"string_decoder/":38,"util":17}],30:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function TransformState(options, stream) { this.afterTransform = function(er, data) { return afterTransform(stream, er, data); }; this.needTransform = false; this.transforming = false; this.writecb = null; this.writechunk = null; } function afterTransform(stream, er, data) { var ts = stream._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); ts.writechunk = null; ts.writecb = null; if (!util.isNullOrUndefined(data)) stream.push(data); if (cb) cb(er); var rs = stream._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { stream._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = new TransformState(options, this); // when the writable side finishes, then flush out anything remaining. var stream = this; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; this.once('prefinish', function() { if (util.isFunction(this._flush)) this._flush(function(er) { done(stream, er); }); else done(stream); }); } Transform.prototype.push = function(chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function(chunk, encoding, cb) { throw new Error('not implemented'); }; Transform.prototype._write = function(chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function(n) { var ts = this._transformState; if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; function done(stream, er) { if (er) return stream.emit('error', er); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided var ws = stream._writableState; var ts = stream._transformState; if (ws.length) throw new Error('calling transform done when ws.length != 0'); if (ts.transforming) throw new Error('calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":27,"core-util-is":32,"inherits":23}],31:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // A bit simpler than readable streams. // Implement an async ._write(chunk, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; /*<replacement>*/ var Buffer = require('buffer').Buffer; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var Stream = require('stream'); util.inherits(Writable, Stream); function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; } function WritableState(options, stream) { var Duplex = require('./_stream_duplex'); options = options || {}; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var defaultHwm = options.objectMode ? 16 : 16 * 1024; this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // cast to ints. this.highWaterMark = ~~this.highWaterMark; this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function(er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.buffer = []; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; } function Writable(options) { var Duplex = require('./_stream_duplex'); // Writable ctor is applied to Duplexes, though they're not // instanceof Writable, they're instanceof Readable. if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); this._writableState = new WritableState(options, this); // legacy. this.writable = true; Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function() { this.emit('error', new Error('Cannot pipe. Not readable.')); }; function writeAfterEnd(stream, state, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); process.nextTick(function() { cb(er); }); } // If we get something that is not a buffer, string, null, or undefined, // and we're not in objectMode, then that's an error. // Otherwise stream chunks are all considered to be of length=1, and the // watermarks determine how many objects to keep in the buffer, rather than // how many bytes or characters. function validChunk(stream, state, chunk, cb) { var valid = true; if (!util.isBuffer(chunk) && !util.isString(chunk) && !util.isNullOrUndefined(chunk) && !state.objectMode) { var er = new TypeError('Invalid non-string/buffer chunk'); stream.emit('error', er); process.nextTick(function() { cb(er); }); valid = false; } return valid; } Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; if (util.isFunction(encoding)) { cb = encoding; encoding = null; } if (util.isBuffer(chunk)) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; if (!util.isFunction(cb)) cb = function() {}; if (state.ended) writeAfterEnd(this, state, cb); else if (validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function() { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function() { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.buffer.length) clearBuffer(this, state); } }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && util.isString(chunk)) { chunk = new Buffer(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); if (util.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) state.buffer.push(new WriteReq(chunk, encoding, cb)); else doWrite(stream, state, false, len, chunk, encoding, cb); return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite); else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { if (sync) process.nextTick(function() { state.pendingcb--; cb(er); }); else { state.pendingcb--; cb(er); } stream._writableState.errorEmitted = true; stream.emit('error', er); } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb); else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(stream, state); if (!finished && !state.corked && !state.bufferProcessing && state.buffer.length) { clearBuffer(stream, state); } if (sync) { process.nextTick(function() { afterWrite(stream, state, finished, cb); }); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; if (stream._writev && state.buffer.length > 1) { // Fast case, write everything using _writev() var cbs = []; for (var c = 0; c < state.buffer.length; c++) cbs.push(state.buffer[c].callback); // count the one we are adding, as well. // TODO(isaacs) clean this up state.pendingcb++; doWrite(stream, state, true, state.length, state.buffer, '', function(err) { for (var i = 0; i < cbs.length; i++) { state.pendingcb--; cbs[i](err); } }); // Clear buffer state.buffer = []; } else { // Slow case, write chunks one-by-one for (var c = 0; c < state.buffer.length; c++) { var entry = state.buffer[c]; var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { c++; break; } } if (c < state.buffer.length) state.buffer = state.buffer.slice(c); else state.buffer.length = 0; } state.bufferProcessing = false; } Writable.prototype._write = function(chunk, encoding, cb) { cb(new Error('not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function(chunk, encoding, cb) { var state = this._writableState; if (util.isFunction(chunk)) { cb = chunk; chunk = null; encoding = null; } else if (util.isFunction(encoding)) { cb = encoding; encoding = null; } if (!util.isNullOrUndefined(chunk)) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(stream, state) { return (state.ending && state.length === 0 && !state.finished && !state.writing); } function prefinish(stream, state) { if (!state.prefinished) { state.prefinished = true; stream.emit('prefinish'); } } function finishMaybe(stream, state) { var need = needFinish(stream, state); if (need) { if (state.pendingcb === 0) { prefinish(stream, state); state.finished = true; stream.emit('finish'); } else prefinish(stream, state); } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb); else stream.once('finish', cb); } state.ended = true; } }).call(this,require('_process')) },{"./_stream_duplex":27,"_process":25,"buffer":18,"core-util-is":32,"inherits":23,"stream":37}],32:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; function isBuffer(arg) { return Buffer.isBuffer(arg); } exports.isBuffer = isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,require("buffer").Buffer) },{"buffer":18}],33:[function(require,module,exports){ module.exports = require("./lib/_stream_passthrough.js") },{"./lib/_stream_passthrough.js":28}],34:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = require('stream'); exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":27,"./lib/_stream_passthrough.js":28,"./lib/_stream_readable.js":29,"./lib/_stream_transform.js":30,"./lib/_stream_writable.js":31,"stream":37}],35:[function(require,module,exports){ module.exports = require("./lib/_stream_transform.js") },{"./lib/_stream_transform.js":30}],36:[function(require,module,exports){ module.exports = require("./lib/_stream_writable.js") },{"./lib/_stream_writable.js":31}],37:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. module.exports = Stream; var EE = require('events').EventEmitter; var inherits = require('inherits'); inherits(Stream, EE); Stream.Readable = require('readable-stream/readable.js'); Stream.Writable = require('readable-stream/writable.js'); Stream.Duplex = require('readable-stream/duplex.js'); Stream.Transform = require('readable-stream/transform.js'); Stream.PassThrough = require('readable-stream/passthrough.js'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; },{"events":22,"inherits":23,"readable-stream/duplex.js":26,"readable-stream/passthrough.js":33,"readable-stream/readable.js":34,"readable-stream/transform.js":35,"readable-stream/writable.js":36}],38:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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. var Buffer = require('buffer').Buffer; var isBufferEncoding = Buffer.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } } function assertEncoding(encoding) { if (encoding && !isBufferEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. CESU-8 is handled as part of the UTF-8 encoding. // // @TODO Handling all encodings inside a single object makes it very difficult // to reason about this code, so it should be split up in the future. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code // points as used by CESU-8. var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes this.surrogateSize = 3; break; case 'ucs2': case 'utf16le': // UTF-16 represents each of Surrogate Pair by 2-bytes this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; case 'base64': // Base-64 stores 3 bytes in 4 chars, and pads the remainder. this.surrogateSize = 3; this.detectIncompleteChar = base64DetectIncompleteChar; break; default: this.write = passThroughWrite; return; } // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. this.charLength = 0; }; // write decodes the given buffer and returns it as JS string that is // guaranteed to not contain any partial multi-byte characters. Any partial // character found at the end of the buffer is buffered up, and will be // returned when calling write again with the remaining bytes. // // Note: Converting a Buffer containing an orphan surrogate to a String // currently works, but converting a String to a Buffer (via `new Buffer`, or // Buffer#write) will replace incomplete surrogates with the unicode // replacement character. See https://codereview.chromium.org/121173009/ . StringDecoder.prototype.write = function(buffer) { var charStr = ''; // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char var available = (buffer.length >= this.charLength - this.charReceived) ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer buffer.copy(this.charBuffer, this.charReceived, 0, available); this.charReceived += available; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } // remove bytes belonging to the current character from the buffer buffer = buffer.slice(available, buffer.length); // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; charStr = ''; continue; } this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char if (buffer.length === 0) { return charStr; } break; } // determine and set charLength / charReceived this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); end -= this.charReceived; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); buffer.copy(this.charBuffer, 0, 0, size); return charStr.substring(0, end); } // or just emit the charStr return charStr; }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at // the end of the given buffer. If so, it sets this.charLength to the byte // length that character, and sets this.charReceived to the number of bytes // that are available for this character. StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an // incomplete char. for (; i > 0; i--) { var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description // 110XXXXX if (i == 1 && c >> 5 == 0x06) { this.charLength = 2; break; } // 1110XXXX if (i <= 2 && c >> 4 == 0x0E) { this.charLength = 3; break; } // 11110XXX if (i <= 3 && c >> 3 == 0x1E) { this.charLength = 4; break; } } this.charReceived = i; }; StringDecoder.prototype.end = function(buffer) { var res = ''; if (buffer && buffer.length) res = this.write(buffer); if (this.charReceived) { var cr = this.charReceived; var buf = this.charBuffer; var enc = this.encoding; res += buf.slice(0, cr).toString(enc); } return res; }; function passThroughWrite(buffer) { return buffer.toString(this.encoding); } function utf16DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 2; this.charLength = this.charReceived ? 2 : 0; } function base64DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 3; this.charLength = this.charReceived ? 3 : 0; } },{"buffer":18}]},{},[1]);
nebulak/privatecircle
static/scryptsy/bundle.js
JavaScript
gpl-2.0
167,439
(function($, window) { var dojo = { postSnippet: function (snippet, baseUrl) { snippet = dojo.fixCDNReferences(snippet); snippet = dojo.addBaseRedirectTag(snippet, baseUrl); snippet = dojo.addConsoleScript(snippet); snippet = dojo.fixLineEndings(snippet); snippet = dojo.replaceCommon(snippet, window.kendoCommonFile); snippet = dojo.replaceTheme(snippet, window.kendoTheme); snippet = window.btoa(encodeURIComponent(snippet)); var form = $('<form method="post" action="' + dojo.configuration.url + '" target="_blank" />').hide().appendTo(document.body); $("<input name='snippet'>").val(snippet).appendTo(form); if ($("#mobile-application-container").length) { $("<input name='mode'>").val("ios7").appendTo(form); } form.submit(); }, replaceCommon: function(code, common) { if (common) { code = code.replace(/common\.min\.css/, common + ".min.css"); } return code; }, replaceTheme: function(code, theme) { if (theme) { code = code.replace(/default\.min\.css/g, theme + ".min.css"); } return code; }, addBaseRedirectTag: function (code, baseUrl) { return code.replace( '<head>', '<head>\n' + ' <base href="' + baseUrl + '">\n' + ' <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>' ); }, addConsoleScript: function (code) { if (code.indexOf("kendoConsole") !== -1) { var styleReference = ' <link rel="stylesheet" href="../content/shared/styles/examples-offline.css">\n'; var scriptReference = ' <script src="../content/shared/js/console.js"></script>\n'; code = code.replace("</head>", styleReference + scriptReference + "</head>"); } return code; }, fixLineEndings: function (code) { return code.replace(/\n/g, "&#10;"); }, fixCDNReferences: function (code) { return code.replace(/<head>[\s\S]*<\/head>/, function (match) { return match .replace(/src="\/?/g, "src=\"" + dojo.configuration.cdnRoot + "/") .replace(/href="\/?/g, "href=\"" + dojo.configuration.cdnRoot + "/"); }); } }; $.extend(window, { dojo: dojo }); })(jQuery, window);
cleitonalmeida1/EstagioAZ
assets/vendor/kendoui/examples/content/shared/js/kendo-dojo.js
JavaScript
gpl-2.0
2,655
/*! * a-tools 1.5.2 * * Copyright (c) 2009 Andrey Kramarev(andrey.kramarev[at]ampparit.com), Ampparit Inc. (www.ampparit.com) * Licensed under the MIT license. * http://www.ampparit.fi/a-tools/license.txt * * Basic usage: <textarea></textarea> <input type="text" /> // Get current selection var sel = $("textarea").getSelection() // Replace current selection $("input").replaceSelection("foo"); // Count characters alert($("textarea").countCharacters()); // Set max length without callback function $("textarea").setMaxLength(7); // Set max length with callback function which will be called when limit is exceeded $("textarea").setMaxLength(10, function() { alert("hello") }); // Removing limit: $("textarea").setMaxLength(-1); // Insert text at current caret position $("#textarea").insertAtCaretPos("hello"); // Set caret position (1 = beginning, -1 = end) $("#textArea").setCaretPos(10); // Set Selection $("#textArea").setSelection(10,15); */ // Modified by Logue 2011/09/23 (function($, window, document, undef){ var caretPositionAmp = new Array(); $(document).ready(function(){ if(navigator.appName == "Microsoft Internet Explorer") { obj = document.getElementsByTagName('TEXTAREA'); var input; var i = 0; for (var i = 0; i < obj.length; i++) { input = obj[i]; caretPositionAmp[i] = input.value.length; input.onmouseup = function() { // for IE because it loses caret position when focus changed input = document.activeElement; for (var i = 0; i < obj.length; i++) { if (obj[i] == input) { break; } } input.focus(); var s = document.selection.createRange(); var re = input.createTextRange(); var rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); caretPositionAmp[i] = rc.text.length; } input.onkeyup = function() { input = document.activeElement; for (var i = 0; i < obj.length; i++) { if (obj[i] == input) { break; } } input.focus(); var s = document.selection.createRange(); var re = input.createTextRange(); var rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); caretPositionAmp[i] = rc.text.length; } } } }); jQuery.fn.extend({ getSelection: function() { // function for getting selection, and position of the selected text var input = this.jquery ? this[0] : this; var start; var end; var part; var number = 0; input.onmousedown = function() { // for IE if (document.selection && typeof(input.selectionStart) != "number") { document.selection.empty(); } else { window.getSelection().removeAllRanges(); } } if (document.selection) { // part for IE and Opera var s = document.selection.createRange(); var minus = 0; var position = 0; var minusEnd = 0; var re; var rc; var obj = document.getElementsByTagName('TEXTAREA'); for (var pos = 0; pos < obj.length; pos++) { if (obj[pos] == input) { break; } } if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } if (s.text) { part = s.text; // OPERA support if (typeof(input.selectionStart) == "number") { start = input.selectionStart; end = input.selectionEnd; // return null if the selected text not from the needed area if (start == end) { return { start: start, end: end, text: s.text, length: end - start }; } } else { // IE support re = input.createTextRange(); rc = re.duplicate(); firstRe = re.text; re.moveToBookmark(s.getBookmark()); secondRe = re.text; rc.setEndPoint("EndToStart", re); // return null if the selectyed text not from the needed area if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) { return { start: caretPositionAmp[pos], end: caretPositionAmp[pos], text: "", length: 0 }; } start = rc.text.length; end = rc.text.length + s.text.length; } // remove all EOL to have the same start and end positons as in MOZILLA if (number > 0) { for (var i = 0; i <= number; i++) { var w = input.value.indexOf("\n", position); if (w != -1 && w < start) { position = w + 1; minus++; minusEnd = minus; } else if (w != -1 && w >= start && w <= end) { if (w == start + 1) { minus--; minusEnd--; position = w + 1; continue; } position = w + 1; minusEnd++; } else { i = number; } } } if (s.text.indexOf("\n", 0) == 1) { minusEnd = minusEnd + 2; } start = start - minus; end = end - minusEnd; return { start: start, end: end, text: s.text, length: end - start }; } input.focus (); if (typeof(input.selectionStart) == "number") { start = input.selectionStart; } else { s = document.selection.createRange(); re = input.createTextRange(); rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); start = rc.text.length; } if (number > 0) { for (var i = 0; i <= number; i++) { var w = input.value.indexOf("\n", position); if (w != -1 && w < start) { position = w + 1; minus++; } else { i = number; } } } start = start - minus; if (start == 0 && typeof(input.selectionStart) != "number") { start = caretPositionAmp[pos]; end = caretPositionAmp[pos]; } return { start: start, end: start, text: s.text, length: 0 }; } else if (typeof(input.selectionStart) == "number" ) { start = input.selectionStart; end = input.selectionEnd; part = input.value.substring(input.selectionStart, input.selectionEnd); return { start: start, end: end, text: part, length: end - start }; } else { return { start: undefined, end: undefined, text: undefined, length: undefined }; } }, // function for the replacement of the selected text replaceSelection: function(inputStr) { var input = this.jquery ? this[0] : this; //part for IE and Opera var start; var end; var position = 0; var rc; var re; var number = 0; var minus = 0; var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop; var obj = document.getElementsByTagName('TEXTAREA'); for (var pos = 0; pos < obj.length; pos++) { if (obj[pos] == input) { break; } } if (document.selection && typeof(input.selectionStart) != "number") { var s = document.selection.createRange(); // IE support if (typeof(input.selectionStart) != "number") { // return null if the selected text not from the needed area var firstRe; var secondRe; re = input.createTextRange(); rc = re.duplicate(); firstRe = re.text; re.moveToBookmark(s.getBookmark()); secondRe = re.text; try { rc.setEndPoint("EndToStart", re); } catch(err) { return this; } if (firstRe == secondRe && firstRe != s.text || rc.text.length > firstRe.length) { return this; } } if (s.text) { part = s.text; if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } // IE support start = rc.text.length; // remove all EOL to have the same start and end positons as in MOZILLA if (number > 0) { for (var i = 0; i <= number; i++) { var w = input.value.indexOf("\n", position); if (w != -1 && w < start) { position = w + 1; minus++; } else { i = number; } } } s.text = inputStr; caretPositionAmp[pos] = rc.text.length + inputStr.length; re.move("character", caretPositionAmp[pos]); document.selection.empty(); input.blur(); } return this; } else if (typeof(input.selectionStart) == "number" && // MOZILLA support input.selectionStart != input.selectionEnd) { start = input.selectionStart; end = input.selectionEnd; input.value = input.value.substr(0, start) + inputStr + input.value.substr(end); position = start + inputStr.length; input.setSelectionRange(position, position); input.scrollTop = mozScrollFix; return this; } return this; }, //Set Selection in text setSelection: function(startPosition, endPosition) { startPosition = parseInt(startPosition); endPosition = parseInt(endPosition); var input = this.jquery ? this[0] : this; input.focus (); if (typeof(input.selectionStart) != "number") { re = input.createTextRange(); if (re.text.length < endPosition) { endPosition = re.text.length+1; } } if (endPosition < startPosition) { return this; } if (document.selection) { var number = 0; var plus = 0; var position = 0; var plusEnd = 0; if (typeof(input.selectionStart) != "number") { // IE re.collapse(true); re.moveEnd('character', endPosition); re.moveStart('character', startPosition); re.select(); return this; } else if (typeof(input.selectionStart) == "number") { // Opera if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } if (number > 0) { for (var i = 0; i <= number; i++) { var w = input.value.indexOf("\n", position); if (w != -1 && w < startPosition) { position = w + 1; plus++; plusEnd = plus; } else if (w != -1 && w >= startPosition && w <= endPosition) { if (w == startPosition + 1) { plus--; plusEnd--; position = w + 1; continue; } position = w + 1; plusEnd++; } else { i = number; } } } startPosition = startPosition + plus; endPosition = endPosition + plusEnd; input.selectionStart = startPosition; input.selectionEnd = endPosition; input.focus (); return this; } else { input.focus (); return this; } } else if (input.selectionStart || input.selectionStart == 0) { // MOZILLA support input.focus (); window.getSelection().removeAllRanges(); input.selectionStart = startPosition; input.selectionEnd = endPosition; input.focus (); return this; } }, // insert text at current caret position insertAtCaretPos: function(inputStr) { var input = this.jquery ? this[0] : this; var start; var end; var position; var s; var re; var rc; var point; var minus = 0; var number = 0; var mozScrollFix = ( input.scrollTop == undefined ) ? 0 : input.scrollTop; var obj = document.getElementsByTagName('TEXTAREA'); for (var pos = 0; pos < obj.length; pos++) { if (obj[pos] == input) { break; } } input.focus(); if (document.selection && typeof(input.selectionStart) != "number") { if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } point = parseInt(caretPositionAmp[pos]); if (number > 0) { for (var i = 0; i <= number; i++) { var w = input.value.indexOf("\n", position); if (w != -1 && w <= point) { position = w + 1; point = point - 1; minus++; } } } } caretPositionAmp[pos] = parseInt(caretPositionAmp[pos]); // IE input.onkeyup = function() { // for IE because it loses caret position when focus changed if (document.selection && typeof(input.selectionStart) != "number") { input.focus(); s = document.selection.createRange(); re = input.createTextRange(); rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); caretPositionAmp[pos] = rc.text.length; } } input.onmouseup = function() { // for IE because it loses caret position when focus changed if (document.selection && typeof(input.selectionStart) != "number") { input.focus(); s = document.selection.createRange(); re = input.createTextRange(); rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); caretPositionAmp[pos] = rc.text.length; } } if (document.selection && typeof(input.selectionStart) != "number") { s = document.selection.createRange(); if (s.text.length != 0) { return this; } re = input.createTextRange(); textLength = re.text.length; rc = re.duplicate(); re.moveToBookmark(s.getBookmark()); rc.setEndPoint("EndToStart", re); start = rc.text.length; if (caretPositionAmp[pos] > 0 && start ==0) { minus = caretPositionAmp[pos] - minus; re.move("character", minus); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] += inputStr.length; } else if (!(caretPositionAmp[pos] >= 0) && textLength ==0) { s = document.selection.createRange(); caretPositionAmp[pos] = inputStr.length + textLength; } else if (!(caretPositionAmp[pos] >= 0) && start ==0) { re.move("character", textLength); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] = inputStr.length + textLength; } else if (!(caretPositionAmp[pos] >= 0) && start > 0) { re.move("character", 0); document.selection.empty(); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] = start + inputStr.length; } else if (caretPositionAmp[pos] >= 0 && caretPositionAmp[pos] == textLength) { if (textLength != 0) { re.move("character", textLength); re.select(); } else { re.move("character", 0); } s = document.selection.createRange(); caretPositionAmp[pos] = inputStr.length + textLength; } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] >= start) { minus = caretPositionAmp[pos] - start; re.move("character", minus); document.selection.empty(); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; } else if (caretPositionAmp[pos] >= 0 && start != 0 && caretPositionAmp[pos] < start) { re.move("character", 0); document.selection.empty(); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; } else { document.selection.empty(); re.select(); s = document.selection.createRange(); caretPositionAmp[pos] = caretPositionAmp[pos] + inputStr.length; } s.text = inputStr; input.focus(); return this; } else if (typeof(input.selectionStart) == "number" && // MOZILLA support input.selectionStart == input.selectionEnd) { position = input.selectionStart + inputStr.length; start = input.selectionStart; end = input.selectionEnd; input.value = input.value.substr(0, start) + inputStr + input.value.substr(end); input.setSelectionRange(position, position); input.scrollTop = mozScrollFix; return this; } return this; }, // Set caret position setCaretPos: function(inputStr) { var input = this.jquery ? this[0] : this; var s; var re; var position; var number = 0; var minus = 0; var w; var obj = document.getElementsByTagName('TEXTAREA'); for (var pos = 0; pos < obj.length; pos++) { if (obj[pos] == input) { break; } } input.focus(); if (parseInt(inputStr) == 0) { return this; } //if (document.selection && typeof(input.selectionStart) == "number") { if (parseInt(inputStr) > 0) { inputStr = parseInt(inputStr) - 1; if (document.selection && typeof(input.selectionStart) == "number" && input.selectionStart == input.selectionEnd) { if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } if (number > 0) { for (var i = 0; i <= number; i++) { w = input.value.indexOf("\n", position); if (w != -1 && w <= inputStr) { position = w + 1; inputStr = parseInt(inputStr) + 1; } } } } } else if (parseInt(inputStr) < 0) { inputStr = parseInt(inputStr) + 1; if (document.selection && typeof(input.selectionStart) != "number") { inputStr = input.value.length + parseInt(inputStr); if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } if (number > 0) { for (var i = 0; i <= number; i++) { w = input.value.indexOf("\n", position); if (w != -1 && w <= inputStr) { position = w + 1; inputStr = parseInt(inputStr) - 1; minus += 1; } } inputStr = inputStr + minus - number; } } else if (document.selection && typeof(input.selectionStart) == "number") { inputStr = input.value.length + parseInt(inputStr); if (input.value.match(/\n/g) != null) { number = input.value.match(/\n/g).length;// number of EOL simbols } if (number > 0) { inputStr = parseInt(inputStr) - number; for (var i = 0; i <= number; i++) { w = input.value.indexOf("\n", position); if (w != -1 && w <= (inputStr)) { position = w + 1; inputStr = parseInt(inputStr) + 1; minus += 1; } } } } else { inputStr = input.value.length + parseInt(inputStr); } } else { return this; } // IE if (document.selection && typeof(input.selectionStart) != "number") { s = document.selection.createRange(); if (s.text != 0) { return this; } re = input.createTextRange(); re.collapse(true); re.moveEnd('character', inputStr); re.moveStart('character', inputStr); re.select(); caretPositionAmp[pos] = inputStr; return this; } else if (typeof(input.selectionStart) == "number" && // MOZILLA support input.selectionStart == input.selectionEnd) { input.setSelectionRange(inputStr, inputStr); return this; } return this; }, countCharacters: function(str) { var input = this.jquery ? this[0] : this; if (input.value.match(/\r/g) != null) { return input.value.length - input.value.match(/\r/g).length; } return input.value.length; }, setMaxLength: function(max, f) { this.each(function() { var input = this.jquery ? this[0] : this; var type = input.type; var isSelected; var maxCharacters; // remove limit if input is a negative number if (parseInt(max) < 0) { max=100000000; } if (type == "text") { input.maxLength = max; } if (type == "textarea" || type == "text") { input.onkeypress = function(e) { var spacesR = input.value.match(/\r/g); maxCharacters = max; if (spacesR != null) { maxCharacters = parseInt(maxCharacters) + spacesR.length; } // get event var key = e || event; var keyCode = key.keyCode; // check if any part of text is selected if (document.selection) { isSelected = document.selection.createRange().text.length > 0; } else { isSelected = input.selectionStart != input.selectionEnd; } if (input.value.length >= maxCharacters && (keyCode > 47 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !key.ctrlKey && !key.altKey && !isSelected) { input.value = input.value.substring(0,maxCharacters); if (typeof(f) == "function") { f() } //callback function return false; } } input.onkeyup = function() { var spacesR = input.value.match(/\r/g); var plus = 0; var position = 0; maxCharacters = max; if (spacesR != null) { for (var i = 0; i <= spacesR.length; i++) { if (input.value.indexOf("\n", position) <= parseInt(max)) { plus++; position = input.value.indexOf("\n", position) + 1; } } maxCharacters = parseInt(max) + plus; } if (input.value.length > maxCharacters) { input.value = input.value.substring(0, maxCharacters); if (typeof(f) == "function") { f() } return this; } } } else { return this; } }) return this; } }); } )(jQuery, this, this.document );
mikoim/pukiwiki_adv
webroot/js/src/jquery.a-tools.js
JavaScript
gpl-2.0
20,675
H5PEditor.language.core = { missingTranslation: '[Fehlende Übersetzung :key]', loading: 'Lädt :type, bitte warten...', selectLibrary: 'Auswählen der Bibliothek, die für den Inhalt verwendet werden soll.', unknownFieldPath: '":path" kann nicht gefunden werden.', notImageField: '":path" ist kein Bild.', notImageOrDimensionsField: '":path" ist kein Bild oder Dimensionsfeld.', requiredProperty: 'Die :property wird benötigt und muss einen Wert besitzen.', onlyNumbers: 'Der :property Wert kann nur Nummern beinhalten.', exceedsMax: 'Der :property Wert übersteigt das Maximum von :max.', belowMin: 'Der :property Wert liegt unter dem Minimum von :min.', outOfStep: 'Der :property Wert kann nur in Schritten von :step geändert werden.', addFile: 'Datei hinzufügen', add: 'Hinzuf\u00fcgen', removeFile: 'Datei entfernen', confirmRemoval: 'Diesen :type ganz sicher entfernen?', removeImage: 'Bild entfernen', confirmImageRemoval: 'Dies wird das Bild entfernen. Ganz sicher fortfahren?', changeFile: 'Datei ändern', changeLibrary: 'Inhaltstyp ändern?', semanticsError: 'Semantischer Fehler: :error', missingProperty: 'Im Feld :index fehlt :property property.', expandCollapse: 'Erweitern/Verkleinern', addEntity: ':entity hinzufügen', tooLong: 'Wert des Feldes ist zu lang. Es sollte :max Buchstaben oder weniger beinhalten.', invalidFormat: 'Der Feldwert beinhaltet ein ungültiges Format oder verbotene Zeichen.', confirmChangeLibrary: 'Wenn dies ausgeführt wird, dann geht alles verloren, was mit dem aktuellen Inhaltstyp erstellt wurde. Ganz sicher den Inhaltstyp wechseln?', moreLibraries: 'Nach <a href="http://h5p.org/content-types-and-applications" target="_blank">mehr Inhaltstypen</a> auf h5p.org Ausschau halten', commonFields: 'Einstellungen und Texte', commonFieldsDescription: 'Hier können Einstellungen bearbeitet oder Texte übersetzt werden, die in diesem Inhalt Verwendung finden.', uploading: 'Lädt hoch, bitte warten...', noFollow: 'Dem Feld ":path" kann nicht gefolgt werden.', editCopyright: 'Urheberrecht bearbeiten', close: 'Schließen', tutorialAvailable: 'Anleitung verfügbar', editMode: 'Bearbeitungsmodus', listLabel: 'Liste', uploadError: 'Datenuploadfehler', fileToLarge: 'Die Datei, die hochgeladen werden soll, könnte zu groß sein.', noSemantics: 'Fehler, das Formular des Inhaltstypen konnte nicht geladen werden.', editImage: 'Bild bearbeiten', saveLabel: 'Speichern', cancelLabel: 'Abbrechen', resetToOriginalLabel: 'Auf Original zurücksetzen', loadingImageEditor: 'Bildeditor lädt, bitte warten...', selectFiletoUpload: 'Datei zum Hochladen ausw\u00e4hlen', or: 'oder', enterAudioUrl: 'URL der Audiodatei eingeben', enterVideoUrl: 'URL der Videodatei oder YouTube-Link eingeben', enterAudioTitle: 'Link oder URL zu Audiodatei einf\u00fcgen', enterVideoTitle: 'YouTube-Link oder andere Video-URL einf\u00fcgen', uploadAudioTitle: 'Audio-Datei hochladen', uploadVideoTitle: 'Video-Datei hochladen', addVideoDescription: 'H5P unterst\u00fctzt externe Videodateien im Format mp4, webm oder ogv, wie bei Vimeo Pro, und unterst\u00fctzt YouTube-Links.', insert: 'Einf\u00fcgen', cancel: 'Abbrechen', height: 'H\u00f6he', width: 'Breite', textField: 'Textfeld', numberField: 'Nummernfeld', orderItemUp: 'Element nach vorne sortieren', orderItemDown: 'Element nach hinten sortieren', removeItem: 'Element entfernen', hubPanelLabel: 'Inhaltstyp ausw\u00e4hlen', importantInstructions: 'Wichtige Hinweise', hideImportantInstructions: 'Wichtige Hinweise ausblenden', hide: 'Ausblenden', example: 'Beispiel', createContentTabLabel: 'Inhalt erstellen', uploadTabLabel: 'Hochladen', uploadPlaceholder: 'Keine Datei ausgew\u00e4hlt', uploadInstructionsTitle: 'Eine H5P-Datei hochladen.', uploadInstructionsContent: 'Du kannst mit Beispielen von <a href="https://h5p.org/content-types-and-applications" target="blank">H5P.org</a> starten.', uploadFileButtonLabel: 'Datei hochladen', uploadFileButtonChangeLabel: 'Datei \u00e4ndern', uploadingThrobber: 'Lade hoch ...', h5pFileWrongExtensionTitle: 'Die ausgew\u00e4hlte Datei konnte nicht hochgeladen werden', h5pFileWrongExtensionContent: 'Nur Dateien mit der Endung .h5p sind erlaubt.', h5pFileValidationFailedTitle: 'Die H5P-Datei konnte nicht \u00fcberpr\u00fcft werden.', h5pFileValidationFailedContent: 'Stelle sicher, dass die hochgeladene Datei g\u00fcltigen H5P-Inhalt enth\u00e4lt. H5P' + '-Dateien, die nur Bibliotheken enthalten, sollten \u00fcber die H5P-Bibliothekenseite hochgeladen werden.', h5pFileUploadServerErrorTitle: 'Die H5P-Datei konnte nicht hochgeladen werden', h5pFileUploadServerErrorContent: 'Ein unerwarteter Fehler ist aufgetreten. Bitte pr\u00fcfe die Fehlerlogdatei des Servers f\u00fcr' + ' mehr Details.', contentTypeSectionAll: 'Alle', contentTypeSectionMine: 'Meine Inhaltstypen', contentTypeSectionPopular: 'Am beliebtesten', contentTypeSectionTitle: 'Inhaltstypen durchst\u00f6bern', contentTypeSearchFieldPlaceholder: 'Nach Inhaltstypen suchen', contentTypeInstallButtonLabel: 'Installieren', contentTypeInstallingButtonLabel: 'Installiere', contentTypeUseButtonLabel: 'Benutzen', contentTypeUpdateButtonLabel: 'Aktualisieren', contentTypeUpdatingButtonLabel: 'Aktualisiere', contentTypeGetButtonLabel: '\u00dcbernehmen', contentTypeBackButtonLabel: 'Zurück', contentTypeIconAltText: 'Symbolbild', contentTypeInstallSuccess: ':contentType erfolgreich installiert!', contentTypeUpdateSuccess: ':contentType erfolgreich aktualisiert!', contentTypeInstallError: ':contentType konnte nicht installiert werden. Kontaktiere bitte deinen Administrator.', contentTypeLicensePanelTitle: 'Lizenz', contentTypeDemoButtonLabel: 'Inhalts-Demo', readMore: 'Mehr lesen', readLess: 'Weniger lesen', contentTypeOwner: 'Von :owner', contentTypeUnsupportedApiVersionTitle: 'Dieser Inhaltstyp erfordert eine neuere Version des H5P-Kerns.', contentTypeUnsupportedApiVersionContent: 'Kontaktiere bitte deinen Systemadministrator, um die notwendigen Aktualisierungen zu erhalten.', contentTypeUpdateAvailable: 'Aktualisierung verf\u00fcgbar', theContentType: 'dem Inhaltstyp', currentMenuSelected: 'aktuelle Auswahl', errorCommunicatingHubTitle: 'Es ist keine Verbindung zum Hub m\u00f6glich.', errorCommunicatingHubContent: 'Ein Fehler ist aufgetreten. Bitte versuche es noch einmal.', warningNoContentTypesInstalled: 'Du hast keine Inhaltstypen installiert.', warningChangeBrowsingToSeeResults: 'Klicke <em>Alle</em>, um eine Liste aller installierbaren Inhaltstypen zu erhalten.', warningUpdateAvailableTitle: 'Eine neuere Version von :contentType ist verf\u00fcgbar.', warningUpdateAvailableBody: 'Aktualisiere auf die neueste Version, um von allen Verbesserungen zu profitieren.', licenseDescription : 'Einige der Lizenzmerkmale sind unten aufgef\u00fchrt. Klicke auf das Info-Symbolbild, um den Originallizenztext zu lesen.', licenseModalTitle: 'Lizenzdetails', licenseModalSubtitle: 'W\u00e4hle eine Lizenz aus, um zu erfahren, welche Auflagen sie umfasst.', licenseUnspecified: 'Nicht näher angegeben', licenseCanUseCommercially: 'Darf kommerziell genutzt werden', licenseCanModify: 'Darf ver\u00e4ndert werden', licenseCanDistribute: 'Darf weitergegeben werden', licenseCanSublicense: 'Unterlizenzvertrag ist m\u00f6glich', licenseCanHoldLiable: 'Haftung wird \u00fcbernommen', licenseCannotHoldLiable: 'Haftung wird nicht \u00fcbernommen', licenseMustIncludeCopyright: 'Muss Urheberrechtshinweis enthalten', licenseMustIncludeLicense: 'Muss Lizenztext enthalten', licenseFetchDetailsFailed: 'Lizenzdetails konnten nicht geladen werden', imageLightboxTitle: 'Bilder', imageLightBoxProgress: ':num von :total', nextImage: 'N\u00e4chstes Bild', previousImage: 'Vorheriges Bild', screenshots: 'Bildschirmfotos', reloadButtonLabel: 'Neu laden', videoQuality: 'Videoaufl\u00f6sung', videoQualityDescription: 'Dieses Label hilft dem Benutzer, die aktuelle Videoaufl\u00f6sung zu erkennen. Z.B.. 1080p, 720p, HD der Mobile', videoQualityDefaultLabel: 'Aufl\u00f6sung :index' };
FeintEars/h5psitedev
sites/all/modules/h5p/modules/h5peditor/h5peditor/language/de.js
JavaScript
gpl-2.0
8,255
edButtons[edButtons.length]=new edButton('Subscribe','Subscribe','[followpluginsubscriptionform]','','',-1);
PhillyDH/PhillyDH.org
wp-content/plugins/follow/include/s2_button.js
JavaScript
gpl-2.0
108
// Load in dependencies var fs = require('fs'); var path = require('path'); var _ = require('underscore'); var async = require('async'); var templater = require('spritesheet-templates'); var spritesmith = require('spritesmith'); var url = require('url2'); // Define class to contain different extension handlers function ExtFormat() { this.formatObj = {}; } ExtFormat.prototype = { add: function (name, val) { this.formatObj[name] = val; }, get: function (filepath) { // Grab the extension from the filepath var ext = path.extname(filepath); var lowerExt = ext.toLowerCase(); // Look up the file extenion from our format object var formatObj = this.formatObj; var format = formatObj[lowerExt]; return format; } }; // Create img and css formats var imgFormats = new ExtFormat(); var cssFormats = new ExtFormat(); // Add our img formats imgFormats.add('.png', 'png'); imgFormats.add('.jpg', 'jpeg'); imgFormats.add('.jpeg', 'jpeg'); // Add our css formats cssFormats.add('.styl', 'stylus'); cssFormats.add('.stylus', 'stylus'); cssFormats.add('.sass', 'sass'); cssFormats.add('.scss', 'scss'); cssFormats.add('.less', 'less'); cssFormats.add('.json', 'json'); cssFormats.add('.css', 'css'); function getCoordinateName(filepath) { // Extract the image name (exlcuding extension) var fullname = path.basename(filepath); var nameParts = fullname.split('.'); // If there is are more than 2 parts, pop the last one if (nameParts.length >= 2) { nameParts.pop(); } // Return our modified filename return nameParts.join('.'); } module.exports = function gruntSpritesmith (grunt) { // Create a SpriteMaker function function SpriteMaker() { // Grab the raw configuration var data = this.data; // If we were invoked via `grunt-newer`, re-localize the info if (data.src === undefined && data.files) { data = data.files[0] || {}; } // Determine the origin and destinations var src = data.src; var destImg = data.dest; var destCss = data.destCss; var cssTemplate = data.cssTemplate; var that = this; // Verify all properties are here if (!src || !destImg || !destCss) { return grunt.fatal('grunt.sprite requires a src, dest (img), and destCss property'); } // Expand all filepaths (e.g. `*.png` -> `home.png`) var srcFiles = grunt.file.expand(src); // If there are settings for retina var retinaSrcFiles; var retinaSrcFilter = data.retinaSrcFilter; var retinaDestImg = data.retinaDest; if (retinaSrcFilter || retinaDestImg) { grunt.log.debug('Retina settings detected'); // Verify our required set is present if (!retinaSrcFilter || !retinaDestImg) { return grunt.fatal('Retina settings detected. We must have both `retinaSrcFilter` and `retinaDest` ' + 'provided for retina to work'); } // Filter out our retina files retinaSrcFiles = []; srcFiles = srcFiles.filter(function filterSrcFile (filepath) { // If we have a retina file, filter it out if (grunt.file.match(retinaSrcFilter, filepath).length) { retinaSrcFiles.push(filepath); return false; // Otherwise, keep it in the src files } else { return true; } }); grunt.verbose.writeln('Retina images found: ' + retinaSrcFiles.join(', ')); // If we have a different amount of normal and retina images, complain and leave if (srcFiles.length !== retinaSrcFiles.length) { return grunt.fatal('Retina settings detected but ' + retinaSrcFiles.length + ' retina images were found. ' + 'We have ' + srcFiles.length + ' normal images and expect these numbers to line up. ' + 'Please double check `retinaSrcFilter`.'); } } // Create an async callback var cb = this.async(); // Determine the format of the image var imgOpts = data.imgOpts || {}; var imgFormat = imgOpts.format || imgFormats.get(destImg) || 'png'; // Set up the defautls for imgOpts _.defaults(imgOpts, {format: imgFormat}); // Prepare spritesmith parameters var spritesmithParams = { src: srcFiles, engine: data.engine, algorithm: data.algorithm, padding: data.padding || 0, algorithmOpts: data.algorithmOpts || {}, engineOpts: data.engineOpts || {}, exportOpts: imgOpts }; // In parallel async.parallel([ // Run our normal task function normalSpritesheet (callback) { spritesmith(spritesmithParams, callback); }, // If we have a retina task, run it as well function retinaSpritesheet (callback) { // DEV: We don't check length since we could have no images passed in if (retinaSrcFiles) { var retinaParams = _.defaults({ src: retinaSrcFiles, padding: spritesmithParams.padding * 2 }, spritesmithParams); spritesmith(retinaParams, callback); } else { process.nextTick(callback); } } ], function handleSpritesheets (err, resultArr) { // If an error occurred, callback with it if (err) { grunt.fatal(err); return cb(err); } // Otherwise, write out the result to destImg var result = resultArr[0]; var destImgDir = path.dirname(destImg); grunt.file.mkdir(destImgDir); fs.writeFileSync(destImg, result.image, 'binary'); // Generate a listing of CSS variables var coordinates = result.coordinates; var properties = result.properties; var spritePath = data.imgPath || url.relative(destCss, destImg); var spritesheetInfo = { width: properties.width, height: properties.height, image: spritePath }; var cssVarMap = data.cssVarMap || function noop () {}; var cleanCoords = []; // Clean up the file name of the file Object.getOwnPropertyNames(coordinates).sort().forEach(function prepareTemplateData (file) { // Extract out our name var name = getCoordinateName(file); var coords = coordinates[file]; // Specify the image for the sprite coords.name = name; coords.source_image = file; // DEV: `image`, `total_width`, `total_height` are deprecated as they are overwritten in `spritesheet-templates` coords.image = spritePath; coords.total_width = properties.width; coords.total_height = properties.height; // Map the coordinates through cssVarMap coords = cssVarMap(coords) || coords; // Save the cleaned name and coordinates cleanCoords.push(coords); }); // If we have retina sprites var retinaCleanCoords; var retinaGroups; var retinaResult = resultArr[1]; var retinaSpritesheetInfo; if (retinaResult) { // Write out the result to destImg var retinaDestImgDir = path.dirname(retinaDestImg); grunt.file.mkdir(retinaDestImgDir); fs.writeFileSync(retinaDestImg, retinaResult.image, 'binary'); // Generate a listing of CSS variables var retinaCoordinates = retinaResult.coordinates; var retinaProperties = retinaResult.properties; var retinaSpritePath = data.retinaImgPath || url.relative(destCss, retinaDestImg); retinaSpritesheetInfo = { width: retinaProperties.width, height: retinaProperties.height, image: retinaSpritePath }; // DEV: We reuse cssVarMap retinaCleanCoords = []; // Clean up the file name of the file Object.getOwnPropertyNames(retinaCoordinates).sort().forEach(function prepareRetinaTemplateData (file) { var name = getCoordinateName(file); var coords = retinaCoordinates[file]; coords.name = name; coords.source_image = file; coords.image = retinaSpritePath; coords.total_width = retinaProperties.width; coords.total_height = retinaProperties.height; coords = cssVarMap(coords) || coords; retinaCleanCoords.push(coords); }); // Generate groups for our coordinates retinaGroups = cleanCoords.map(function getRetinaGroups (normalSprite, i) { // Assert that image sizes line up for debugging purposes var retinaSprite = retinaCleanCoords[i]; if (retinaSprite.width !== normalSprite.width * 2 || retinaSprite.height !== normalSprite.height * 2) { grunt.log.warn('Normal sprite has inconsistent size with retina sprite. ' + '"' + normalSprite.name + '" is ' + normalSprite.width + 'x' + normalSprite.height + ' while ' + '"' + retinaSprite.name + '" is ' + retinaSprite.width + 'x' + retinaSprite.height + '.'); } // Generate our group // DEV: Name is inherited from `cssVarMap` on normal sprite return { name: normalSprite.name, index: i }; }); } // If we have handlebars helpers, register them var handlebarsHelpers = data.cssHandlebarsHelpers; if (handlebarsHelpers) { Object.keys(handlebarsHelpers).forEach(function registerHelper (helperKey) { templater.registerHandlebarsHelper(helperKey, handlebarsHelpers[helperKey]); }); } // If there is a custom template, use it var cssFormat = 'spritesmith-custom'; var cssOptions = data.cssOpts || {}; if (cssTemplate) { if (typeof cssTemplate === 'function') { templater.addTemplate(cssFormat, cssTemplate); } else { templater.addHandlebarsTemplate(cssFormat, fs.readFileSync(cssTemplate, 'utf8')); } } else { // Otherwise, override the cssFormat and fallback to 'json' cssFormat = data.cssFormat; if (!cssFormat) { cssFormat = cssFormats.get(destCss) || 'json'; // If we are dealing with retina items, move to retina flavor (e.g. `scss` -> `scss_retina`) if (retinaGroups) { cssFormat += '_retina'; } } } // Render the variables via `spritesheet-templates` var cssStr = templater({ sprites: cleanCoords, spritesheet: spritesheetInfo, spritesheet_info: { name: data.cssSpritesheetName }, retina_groups: retinaGroups, retina_sprites: retinaCleanCoords, retina_spritesheet: retinaSpritesheetInfo, retina_spritesheet_info: { name: data.cssRetinaSpritesheetName }, retina_groups_info: { name: data.cssRetinaGroupsName } }, { format: cssFormat, formatOpts: cssOptions }); // Write it out to the CSS file var destCssDir = path.dirname(destCss); grunt.file.mkdir(destCssDir); fs.writeFileSync(destCss, cssStr, 'utf8'); // Fail task if errors were logged. if (that.errorCount) { cb(false); } // Otherwise, print a success message. if (retinaDestImg) { grunt.log.writeln('Files "' + destCss + '", "' + destImg + '", "' + retinaDestImg + '" created.'); } else { grunt.log.writeln('Files "' + destCss + '", "' + destImg + '" created.'); } // Callback cb(true); }); } // Export the SpriteMaker function grunt.registerMultiTask('sprite', 'Spritesheet making utility', SpriteMaker); };
dgcohen/Clocktower-D7
sites/all/themes/clocktower/node_modules/grunt-spritesmith/src/grunt-spritesmith.js
JavaScript
gpl-2.0
11,529
/** A base class for helping us display modal content @class ModalBodyView @extends Discourse.View @namespace Discourse @module Discourse **/ Discourse.ModalBodyView = Discourse.View.extend({ // Focus on first element didInsertElement: function() { var modalBodyView = this; Em.run.next(function() { modalBodyView.$('form input:first').focus(); }); }, // Pass the errors to our errors view displayErrors: function(errors, callback) { this.set('parentView.parentView.modalErrorsView.errors', errors); if (typeof callback === "function") callback(); }, // Just use jQuery to show an alert. We don't need anythign fancier for now // like an actual ember view flash: function(msg, flashClass) { if (!flashClass) flashClass = "success"; var $alert = $('#modal-alert').hide().removeClass('alert-error', 'alert-success'); $alert.addClass("alert alert-" + flashClass).html(msg); $alert.fadeIn(); } });
alexknowshtml/discourse
app/assets/javascripts/discourse/views/modal/modal_body_view.js
JavaScript
gpl-2.0
962
(function($) { /** * Initialize editor instances. * * @todo Is the following note still valid for 3.x? * This function needs to be called before the page is fully loaded, as * calling tinyMCE.init() after the page is loaded breaks IE6. * * @param editorSettings * An object containing editor settings for each input format. */ Drupal.wysiwyg.editor.init.tinymce = function(settings) { // Fix Drupal toolbar obscuring editor toolbar in fullscreen mode. var $drupalToolbar = $('#toolbar', Drupal.overlayChild ? window.parent.document : document); tinyMCE.onAddEditor.add(function (mgr, ed) { if (ed.id == 'mce_fullscreen') { $drupalToolbar.hide(); } }); tinyMCE.onRemoveEditor.add(function (mgr, ed) { if (ed.id == 'mce_fullscreen') { $drupalToolbar.show(); } }); // Initialize editor configurations. for (var format in settings) { if (Drupal.settings.wysiwyg.plugins[format]) { // Load native external plugins. // Array syntax required; 'native' is a predefined token in JavaScript. for (var plugin in Drupal.settings.wysiwyg.plugins[format]['native']) { tinymce.PluginManager.load(plugin, Drupal.settings.wysiwyg.plugins[format]['native'][plugin]); } // Load Drupal plugins. for (var plugin in Drupal.settings.wysiwyg.plugins[format].drupal) { Drupal.wysiwyg.editor.instance.tinymce.addPlugin(plugin, Drupal.settings.wysiwyg.plugins[format].drupal[plugin], Drupal.settings.wysiwyg.plugins.drupal[plugin]); } } } }; /** * Attach this editor to a target element. * * See Drupal.wysiwyg.editor.attach.none() for a full desciption of this hook. */ Drupal.wysiwyg.editor.attach.tinymce = function(context, params, settings) { // Configure editor settings for this input format. var ed = new tinymce.Editor(params.field, settings); // Reset active instance id on any event. ed.onEvent.add(function(ed, e) { Drupal.wysiwyg.activeId = ed.id; }); // Indicate that the DOM has been loaded (in case of Ajax). tinymce.dom.Event.domLoaded = true; // Make toolbar buttons wrappable (required for IE). ed.onPostRender.add(function (ed) { var $toolbar = $('<div class="wysiwygToolbar"></div>'); $('#' + ed.editorContainer + ' table.mceToolbar > tbody > tr > td').each(function () { $('<div></div>').addClass(this.className).append($(this).children()).appendTo($toolbar); }); $('#' + ed.editorContainer + ' table.mceLayout td.mceToolbar').append($toolbar); $('#' + ed.editorContainer + ' table.mceToolbar').remove(); }); // Remove TinyMCE's internal mceItem class, which was incorrectly added to // submitted content by Wysiwyg <2.1. TinyMCE only temporarily adds the class // for placeholder elements. If preemptively set, the class prevents (native) // editor plugins from gaining an active state, so we have to manually remove // it prior to attaching the editor. This is done on the client-side instead // of the server-side, as Wysiwyg has no way to figure out where content is // stored, and the class only affects editing. $field = $('#' + params.field); $field.val($field.val().replace(/(<.+?\s+class=['"][\w\s]*?)\bmceItem\b([\w\s]*?['"].*?>)/ig, '$1$2')); // Attach editor. ed.render(); }; /** * Detach a single or all editors. * * See Drupal.wysiwyg.editor.detach.none() for a full desciption of this hook. */ Drupal.wysiwyg.editor.detach.tinymce = function (context, params, trigger) { if (typeof params != 'undefined') { var instance = tinyMCE.get(params.field); if (instance) { instance.save(); if (trigger != 'serialize') { instance.remove(); } } } else { // Save contents of all editors back into textareas. tinyMCE.triggerSave(); if (trigger != 'serialize') { // Remove all editor instances. for (var instance in tinyMCE.editors) { tinyMCE.editors[instance].remove(); } } } }; Drupal.wysiwyg.editor.instance.tinymce = { addPlugin: function(plugin, settings, pluginSettings) { if (typeof Drupal.wysiwyg.plugins[plugin] != 'object') { return; } tinymce.create('tinymce.plugins.' + plugin, { /** * Initialize the plugin, executed after the plugin has been created. * * @param ed * The tinymce.Editor instance the plugin is initialized in. * @param url * The absolute URL of the plugin location. */ init: function(ed, url) { // Register an editor command for this plugin, invoked by the plugin's button. ed.addCommand(plugin, function() { if (typeof Drupal.wysiwyg.plugins[plugin].invoke == 'function') { var data = { format: 'html', node: ed.selection.getNode(), content: ed.selection.getContent() }; // TinyMCE creates a completely new instance for fullscreen mode. var instanceId = ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id; Drupal.wysiwyg.plugins[plugin].invoke(data, pluginSettings, instanceId); } }); // Register the plugin button. ed.addButton(plugin, { title : settings.iconTitle, cmd : plugin, image : settings.icon }); // Load custom CSS for editor contents on startup. ed.onInit.add(function() { if (settings.css) { ed.dom.loadCSS(settings.css); } }); // Attach: Replace plain text with HTML representations. ed.onBeforeSetContent.add(function(ed, data) { var editorId = (ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id); if (typeof Drupal.wysiwyg.plugins[plugin].attach == 'function') { data.content = Drupal.wysiwyg.plugins[plugin].attach(data.content, pluginSettings, editorId); data.content = Drupal.wysiwyg.editor.instance.tinymce.prepareContent(data.content); } }); // Detach: Replace HTML representations with plain text. ed.onGetContent.add(function(ed, data) { var editorId = (ed.id == 'mce_fullscreen' ? ed.getParam('fullscreen_editor_id') : ed.id); if (typeof Drupal.wysiwyg.plugins[plugin].detach == 'function') { data.content = Drupal.wysiwyg.plugins[plugin].detach(data.content, pluginSettings, editorId); } }); // isNode: Return whether the plugin button should be enabled for the // current selection. ed.onNodeChange.add(function(ed, command, node) { if (typeof Drupal.wysiwyg.plugins[plugin].isNode == 'function') { command.setActive(plugin, Drupal.wysiwyg.plugins[plugin].isNode(node)); } }); }, /** * Return information about the plugin as a name/value array. */ getInfo: function() { return { longname: settings.title }; } }); // Register plugin. tinymce.PluginManager.add(plugin, tinymce.plugins[plugin]); }, openDialog: function(dialog, params) { var instanceId = this.getInstanceId(); var editor = tinyMCE.get(instanceId); editor.windowManager.open({ file: dialog.url + '/' + instanceId, width: dialog.width, height: dialog.height, inline: 1 }, params); }, closeDialog: function(dialog) { var editor = tinyMCE.get(this.getInstanceId()); editor.windowManager.close(dialog); }, prepareContent: function(content) { // Certain content elements need to have additional DOM properties applied // to prevent this editor from highlighting an internal button in addition // to the button of a Drupal plugin. var specialProperties = { img: { 'class': 'mceItem' } }; var $content = $('<div>' + content + '</div>'); // No .outerHTML() in jQuery :( // Find all placeholder/replacement content of Drupal plugins. $content.find('.drupal-content').each(function() { // Recursively process DOM elements below this element to apply special // properties. var $drupalContent = $(this); $.each(specialProperties, function(element, properties) { $drupalContent.find(element).andSelf().each(function() { for (var property in properties) { if (property == 'class') { $(this).addClass(properties[property]); } else { $(this).attr(property, properties[property]); } } }); }); }); return $content.html(); }, insert: function(content) { content = this.prepareContent(content); tinyMCE.execInstanceCommand(this.getInstanceId(), 'mceInsertContent', false, content); }, setContent: function (content) { content = this.prepareContent(content); tinyMCE.execInstanceCommand(this.getInstanceId(), 'mceSetContent', false, content); }, getContent: function () { return tinyMCE.get(this.getInstanceId()).getContent(); }, isFullscreen: function() { // TinyMCE creates a completely new instance for fullscreen mode. return tinyMCE.activeEditor.id == 'mce_fullscreen' && tinyMCE.activeEditor.getParam('fullscreen_editor_id') == this.field; }, getInstanceId: function () { return this.isFullscreen() ? 'mce_fullscreen' : this.field; } }; })(jQuery); ;/**/ (function($) { /** * Attach this editor to a target element. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * An object containing input format parameters. Default parameters are: * - editor: The internal editor name. * - theme: The name/key of the editor theme/profile to use. * - field: The CSS id of the target element. * @param settings * An object containing editor settings for all enabled editor themes. */ Drupal.wysiwyg.editor.attach.none = function(context, params, settings) { if (params.resizable) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.addClass('resizable'); if (Drupal.behaviors.textarea) { Drupal.behaviors.textarea.attach(); } } }; /** * Detach a single or all editors. * * The editor syncs its contents back to the original field before its instance * is removed. * * @param context * A DOM element, supplied by Drupal.attachBehaviors(). * @param params * (optional) An object containing input format parameters. If defined, * only the editor instance in params.field should be detached. Otherwise, * all editors should be detached and saved, so they can be submitted in * AJAX/AHAH applications. * @param trigger * A string describing why the editor is being detached. * Possible triggers are: * - unload: (default) Another or no editor is about to take its place. * - move: Currently expected to produce the same result as unload. * - serialize: The form is about to be serialized before an AJAX request or * a normal form submission. If possible, perform a quick detach and leave * the editor's GUI elements in place to avoid flashes or scrolling issues. * @see Drupal.detachBehaviors */ Drupal.wysiwyg.editor.detach.none = function (context, params, trigger) { if (typeof params != 'undefined' && (trigger != 'serialize')) { var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first'); $wrapper.removeOnce('textarea').removeClass('.resizable-textarea') .find('.grippie').remove(); } }; /** * Instance methods for plain text areas. */ Drupal.wysiwyg.editor.instance.none = { insert: function(content) { var editor = document.getElementById(this.field); // IE support. if (document.selection) { editor.focus(); var sel = document.selection.createRange(); sel.text = content; } // Mozilla/Firefox/Netscape 7+ support. else if (editor.selectionStart || editor.selectionStart == '0') { var startPos = editor.selectionStart; var endPos = editor.selectionEnd; editor.value = editor.value.substring(0, startPos) + content + editor.value.substring(endPos, editor.value.length); } // Fallback, just add to the end of the content. else { editor.value += content; } }, setContent: function (content) { $('#' + this.field).val(content); }, getContent: function () { return $('#' + this.field).val(); } }; })(jQuery); ;/**/ /** * @file: Popup dialog interfaces for the media project. * * Drupal.media.popups.mediaBrowser * Launches the media browser which allows users to pick a piece of media. * * Drupal.media.popups.mediaStyleSelector * Launches the style selection form where the user can choose * what format / style they want their media in. * */ (function ($) { namespace('Drupal.media.popups'); /** * Media browser popup. Creates a media browser dialog. * * @param {function} * onSelect Callback for when dialog is closed, received (Array * media, Object extra); * @param {Object} * globalOptions Global options that will get passed upon initialization of the browser. * @see Drupal.media.popups.mediaBrowser.getDefaults(); * * @param {Object} * pluginOptions Options for specific plugins. These are passed * to the plugin upon initialization. If a function is passed here as * a callback, it is obviously not passed, but is accessible to the plugin * in Drupal.settings.variables. * * Example * pluginOptions = {library: {url_include_patterns:'/foo/bar'}}; * * @param {Object} * widgetOptions Options controlling the appearance and behavior of the * modal dialog. * @see Drupal.media.popups.mediaBrowser.getDefaults(); */ Drupal.media.popups.mediaBrowser = function (onSelect, globalOptions, pluginOptions, widgetOptions) { var options = Drupal.media.popups.mediaBrowser.getDefaults(); options.global = $.extend({}, options.global, globalOptions); options.plugins = pluginOptions; options.widget = $.extend({}, options.widget, widgetOptions); // Create it as a modal window. var browserSrc = options.widget.src; if ($.isArray(browserSrc) && browserSrc.length) { browserSrc = browserSrc[browserSrc.length - 1]; } // Params to send along to the iframe. WIP. var params = {}; $.extend(params, options.global); params.plugins = options.plugins; browserSrc += '&' + $.param(params); var mediaIframe = Drupal.media.popups.getPopupIframe(browserSrc, 'mediaBrowser'); // Attach the onLoad event mediaIframe.bind('load', options, options.widget.onLoad); /** * Setting up the modal dialog */ var ok = 'OK'; var notSelected = 'You have not selected anything!'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = options.dialog; dialogOptions.buttons[ok] = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad = function (e) { var options = e.data; if (this.contentWindow.Drupal.media == undefined) return; if (this.contentWindow.Drupal.media.browser.selectedMedia.length > 0) { var ok = (Drupal && Drupal.t) ? Drupal.t('OK') : 'OK'; var ok_func = $(this).dialog('option', 'buttons')[ok]; ok_func.call(this); return; } }; Drupal.media.popups.mediaBrowser.getDefaults = function () { return { global: { types: [], // Types to allow, defaults to all. activePlugins: [] // If provided, a list of plugins which should be enabled. }, widget: { // Settings for the actual iFrame which is launched. src: Drupal.settings.media.browserUrl, // Src of the media browser (if you want to totally override it) onLoad: Drupal.media.popups.mediaBrowser.mediaBrowserOnLoad // Onload function when iFrame loads. }, dialog: Drupal.media.popups.getDialogOptions() }; }; Drupal.media.popups.mediaBrowser.finalizeSelection = function () { var selected = this.contentWindow.Drupal.media.browser.selectedMedia; if (selected.length < 1) { alert(notSelected); return; } onSelect(selected); $(this).dialog("close"); } /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaStyleSelector = function (mediaFile, onSelect, options) { var defaults = Drupal.media.popups.mediaStyleSelector.getDefaults(); // @todo: remove this awful hack :( if (typeof defaults.src === 'string' ) { defaults.src = defaults.src.replace('-media_id-', mediaFile.fid) + '&fields=' + encodeURIComponent(JSON.stringify(mediaFile.fields)); } else { var src = defaults.src.shift(); defaults.src.unshift(src); defaults.src = src.replace('-media_id-', mediaFile.fid) + '&fields=' + encodeURIComponent(JSON.stringify(mediaFile.fields)); } options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaStyleSelector'); // Attach the onLoad event mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog.parents(".ui-dialog")); return mediaIframe; }; Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaStyleSelector.getDefaults = function () { return { src: Drupal.settings.media.styleSelectorUrl, onLoad: Drupal.media.popups.mediaStyleSelector.mediaBrowserOnLoad }; }; /** * Style chooser Popup. Creates a dialog for a user to choose a media style. * * @param mediaFile * The mediaFile you are requesting this formatting form for. * @todo: should this be fid? That's actually all we need now. * * @param Function * onSubmit Function to be called when the user chooses a media * style. Takes one parameter (Object formattedMedia). * * @param Object * options Options for the mediaStyleChooser dialog. */ Drupal.media.popups.mediaFieldEditor = function (fid, onSelect, options) { var defaults = Drupal.media.popups.mediaFieldEditor.getDefaults(); // @todo: remove this awful hack :( defaults.src = defaults.src.replace('-media_id-', fid); options = $.extend({}, defaults, options); // Create it as a modal window. var mediaIframe = Drupal.media.popups.getPopupIframe(options.src, 'mediaFieldEditor'); // Attach the onLoad event // @TODO - This event is firing too early in IE on Windows 7, // - so the height being calculated is too short for the content. mediaIframe.bind('load', options, options.onLoad); /** * Set up the button text */ var ok = 'OK'; var notSelected = 'Very sorry, there was an unknown error embedding media.'; if (Drupal && Drupal.t) { ok = Drupal.t(ok); notSelected = Drupal.t(notSelected); } // @todo: let some options come through here. Currently can't be changed. var dialogOptions = Drupal.media.popups.getDialogOptions(); dialogOptions.buttons[ok] = function () { var formattedMedia = this.contentWindow.Drupal.media.formatForm.getFormattedMedia(); if (!formattedMedia) { alert(notSelected); return; } onSelect(formattedMedia); $(this).dialog("close"); }; var dialog = mediaIframe.dialog(dialogOptions); Drupal.media.popups.sizeDialog(dialog); Drupal.media.popups.resizeDialog(dialog); Drupal.media.popups.scrollDialog(dialog); Drupal.media.popups.overlayDisplace(dialog); return mediaIframe; }; Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad = function (e) { }; Drupal.media.popups.mediaFieldEditor.getDefaults = function () { return { // @todo: do this for real src: '/media/-media_id-/edit?render=media-popup', onLoad: Drupal.media.popups.mediaFieldEditor.mediaBrowserOnLoad }; }; /** * Generic functions to both the media-browser and style selector */ /** * Returns the commonly used options for the dialog. */ Drupal.media.popups.getDialogOptions = function () { return { buttons: {}, dialogClass: Drupal.settings.media.dialogOptions.dialogclass, modal: Drupal.settings.media.dialogOptions.modal, draggable: Drupal.settings.media.dialogOptions.draggable, resizable: Drupal.settings.media.dialogOptions.resizable, minWidth: Drupal.settings.media.dialogOptions.minwidth, width: Drupal.settings.media.dialogOptions.width, height: Drupal.settings.media.dialogOptions.height, position: Drupal.settings.media.dialogOptions.position, overlay: { backgroundColor: Drupal.settings.media.dialogOptions.overlay.backgroundcolor, opacity: Drupal.settings.media.dialogOptions.overlay.opacity }, zIndex: Drupal.settings.media.dialogOptions.zindex, close: function (event, ui) { $(event.target).remove(); } }; }; /** * Get an iframe to serve as the dialog's contents. Common to both plugins. */ Drupal.media.popups.getPopupIframe = function (src, id, options) { var defaults = {width: '100%', scrolling: 'auto'}; var options = $.extend({}, defaults, options); return $('<iframe class="media-modal-frame"/>') .attr('src', src) .attr('width', options.width) .attr('id', id) .attr('scrolling', options.scrolling); }; Drupal.media.popups.overlayDisplace = function (dialog) { if (parent.window.Drupal.overlay && jQuery.isFunction(parent.window.Drupal.overlay.getDisplacement)) { var overlayDisplace = parent.window.Drupal.overlay.getDisplacement('top'); if (dialog.offset().top < overlayDisplace) { dialog.css('top', overlayDisplace); } } } /** * Size the dialog when it is first loaded and keep it centered when scrolling. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.sizeDialog = function (dialogElement) { if (!dialogElement.is(':visible')) { return; } var windowWidth = $(window).width(); var dialogWidth = windowWidth * 0.8; var windowHeight = $(window).height(); var dialogHeight = windowHeight * 0.8; dialogElement.dialog("option", "width", dialogWidth); dialogElement.dialog("option", "height", dialogHeight); dialogElement.dialog("option", "position", 'center'); $('.media-modal-frame').width('100%'); } /** * Resize the dialog when the window changes. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.resizeDialog = function (dialogElement) { $(window).resize(function() { Drupal.media.popups.sizeDialog(dialogElement); }); } /** * Keeps the dialog centered when the window is scrolled. * * @param jQuery dialogElement * The element which has .dialog() attached to it. */ Drupal.media.popups.scrollDialog = function (dialogElement) { // Keep the dialog window centered when scrolling. $(window).scroll(function() { if (!dialogElement.is(':visible')) { return; } dialogElement.dialog("option", "position", 'center'); }); } })(jQuery); ;/**/
mikeusry/palmetto
LASIK/advagg_js/js__7hlBWPf1ttIudqF3iXkeU8oj7-zn_KRtVHFZdJJJ7v0__aTMdf5d7seM9dLI2fkwXQ2X0SNki2Q_-7ojT8gPzfnw__f87EqBUvTXEvjkncqMkj5xIZ6nPMQzVQhJdgieC7TpU.js
JavaScript
gpl-2.0
24,815
/* * textillate.js * http://jschr.github.com/textillate * MIT licensed * * Copyright (C) 2012-2013 Jordan Schroter */ (function ($) { "use strict"; function isInEffect (effect) { return /In/.test(effect) || $.inArray(effect, $.fn.textillate.defaults.inEffects) >= 0; }; function isOutEffect (effect) { return /Out/.test(effect) || $.inArray(effect, $.fn.textillate.defaults.outEffects) >= 0; }; // custom get data api method function getData (node) { var attrs = node.attributes || [] , data = {}; if (!attrs.length) return data; $.each(attrs, function (i, attr) { if (/^data-in-*/.test(attr.nodeName)) { data.in = data.in || {}; data.in[attr.nodeName.replace(/data-in-/, '')] = attr.nodeValue; } else if (/^data-out-*/.test(attr.nodeName)) { data.out = data.out || {}; data.out[attr.nodeName.replace(/data-out-/, '')] = attr.nodeValue; } else if (/^data-*/.test(attr.nodeName)) { data[attr.nodeName] = attr.nodeValue; } }) return data; } function shuffle (o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } function animate ($c, effect, cb) { $c.addClass('animated ' + effect) .css('visibility', 'visible') .show(); $c.one('animationend webkitAnimationEnd oAnimationEnd', function () { $c.removeClass('animated ' + effect); cb && cb(); }); } function animateChars ($chars, options, cb) { var that = this , count = $chars.length; if (!count) { cb && cb(); return; } if (options.shuffle) shuffle($chars); $chars.each(function (i) { var $this = $(this); function complete () { if (isInEffect(options.effect)) { $this.css('visibility', 'visible'); } else if (isOutEffect(options.effect)) { $this.css('visibility', 'hidden'); } count -= 1; if (!count && cb) cb(); } var delay = options.sync ? options.delay : options.delay * i * options.delayScale; $this.text() ? setTimeout(function () { animate($this, options.effect, complete) }, delay) : complete(); }) }; var Textillate = function (element, options) { var base = this , $element = $(element); base.init = function () { base.$texts = $element.find(options.selector); if (!base.$texts.length) { base.$texts = $('<ul class="texts"><li>' + $element.html() + '</li></ul>'); $element.html(base.$texts); } base.$texts.hide(); base.$current = $('<span>') .text(base.$texts.find(':first-child').html()) .prependTo($element); if (isInEffect(options.effect)) { base.$current.css('visibility', 'hidden'); } else if (isOutEffect(options.effect)) { base.$current.css('visibility', 'visible'); } base.setOptions(options); setTimeout(function () { base.options.autoStart && base.start(); }, base.options.initialDelay) }; base.setOptions = function (options) { base.options = options; }; base.start = function (index) { var $next = base.$texts.find(':nth-child(' + (index || 1) + ')'); (function run ($elem) { var options = $.extend({}, base.options, getData($elem)); base.$current .text($elem.html()) .lettering('words'); base.$current.find('[class^="word"]') .css({ 'display': 'inline-block', // fix for poor ios performance '-webkit-transform': 'translate3d(0,0,0)', '-moz-transform': 'translate3d(0,0,0)', '-o-transform': 'translate3d(0,0,0)', 'transform': 'translate3d(0,0,0)' }) .each(function () { $(this).lettering() }); var $chars = base.$current.find('[class^="char"]') .css('display', 'inline-block'); if (isInEffect(options.in.effect)) { $chars.css('visibility', 'hidden'); } else if (isOutEffect(options.in.effect)) { $chars.css('visibility', 'visible'); } animateChars($chars, options.in, function () { setTimeout(function () { // in case options have changed var options = $.extend({}, base.options, getData($elem)); var $next = $elem.next(); if (base.options.loop && !$next.length) { $next = base.$texts.find(':first-child'); } if (!$next.length) return; animateChars($chars, options.out, function () { run($next) }); }, base.options.minDisplayTime); }); }($next)); }; base.init(); } $.fn.textillate = function (settings, args) { return this.each(function () { var $this = $(this) , data = $this.data('textillate') , options = $.extend(true, {}, $.fn.textillate.defaults, getData(this), typeof settings == 'object' && settings); if (!data) { $this.data('textillate', (data = new Textillate(this, options))); } else if (typeof settings == 'string') { data[settings].apply(data, [].concat(args)); } else { data.setOptions.call(data, options); } }) }; $.fn.textillate.defaults = { selector: '.texts', loop: false, minDisplayTime: 2000, initialDelay: 0, in: { effect: 'fadeInLeftBig', delayScale: 1.5, delay: 50, sync: false, shuffle: false }, out: { effect: 'hinge', delayScale: 1.5, delay: 50, sync: false, shuffle: false, }, autoStart: true, inEffects: [], outEffects: [ 'hinge' ] }; }(jQuery));
niceit/rockets
wp-content/themes/AvaLance/js/jquery.textillate.js
JavaScript
gpl-2.0
5,888
/** * BxSlider v4.1.2 - Fully loaded, responsive content slider * http://bxslider.com * * Copyright 2014, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com * Written while drinking Belgian ales and listening to jazz * * Released under the MIT license - http://opensource.org/licenses/MIT */ ;(function($){ var plugin = {}; var defaults = { // GENERAL mode: 'horizontal', slideSelector: '', infiniteLoop: true, hideControlOnEnd: false, speed: 1000, easing: 'linear', slideMargin: 0, startSlide: 0, randomStart: false, captions: false, ticker: false, tickerHover: false, adaptiveHeight: false, adaptiveHeightSpeed: 500, video: false, useCSS: false, preloadImages: 'visible', responsive: true, slideZIndex: 50, wrapperClass: 'bx-wrapper', // TOUCH touchEnabled: true, swipeThreshold: 50, oneToOneTouch: true, preventDefaultSwipeX: true, preventDefaultSwipeY: false, // PAGER pager: false, pagerType: 'full', pagerShortSeparator: ' / ', pagerSelector: null, buildPager: null, pagerCustom: null, // CONTROLS controls: true, nextText: 'Next', prevText: 'Prev', nextSelector: null, prevSelector: null, autoControls: false, startText: 'Start', stopText: 'Stop', autoControlsCombine: false, autoControlsSelector: null, // AUTO auto: true, pause: 4000, autoStart: true, autoDirection: 'next', autoHover: true, autoDelay: 0, autoSlideForOnePage: false, // CAROUSEL minSlides: 1, maxSlides: 1, moveSlides: 0, slideWidth: 0, widthType: 'px', // CALLBACKS onSliderLoad: function() {}, onSlideBefore: function() {}, onSlideAfter: function() {}, onSlideNext: function() {}, onSlidePrev: function() {}, onSliderResize: function() {} } $.fn.bxSlider = function(options){ if(this.length == 0) return this; // support mutltiple elements if(this.length > 1){ this.each(function(){$(this).bxSlider(options)}); return this; } // create a namespace to be used throughout the plugin var slider = {}; // set a reference to our slider element var el = this; plugin.el = this; /** * Makes slideshow responsive */ // first get the original window dimens (thanks alot IE) var windowWidth = $(window).width(); var windowHeight = $(window).height(); /** * =================================================================================== * = PRIVATE FUNCTIONS * =================================================================================== */ /** * Initializes namespace settings to be used throughout plugin */ var init = function(){ // merge user-supplied options with the defaults slider.settings = $.extend({}, defaults, options); // parse slideWidth setting slider.settings.slideWidth = parseInt(slider.settings.slideWidth); slider.settings.pagerType = parseInt(slider.settings.navigation); slider.settings.slideMargin = parseInt(slider.settings.slideMargin); slider.settings.oneToOneTouch = slider.settings.oneToOne; // store the original children slider.children = el.children(slider.settings.slideSelector); // check if actual number of slides is less than minSlides / maxSlides if(slider.children.length < slider.settings.minSlides) slider.settings.minSlides = slider.children.length; if(slider.children.length < slider.settings.maxSlides) slider.settings.maxSlides = slider.children.length; // if random start, set the startSlide setting to random number if(slider.settings.randomStart) slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); // store active slide information slider.active = { index: slider.settings.startSlide } // store if the slider is in carousel mode (displaying / moving multiple slides) slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1; // if carousel, force preloadImages = 'all' if(slider.carousel) slider.settings.preloadImages = 'all'; // calculate the min / max width thresholds based on min / max number of slides // used to setup and update carousel slides dimensions slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin); slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); // store the current state of the slider (if currently animating, working is true) slider.working = false; // initialize the controls object slider.controls = {}; // initialize an auto interval slider.interval = null; // determine which property to use for transitions slider.animProp = slider.settings.mode == 'vertical' ? 'top' : 'left'; if(slider.settings.auto == 'enable') { slider.settings.auto = true; } else { slider.settings.auto = false; } if(slider.settings.slideshowControls == 'enable' && slider.settings.auto) { slider.settings.autoControls = true; } else { slider.settings.autoControls = false; } slider.settings.pager = slider.settings.pagerEnabled; // determine if hardware acceleration can be used slider.usingCSS = slider.settings.useCSS && slider.settings.mode != 'fade' && (function(){ // create our test div element var div = document.createElement('div'); // css transition properties var props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']; // test for each property for(var i in props){ if(div.style[props[i]] !== undefined){ slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase(); slider.animProp = '-' + slider.cssPrefix + '-transform'; return true; } } return false; }()); // if vertical mode always make maxSlides and minSlides equal if(slider.settings.mode == 'vertical') slider.settings.maxSlides = slider.settings.minSlides; // save original style data el.data("origStyle", el.attr("style")); el.children(slider.settings.slideSelector).each(function() { $(this).data("origStyle", $(this).attr("style")); }); // perform all DOM / CSS modifications setup(); } /** * Performs all DOM and CSS modifications */ var setup = function(){ // wrap el in a wrapper el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="bx-viewport"></div></div>'); // store a namspace reference to .bx-viewport slider.viewport = el.parent(); // add a loading div to display while images are loading slider.loader = $('<div class="bx-loading" />'); slider.viewport.prepend(slider.loader); // set el to a massive width, to hold any needed slides // also strip any margin and padding from el el.css({ width: slider.settings.mode == 'horizontal' ? (slider.children.length * 100 + 215) + '%' : 'auto', position: 'relative' }); // if using CSS, add the easing property if(slider.usingCSS && slider.settings.easing){ el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing); // if not using CSS and no easing value was supplied, use the default JS animation easing (swing) }else if(!slider.settings.easing){ slider.settings.easing = 'swing'; } var slidesShowing = getNumberSlidesShowing(); // make modifications to the viewport (.bx-viewport) slider.viewport.css({ width: '100%', overflow: 'hidden', position: 'relative' }); slider.viewport.parent().css({ maxWidth: getViewportMaxWidth() }); // make modification to the wrapper (.bx-wrapper) if(!slider.settings.pager) { slider.viewport.parent().css({ margin: '0 auto 0px' }); } // apply css to all slider children slider.children.css({ 'float': slider.settings.mode == 'horizontal' ? 'left' : 'none', listStyle: 'none', position: 'relative' }); // apply the calculated width after the float is applied to prevent scrollbar interference slider.children.css('width', getSlideWidth()); // if slideMargin is supplied, add the css if(slider.settings.mode == 'horizontal' && slider.settings.slideMargin > 0) slider.children.css('marginRight', slider.settings.slideMargin); if(slider.settings.mode == 'vertical' && slider.settings.slideMargin > 0) slider.children.css('marginBottom', slider.settings.slideMargin); // if "fade" mode, add positioning and z-index CSS if(slider.settings.mode == 'fade'){ slider.children.css({ position: 'absolute', zIndex: 0, display: 'none' }); // prepare the z-index on the showing element slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'}); } //set thumbnails function /*if(slider.settings.pagerType) { var resources = $('.thumbnails').clone(); slider.settings.buildPager = function(index) { var img = resources.find('li').get(index); var video = $('.supsystic-slider li').get(index); if($(video).children().hasClass('fluid-width-video-wrapper')) { return '<img src="http://placehold.it/' + Math.floor(this.slideWidth/4.0) + 'x' + Math.floor(this.height/3.0) + '&text=Video">'; } return '<img src="' + $(img).find('img').attr('src') + '">'; } } $('.thumbnails').remove();*/ // create an element to contain all slider controls (pager, start / stop, etc) slider.controls.el = $('<div class="bx-controls" />'); // if captions are requested, add them if(slider.settings.captions) appendCaptions(); // check if startSlide is last slide slider.active.last = slider.settings.startSlide == getPagerQty() - 1; // if video is true, set up the fitVids plugin if(slider.settings.video) el.fitVids(); // set the default preload selector (visible) var preloadSelector = slider.children.eq(slider.settings.startSlide); if (slider.settings.preloadImages == "all") preloadSelector = slider.children; // only check for control addition if not in "ticker" mode if(!slider.settings.ticker){ // if pager is requested, add it if(slider.settings.pager) appendPager(); // if controls are requested, add them if(slider.settings.controls) appendControls(); // if auto is true, and auto controls are requested, add them if(slider.settings.auto && slider.settings.autoControls) appendControlsAuto(); // if any control option is requested, add the controls wrapper if(slider.settings.controls || slider.settings.autoControls || slider.settings.pager) slider.viewport.after(slider.controls.el); // if ticker mode, do not allow a pager }else{ slider.settings.pager = false; } // preload all images, then perform final DOM / CSS modifications that depend on images being loaded loadElements(preloadSelector, start); } var loadElements = function(selector, callback){ var total = selector.find('img, iframe').length; if (total == 0){ callback(); return; } var count = 0; selector.find('img, iframe').each(function(){ $(this).one('load', function() { if(++count == total) callback(); }).each(function() { if(this.complete) $(this).load(); }); }); } /** * Start the slider */ var start = function(){ // if infinite loop, prepare additional slides if(slider.settings.infiniteLoop && slider.settings.mode != 'fade' && !slider.settings.ticker){ var slice = slider.settings.mode == 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides; var sliceAppend = slider.children.slice(0, slice).clone().addClass('bx-clone'); var slicePrepend = slider.children.slice(-slice).clone().addClass('bx-clone'); el.append(sliceAppend).prepend(slicePrepend); } // remove the loading DOM element slider.loader.remove(); // set the left / top position of "el" setSlidePosition(); // if "vertical" mode, always use adaptiveHeight to prevent odd behavior if (slider.settings.mode == 'vertical') slider.settings.adaptiveHeight = true; // set the viewport height slider.viewport.height(getViewportHeight()); // make sure everything is positioned just right (same as a window resize) el.redrawSlider(); // onSliderLoad callback slider.settings.onSliderLoad(slider.active.index); // slider has been fully initialized slider.initialized = true; // bind the resize call to the window if (slider.settings.responsive) $(window).bind('resize', resizeWindow); // if auto is true and has more than 1 page, start the show if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) initAuto(); // if ticker is true, start the ticker if (slider.settings.ticker) initTicker(); // if pager is requested, make the appropriate pager link active if (slider.settings.pager) updatePagerActive(slider.settings.startSlide); // check for any updates to the controls (like hideControlOnEnd updates) if (slider.settings.controls) updateDirectionControls(); // if touchEnabled is true, setup the touch events if (slider.settings.touchEnabled && !slider.settings.ticker) initTouch(); } /** * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value */ var getViewportHeight = function(){ var height = 0; // first determine which children (slides) should be used in our height calculation var children = $(); // if mode is not "vertical" and adaptiveHeight is false, include all children if(slider.settings.mode != 'vertical' && !slider.settings.adaptiveHeight){ children = slider.children; }else{ // if not carousel, return the single active child if(!slider.carousel){ children = slider.children.eq(slider.active.index); // if carousel, return a slice of children }else{ // get the individual slide index var currentIndex = slider.settings.moveSlides == 1 ? slider.active.index : slider.active.index * getMoveBy(); // add the current slide to the children children = slider.children.eq(currentIndex); // cycle through the remaining "showing" slides for (i = 1; i <= slider.settings.maxSlides - 1; i++){ // if looped back to the start if(currentIndex + i >= slider.children.length){ children = children.add(slider.children.eq(i - 1)); }else{ children = children.add(slider.children.eq(currentIndex + i)); } } } } // if "vertical" mode, calculate the sum of the heights of the children if(slider.settings.mode == 'vertical'){ children.each(function(index) { height += $(this).outerHeight(); }); // add user-supplied margins if(slider.settings.slideMargin > 0){ height += slider.settings.slideMargin * (slider.settings.minSlides - 1); } // if not "vertical" mode, calculate the max height of the children }else{ height = Math.max.apply(Math, children.map(function(){ return $(this).outerHeight(false); }).get()); } if(slider.viewport.css('box-sizing') == 'border-box'){ height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) + parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width')); }else if(slider.viewport.css('box-sizing') == 'padding-box'){ height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')); } return height; } /** * Returns the calculated width to be used for the outer wrapper / viewport */ var getViewportMaxWidth = function(){ var width = '100%'; if(slider.settings.slideWidth > 0){ if(slider.settings.mode == 'horizontal'){ width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); }else{ width = slider.settings.slideWidth; } } return width; }; /** * Returns the calculated width to be applied to each slide */ var getSlideWidth = function(){ // start with any user-supplied slide width var newElWidth = slider.settings.slideWidth; // get the current viewport width var wrapWidth = slider.viewport.width(); // if slide width was not supplied, or is larger than the viewport use the viewport width if(slider.settings.slideWidth == 0 || (slider.settings.slideWidth > wrapWidth && !slider.carousel) || slider.settings.mode == 'vertical'){ newElWidth = wrapWidth; // if carousel, use the thresholds to determine the width }else if(slider.settings.maxSlides > 1 && slider.settings.mode == 'horizontal'){ if(wrapWidth > slider.maxThreshold){ // newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.maxSlides - 1))) / slider.settings.maxSlides; }else if(wrapWidth < slider.minThreshold){ newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides; } } return newElWidth; } /** * Returns the number of slides currently visible in the viewport (includes partially visible slides) */ var getNumberSlidesShowing = function(){ var slidesShowing = 1; if(slider.settings.mode == 'horizontal' && slider.settings.slideWidth > 0){ // if viewport is smaller than minThreshold, return minSlides if(slider.viewport.width() < slider.minThreshold){ slidesShowing = slider.settings.minSlides; // if viewport is larger than minThreshold, return maxSlides }else if(slider.viewport.width() > slider.maxThreshold){ slidesShowing = slider.settings.maxSlides; // if viewport is between min / max thresholds, divide viewport width by first child width }else{ var childWidth = slider.children.first().width() + slider.settings.slideMargin; slidesShowing = Math.floor((slider.viewport.width() + slider.settings.slideMargin) / childWidth); } // if "vertical" mode, slides showing will always be minSlides }else if(slider.settings.mode == 'vertical'){ slidesShowing = slider.settings.minSlides; } return slidesShowing; } /** * Returns the number of pages (one full viewport of slides is one "page") */ var getPagerQty = function(){ var pagerQty = 0; // if moveSlides is specified by the user if(slider.settings.moveSlides > 0){ if(slider.settings.infiniteLoop){ pagerQty = Math.ceil(slider.children.length / getMoveBy()); }else{ // use a while loop to determine pages var breakPoint = 0; var counter = 0 // when breakpoint goes above children length, counter is the number of pages while (breakPoint < slider.children.length){ ++pagerQty; breakPoint = counter + getNumberSlidesShowing(); counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing(); } } // if moveSlides is 0 (auto) divide children length by sides showing, then round up }else{ pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing()); } return pagerQty; } /** * Returns the number of indivual slides by which to shift the slider */ var getMoveBy = function(){ // if moveSlides was set by the user and moveSlides is less than number of slides showing if(slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()){ return slider.settings.moveSlides; } // if moveSlides is 0 (auto) return getNumberSlidesShowing(); } /** * Sets the slider's (el) left or top position */ var setSlidePosition = function(){ // if last slide, not infinite loop, and number of children is larger than specified maxSlides if(slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop){ if (slider.settings.mode == 'horizontal'){ // get the last child's position var lastChild = slider.children.last(); var position = lastChild.position(); // set the left position setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0); }else if(slider.settings.mode == 'vertical'){ // get the last showing index's position var lastShowingIndex = slider.children.length - slider.settings.minSlides; var position = slider.children.eq(lastShowingIndex).position(); // set the top position setPositionProperty(-position.top, 'reset', 0); } // if not last slide }else{ // get the position of the first showing slide var position = slider.children.eq(slider.active.index * getMoveBy()).position(); // check for last slide if (slider.active.index == getPagerQty() - 1) slider.active.last = true; // set the repective position if (position != undefined){ if (slider.settings.mode == 'horizontal') setPositionProperty(-position.left, 'reset', 0); else if (slider.settings.mode == 'vertical') setPositionProperty(-position.top, 'reset', 0); } } } /** * Sets the el's animating property position (which in turn will sometimes animate el). * If using CSS, sets the transform property. If not using CSS, sets the top / left property. * * @param value (int) * - the animating property's value * * @param type (string) 'slider', 'reset', 'ticker' * - the type of instance for which the function is being * * @param duration (int) * - the amount of time (in ms) the transition should occupy * * @param params (array) optional * - an optional parameter containing any variables that need to be passed in */ var setPositionProperty = function(value, type, duration, params){ // use CSS transform if(slider.usingCSS){ // determine the translate3d value var propValue = slider.settings.mode == 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)'; // add the CSS transition-duration el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's'); if(type == 'slide'){ // set the property value el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, propValue); }else if(type == 'ticker'){ // make the transition use 'linear' el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear'); el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); // reset the position setPositionProperty(params['resetValue'], 'reset', 0); // start the loop again tickerLoop(); }); } // use JS animate }else{ var animateObj = {}; animateObj[slider.animProp] = value; if(type == 'slide'){ el.animate(animateObj, duration, slider.settings.easing, function(){ updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, value) }else if(type == 'ticker'){ el.animate(animateObj, speed, 'linear', function(){ setPositionProperty(params['resetValue'], 'reset', 0); // run the recursive loop after animation tickerLoop(); }); } } } /** * Populates the pager with proper amount of pages */ var populatePager = function(){ var pagerHtml = ''; var pagerQty = getPagerQty(); // loop through each pager item for(var i=0; i < pagerQty; i++){ var linkContent = ''; // if a buildPager function is supplied, use it to get pager link value, else use index + 1 if(slider.settings.buildPager && $.isFunction(slider.settings.buildPager)){ linkContent = slider.settings.buildPager(i); slider.pagerEl.addClass('bx-custom-pager'); }else{ linkContent = i + 1; slider.pagerEl.addClass('bx-default-pager'); } // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1; // add the markup to the string pagerHtml += '<li class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></li>'; }; // populate the pager element with pager links slider.pagerEl.html(pagerHtml); } /** * Appends the pager to the controls element */ var appendPager = function(){ if(!slider.settings.pagerCustom){ // create the pager DOM element slider.pagerEl = $('<ul class="bx-pager" data-center="1" data-transform="0"/>'); // if a pager selector was supplied, populate it with the pager if(slider.settings.pagerSelector){ $(slider.settings.pagerSelector).html(slider.pagerEl); // if no pager selector was supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl); if(slider.settings.pagerType) { slider.controls.el.addClass('thumbnails'); } } // populate the pager populatePager(); }else{ slider.pagerEl = $(slider.settings.pagerCustom); } // assign the pager click binding slider.pagerEl.on('click', 'a', clickPagerBind); } /** * Appends prev / next controls to the controls element */ var appendControls = function(){ slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>'); slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>'); // bind click actions to the controls slider.controls.next.bind('click', clickNextBind); slider.controls.prev.bind('click', clickPrevBind); // if nextSlector was supplied, populate it if(slider.settings.nextSelector){ $(slider.settings.nextSelector).append(slider.controls.next); } // if prevSlector was supplied, populate it if(slider.settings.prevSelector){ $(slider.settings.prevSelector).append(slider.controls.prev); } // if no custom selectors were supplied if(!slider.settings.nextSelector && !slider.settings.prevSelector){ // add the controls to the DOM slider.controls.directionEl = $('<div class="bx-controls-direction" />'); // add the control elements to the directionEl slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next); // slider.viewport.append(slider.controls.directionEl); slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl); } } /** * Appends start / stop auto controls to the controls element */ var appendControlsAuto = function(){ slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>'); slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>'); // add the controls to the DOM slider.controls.autoEl = $('<div class="bx-controls-auto" />'); // bind click actions to the controls slider.controls.autoEl.on('click', '.bx-start', clickStartBind); slider.controls.autoEl.on('click', '.bx-stop', clickStopBind); // if autoControlsCombine, insert only the "start" control if(slider.settings.autoControlsCombine){ slider.controls.autoEl.append(slider.controls.start); // if autoControlsCombine is false, insert both controls }else{ slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop); } // if auto controls selector was supplied, populate it with the controls if(slider.settings.autoControlsSelector){ $(slider.settings.autoControlsSelector).html(slider.controls.autoEl); // if auto controls selector was not supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl); } // update the auto controls updateAutoControls(slider.settings.autoStart ? 'stop' : 'start'); } /** * Appends image captions to the DOM */ var appendCaptions = function(){ var htmlDecode = function(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }; // cycle through each child slider.children.each(function(index){ // get the image title attribute var title = $(this).find('img:first').attr('title'); // append the caption if (title != undefined && ('' + title).length) { $(this).append('<div class="bx-caption"><span class="caption"></span></div>'); if(/<[a-z][\s\S]*>/i.test(htmlDecode(title))) { title = $(htmlDecode(title)); } $(this).find('.caption').append(title); //var padding = parseInt($(this).find('.bx-caption').css('padding'), 10); //$(this).find('.bx-caption').css('width', (getSlideWidth() - 2*padding) + 'px'); } }); } /** * Click next binding * * @param e (event) * - DOM event object */ var clickNextBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToNextSlide(); /*if(slider.settings.pagerType) { pagerMoveLeft(); }*/ e.preventDefault(); }; /** * Click prev binding * * @param e (event) * - DOM event object */ var clickPrevBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToPrevSlide(); /*if(slider.settings.pagerType) { pagerMoveRight(); }*/ e.preventDefault(); }; /** * Click start binding * * @param e (event) * - DOM event object */ var clickStartBind = function(e){ el.startAuto(); e.preventDefault(); } /** * Click stop binding * * @param e (event) * - DOM event object */ var clickStopBind = function(e){ el.stopAuto(); e.preventDefault(); } /** * Click pager binding * * @param e (event) * - DOM event object */ var clickPagerBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); var pagerLink = $(e.currentTarget); if(pagerLink.attr('data-slide-index') !== undefined){ var pagerIndex = parseInt(pagerLink.attr('data-slide-index')); // if clicked pager link is not active, continue with the goToSlide call if(pagerIndex != slider.active.index) el.goToSlide(pagerIndex); e.preventDefault(); } /*if(slider.settings.pagerType) { pagerTranslate(this); }*/ }; /*var pagerTranslate = function(self) { var $pager = $('.bx-pager'); if($(self).parent('li').index() > parseInt($pager.data('center'), 10)) { $pager.data('center', parseInt($pager.data('center'), 10) + $pager.find('li').length - $(self).parent('li').index()); }else { $pager.data('center', parseInt($pager.data('center'), 10) - $pager.find('li').length - $(self).parent('li').index()); } }; var thumbnailTranslate = function(element, translate, $pager) { element.css({ 'transform': 'translateX(' + translate + 'px)', '-webkit-transform': 'translateX(' + translate + 'px)', '-moz-transform': 'translateX(' + translate + 'px)', '-o-transform': 'translateX(' + translate + 'px)', 'transition': '0.4s', '-webkit-transition': '0.4s', '-moz-transition': '0.4s', '-o-transition': '0.4s' }); $pager.data('transform', translate); }; var pagerMoveLeft = function() { var $pager = $('.bx-pager'), translate = $pager.data('transform'); if(parseInt($pager.data('center')) < $pager.find('li').length - 3) { translate -= slider.settings.slideWidth/4; $pager.find('li').each(function() { //translate = new WebKitCSSMatrix(translate).m41; thumbnailTranslate($(this), translate, $pager); }); } if(parseInt($pager.data('center')) == $pager.find('li').length) { $pager.data('center', parseInt($pager.data('center'), 10) - $pager.find('li').length); $pager.find('li').each(function() { //translate = new WebKitCSSMatrix(translate).m41; thumbnailTranslate($(this), Math.floor(slider.settings.slideWidth/4)*($pager.find('li').length - 5), $pager); }); } $pager.data('center', parseInt($pager.data('center'), 10) + 1); }; var pagerMoveRight = function() { var $pager = $('.bx-pager'), translate = $pager.data('transform'); if(parseInt($pager.data('center')) > 4 ) { translate += slider.settings.slideWidth/4; $pager.find('li').each(function() { //translate = new WebKitCSSMatrix(translate).m41; thumbnailTranslate($(this), translate, $pager); }); } if(parseInt($pager.data('center')) == 1) { $pager.data('center', parseInt($pager.data('center'), 10) + $pager.find('li').length); $pager.find('li').each(function() { //translate = new WebKitCSSMatrix(translate).m41; thumbnailTranslate($(this), -Math.floor(slider.settings.slideWidth/4)*($pager.find('li').length - 4), $pager); }); } $pager.data('center', parseInt($pager.data('center'), 10) - 1); };*/ /** * Updates the pager links with an active class * * @param slideIndex (int) * - index of slide to make active */ var updatePagerActive = function(slideIndex){ // if "short" pager type var len = slider.children.length; // nb of children if(slider.settings.pagerType == 'short'){ if(slider.settings.maxSlides > 1) { len = Math.ceil(slider.children.length/slider.settings.maxSlides); } slider.pagerEl.html( (slideIndex + 1) + slider.settings.pagerShortSeparator + len); return; } // remove all pager active classes slider.pagerEl.find('a').removeClass('active'); // apply the active class for all pagers slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); }); } /** * Performs needed actions after a slide transition */ var updateAfterSlideTransition = function(){ // if infinte loop is true if(slider.settings.infiniteLoop){ var position = ''; // first slide if(slider.active.index == 0){ // set the new position position = slider.children.eq(0).position(); // carousel, last slide }else if(slider.active.index == getPagerQty() - 1 && slider.carousel){ position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position(); // last slide }else if(slider.active.index == slider.children.length - 1){ position = slider.children.eq(slider.children.length - 1).position(); } if(position){ if (slider.settings.mode == 'horizontal') { setPositionProperty(-position.left, 'reset', 0); } else if (slider.settings.mode == 'vertical') { setPositionProperty(-position.top, 'reset', 0); } } } // declare that the transition is complete slider.working = false; // onSlideAfter callback slider.settings.onSlideAfter(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } /** * Updates the auto controls state (either active, or combined switch) * * @param state (string) "start", "stop" * - the new state of the auto show */ var updateAutoControls = function(state){ // if autoControlsCombine is true, replace the current control with the new state if(slider.settings.autoControlsCombine){ slider.controls.autoEl.html(slider.controls[state]); // if autoControlsCombine is false, apply the "active" class to the appropriate control }else{ slider.controls.autoEl.find('a').removeClass('active'); slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active'); } } /** * Updates the direction controls (checks if either should be hidden) */ var updateDirectionControls = function(){ if(getPagerQty() == 1){ slider.controls.prev.addClass('disabled'); slider.controls.next.addClass('disabled'); }else if(!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd){ // if first slide if (slider.active.index == 0){ slider.controls.prev.addClass('disabled'); slider.controls.next.removeClass('disabled'); // if last slide }else if(slider.active.index == getPagerQty() - 1){ slider.controls.next.addClass('disabled'); slider.controls.prev.removeClass('disabled'); // if any slide in the middle }else{ slider.controls.prev.removeClass('disabled'); slider.controls.next.removeClass('disabled'); } } } /** * Initialzes the auto process */ var initAuto = function(){ // if autoDelay was supplied, launch the auto show using a setTimeout() call if(slider.settings.autoDelay > 0){ var timeout = setTimeout(el.startAuto, slider.settings.autoDelay); // if autoDelay was not supplied, start the auto show normally }else{ el.startAuto(); } // if autoHover is requested if(slider.settings.autoHover){ // on el hover el.hover(function(){ // if the auto show is currently playing (has an active interval) if(slider.interval){ // stop the auto show and pass true agument which will prevent control update el.stopAuto(true); // create a new autoPaused value which will be used by the relative "mouseout" event slider.autoPaused = true; } }, function(){ // if the autoPaused value was created be the prior "mouseover" event if(slider.autoPaused){ // start the auto show and pass true agument which will prevent control update el.startAuto(true); // reset the autoPaused value slider.autoPaused = null; } }); } } /** * Initialzes the ticker process */ var initTicker = function(){ var startPosition = 0; // if autoDirection is "next", append a clone of the entire slider if(slider.settings.autoDirection == 'next'){ el.append(slider.children.clone().addClass('bx-clone')); // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position }else{ el.prepend(slider.children.clone().addClass('bx-clone')); var position = slider.children.first().position(); startPosition = slider.settings.mode == 'horizontal' ? -position.left : -position.top; } setPositionProperty(startPosition, 'reset', 0); // do not allow controls in ticker mode slider.settings.pager = false; slider.settings.controls = false; slider.settings.autoControls = false; // if autoHover is requested if(slider.settings.tickerHover && !slider.usingCSS){ // on el hover slider.viewport.hover(function(){ el.stop(); }, function(){ // calculate the total width of children (used to calculate the speed ratio) var totalDimens = 0; slider.children.each(function(index){ totalDimens += slider.settings.mode == 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true); }); // calculate the speed ratio (used to determine the new speed to finish the paused animation) var ratio = slider.settings.speed / totalDimens; // determine which property to use var property = slider.settings.mode == 'horizontal' ? 'left' : 'top'; // calculate the new speed var newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property))))); tickerLoop(newSpeed); }); } // start the ticker loop tickerLoop(); } /** * Runs a continuous loop, news ticker-style */ var tickerLoop = function(resumeSpeed){ speed = resumeSpeed ? resumeSpeed : slider.settings.speed; var position = {left: 0, top: 0}; var reset = {left: 0, top: 0}; // if "next" animate left position to last child, then reset left to 0 if(slider.settings.autoDirection == 'next'){ position = el.find('.bx-clone').first().position(); // if "prev" animate left position to 0, then reset left to first non-clone child }else{ reset = slider.children.first().position(); } var animateProperty = slider.settings.mode == 'horizontal' ? -position.left : -position.top; var resetValue = slider.settings.mode == 'horizontal' ? -reset.left : -reset.top; var params = {resetValue: resetValue}; setPositionProperty(animateProperty, 'ticker', speed, params); } /** * Initializes touch events */ var initTouch = function(){ // initialize object to contain all touch values slider.touch = { start: {x: 0, y: 0}, end: {x: 0, y: 0} } slider.viewport.bind('touchstart', onTouchStart); } /** * Event handler for "touchstart" * * @param e (event) * - DOM event object */ var onTouchStart = function(e){ if(slider.working){ e.preventDefault(); }else{ // record the original position when touch starts slider.touch.originalPos = el.position(); var orig = e.originalEvent; // record the starting touch x, y coordinates slider.touch.start.x = orig.changedTouches[0].pageX; slider.touch.start.y = orig.changedTouches[0].pageY; // bind a "touchmove" event to the viewport slider.viewport.bind('touchmove', onTouchMove); // bind a "touchend" event to the viewport slider.viewport.bind('touchend', onTouchEnd); } } /** * Event handler for "touchmove" * * @param e (event) * - DOM event object */ var onTouchMove = function(e){ var orig = e.originalEvent; // if scrolling on y axis, do not prevent default var xMovement = Math.abs(orig.changedTouches[0].pageX - slider.touch.start.x); var yMovement = Math.abs(orig.changedTouches[0].pageY - slider.touch.start.y); // x axis swipe if((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX){ e.preventDefault(); // y axis swipe }else if((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY){ e.preventDefault(); } if(slider.settings.mode != 'fade' && slider.settings.oneToOneTouch){ var value = 0; // if horizontal, drag along x axis if(slider.settings.mode == 'horizontal'){ var change = orig.changedTouches[0].pageX - slider.touch.start.x; value = slider.touch.originalPos.left + change; // if vertical, drag along y axis }else{ var change = orig.changedTouches[0].pageY - slider.touch.start.y; value = slider.touch.originalPos.top + change; } setPositionProperty(value, 'reset', 0); } } /** * Event handler for "touchend" * * @param e (event) * - DOM event object */ var onTouchEnd = function(e){ slider.viewport.unbind('touchmove', onTouchMove); var orig = e.originalEvent; var value = 0; // record end x, y positions slider.touch.end.x = orig.changedTouches[0].pageX; slider.touch.end.y = orig.changedTouches[0].pageY; // if fade mode, check if absolute x distance clears the threshold if(slider.settings.mode == 'fade'){ var distance = Math.abs(slider.touch.start.x - slider.touch.end.x); if(distance >= slider.settings.swipeThreshold){ slider.touch.start.x > slider.touch.end.x ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); } // not fade mode }else{ var distance = 0; // calculate distance and el's animate property if(slider.settings.mode == 'horizontal'){ distance = slider.touch.end.x - slider.touch.start.x; value = slider.touch.originalPos.left; }else{ distance = slider.touch.end.y - slider.touch.start.y; value = slider.touch.originalPos.top; } // if not infinite loop and first / last slide, do not attempt a slide transition if(!slider.settings.infiniteLoop && ((slider.active.index == 0 && distance > 0) || (slider.active.last && distance < 0))){ setPositionProperty(value, 'reset', 200); }else{ // check if distance clears threshold if(Math.abs(distance) >= slider.settings.swipeThreshold){ distance < 0 ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); }else{ // el.animate(property, 200); setPositionProperty(value, 'reset', 200); } } } slider.viewport.unbind('touchend', onTouchEnd); } /** * Window resize event callback */ var resizeWindow = function(e){ // don't do anything if slider isn't initialized. if(!slider.initialized) return; // get the new window dimens (again, thank you IE) var windowWidthNew = $(window).width(); var windowHeightNew = $(window).height(); // make sure that it is a true window resize // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements // are resized. Can you just die already?* if(windowWidth != windowWidthNew || windowHeight != windowHeightNew){ // set the new window dimens windowWidth = windowWidthNew; windowHeight = windowHeightNew; // update all dynamic elements el.redrawSlider(); // Call user resize handler slider.settings.onSliderResize.call(el, slider.active.index); } } /** * =================================================================================== * = PUBLIC FUNCTIONS * =================================================================================== */ /** * Performs slide transition to the specified slide * * @param slideIndex (int) * - the destination slide's index (zero-based) * * @param direction (string) * - INTERNAL USE ONLY - the direction of travel ("prev" / "next") */ el.goToSlide = function(slideIndex, direction){ // if plugin is currently in motion, ignore request if(slider.working || slider.active.index == slideIndex) return; // declare that plugin is in motion slider.working = true; // store the old index slider.oldIndex = slider.active.index; // if slideIndex is less than zero, set active index to last child (this happens during infinite loop) if(slideIndex < 0){ slider.active.index = getPagerQty() - 1; // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop) }else if(slideIndex >= getPagerQty()){ slider.active.index = 0; // set active index to requested slide }else{ slider.active.index = slideIndex; } // onSlideBefore, onSlideNext, onSlidePrev callbacks slider.settings.onSlideBefore(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); if(direction == 'next'){ slider.settings.onSlideNext(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); }else if(direction == 'prev'){ slider.settings.onSlidePrev(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } // check if last slide slider.active.last = slider.active.index >= getPagerQty() - 1; // update the pager with active class if(slider.settings.pager) updatePagerActive(slider.active.index); // // check for direction control update if(slider.settings.controls) updateDirectionControls(); // if slider is set to mode: "fade" if(slider.settings.mode == 'fade'){ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } // fade out the visible child and reset its z-index value slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0}); // fade in the newly requested slide slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex+1).fadeIn(slider.settings.speed, function(){ $(this).css('zIndex', slider.settings.slideZIndex); updateAfterSlideTransition(); }); // slider mode is not "fade" }else{ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } var moveBy = 0; var position = {left: 0, top: 0}; // if carousel and not infinite loop if(!slider.settings.infiniteLoop && slider.carousel && slider.active.last){ if(slider.settings.mode == 'horizontal'){ // get the last child position var lastChild = slider.children.eq(slider.children.length - 1); position = lastChild.position(); // calculate the position of the last slide moveBy = slider.viewport.width() - lastChild.outerWidth(); }else{ // get last showing index position var lastShowingIndex = slider.children.length - slider.settings.minSlides; position = slider.children.eq(lastShowingIndex).position(); } // horizontal carousel, going previous while on first slide (infiniteLoop mode) }else if(slider.carousel && slider.active.last && direction == 'prev'){ // get the last child position var eq = slider.settings.moveSlides == 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides); var lastChild = el.children('.bx-clone').eq(eq); position = lastChild.position(); // if infinite loop and "Next" is clicked on the last slide }else if(direction == 'next' && slider.active.index == 0){ // get the last clone position position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position(); slider.active.last = false; // normal non-zero requests }else if(slideIndex >= 0){ var requestEl = slideIndex * getMoveBy(); position = slider.children.eq(requestEl).position(); } /* If the position doesn't exist * (e.g. if you destroy the slider on a next click), * it doesn't throw an error. */ if ("undefined" !== typeof(position)) { var value = slider.settings.mode == 'horizontal' ? -(position.left - moveBy) : -position.top; // plugin values to be animated setPositionProperty(value, 'slide', slider.settings.speed); } } } /** * Transitions to the next slide in the show */ el.goToNextSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.last) return; var pagerIndex = parseInt(slider.active.index) + 1; el.goToSlide(pagerIndex, 'next'); } /** * Transitions to the prev slide in the show */ el.goToPrevSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.index == 0) return; var pagerIndex = parseInt(slider.active.index) - 1; el.goToSlide(pagerIndex, 'prev'); } /** * Starts the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.startAuto = function(preventControlUpdate){ // if an interval already exists, disregard call if(slider.interval) return; // create an interval slider.interval = setInterval(function(){ slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide(); }, slider.settings.pause); // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop'); } /** * Stops the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.stopAuto = function(preventControlUpdate){ // if no interval exists, disregard call if(!slider.interval) return; // clear the interval clearInterval(slider.interval); slider.interval = null; // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('start'); } /** * Returns current slide index (zero-based) */ el.getCurrentSlide = function(){ return slider.active.index; } /** * Returns current slide element */ el.getCurrentSlideElement = function(){ return slider.children.eq(slider.active.index); } /** * Returns number of slides in show */ el.getSlideCount = function(){ return slider.children.length; } /** * Update all dynamic slider elements */ el.redrawSlider = function(){ // resize all children in ratio to new screen size slider.children.add(el.find('.bx-clone')).width(getSlideWidth()); // adjust the height slider.viewport.css('height', getViewportHeight()); // update the slide position if(!slider.settings.ticker) setSlidePosition(); // if active.last was true before the screen resize, we want // to keep it last no matter what screen size we end on if (slider.active.last) slider.active.index = getPagerQty() - 1; // if the active index (page) no longer exists due to the resize, simply set the index as last if (slider.active.index >= getPagerQty()) slider.active.last = true; // if a pager is being displayed and a custom pager is not being used, update it if(slider.settings.pager && !slider.settings.pagerCustom){ //populatePager(); updatePagerActive(slider.active.index); } } /** * Destroy the current instance of the slider (revert everything back to original state) */ el.destroySlider = function(){ // don't do anything if slider has already been destroyed if(!slider.initialized) return; slider.initialized = false; $('.bx-clone', this).remove(); slider.children.each(function() { $(this).data("origStyle") != undefined ? $(this).attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); }); $(this).data("origStyle") != undefined ? this.attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); $(this).unwrap().unwrap(); if(slider.controls.el) slider.controls.el.remove(); if(slider.controls.next) slider.controls.next.remove(); if(slider.controls.prev) slider.controls.prev.remove(); if(slider.pagerEl && slider.settings.controls) slider.pagerEl.remove(); $('.bx-caption', this).remove(); if(slider.controls.autoEl) slider.controls.autoEl.remove(); clearInterval(slider.interval); if(slider.settings.responsive) $(window).unbind('resize', resizeWindow); } /** * Reload the slider (revert all DOM changes, and re-initialize) */ el.reloadSlider = function(settings){ if (settings != undefined) options = settings; el.destroySlider(); init(); } init(); // returns the current jQuery object return this; } })(jQuery);
dibstigz/myrecipechannel
wp-content/plugins/slider-by-supsystic/src/SupsysticSlider/Bx/assets/js/jquery.bxslider.js
JavaScript
gpl-2.0
55,186
var FuppesLog = new Class({ initialize: function(options) { this.worker = null; this.scroll = new Fx.Scroll($('log-output').getParent()); }, start: function() { if(this.worker != null) { delete this.worker; this.worker = null; } this.worker = new Worker('fuppes-log-worker.js'); this.worker.onmessage = this.onWorkerMessage.bind(this); this.worker.postMessage('start'); }, onWorkerMessage: function(event) { var result = "<div style=\"border: 1px solid green;\">"; xml = loadXmlResult(event.data); xml.documentElement.getChildren().each(function(item, index) { result += "<p style=\"border: 1px solid red;\">"; result += item.getElement('message').get('text'); result += "</p>"; }); result += "</div>"; $('log-output').innerHTML += result; this.scroll.toBottom(); }, stop: function() { this.worker.postMessage('stop'); }, }); var fuppeslog = null; window.addEvent('load', function() { $('log-output').getParent().setStyle('overflow-y', 'scroll'); fuppeslog = new FuppesLog(); $('btn-start').addEvent('click', function() { fuppeslog.start(); }); $('btn-stop').addEvent('click', function() { fuppeslog.stop(); }); $('btn-clear').addEvent('click', function() { $('log-output').innerHTML = ""; }); });
uvoelkel/fuppes
resources/fuppes-log.js
JavaScript
gpl-2.0
1,337
function changeNameLength(name, limit) { return (name.length > limit) ? name.substring(0, limit - 3) + "..." : name; } function getTimesheet(data) { data = $.parseJSON(data); $(".alert").addClass("display-hide"); $(".schedule-info").removeClass("display-hide"); $("#turn").hide(); $(".table-container").hide(); if (data.valid == null) { $(".schedule-info").addClass("display-hide"); } else if (!data.valid) { if (data.error == "curricularMatrix") { $(".alert").removeClass("display-hide"); } } else { $(".table-container").show(); $("#turn").show(); generateTimesheet(data.schedules); } } $(document).on("click", ".btn-generate-timesheet", function () { var classroom = $("select.classroom-id").val(); $.ajax({ 'url': generateTimesheetURL, 'type': 'POST', 'data': { 'classroom': classroom, }, }).success(function (result) { getTimesheet(result); }); }); function generateTimesheet(data) { var i = 0; var turn = 0; $(".table-timesheet tr td").children().remove(); $.each(data, function (weekDay, schedules) { $.each(schedules, function (schedule, info) { if (i == 0) { if (info.turn == 0) turn = "Manhã"; if (info.turn == 1) turn = "Tarde"; if (info.turn == 2) turn = "Noite"; i++; } var discipline = changeNameLength(info.disciplineName, 20); var instructor = changeNameLength(info.instructorInfo.name, 30); var icons = ""; if (info.instructorInfo.unavailable) icons += "<i title='Horário indisponível para o instrutor.' class='unavailability-icon fa fa-times-circle darkred'></i>"; if (info.instructorInfo.countConflicts > 1) icons += "<i title='Instrutor possui " + info.instructorInfo.countConflicts + " conflitos neste horário.' class='fa fa-exclamation-triangle conflict-icon darkgoldenrod'></i>"; $(".table-timesheet tr#h" + schedule + " td[week_day=" + weekDay + "]").html( "<div schedule='"+info.id+"' class='schedule-block'>"+ "<p class='discipline-name' discipline_id='" + info.disciplineId + "' title='" + info.disciplineName + "'>" + discipline + "</p>" + "<p class='instructor-name' instructor_id='"+ info.instructorInfo.id +"' title='" + info.instructorInfo.name + "'>" + instructor + "<i class='fa fa-pencil edit-instructor'></i></p>" + icons+ "</div>"); }); }); $("#turn").text(turn); } $(document).on("click", ".schedule-selected .instructor-name",function(){ var instructorId = $(this).attr("instructor_id"); var disciplineId = $(this).parent().find(".discipline-name").attr("discipline_id"); var scheduleId = $(this).parent().attr("schedule"); $.ajax({ 'url': getInstructorsUrl, 'type': 'POST', 'data': { 'discipline':disciplineId }, }).success(function (result) { $("#change-instructor-schedule").val(scheduleId); $("#change-instructor-id").html(result); $("#change-instructor-id").val(instructorId).select2(); $("#change-instructor-modal").modal(); }); }); $(document).on("click", "#change-instructor-button", function(){ $.ajax({ 'url': changeInstructorUrl, 'type': 'POST', 'data': { 'schedule':$("#change-instructor-schedule").val(), 'instructor':$("#change-instructor-id").val() }, }).success(function (result) { getTimesheet(result); $("#change-instructor-modal").modal('hide'); }); }); $(document).on("click", ".table-timesheet td",function(){ if($(this).hasClass("schedule-selected")){ $(this).removeClass("schedule-selected"); }else{ //Já selecionou alguem if($(".table-timesheet").find(".schedule-selected").length > 0){ var firstSelected = $(".table-timesheet").find(".schedule-selected"); var secondSelected = $(this); var firstSchedule = null; var secondSchedule = null; if(firstSelected.find(".schedule-block").length > 0){ firstSchedule = {"id":firstSelected.find(".schedule-block").attr("schedule")}; }else{ firstSchedule = {"id":null, "week_day": firstSelected.attr("week_day"), "schedule":firstSelected.parent().attr("id").replace("h","")}; } if(secondSelected.find(".schedule-block").length > 0){ secondSchedule = {"id":secondSelected.find(".schedule-block").attr("schedule")}; }else{ secondSchedule = {"id":null, "week_day": secondSelected.attr("week_day"), "schedule":secondSelected.parent().attr("id").replace("h","")}; } changeSchedule(firstSchedule, secondSchedule); }else { //Primeira seleção $(this).addClass("schedule-selected"); } } }); function changeSchedule(firstSchedule, secondSchedule){ $.ajax({ 'url': changeSchedulesURL, 'type': 'POST', 'data': { 'firstSchedule': firstSchedule, 'secondSchedule': secondSchedule, }, }).success(function (result) { getTimesheet(result); $('.schedule-selected').removeClass("schedule-selected"); }); }
ipti/br.tag
app/modules/timesheet/resources/common/js/timesheet.js
JavaScript
gpl-2.0
5,484
/* * Copyright (C) eZ Systems AS. All rights reserved. * For full copyright and license information view LICENSE file distributed with this source code. */ YUI.add('ez-relationlist-editview-tests', function (Y) { var viewTest, registerTest, universalDiscoveryRelationTest, getFieldTest, getEmptyFieldTest, tapTest, loadObjectRelationsTest, initializerTest, Assert = Y.Assert; viewTest = new Y.Test.Case({ name: "eZ Relation list View test", _getFieldDefinition: function (required) { return { isRequired: required }; }, setUp: function () { this.relatedContents = []; this.fieldDefinitionIdentifier= "niceField"; this.fieldDefinition = { fieldType: "ezobjectrelationlist", identifier: this.fieldDefinitionIdentifier, isRequired: false }; this.field = {fieldValue: {destinationContentIds: [45, 42]}}; this.jsonContent = {}; this.jsonContentType = {}; this.jsonVersion = {}; this.loadingError = false; this.content = new Y.Mock(); this.version = new Y.Mock(); this.contentType = new Y.Mock(); Y.Mock.expect(this.content, { method: 'toJSON', returns: this.jsonContent }); Y.Mock.expect(this.version, { method: 'toJSON', returns: this.jsonVersion }); Y.Mock.expect(this.contentType, { method: 'toJSON', returns: this.jsonContentType }); this.view = new Y.eZ.RelationListEditView({ container: '.container', field: this.field, fieldDefinition: this.fieldDefinition, content: this.content, version: this.version, contentType: this.contentType, relatedContents: this.relatedContents, translating: false, }); }, tearDown: function () { this.view.destroy(); delete this.view; }, _testAvailableVariables: function (required, expectRequired) { var fieldDefinition = this._getFieldDefinition(required), that = this, destContentToJSONArray = []; this.view.set('fieldDefinition', fieldDefinition); this.view.template = function (variables) { Y.Assert.isObject(variables, "The template should receive some variables"); Y.Assert.areEqual(10, Y.Object.keys(variables).length, "The template should receive 10 variables"); Y.Assert.areSame( that.jsonContent, variables.content, "The content should be available in the field edit view template" ); Y.Assert.areSame( that.jsonVersion, variables.version, "The version should be available in the field edit view template" ); Y.Assert.areSame( that.jsonContentType, variables.contentType, "The contentType should be available in the field edit view template" ); Y.Assert.areSame( fieldDefinition, variables.fieldDefinition, "The fieldDefinition should be available in the field edit view template" ); Y.Assert.areSame( that.field, variables.field, "The field should be available in the field edit view template" ); Y.Assert.isFalse( variables.isNotTranslatable, "The isNotTranslatable should be available in the field edit view template" ); Y.Assert.areSame( that.view.get('loadingError'), variables.loadingError, "The field should be available in the field edit view template" ); Y.Array.each(that.view.get('relatedContents'), function (destContent) { destContentToJSONArray.push(destContent.toJSON()); }); for ( var i = 0; i<= variables.relatedContents.length; i++){ Y.Assert.areSame( destContentToJSONArray[i], variables.relatedContents[i], "The field should be available in the field edit view template" ); } Y.Assert.areSame(expectRequired, variables.isRequired); return ''; }; this.view.render(); }, "Test required field": function () { this._testAvailableVariables(true, true); }, "Test not required field": function () { this._testAvailableVariables(false, false); }, "Test validate no constraints": function () { var fieldDefinition = this._getFieldDefinition(false); this.view.set('fieldDefinition', fieldDefinition); this.view.set('relatedContents', []); this.view.render(); this.view.validate(); Y.Assert.isTrue( this.view.isValid(), "An empty relation is valid" ); }, "Test validate required": function () { var fieldDefinition = this._getFieldDefinition(true); this.view.set('fieldDefinition', fieldDefinition); this.view.set('relatedContents', []); this.view.validate(); this.view.render(); Y.Assert.isFalse( this.view.isValid(), "An empty relation is NOT valid" ); }, "Should render the view when the loadingError attribute changes": function () { var templateCalled = false, origTpl = this.view.template; this.view.template = function (variables) { templateCalled = true; return origTpl.apply(this, arguments); }; this.view.set('loadingError', true); Y.Assert.isTrue(templateCalled, "The template has not been used"); }, "Should render the view when the destinationContent attribute changes": function () { var templateCalled = false, origTpl = this.view.template; this.view.template = function (variables) { templateCalled = true; return origTpl.apply(this, arguments); }; this.view.set('relatedContents', this.relatedContents); Y.Assert.isTrue(templateCalled, "The template has not been used"); }, }); Y.Test.Runner.setName("eZ Relation list Edit View tests"); Y.Test.Runner.add(viewTest); initializerTest = new Y.Test.Case({ name: "eZ Relation list initializing test", _getFieldDefinition: function (required) { return { isRequired: required }; }, setUp: function () { this.fieldDefinitionIdentifier= "niceField"; this.fieldDefinition = { fieldType: "ezobjectrelationlist", identifier: this.fieldDefinitionIdentifier, isRequired: false }; this.field = {fieldValue: {destinationContentIds: [45, 42]}}; this.view = new Y.eZ.RelationListEditView({ field: this.field, fieldDefinition: this.fieldDefinition, relatedContents: this.relatedContents, }); }, tearDown: function () { this.view.destroy(); delete this.view; }, "Should fill the destinationContentsIds attribute from the field": function () { Y.Assert.isArray( this.view.get('destinationContentsIds'), "destinationContentsIds should be an array" ); for (var i = 0; i <= this.view.get('destinationContentsIds').length; i++) { Y.Assert.areSame( this.view.get('field').fieldValue.destinationContentIds[i], this.view.get('destinationContentsIds')[i], "The destinationContentId of the field value should be the same than the attribute" ); } }, }); Y.Test.Runner.add(initializerTest); universalDiscoveryRelationTest = new Y.Test.Case({ name: "eZ Relation list universal discovery relation test", _getFieldDefinition: function (required) { return { isRequired: required, fieldSettings: {}, }; }, setUp: function () { this.relatedContents = []; this.fieldDefinitionIdentifier= "niceField"; this.fieldDefinition = { fieldType: "ezobjectrelationlist", identifier: this.fieldDefinitionIdentifier, isRequired: false, fieldSettings: { selectionContentTypes: ['allowed_content_type_identifier'] } }; this.field = {fieldValue: {destinationContentIds: [45, 42]}}; this.jsonContent = {}; this.jsonContentType = {}; this.jsonVersion = {}; this.content = new Y.Mock(); this.version = new Y.Mock(); this.contentType = new Y.Mock(); Y.Mock.expect(this.content, { method: 'toJSON', returns: this.jsonContent }); Y.Mock.expect(this.version, { method: 'toJSON', returns: this.jsonVersion }); Y.Mock.expect(this.contentType, { method: 'toJSON', returns: this.jsonContentType }); this.view = new Y.eZ.RelationListEditView({ container: '.container', field: this.field, fieldDefinition: this.fieldDefinition, content: this.content, version: this.version, contentType: this.contentType, relatedContents: this.relatedContents, }); }, tearDown: function () { this.view.destroy(); delete this.view; }, "Should validate when the universal discovery is canceled (empty relation)": function () { var that = this, fieldDefinition = this._getFieldDefinition(true); this.view.set('fieldDefinition', fieldDefinition); this.view._set('destinationContentsIds', null); this.view.on('contentDiscover', function (e) { that.resume(function () { e.config.cancelDiscoverHandler.call(this); Y.Assert.areSame( this.view.get('errorStatus'), 'this.field.is.required domain=fieldedit', 'errorStatus should be true' ); }); }); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, "Should validate when the universal discovery is canceled": function () { var that = this, fieldDefinition = this._getFieldDefinition(false); this.view.set('fieldDefinition', fieldDefinition); this.view.on('contentDiscover', function (e) { that.resume(function () { e.config.cancelDiscoverHandler.call(this); Y.Assert.isFalse(this.view.get('errorStatus'),'errorStatus should be false'); }); }); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, "Should fill the relation with the universal discovery widget selection": function () { var that = this, contentInfoMock1 = new Y.Mock(), contentInfoMock2 = new Y.Mock(), fakeEventFacade = {selection: [{contentInfo: contentInfoMock1}, {contentInfo: contentInfoMock2}]}, contentIdsArray; this.view._set('destinationContentsIds', [42, 45]); contentIdsArray = Y.Array.dedupe(that.view.get('destinationContentsIds')); Y.Mock.expect(contentInfoMock1, { method: 'toJSON', returns: {name: 'me', publishedDate: 'yesterday', lastModificationDate: 'tomorrow'} }); Y.Mock.expect(contentInfoMock1, { method: 'get', args: ['contentId'], returns: 42 }); Y.Mock.expect(contentInfoMock2, { method: 'toJSON', returns: {name: 'me', publishedDate: 'yesterday', lastModificationDate: 'tomorrow'} }); Y.Mock.expect(contentInfoMock2, { method: 'get', args: ['contentId'], returns: 51 }); this.view.on('contentDiscover', function (e) { that.resume(function () { Y.Array.each(fakeEventFacade.selection, function (selection) { if ( that.view.get('destinationContentsIds').indexOf(selection.contentInfo.get('contentId')) == -1) { contentIdsArray.push(selection.contentInfo.get('contentId')); } }); e.config.contentDiscoveredHandler.call(this, fakeEventFacade); Y.ArrayAssert.itemsAreEqual( contentIdsArray, [42,45,51], 'destinationContentsIds should match the contentIds of the selected relation' ); }); }); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, "Should run the UniversalDiscoveryWidget": function () { var that = this, allowedContentType = new Y.Mock(), notAllowedContentType = new Y.Mock(); Y.Mock.expect(allowedContentType, { method: 'get', args: ['identifier'], returns: this.fieldDefinition.fieldSettings.selectionContentTypes[0] }); Y.Mock.expect(notAllowedContentType, { method: 'get', args: ['identifier'], returns: 'not_allowed_content_type_identifier' }); this.view.on('contentDiscover', function (e) { that.resume(function () { Y.Assert.isObject(e.config, "contentDiscover config should be an object"); Y.Assert.isFunction(e.config.contentDiscoveredHandler, "config should have a function named contentDiscoveredHandler"); Y.Assert.isFunction(e.config.cancelDiscoverHandler, "config should have a function named cancelDiscoverHandler"); Y.Assert.isFunction(e.config.isSelectable, "config should have a function named isSelectable"); Y.Assert.isTrue( e.config.isSelectable({contentType: allowedContentType}), "isSelectable should return TRUE if selected content's content type is on allowed content types list" ); Y.Assert.isFalse( e.config.isSelectable({contentType: notAllowedContentType}), "isSelectable should return FALSE if selected content's content type is not on allowed content types list" ); Assert.isUndefined( e.config.startingLocationId, "The starting Location id parameter should not be set" ); }); }); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, "Should run the UniversalDiscoveryWidget starting at selectionDefaultLocation": function () { var locationId = 'whatever/location/id'; this.fieldDefinition.fieldSettings.selectionContentTypes = []; this.fieldDefinition.fieldSettings.selectionDefaultLocationHref = locationId; this.view.on('contentDiscover', this.next(function (e) { Assert.areEqual( locationId, e.config.startingLocationId, "The starting Location id parameter should be set" ); }, this)); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, }); Y.Test.Runner.add(universalDiscoveryRelationTest); tapTest = new Y.Test.Case({ name: "eZ Relation list tap test", _getFieldDefinition: function (required) { return { isRequired: required }; }, setUp: function () { this.destinationContent1 = new Y.Mock(); this.destinationContent1ToJSON = {anythingJSONed: 'somethingJSONed'}; Y.Mock.expect(this.destinationContent1, { method: 'toJSON', returns: this.destinationContent1ToJSON }); Y.Mock.expect(this.destinationContent1, { method: 'get', args: [Y.Mock.Value.String], run: function (arg) { if ( arg == 'contentId' ) { return 45; } else if ( arg == 'id') { return "/api/ezp/v2/content/objects/45"; } else { Y.Assert.fail('argument for get() not expected'); } } }); this.destinationContent2 = new Y.Mock(); this.destinationContent2ToJSON = {anythingJSONed2: 'somethingJSONed2'}; Y.Mock.expect(this.destinationContent2, { method: 'toJSON', returns: this.destinationContent2ToJSON }); Y.Mock.expect(this.destinationContent2, { method: 'get', args: [Y.Mock.Value.String], run: function (arg) { if ( arg == 'contentId' ) { return 42; } else if ( arg == 'id') { return "/api/ezp/v2/content/objects/42"; } else { Y.Assert.fail('argument for get() not expected'); } } }); this.relatedContents = [this.destinationContent1, this.destinationContent2]; this.fieldDefinitionIdentifier= "niceField"; this.fieldDefinition = { fieldType: "ezobjectrelationlist", identifier: this.fieldDefinitionIdentifier, isRequired: false, fieldSettings: {}, }; this.field = {fieldValue: {destinationContentIds: [45, 42]}}; this.jsonContent = {}; this.jsonContentType = {}; this.jsonVersion = {}; this.content = new Y.Mock(); this.version = new Y.Mock(); this.contentType = new Y.Mock(); Y.Mock.expect(this.content, { method: 'toJSON', returns: this.jsonContent }); Y.Mock.expect(this.version, { method: 'toJSON', returns: this.jsonVersion }); Y.Mock.expect(this.contentType, { method: 'toJSON', returns: this.jsonContentType }); this.view = new Y.eZ.RelationListEditView({ container: '.container', field: this.field, fieldDefinition: this.fieldDefinition, content: this.content, version: this.version, contentType: this.contentType, relatedContents: this.relatedContents, }); }, tearDown: function () { this.view.destroy(); delete this.view; }, "Should prevent default behaviour of the tap event for select button": function () { var that = this; this.view.render(); this.view.get('container').once('tap', function (e) { that.resume(function () { Y.Assert.isTrue( !!e.prevented, "The tap event should have been prevented" ); }); }); this.view.get('container').one('.ez-relation-discover').simulateGesture('tap'); this.wait(); }, "Should remove the relation related to the remove button when it is tapped": function () { var that = this, contentId = 42; this.view.get('container').once('tap', function (e) { that.resume(function () { Y.Assert.isTrue( !!e.prevented, "The tap event should have been prevented" ); Y.ArrayAssert.doesNotContain( contentId, that.view.get('destinationContentsIds'), "The contentId of the relation removed should be deleted" ); }); }); this.view.get('container').one('button[data-content-id="/api/ezp/v2/content/objects/'+ contentId +'"]').simulateGesture('tap'); this.wait(); }, "Should render the view and make the table disapear when we remove the last relation": function () { var that = this, contentId = 42; this.view.set('relatedContents', [this.destinationContent2]); this.view.render(); that.view.template = function () { that.resume(function () { Y.Assert.isNull(that.view.get('container').one('.ez-relationlist-contents'), 'The relation list table should have disapeared'); }); }; this.view.get('container').one('button[data-content-id="/api/ezp/v2/content/objects/'+ contentId +'"]').simulateGesture('tap'); this.wait(); }, "Should remove the table row of the relation when we tap on its remove button ": function () { var that = this, contentId = 42; this.view.set('relatedContents', [this.destinationContent1, this.destinationContent2]); this.view.render(); that.view.get('container').onceAfter(['webkitTransitionEnd', 'transitionend'], Y.bind(function () { that.resume(function () { Y.Assert.isNull( that.view.get('container').one('tr[data-content-id="' + contentId + '"]'), 'The relation table row should have disapeared'); }); }, this)); this.view.get('container').one('button[data-content-id="/api/ezp/v2/content/objects/'+ contentId +'"]').simulateGesture('tap'); this.wait(); }, }); Y.Test.Runner.add(tapTest); loadObjectRelationsTest = new Y.Test.Case({ name: "eZ Relations list loadObjectRelations event test", _getFieldDefinition: function (required) { return { isRequired: required }; }, setUp: function () { this.fieldDefinitionIdentifier= "niceField"; this.fieldDefinition = { fieldType: "ezobjectrelationlist", identifier: this.fieldDefinitionIdentifier, isRequired: false }; this.field = {fieldValue: {destinationContentIds: [45, 42]}}; this.content = {}; this.view = new Y.eZ.RelationListEditView({ field: this.field, fieldDefinition: this.fieldDefinition, content: this.content, }); }, tearDown: function () { this.view.destroy(); delete this.view; }, "Should fire the loadObjectRelations event": function () { var loadContentEvent = false; this.view.on('loadObjectRelations', Y.bind(function (e) { Y.Assert.areSame( this.fieldDefinitionIdentifier, e.fieldDefinitionIdentifier, "fieldDefinitionIdentifier is the same than the one in the field" ); Y.Assert.areSame( this.content, e.content, "The content should be provided in the event facade" ); loadContentEvent = true; }, this)); this.view.set('active', true); Y.Assert.isTrue(loadContentEvent, "loadObjectRelations event should be fired when getting active"); }, "Should NOT fire the loadObjectRelations event if field is empty": function () { var loadContentEvent = false, that = this; this.view.on('loadObjectRelations', function (e) { Y.Assert.areSame( that.fieldDefinitionIdentifier, e.fieldDefinitionIdentifier, "fieldDefinitionIdentifier is the same than the one in the field" ); loadContentEvent = true; }); this.view._set('destinationContentsIds', null); this.view.set('active', true); Y.Assert.isFalse(loadContentEvent, "loadContentEvent should NOT be called when changing active value"); }, }); Y.Test.Runner.add(loadObjectRelationsTest); getFieldTest = new Y.Test.Case( Y.merge(Y.eZ.Test.GetFieldTests, { fieldDefinition: {isRequired: false}, ViewConstructor: Y.eZ.RelationListEditView, value: {destinationContentsIds: [45, 42]}, newValue: [45, 42], _setNewValue: function () { this.view._set("destinationContentsIds", this.newValue); }, _assertCorrectFieldValue: function (fieldValue, msg) { Y.Assert.isObject(fieldValue, 'fieldValue should be an object'); Y.Assert.areEqual(this.newValue, fieldValue.destinationContentIds, msg); }, }) ); Y.Test.Runner.add(getFieldTest); getEmptyFieldTest = new Y.Test.Case( Y.merge(Y.eZ.Test.GetFieldTests, { fieldDefinition: {isRequired: false}, ViewConstructor: Y.eZ.RelationListEditView, value: {destinationContentsIds: null}, newValue: null, _setNewValue: function () { this.view._set("destinationContentsIds", this.newValue); }, _assertCorrectFieldValue: function (fieldValue, msg) { Y.Assert.isObject(fieldValue, 'fieldValue should be an object'); Y.Assert.areEqual(this.newValue, fieldValue.destinationContentIds, msg); }, }) ); Y.Test.Runner.add(getEmptyFieldTest); registerTest = new Y.Test.Case(Y.eZ.EditViewRegisterTest); registerTest.name = "Relation List Edit View registration test"; registerTest.viewType = Y.eZ.RelationListEditView; registerTest.viewKey = "ezobjectrelationlist"; Y.Test.Runner.add(registerTest); }, '', {requires: ['test', 'getfield-tests', 'node-event-simulate', 'editviewregister-tests', 'ez-relationlist-editview']});
intenseprogramming/PlatformUIBundle
Tests/js/views/fields/assets/ez-relationlist-editview-tests.js
JavaScript
gpl-2.0
28,458
/** * Controls for setting the clip for the histogram, either as a [min,max] range * or as a percentage. */ /*global mImport */ /******************************************************************************* * @ignore( mImport) ******************************************************************************/ qx.Class.define("skel.widgets.Histogram.HistogramClip", { extend : qx.ui.core.Widget, construct : function( ) { this.base(arguments); this._init( ); //Initiate connector. if ( typeof mImport !== "undefined"){ this.m_connector = mImport("connector"); } }, statics : { CMD_SET_CLIP_MIN : "setColorMin", CMD_SET_CLIP_MIN_PERCENT: "setColorMinPercent", CMD_SET_CLIP_MAX : "setColorMax", CMD_SET_CLIP_MAX_PERCENT: "setColorMaxPercent", CMD_APPLY_CLIP_IMAGE : "setClipToImage" }, members : { /** * Callback for showing/clearing errors in a text field. * @param textWidget {skel.widgets.CustomUI.ErrorTextField} the text field. * @return {function} the callback which will show/clear the error based on the * error message. */ _errorCB : function( textWidget ){ return function( msg ){ if ( msg !== null && msg.length > 0 ){ textWidget.setError( true ); } else { var oldError = textWidget.isError(); if ( oldError ){ textWidget.setError( false ); var errorMan = skel.widgets.ErrorHandler.getInstance(); errorMan.clearErrors(); } } }; }, /** * Callback for a server error when setting the histogram minimum clip value. * @return {function} which displays/clears the error. */ _errorClipMinCB : function( ){ return this._errorCB( this.m_minClipText ); }, /** * Callback for a server error when setting the histogram maximum clip value. * @return {function} which displays/clears the error. */ _errorClipMaxCB : function(){ return this._errorCB( this.m_maxClipText ); }, /** * Callback for a server error when setting the histogram minimum clip percent. * @return {function} which displays/clears the error. */ _errorClipMinPercentCB : function( ){ return this._errorCB(this.m_percentMinClipText ); }, /** * Callback for a server error when setting the histogram maximum clip percent. * @return {function} which displays/clears the error. */ _errorClipMaxPercentCB : function( ){ return this._errorCB( this.m_percentMaxClipText ); }, /** * Initializes the UI. */ _init : function( ) { var widgetLayout = new qx.ui.layout.HBox(1); this._setLayout(widgetLayout); var overallContainer = new qx.ui.groupbox.GroupBox( "Linked Image Clip (shift + mouse left drag)", ""); overallContainer.setLayout( new qx.ui.layout.VBox(1)); overallContainer.setContentPadding(1,1,1,1); this._add( overallContainer ); //Custom clip var rangeContainer = new qx.ui.container.Composite(); this.m_customCheck = new qx.ui.form.CheckBox( "Custom Image Clip"); this.m_customCheck.setValue( true ); this.m_customCheck.addListener(skel.widgets.Path.CHANGE_VALUE, function(){ var customValue = this.m_customCheck.getValue(); rangeContainer.setEnabled( customValue ); this._sendCustomClipCmd(); }, this ); var horContainer2 = new qx.ui.container.Composite(); horContainer2.setLayout( new qx.ui.layout.HBox(1)); horContainer2.add( new qx.ui.core.Spacer(), {flex:1} ); horContainer2.add( this.m_customCheck ); horContainer2.add( new qx.ui.core.Spacer(), {flex:1} ); overallContainer.add(horContainer2 ); var gridLayout = new qx.ui.layout.Grid(); gridLayout.setColumnAlign(0, "right","middle"); gridLayout.setRowAlign( 0, "center", "middle"); gridLayout.setSpacingX( 1 ); gridLayout.setSpacingY( 1 ); rangeContainer.setLayout( gridLayout); overallContainer.add( rangeContainer); //Minimum var minLabel = new qx.ui.basic.Label( "Min"); minLabel.setTextAlign( "center"); this.m_minClipText = new skel.widgets.CustomUI.NumericTextField( null, null); this.m_minClipText.setToolTipText( "Smallest value on the horizontal axis."); this.m_minClipText.setIntegerOnly( false ); this.m_minClipListenerId = this.m_minClipText.addListener( "textChanged", this._sendClipMinCmd, this ); var valueLabel = new qx.ui.basic.Label( "Value:"); valueLabel.setTextAlign( "right"); this.m_percentMinClipText = new skel.widgets.CustomUI.NumericTextField( 0, 100); this.m_percentMinClipText.setToolTipText( "Percentage to clip from the left on the horizontal axis; 0 is no clipping."); this.m_percentMinClipText.setIntegerOnly( false ); this.m_percentMinClipListenerId = this.m_percentMinClipText.addListener( "textChanged", this._sendClipMinPercentCmd, this ); rangeContainer.add( minLabel, {row: 0, column:1}); rangeContainer.add( this.m_minClipText, {row:1, column:1}); rangeContainer.add( this.m_percentMinClipText, {row:2, column:1}); rangeContainer.add( valueLabel, {row:1, column:0}); //Maximum var maxLabel = new qx.ui.basic.Label( "Max"); maxLabel.setTextAlign( "center"); this.m_maxClipText = new skel.widgets.CustomUI.NumericTextField( null, null ); this.m_maxClipText.setToolTipText( "Largest value on the horizontal axis"); this.m_maxClipText.setIntegerOnly( false ); this.m_maxClipListenerId = this.m_maxClipText.addListener( "textChanged", this._sendClipMaxCmd, this ); var percentLabel = new qx.ui.basic.Label( "Percent:"); percentLabel.setTextAlign( "right"); this.m_percentMaxClipText = new skel.widgets.CustomUI.NumericTextField( 0, 100); this.m_percentMaxClipText.setToolTipText( "Percentage to clip from the right on the horizontal axis; 0 is no clipping."); this.m_percentMaxClipText.setIntegerOnly( false ); this.m_percentMaxClipListenerId = this.m_percentMaxClipText.addListener( "textChanged", this._sendClipMaxPercentCmd, this ); rangeContainer.add( maxLabel, {row:0, column:2}); rangeContainer.add( this.m_maxClipText, {row:1, column:2}); rangeContainer.add( this.m_percentMaxClipText, {row:2, column:2}); rangeContainer.add( percentLabel, {row:2, column:0}); //Apply to image this.m_applyImageClip = new qx.ui.form.Button( "Apply to Image"); this.m_applyImageClip.setToolTipText( "Clip all linked images by minimum and maximum range values."); this.m_applyImageClip.addListener( "execute", function(e){ if ( this.m_connector !== null ){ var path = skel.widgets.Path.getInstance(); var cmd = this.m_id + path.SEP_COMMAND + skel.widgets.Histogram.HistogramClip.CMD_APPLY_CLIP_IMAGE; var params = ""; this.m_connector.sendCommand( cmd, params, function(){}); } }, this ); var horContainer = new qx.ui.container.Composite(); horContainer.setLayout( new qx.ui.layout.HBox(2)); horContainer.add( new qx.ui.core.Spacer(1), {flex:1}); horContainer.add( this.m_applyImageClip ); horContainer.add( new qx.ui.core.Spacer(1), {flex:1}); overallContainer.add( horContainer ); }, /** * Notify the server of the lower clip amount. */ _sendClipMinCmd: function(){ if( this.m_connector !== null ){ var minClip = this.m_minClipText.getValue(); if( !isNaN(minClip) ){ var path = skel.widgets.Path.getInstance(); var cmd = this.m_id+path.SEP_COMMAND+skel.widgets.Histogram.HistogramClip.CMD_SET_CLIP_MIN; var params = "colorMin:"+minClip; this.m_connector.sendCommand( cmd, params, this._errorClipMinCB( )); } } }, /** * Notify the server of the upper clip amount. */ _sendClipMaxCmd: function(){ if( this.m_connector !== null ){ var maxClip = this.m_maxClipText.getValue(); if( !isNaN(maxClip) ){ var path = skel.widgets.Path.getInstance(); var cmd = this.m_id+path.SEP_COMMAND+skel.widgets.Histogram.HistogramClip.CMD_SET_CLIP_MAX; var params = "colorMax:"+maxClip; this.m_connector.sendCommand( cmd, params, this._errorClipMaxCB()); } } }, /** * Notify the server of the lower clip percentage. */ _sendClipMinPercentCmd: function(){ if( this.m_connector !== null ){ var minPercentClip = this.m_percentMinClipText.getValue(); if( !isNaN(minPercentClip) ){ var path = skel.widgets.Path.getInstance(); var cmd = this.m_id+path.SEP_COMMAND+skel.widgets.Histogram.HistogramClip.CMD_SET_CLIP_MIN_PERCENT; var params = "colorMinPercent:"+minPercentClip; this.m_connector.sendCommand( cmd, params, this._errorClipMinPercentCB()); } } }, /** * Notify the server of the upper clip percentage. */ _sendClipMaxPercentCmd: function(){ if( this.m_connector !== null ){ var maxPercentClip = this.m_percentMaxClipText.getValue(); if( !isNaN(maxPercentClip) ){ var path = skel.widgets.Path.getInstance(); var cmd = this.m_id+path.SEP_COMMAND+skel.widgets.Histogram.HistogramClip.CMD_SET_CLIP_MAX_PERCENT; var params = "colorMaxPercent:"+maxPercentClip; this.m_connector.sendCommand( cmd, params, this._errorClipMaxPercentCB( )); } } }, /** * Send a command to the server indicating whether or not to use clips * separate from zoom. */ _sendCustomClipCmd : function(){ if ( this.m_connector !== null ){ var customClip = this.m_customCheck.getValue(); var path = skel.widgets.Path.getInstance(); var cmd = this.m_id + path.SEP_COMMAND + "setCustomClip"; var params = "customClip:"+customClip; this.m_connector.sendCommand( cmd, params, function(){}); } }, /** * Set upper and lower bounds for the histogram range. * @param min {Number} a lower (inclusive) bound. * @param max {Number} an upper (inclusive) bound. */ setColorRange : function( min, max ){ this.m_minClipText.removeListenerById( this.m_minClipListenerId ); this.m_maxClipText.removeListenerById( this.m_maxClipListenerId ); var oldClipMin = this.m_minClipText.getValue(); if ( oldClipMin != min ){ this.m_minClipText.setValue( min ); } var oldClipMax = this.m_maxClipText.getValue(); if ( oldClipMax != max ){ this.m_maxClipText.setValue( max ); } this.m_maxClipListenerId = this.m_maxClipText.addListener( "textChanged", this._sendClipMaxCmd, this ); this.m_minClipListenerId = this.m_minClipText.addListener( "textChanged", this._sendClipMinCmd, this ); }, /** * Set the amount to clip at each end of the histogram based on percentiles. * @param min {Number} a decimal [0,1] representing the left amount to clip. * @param max {Number} a decimal [0,1] representing the right amount to clip. */ setColorRangePercent : function( min, max ){ this.m_percentMinClipText.removeListenerById( this.m_percentMinClipListenerId ); this.m_percentMaxClipText.removeListenerById( this.m_percentMaxClipListenerId ); var newMin = min; var newMax = max; var oldClipMinPercent = this.m_percentMinClipText.getValue(); if ( oldClipMinPercent != newMin ){ this.m_percentMinClipText.setValue( newMin ); } var oldClipMax = this.m_percentMaxClipText.getValue(); if ( oldClipMax != newMax ){ this.m_percentMaxClipText.setValue( newMax ); } this.m_percentMinClipListenerId = this.m_percentMinClipText.addListener( "textChanged", this._sendClipMinPercentCmd, this ); this.m_percentMaxClipListenerId = this.m_percentMaxClipText.addListener( "textChanged", this._sendClipMaxPercentCmd, this ); }, /** * Set whether or not to enable custom clip settings. * @param val {boolean} true to enable custom clip settings; false otherwise. */ setCustomClip : function( val ){ var oldValue = this.m_customCheck.getValue(); if ( val != oldValue ){ this.m_customCheck.setValue( val ); } }, /** * Set the server side id of this histogram. * @param id {String} the server side id of the object that produced this histogram. */ setId : function( id ){ this.m_id = id; }, m_id : null, m_connector : null, m_maxClipText : null, m_minClipText : null, m_maxClipListenerId : null, m_minClipListenerId : null, m_percentMinClipText : null, m_percentMaxClipText : null, m_percentMinClipListenerId : null, m_percentMaxClipListenerId : null, m_customCheck : null }, properties : { appearance : { refine : true, init : "internal-area" } } });
pfederl/CARTAvis
carta/html5/common/skel/source/class/skel/widgets/Histogram/HistogramClip.js
JavaScript
gpl-2.0
15,206
/** * Themes a checkbox input. * @param {Object} variables * @return {String} */ function theme_checkbox(variables) { try { variables.attributes.type = 'checkbox'; // Check the box? if (variables.checked) { variables.attributes.checked = 'checked'; } var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_checkbox - ' + error); } } /** * Themes checkboxes input. * @param {Object} variables * @return {String} */ function theme_checkboxes(variables) { try { var html = ''; variables.attributes.type = 'checkboxes'; for (var value in variables.options) { if (!variables.options.hasOwnProperty(value)) { continue; } var label = variables.options[value]; if (value == 'attributes') { continue; } // Skip attributes. var _label = value; if (!empty(label)) { _label = label; } var checkbox = { value: value, attributes: { name: variables.name + '[' + value + ']', 'class': variables.name, value: value } }; if (variables.value && variables.value[value]) { checkbox.checked = true; } html += '<label>' + theme('checkbox', checkbox) + '&nbsp;' + label + '</label>'; } // Check the box? /*if (variables.checked) { variables.attributes.checked = 'checked'; }*/ return html; } catch (error) { console.log('theme_checkbox - ' + error); } } /** * Themes a email input. * @param {Object} variables * @return {String} */ function theme_email(variables) { try { variables.attributes.type = 'email'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_email - ' + error); } } /** * Themes a file input. * @param {Object} variables * @return {String} */ function theme_file(variables) { try { variables.attributes.type = 'file'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_file - ' + error); } } /** * Themes a form element label. * @param {Object} variables * @return {String} */ function theme_form_element_label(variables) { try { var element = variables.element; if (empty(element.title)) { return ''; } // Any elements with a title_placeholder set to true // By default, use the element id as the label for, unless the element is // a radio, then use the name. var label_for = ''; if (element.id) { label_for = element.id; } else if (element.attributes && element.attributes['for']) { label_for = element.attributes['for']; } if (element.type == 'radios') { label_for = element.name; } // Render the label. var html = '<label for="' + label_for + '"><strong>' + element.title + '</strong>'; if (element.required) { html += theme('form_required_marker', { }); } html += '</label>'; return html; } catch (error) { console.log('theme_form_element_label - ' + error); } } /** * Themes a marker for a required form element label. * @param {Object} variables * @return {String} */ function theme_form_required_marker(variables) { return '*'; } /** * Themes a number input. * @param {Object} variables * @return {String} */ function theme_number(variables) { try { variables.attributes.type = 'number'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_number - ' + error); } } /** * Themes a hidden input. * @param {Object} variables * @return {String} */ function theme_hidden(variables) { try { variables.attributes.type = 'hidden'; if (!variables.attributes.value && variables.value != null) { variables.attributes.value = variables.value; } var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_hidden - ' + error); } } /** * Themes a password input. * @param {Object} variables * @return {String} */ function theme_password(variables) { try { variables.attributes.type = 'password'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_password - ' + error); } } /** * Themes radio buttons. * @param {Object} variables * @return {String} */ function theme_radios(variables) { try { var radios = ''; if (variables.options) { variables.attributes.type = 'radio'; // Determine an id prefix to use. var id = 'radio'; if (variables.attributes.id) { id = variables.attributes.id; delete variables.attributes.id; } // Set the radio name equal to the id if one doesn't exist. if (!variables.attributes.name) { variables.attributes.name = id; } // Init a delta value so each radio button can have a unique id. var delta = 0; for (var value in variables.options) { if (!variables.options.hasOwnProperty(value)) { continue; } var label = variables.options[value]; if (value == 'attributes') { continue; } // Skip the attributes. var checked = ''; if (variables.value && variables.value == value) { checked = ' checked="checked" '; } var input_id = id + '_' + delta.toString(); var input_label = '<label for="' + input_id + '">' + label + '</label>'; radios += '<input id="' + input_id + '" value="' + value + '" ' + drupalgap_attributes(variables.attributes) + checked + ' />' + input_label; delta++; } } return radios; } catch (error) { console.log('theme_radios - ' + error); } } /** * Themes a range input. * @param {Object} variables * @return {String} */ function theme_range(variables) { try { variables.attributes.type = 'range'; if (typeof variables.attributes.value === 'undefined') { variables.attributes.value = variables.value; } var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_range - ' + error); } } /** * Themes a search input. * @param {Object} variables * @return {String} */ function theme_search(variables) { try { variables.attributes.type = 'search'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_search - ' + error); } } /** * Themes a select list input. * @param {Object} variables * @return {String} */ function theme_select(variables) { try { var options = ''; if (variables.options) { for (var value in variables.options) { if (!variables.options.hasOwnProperty(value)) { continue; } var label = variables.options[value]; if (value == 'attributes') { continue; } // Skip the attributes. // Is the option selected? var selected = ''; if (typeof variables.value !== 'undefined') { if ( ($.isArray(variables.value) && in_array(value, variables.value)) || variables.value == value ) { selected = ' selected '; } } // Render the option. options += '<option value="' + value + '" ' + selected + '>' + label + '</option>'; } } return '<select ' + drupalgap_attributes(variables.attributes) + '>' + options + '</select>'; } catch (error) { console.log('theme_select - ' + error); } } /** * Themes a telephone input. * @param {Object} variables * @return {String} */ function theme_tel(variables) { try { variables.attributes['type'] = 'tel'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_tel - ' + error); } } /** * Themes a text input. * @param {Object} variables * @return {String} */ function theme_textfield(variables) { try { variables.attributes.type = 'text'; var output = '<input ' + drupalgap_attributes(variables.attributes) + ' />'; return output; } catch (error) { console.log('theme_textfield - ' + error); } } /** * Themes a textarea input. * @param {Object} variables * @return {String} */ function theme_textarea(variables) { try { var output = '<div><textarea ' + drupalgap_attributes(variables.attributes) + '>' + variables.value + '</textarea></div>'; return output; } catch (error) { console.log('theme_textarea - ' + error); } }
terotic/DrupalGap
src/includes/form.theme.inc.js
JavaScript
gpl-2.0
8,914
var searchData= [ ['out',['Out',['../classNumericalSHOCK.html#a74f7811f85ca6d4e7192cc143926f3b4',1,'NumericalSHOCK']]] ];
jackycfd/WENO
doc/html/search/functions_6f.js
JavaScript
gpl-2.0
124
/*! * iCheck v1.0.1, http://git.io/arlzeA * =================================== * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Sultanov, http://fronteed.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]', stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); }; }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'destroy') { tidy(self, 'ifDestroyed'); } else { operate(self, true, options); }; // Fire method's callback if ($.isFunction(fire)) { fire(); }; }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true, aria: false }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = 'input[type="' + selector + '"]'; }; // Clickable area limit if (area < -50) { area = -50; }; // Walk around the selector walker(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Check ARIA option aria = !!settings.aria, // Set ARIA placeholder ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6), // Parent & helper parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''), helper; // Set ARIA "labelledby" if (aria) { label.each(function() { parent += 'aria-labelledby="'; if (this.id) { parent += this.id; } else { this.id = ariaID; parent += ariaID; } parent += '"'; }); }; // Wrap input parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert); // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className || ''); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { if ($(event.target).is('a')) { return; } operate(self, false, true); // Hover state } else if (labelHover) { // mouseout|touchend if (/ut|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }; // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); }; }; return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); }; }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); }; // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); }; }; if (_mobile) { event.stopPropagation(); } else { return false; }; }; }); }); } else { return this; }; }; // Do something with inputs function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var state in active) { if (active[state]) { on(input, state, true); } else { off(input, state, true); }; }; } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); }; // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); }; } else { on(input, state); }; }; }; // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); }; }); }; // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); }; // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; }; // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); }; }; // Trigger callbacks callbacks(input, checked, state, keep); }; // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); }; // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true'); // Remove regular state class parent[_remove](regular || option(input, callback) || ''); }; // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; }; // Trigger callbacks callbacks(input, checked, callback, keep); }; // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); }; // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false'); // Add regular state class parent[_add](regular || option(input, callback) || ''); }; // Remove all traces function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); }; // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); }; }; // Get some option function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; }; }; // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); }; input[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); }; }; })(window.jQuery || window.Zepto);
mautd29388/mtheme
wp-content/themes/01-Sources/js/icheck/icheck.js
JavaScript
gpl-2.0
14,154
jQuery(function($){ var window_height = $(window).height(); var element_height = $("#top_university_float_box").height(); var window_scrollTop = $(window).scrollTop(); var ep = window_scrollTop + ( window_height - element_height) /2; $("#top_university_float_box").stop().animate({ top: ep, }, 1000, function() { // Animation complete. }); $(window).scroll(function(){ //alert("window scrolled"); var window_height = $(window).height(); var element_height = $("#top_university_float_box").height(); var window_scrollTop = $(window).scrollTop(); var ep = window_scrollTop + ( window_height - element_height) /2; //alert(window_scrollTop); $("#top_university_float_box").stop().animate({ top: ep, }, 1000, function() { // Animation complete. }); }); //$("#top_university_float_box"). /*$(".has_menu").mouseover(function(){ if (!$(this).hasClass("menu_active")){ //$(".menu_body").slideUp(); $(".menu_body").hide(); $(".menu_title").css("background","transparent").removeClass("menu_active"); $(".menu_title").css("color","#000"); } $(this).addClass("menu_active"); var id = $(this).attr('id'); var bd = id.replace("_title", "_body"); //$(this).css("background-color","#ff0"); if( id == "courses_title" ) $(this).css('background-color','#09f'); if( id == "students_title" ) $(this).css('background-color','#f90'); if( id == "useful_title" ) $(this).css('background-color','#c0f'); if( id == "about_title" ) $(this).css('background-color','#060'); if( id == "social_title" ) $(this).css('background-color','#c00'); //$(this).css('background-image','url(../img/menu_tab.jpg)'); //$(this).css('background-image','url(../img/menu_tab_gradient.jpg)'); //$(this).addClass("menu_title_over"); $(this).css("color","#fff"); //$(this).css("border-left","solid 1px #ff0"); $("#"+bd).show(); }); $("#header, .info_block, #footer, #home_title,#top_banner").mouseover(function(){ $("#mask").hide(); $(".menu_title").css("background","transparent").removeClass("menu_active"); $(".menu_title").css("color","#000"); //$(".menu_body").slideUp(300); $(".menu_body").hide(); });*/ });
kenorb-contrib/eidold
jquery.topUniversityFloatBox.js
JavaScript
gpl-2.0
2,223
// Copyright (c) 2007 Divmod. // See LICENSE for details. /** * Utilities for testing L{Nevow.Athena.Widget} subclasses. */ /** * Make a node suitable for passing as the first argument to a * L{Nevow.Athena.Widget} constructor. * * @param athenaID: the athena ID of the widget this node belongs to. * defaults to '1'. * @type athenaID: C{Number} * * @return: a node. */ Nevow.Test.WidgetUtil.makeWidgetNode = function makeWidgetNode(athenaID/*=1*/) { if(athenaID === undefined) { athenaID = 1; } var node = document.createElement('div'); node.id = Nevow.Athena.Widget.translateAthenaID(athenaID); return node; } /** * Tell athena that there is a widget with the ID C{athenaID}. * * @param widget: a widget (the one to associate with C{athenaID}). * @type widget: L{Nevow.Athena.Widget} * * @param athenaID: the athena ID of this widget. defaults to '1'. * @type athenaID: C{Number} * * @rtype: C{undefined} */ Nevow.Test.WidgetUtil.registerWidget = function registerWidget(widget, athenaID/*=1*/) { if(athenaID == undefined) { athenaID = 1; } Nevow.Athena.Widget._athenaWidgets[athenaID] = widget; } /** * Replace required global state for operating Athena widgets and events. * * @return: a thunk which will restore the global state to what it was at the * time this function was called. * @rtype: C{Function} */ Nevow.Test.WidgetUtil.mockTheRDM = function mockTheRDM() { var originalRDM = Nevow.Athena.page; Nevow.Athena.page = Nevow.Athena.PageWidget("fake-page-id", function (page) { var c = { pause: function () { }, unpause: function () { }}; return c; }); return function() { Nevow.Athena.page = originalRDM; }; }
UstadMobile/exelearning-ustadmobile-work
nevow/js/Nevow/Test/WidgetUtil.js
JavaScript
gpl-2.0
1,791
function fileQueueError(file, error_code, message) { try { var error_name = ""; switch (error_code) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: error_name = swfuCallbackL10n.file + " " + file.name + " " + swfuCallbackL10n.isZero; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: error_name = swfuCallbackL10n.file + " " + file.name + swfuCallbackL10n.exceed + " " + this.getSetting('file_size_limit') + swfuCallbackL10n.ini; break; case SWFUpload.ERROR_CODE_QUEUE_LIMIT_EXCEEDED: error_name = swfuCallbackL10n.tooMany; break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: error_name = swfuCallbackL10n.file + " " + file.name + " " + swfuCallbackL10n.invType; break; default: error_name = message; break; } alert(error_name); } catch (ex) { this.debug(ex); } } function fileQueued(file) { try { uplsize += Math.round(file.size/1024); if ( jQuery("#SWFUploadFileListingFiles ul").length == 0 ){ jQuery("#SWFUploadFileListingFiles").append("<h4 id='queueinfo' class='thead'>"+swfuCallbackL10n.queueEmpty+"</h4><ul></ul>"); } jQuery("#SWFUploadFileListingFiles") .children("ul:first") .append("<li id='" + file.id + "' class='SWFUploadFileItem'>" + file.name +"<a id='" + file.id + "deletebtn' class='cancelbtn' href='javascript:swfu.cancelUpload(\"" + file.id + "\");'><!-- IE --></a><span class='progressBar' id='" + file.id + "progress'></span></li>") .children("li:last").slideDown("slow") .end(); } catch (ex) { this.debug(ex); } } function fileDialogComplete(queuelength) { try { if (queuelength > 0) { jQuery("#queueinfo").text(queuelength + " " + swfuCallbackL10n.queued + "( " + uplsize + "KB )"); jQuery("#" + swfu.movieName + "UploadBtn").css("display", "inline"); jQuery(".browsebtn").text(swfuCallbackL10n.addMore); jQuery("#ftpUploadBtn").css("display", "none"); //start auto upload this.startUpload(); } } catch (ex) { this.debug(ex); } } function uploadFileCancelled(file, queuelength) { } function uploadStart(file) { try{ jQuery("#queueinfo").text(swfuCallbackL10n.uploading + " " + file.name); jQuery("#" + file.id).addClass("fileUploading"); } catch (ex) { this.debug(ex); } return true; } function uploadProgress(file, bytesLoaded, bytesTotal) { try{ var percent = Math.ceil((bytesLoaded / bytesTotal) * 350) jQuery("#" + file.id + "progress").css("background", "url("+swfuCallbackL10n.progressBarUrl+") no-repeat -" + (350-percent) + "px"); } catch (ex) { this.debug(ex); } } function uploadError(file, error_code, message) { try { switch (error_code) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { jQuery("#"+file.id).text(file.name + " - " + swfuCallbackL10n.cancelled) .attr("class","SWFUploadFileItem uploadCancelled") .slideUp("fast",function(){ jQuery(this).remove(); }); uplsize -= Math.round(file.size/1024); jQuery("#queueinfo").text(this.getStats().files_queued + " " + swfuCallbackL10n.queued + "( " + uplsize + "KB )"); if(!this.getStats().files_queued){ jQuery("#" + swfu.movieName + "UploadBtn").css("display","none"); jQuery("#SWFUploadFileListingFiles").empty(); jQuery(".browsebtn").text(swfuCallbackL10n.select); } } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: this.debug("Upload stopped: File name: " + file.name); break; case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: alert("Upload Error: " + message); this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: alert("Upload Failed."); this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: alert("Server (IO) Error"); this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: alert("Security Error"); this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: alert("Upload limit exceeded."); this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: alert("Failed Validation. Upload skipped."); this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message); break; default: alert(message); break; } } catch (ex3) { this.debug(ex3); } } function uploadSuccess(file, server_data) { try { jQuery("#" + file.id + "progress").css("background", "url("+swfuCallbackL10n.progressBarUrl+") no-repeat -0px"); jQuery("#" + file.id).attr("class", "SWFUploadFileItem uploadCompleted"); jQuery("#" + file.id + "> a").before("<span class='okbtn'><!--IE--></span>"); } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued > 0) { this.startUpload(); } else { jQuery("#queueinfo").text(swfuCallbackL10n.allUp); jQuery("#commonInfo").slideDown('slow'); } } catch (ex) { this.debug(ex); } } function cancelUpload() { try{ var queuelength = swfu.getStats().files_queued; if(queuelength){ if(confirm(swfuCallbackL10n.cancelConfirm)){ swfu.stopUpload(); for(var index=0; index<queuelength; index++) { swfu.cancelUpload(); } } }else window.location = window.location.href; } catch (ex) { this.debug(ex); } }
alx/Tetalab
wp-content/plugins/photoq-photoblog-plugin/js/swfu-callback.js
JavaScript
gpl-2.0
6,024
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert, Spinner } from 'patternfly-react'; import { translate as __ } from 'foremanReact/common/I18n'; import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories'; import RepositorySetRepository from './RepositorySetRepository/'; import { yStream } from './RepositorySetRepositoriesHelpers'; class RepositorySetRepositories extends Component { componentDidMount() { const { contentId, productId } = this.props; if (this.props.data.loading) { this.props.loadRepositorySetRepos(contentId, productId); } } sortedRepos = repos => [...repos.filter(({ enabled }) => !enabled)] .sort((repo1, repo2) => { const repo1YStream = yStream(repo1.releasever || ''); const repo2YStream = yStream(repo2.releasever || ''); if (repo1YStream < repo2YStream) { return -1; } if (repo2YStream < repo1YStream) { return 1; } if (repo1.arch === repo2.arch) { const repo1MajorMinor = repo1.releasever.split('.'); const repo2MajorMinor = repo2.releasever.split('.'); const repo1Major = parseInt(repo1MajorMinor[0], 10); const repo2Major = parseInt(repo2MajorMinor[0], 10); if (repo1Major === repo2Major) { const repo1Minor = parseInt(repo1MajorMinor[1], 10); const repo2Minor = parseInt(repo2MajorMinor[1], 10); if (repo1Minor === repo2Minor) { return 0; } return (repo1Minor > repo2Minor) ? -1 : 1; } return (repo1Major > repo2Major) ? -1 : 1; } return (repo1.arch > repo2.arch) ? -1 : 1; }); render() { const { data, type } = this.props; if (data.error) { return ( <Alert type="danger"> <span>{data.error.displayMessage}</span> </Alert> ); } const availableRepos = this.sortedRepos(data.repositories).map(repo => ( <RepositorySetRepository key={repo.arch + repo.releasever} type={type} {...repo} /> )); const repoMessage = (data.repositories.length > 0 && availableRepos.length === 0 ? __('All available architectures for this repo are enabled.') : __('No repositories available.')); return ( <Spinner loading={data.loading}> {availableRepos.length ? availableRepos : <div>{repoMessage}</div>} </Spinner> ); } } RepositorySetRepositories.propTypes = { loadRepositorySetRepos: PropTypes.func.isRequired, contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, type: PropTypes.string, data: PropTypes.shape({ loading: PropTypes.bool.isRequired, repositories: PropTypes.arrayOf(PropTypes.object), error: PropTypes.shape({ displayMessage: PropTypes.string, }), }).isRequired, }; RepositorySetRepositories.defaultProps = { type: '', }; const mapStateToProps = ( { katello: { redHatRepositories: { repositorySetRepositories } } }, props, ) => ({ data: repositorySetRepositories[props.contentId] || { loading: true, repositories: [], error: null, }, }); export default connect(mapStateToProps, { loadRepositorySetRepos, })(RepositorySetRepositories);
adamruzicka/katello
webpack/scenes/RedHatRepositories/components/RepositorySetRepositories.js
JavaScript
gpl-2.0
3,291
"use strict"; /* * Native edits */ /** WYMeditor.NativeEditRegistration ================================ Constructs a native edits registration mechanism for a provided editor. */ WYMeditor.NativeEditRegistration = function (wym) { var nativeEditRegistration = this; nativeEditRegistration.wym = wym; // https:/github.com/mightyiam/edited nativeEditRegistration.edited = new WYMeditor.EXTERNAL_MODULES.Edited( wym._doc.body, nativeEditRegistration._onSensibleNativeEdit .bind(nativeEditRegistration), nativeEditRegistration._onAnyNativeEdit .bind(nativeEditRegistration) ); }; /** WYMeditor.NativeEditRegistration._onSensibleNativeEdit ====================================================== Handles "sensible" native edits. Sensible according to https://github.com/PolicyStat/edited */ WYMeditor.NativeEditRegistration.prototype ._onSensibleNativeEdit = function () { var nativeEditRegistration = this; nativeEditRegistration.wym.registerModification(true); }; /** WYMeditor.NativeEditRegistration._onAnyNativeEdit ================================================= Handles all native edits. */ WYMeditor.NativeEditRegistration.prototype._onAnyNativeEdit = function () { var nativeEditRegistration = this, undoRedo = nativeEditRegistration.wym.undoRedo; // remove redo points if (undoRedo.history) { undoRedo.history.forgetAllForward(); } // Non-native modifications are registered when they are performed. // Contrary to those, native edits (e.g. typing) aren't registered // until word boundaries are reached (space, enter) or edit actions // (backspace, delete, cut, paste, etc). // This handles an undo after e.g. only part of word is typed. // // A state with unregistered modifications will be lost upon an undo // and redo because it was never registered. // The last registered state doesn't include it and that will be the result // of the undo and redo operation. // This flag lets the undo operation know that it should add the current // state as a history point (register it) before undoing. // Then the next redo will revert to this state. undoRedo.hasUnregisteredModification = true; };
haryshwaran/wymeditor
src/wymeditor/editor/native-edit-registration.js
JavaScript
gpl-2.0
2,327
/* This file is part of Jeedom. * * Jeedom 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. * * Jeedom 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 Jeedom. If not, see <http://www.gnu.org/licenses/>. */ $("#security_tab").delegate('a', 'click', function(event) { $(this).tab('show'); $.hideAlert(); }); if (getUrlVars('removeSuccessFull') == 1) { $('#div_alert').showAlert({message: '{{Suppression effectuée avec succès}}', level: 'success'}); } if (getUrlVars('saveSuccessFull') == 1) { $('#div_alert').showAlert({message: '{{Sauvegarde effectuée avec succès}}', level: 'success'}); } jwerty.key('ctrl+s', function (e) { e.preventDefault(); $('#bt_saveSecurityConfig').click(); }); $('#bt_saveSecurityConfig').on('click', function() { jeedom.config.save({ configuration: $('#config').getValues('.configKey')[0], error: function(error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function() { jeedom.config.load({ configuration: $('#config').getValues('.configKey')[0], error: function(error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function(data) { $('#config').setValues(data, '.configKey'); modifyWithoutSave = false; $('#div_alert').showAlert({message: '{{Sauvegarde réussie}}', level: 'success'}); } }); } }); }); $('#table_security').delegate('.remove', 'click', function() { var tr = $(this).closest('tr'); bootbox.confirm("{{Etes-vous sûr de vouloir supprimer cette connexion ? Si l\'IP :}} " + tr.find('.ip').text() + " {{était banni celle-ci ne le sera plus}}", function(result) { if (result) { jeedom.security.remove({ id: tr.attr('data-id'), error: function(error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function() { modifyWithoutSave = false; window.location.replace('index.php?v=d&p=security&removeSuccessFull=1'); } }); } }); }); $('#table_security').delegate('.ban', 'click', function() { var tr = $(this).closest('tr'); bootbox.confirm("{{Etes-vous sûr de vouloir bannir cette IP :}} " + tr.find('.ip').text() + " ?", function(result) { if (result) { jeedom.security.ban({ id: tr.attr('data-id'), error: function(error) { $('#div_alert').showAlert({message: error.message, level: 'danger'}); }, success: function() { modifyWithoutSave = false; window.location.replace('index.php?v=d&p=security&saveSuccessFull=1'); } }); } }); }); $.showLoading(); jeedom.config.load({ configuration: $('#config').getValues('.configKey')[0], success: function(data) { $('#config').setValues(data, '.configKey'); modifyWithoutSave = false; } }); $('body').delegate('.configKey', 'change', function() { modifyWithoutSave = true; });
kouaw/core
desktop/js/security.js
JavaScript
gpl-3.0
3,928
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * 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, see <http://www.gnu.org/licenses/>. */ CStudioForms.Controls.LinkInput = CStudioForms.Controls.LinkInput || function (id, form, owner, properties, constraints, readonly) { this.owner = owner; this.owner.registerField(this); this.errors = []; this.properties = properties; this.constraints = constraints; this.inputEl = null; this.patternErrEl = null; this.countEl = null; this.required = false; this.value = '_not-set'; this.form = form; this.id = id; this.readonly = readonly; return this; }; YAHOO.extend(CStudioForms.Controls.LinkInput, CStudioForms.CStudioFormField, { getLabel: function () { return CMgs.format(langBundle, 'linkInput'); }, _onChange: function (evt, obj) { obj.value = obj.inputEl.value; var validationExist = false; var validationResult = true; if (obj.required) { if (obj.inputEl.value == '') { obj.setError('required', 'Field is Required'); validationExist = true; validationResult = false; } else { obj.clearError('required'); } } else { var id = obj.id; if (obj.inputEl.value != '') { var fields = obj.owner.fields.forEach(function (item) { var el = item; var properties = item.properties.forEach(function (prop) { if (prop.name == 'depends') { if (id.includes(prop.value) && prop.value != '' && el.value == '_blank') { el.required = true; el.setError('required', 'Field is Required'); el.renderValidation(true, false); var constraints = el.constraints.forEach(function (constr) { if (constr.name == 'required') { constr.value = 'true'; } }); } } }); }); } else { var fields = obj.owner.fields.forEach(function (item) { var el = item; var properties = item.properties.forEach(function (prop) { if (prop.name == 'depends') { if (id.includes(prop.value) && prop.value != '') { el.required = false; el.clearError('required'); el.renderValidation(false, false); var constraints = el.constraints.forEach(function (constr) { if (constr.name == 'required') { constr.value = 'false'; } }); } } }); }); } } if ((!validationExist && obj.inputEl.value != '') || (validationExist && validationResult)) { for (var i = 0; i < obj.constraints.length; i++) { var constraint = obj.constraints[i]; if (constraint.name == 'pattern') { var regex = constraint.value; if (regex != '') { if (obj.inputEl.value.match(regex)) { // only when there is no other validation mark it as passed obj.clearError('pattern'); YAHOO.util.Dom.removeClass(obj.patternErrEl, 'on'); validationExist = true; } else { if (obj.inputEl.value != '') { YAHOO.util.Dom.addClass(obj.patternErrEl, 'on'); } obj.setError('pattern', 'The value entered is not allowed in this field.'); validationExist = true; validationResult = false; } } break; } } } // actual validation is checked by # of errors // renderValidation does not require the result being passed obj.renderValidation(validationExist, validationResult); obj.owner.notifyValidation(); obj.form.updateModel(obj.id, obj.getValue()); }, _onChangeVal: function (evt, obj) { obj.edited = true; this._onChange(evt, obj); }, /** * perform count calculation on keypress * @param evt event * @param el element */ count: function (evt, countEl, el) { // 'this' is the input box el = el ? el : this; var text = el.value; var charCount = text.length ? text.length : el.textLength ? el.textLength : 0; var maxlength = el.maxlength && el.maxlength != '' ? el.maxlength : -1; if (maxlength != -1) { if (charCount > el.maxlength) { // truncate if exceeds max chars if (charCount > el.maxlength) { this.value = text.substr(0, el.maxlength); charCount = el.maxlength; } if ( evt && evt != null && evt.keyCode != 8 && evt.keyCode != 46 && evt.keyCode != 37 && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40 && // arrow keys evt.keyCode != 88 && evt.keyCode != 86 ) { // allow backspace and // delete key and arrow keys (37-40) // 86 -ctrl-v, 90-ctrl-z, if (evt) YAHOO.util.Event.stopEvent(evt); } } } if (maxlength != -1) { countEl.innerHTML = charCount + ' / ' + el.maxlength; } else { countEl.innerHTML = charCount; } }, render: function (config, containerEl) { // we need to make the general layout of a control inherit from common // you should be able to override it -- but most of the time it wil be the same containerEl.id = this.id; var titleEl = document.createElement('span'); YAHOO.util.Dom.addClass(titleEl, 'cstudio-form-field-title'); titleEl.textContent = config.title; var controlWidgetContainerEl = document.createElement('div'); YAHOO.util.Dom.addClass(controlWidgetContainerEl, 'cstudio-form-control-link-input-container'); var validEl = document.createElement('span'); YAHOO.util.Dom.addClass(validEl, 'validation-hint'); YAHOO.util.Dom.addClass(validEl, 'cstudio-form-control-validation fa fa-check'); controlWidgetContainerEl.appendChild(validEl); var inputEl = document.createElement('input'); this.inputEl = inputEl; YAHOO.util.Dom.addClass(inputEl, 'datum'); YAHOO.util.Dom.addClass(inputEl, 'cstudio-form-control-input'); inputEl.value = (this.value = '_not-set') ? config.defaultValue : this.value; controlWidgetContainerEl.appendChild(inputEl); YAHOO.util.Event.on( inputEl, 'focus', function (evt, context) { context.form.setFocusedField(context); }, this ); YAHOO.util.Event.on(inputEl, 'change', this._onChangeVal, this); YAHOO.util.Event.on(inputEl, 'blur', this._onChange, this); for (var i = 0; i < config.properties.length; i++) { var prop = config.properties[i]; if (prop.name == 'size') { inputEl.size = prop.value; } if (prop.name == 'maxlength') { inputEl.maxlength = prop.value; } if (prop.name == 'readonly' && prop.value == 'true') { this.readonly = true; } } if (this.readonly == true) { inputEl.disabled = true; } var countEl = document.createElement('div'); YAHOO.util.Dom.addClass(countEl, 'char-count'); YAHOO.util.Dom.addClass(countEl, 'cstudio-form-control-input-count'); controlWidgetContainerEl.appendChild(countEl); this.countEl = countEl; var patternErrEl = document.createElement('div'); patternErrEl.innerHTML = 'The value entered is not allowed in this field.'; YAHOO.util.Dom.addClass(patternErrEl, 'cstudio-form-control-input-url-err'); controlWidgetContainerEl.appendChild(patternErrEl); this.patternErrEl = patternErrEl; YAHOO.util.Event.on(inputEl, 'keyup', this.count, countEl); YAHOO.util.Event.on(inputEl, 'keypress', this.count, countEl); YAHOO.util.Event.on(inputEl, 'mouseup', this.count, countEl); this.renderHelp(config, controlWidgetContainerEl); var descriptionEl = document.createElement('span'); YAHOO.util.Dom.addClass(descriptionEl, 'description'); YAHOO.util.Dom.addClass(descriptionEl, 'cstudio-form-field-description'); descriptionEl.textContent = config.description; containerEl.appendChild(titleEl); containerEl.appendChild(controlWidgetContainerEl); containerEl.appendChild(descriptionEl); }, getValue: function () { return this.value; }, setValue: function (value) { this.value = value; this.inputEl.value = value; this.count(null, this.countEl, this.inputEl); this._onChange(null, this); this.edited = false; }, getName: function () { return 'link-input'; }, getSupportedProperties: function () { return [ { label: CMgs.format(langBundle, 'displaySize'), name: 'size', type: 'int', defaultValue: '50' }, { label: CMgs.format(langBundle, 'maxLength'), name: 'maxlength', type: 'int', defaultValue: '50' }, { label: CMgs.format(langBundle, 'readonly'), name: 'readonly', type: 'boolean' }, { label: 'Tokenize for Indexing', name: 'tokenize', type: 'boolean', defaultValue: 'false' } ]; }, getSupportedConstraints: function () { return [ { label: CMgs.format(langBundle, 'required'), name: 'required', type: 'boolean' }, { label: CMgs.format(langBundle, 'matchPattern'), name: 'pattern', type: 'string' } ]; } }); CStudioAuthoring.Module.moduleLoaded('cstudio-forms-controls-link-input', CStudioForms.Controls.LinkInput);
rart/studio-ui
static-assets/components/cstudio-forms/controls/link-input.js
JavaScript
gpl-3.0
10,102
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MonitorToggleButton from 'Components/MonitorToggleButton'; import EditImportListModalConnector from 'Settings/ImportLists/ImportLists/EditImportListModalConnector'; import styles from './MovieCollection.css'; class MovieCollection extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditImportListModalOpen: false }; } onAddImportListPress = (monitored) => { if (this.props.collectionList) { this.props.onMonitorTogglePress(monitored); } else { this.props.onMonitorTogglePress(monitored); this.setState({ isEditImportListModalOpen: true }); } } onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); } render() { const { name, collectionList, isSaving } = this.props; const monitored = collectionList !== undefined && collectionList.enabled && collectionList.enableAuto; const importListId = collectionList ? collectionList.id : 0; return ( <div> <MonitorToggleButton className={styles.monitorToggleButton} monitored={monitored} isSaving={isSaving} size={15} onPress={this.onAddImportListPress} /> {name} <EditImportListModalConnector id={importListId} isOpen={this.state.isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} onDeleteImportListPress={this.onDeleteImportListPress} /> </div> ); } } MovieCollection.propTypes = { tmdbId: PropTypes.number.isRequired, name: PropTypes.string.isRequired, collectionList: PropTypes.object, isSaving: PropTypes.bool.isRequired, onMonitorTogglePress: PropTypes.func.isRequired }; export default MovieCollection;
Radarr/Radarr
frontend/src/Movie/MovieCollection.js
JavaScript
gpl-3.0
1,954
Equipment=null; EquipmentPanel = Popup.extend({ getIdentifier:function(){ return "Equipment"; }, getLayoutObject:function(){ var equipment_panel={}; equipment_panel["head"] = { texture:"GUI/defaultitem.png", position:cc.p(88,162), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["legs"] = { texture:"GUI/defaultitem.png", position:cc.p(88,82), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["feet"] = { texture:"GUI/defaultitem.png", position:cc.p(88,40), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["body"] = { texture:"GUI/defaultitem.png", position:cc.p(88,122), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["lArm"] = { texture:"GUI/defaultitem.png", position:cc.p(48,122), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["rArm"] = { texture:"GUI/defaultitem.png", position:cc.p(128,122), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; equipment_panel["mod"] = { texture:"GUI/defaultitem.png", position:cc.p(8,162), size: cc.size(32,32), anchorPoint:cc.p(0,1), }; return { "panels":{ position:cc.p(100,300), children:{ "main_panel":{ anchorPoint:cc.p(0,0), size: cc.size(168,168), texture:"GUI/equipment.png", children: equipment_panel, }, "control_panel":{ anchorPoint:cc.p(0,0), position: cc.p(0,168), size: cc.size(168,32), children:{ "header":{ label:settingsData["Equipment Header"], fontSize:20, anchorPoint:cc.p(0,0.5), position:cc.p(8,16), }, "exitBtn":{ position: cc.p(144,6), size: cc.size(20,20), anchorPoint:cc.p(0,0), texture:"GUI/close.png" } } }, "item_name":{ position:cc.p(0,0), color:cc.c4b(200,200,200,200), size:cc.size(64,16), visible:false, children:{ "content":{ label:"", fontSize:14, color:cc.c3b(0,0,0), anchorPoint:cc.p(0.5,0.5), position:cc.p(32,8), } } }, } } }; }, updateTileGrid:function(){ var equipmentList = PlayersController.getYou().getEquipment(); this.panels["main_panel"]["head"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["body"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["legs"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["feet"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["lArm"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["rArm"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); this.panels["main_panel"]["mod"].setTexture(cc.TextureCache.getInstance().addImage("GUI/defaultitem.png")); for(var i in equipmentList){ if(equipmentList[i]){ var item = ObjectLists.getItemList()[equipmentList[i]["number"]]; for(var j in tileTextureList){ if(tileTextureList[j]["name"]==item["sprite"]["texture"]){ var texture=tileTextureList[j]["texture"]; } } if(this.panels["main_panel"][i]){ this.panels["main_panel"][i].setAnchorPoint(0,1); this.panels["main_panel"][i].setTexture(texture); this.panels["main_panel"][i].setTextureRect(cc.rect(item["sprite"]["position"].x*32, (item["sprite"]["position"].y*32),32,32)); } } } }, listItemSelected:function(val){ switch(val){ case 0:PlayersController.getYou().dequipItem(this.delegate.itemContext);break; case 1: PlayersController.getYou().dropItem(this.delegate.itemContext,"equipped"); break; } }, onTouchBegan:function(touch){ if(this._super(touch)){ return true; } this.prevMovPos=null; var truePos = this.panels["main_panel"].convertToNodeSpace(touch._point); var equipmentList = PlayersController.getYou().getEquipment(); for(var i in equipmentList){ if(equipmentList[i]){ var item = ObjectLists.getItemList()[equipmentList[i]["number"]]; var reducer= 32; if(isTouching(this.panels["main_panel"][i],cc.p(truePos.x,truePos.y+reducer))){ this.itemContext=i; this.panels["item_name"].setVisible(false) var firstItem = settingsData["Item Dropdown Unequip"]+""; firstItem = firstItem.replace("<ITEM>",(item["name"])); var secondItem = settingsData["Item Dropdown Drop"]+""; secondItem = secondItem.replace("<ITEM>",(item["name"])); this.addChild(DropDownList.createWithListAndPosition(this,this.listItemSelected,[firstItem,secondItem],touch._point)); return true; } } } }, onMouseMoved:function(event){ var pos = event.getLocation(); var truePos = this.panels["main_panel"].convertToNodeSpace(pos); this.panels["item_name"].setVisible(false); var equipmentList = PlayersController.getYou().getEquipment(); for(var i in equipmentList){ if(equipmentList[i]){ var item = ObjectLists.getItemList()[equipmentList[i]["number"]]; var reducer= 32; if(isTouching(this.panels["main_panel"][i],cc.p(truePos.x,truePos.y+reducer))){ this.panels["item_name"]["content"].setString(item["name"]); this.panels["item_name"].setVisible(true); this.panels["item_name"].setContentSize(this.panels["item_name"]["content"].getContentSize()); this.panels["item_name"]["content"].setPositionX(this.panels["item_name"]["content"].getContentSize().width/2); this.panels["item_name"].setPosition(cc.p(this.panels["main_panel"][i].getPositionX()-(this.panels["item_name"]["content"].getContentSize().width/2)+16,this.panels["main_panel"][i].getPositionY())); return true; } } } }, scheduledupdateTileGrid:function(){ if(this.panels["main_panel"]["head"].getTexture()){ this.unschedule(this.scheduledupdateTileGrid); this.updateTileGrid(); } }, didBecomeActive:function(){ this._super(); if(!this.panels["main_panel"]["head"].getTexture()){ this.schedule(this.scheduledupdateTileGrid); }else{ this.updateTileGrid(); } }, });
RPGCreation/powderengine
client/src/popups/Equipment.js
JavaScript
gpl-3.0
6,282
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1) */ /** * A menu containing an Ext.picker.Date Component. * * Notes: * * - Although not listed here, the **constructor** for this class accepts all of the * configuration options of **{@link Ext.picker.Date}**. * - If subclassing DateMenu, any configuration options for the DatePicker must be applied * to the **initialConfig** property of the DateMenu. Applying {@link Ext.picker.Date Date Picker} * configuration settings to **this** will **not** affect the Date Picker's configuration. * * Example: * * @example * var dateMenu = Ext.create('Ext.menu.DatePicker', { * handler: function(dp, date){ * Ext.Msg.alert('Date Selected', 'You selected ' + Ext.Date.format(date, 'M j, Y')); * } * }); * * Ext.create('Ext.menu.Menu', { * items: [{ * text: 'Choose a date', * menu: dateMenu * },{ * iconCls: 'add16', * text: 'Icon item' * },{ * text: 'Regular item' * }] * }).showAt([5, 5]); */ Ext.define('Ext.menu.DatePicker', { extend: 'Ext.menu.Menu', alias: 'widget.datemenu', requires: [ 'Ext.picker.Date' ], /** * @cfg {Boolean} hideOnClick * False to continue showing the menu after a date is selected. */ hideOnClick : true, /** * @cfg {String} pickerId * An id to assign to the underlying date picker. */ pickerId : null, /** * @cfg {Number} maxHeight * @private */ /** * @property {Ext.picker.Date} picker * The {@link Ext.picker.Date} instance for this DateMenu */ initComponent : function(){ var me = this, cfg = Ext.apply({}, me.initialConfig); // Ensure we clear any listeners so they aren't duplicated delete cfg.listeners; Ext.apply(me, { showSeparator: false, plain: true, bodyPadding: 0, // remove the body padding from the datepicker menu item so it looks like 3.3 items: Ext.applyIf({ cls: Ext.baseCSSPrefix + 'menu-date-item', margin: 0, border: false, id: me.pickerId, xtype: 'datepicker' }, cfg) }); me.callParent(arguments); me.picker = me.down('datepicker'); /** * @event select * @inheritdoc Ext.picker.Date#select */ me.relayEvents(me.picker, ['select']); if (me.hideOnClick) { me.on('select', me.hidePickerOnSelect, me); } }, hidePickerOnSelect: function() { Ext.menu.Manager.hideAll(); } });
CCAFS/CCAFS-Climate
libs/ext-4.2.2/src/menu/DatePicker.js
JavaScript
gpl-3.0
3,457
import * as util from '../src/utils.js' import World from '../src/World.js' import Color from '../src/Color.js' import ColorMap from '../src/ColorMap.js' import ThreeView from '../src/ThreeView.js' const params = util.RESTapi({ seed: false, population: 100, maxX: 30, maxY: 30, steps: 500, shapeSize: 2, }) if (params.seed) util.randomSeed() params.world = World.defaultOptions(params.maxX, params.maxY) const nestColor = Color.typedColor('yellow') const foodColor = Color.typedColor('blue') const nestColorMap = ColorMap.gradientColorMap(20, ['black', nestColor.css]) const foodColorMap = ColorMap.gradientColorMap(20, ['black', foodColor.css]) const worker = new Worker('./antsWorker.js', { type: 'module' }) worker.postMessage({ cmd: 'init', params: params }) const view = new ThreeView(params.world) const nestSprite = view.getSprite('bug', nestColor.css) const foodSprite = view.getSprite('bug', foodColor.css) util.toWindow({ view, worker, params, util }) const perf = util.fps() // Just for testing, not needed for production. worker.onmessage = e => { if (e.data === 'done') { console.log(`Done, steps: ${perf.steps}, fps: ${perf.fps}`) view.idle() } else { view.drawPatches(e.data.patches, p => { if (p.isNest) return nestColor.pixel if (p.isFood) return foodColor.pixel const color = p.foodPheromone > p.nestPheromone ? foodColorMap.scaleColor(p.foodPheromone, 0, 1) : nestColorMap.scaleColor(p.nestPheromone, 0, 1) return color.pixel }) view.drawTurtles(e.data.turtles, t => ({ sprite: t.carryingFood ? nestSprite : foodSprite, size: params.shapeSize, })) view.render() worker.postMessage({ cmd: 'step' }) perf() } } // util.timeoutLoop(() => { // model.step() // view.drawPatches(model.patches, p => { // if (p.isNest) return nestColor.pixel // if (p.isFood) return foodColor.pixel // const color = // p.foodPheromone > p.nestPheromone // ? foodColorMap.scaleColor(p.foodPheromone, 0, 1) // : nestColorMap.scaleColor(p.nestPheromone, 0, 1) // return color.pixel // }) // view.drawTurtles(model.turtles, t => ({ // sprite: t.carryingFood ? nestSprite : foodSprite, // size: params.shapeSize, // })) // view.render() // perf() // }, 500).then(() => { // console.log(`Done, steps: ${perf.steps}, fps: ${perf.fps}`) // view.idle() // })
backspaces/CoreAS
workers3/ants.js
JavaScript
gpl-3.0
2,618
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * 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, see <http://www.gnu.org/licenses/>. */ /** * editor tools */ CStudioAuthoring.MediumPanel.IPad = CStudioAuthoring.MediumPanel.IPad || { initialized: false, /** * initialize module */ initialize: function (config) { if (this.initialized == false) { this.initialized = true; } }, render: function (containerEl, config) { var emulateEl = document.getElementById('cstudio-emulate'); var mode = 'vert'; if (!emulateEl) { emulateEl = document.createElement('div'); emulateEl.id = 'cstudio-emulate'; document.body.appendChild(emulateEl); } else { emulateEl.innerHTML = ''; mode = emulateEl.mode; } if (mode == 'vert') { emulateEl.style.position = 'absolute'; emulateEl.style.width = '850px'; emulateEl.style.height = '1100px'; emulateEl.style.top = '32px'; emulateEl.style.background = "url('" + CStudioAuthoringContext.authoringAppBaseUri + "/static-assets/components/cstudio-preview-tools/mods/agent-plugins/ipad/ipad.gif')"; emulateEl.style.marginLeft = '' + (CStudioAuthoring.Utils.viewportWidth() / 2 - 440) + 'px'; var iframeEl = document.createElement('iframe'); emulateEl.appendChild(iframeEl); iframeEl.style.border = 'none'; iframeEl.style.height = '885px'; iframeEl.style.marginLeft = '93px'; iframeEl.style.marginTop = '105px'; iframeEl.style.width = '665px'; iframeEl.style.background = 'white'; iframeEl.style.scrolling = 'no'; var rotateControlEl = document.createElement('div'); emulateEl.appendChild(rotateControlEl); rotateControlEl.style.background = "url('" + CStudioAuthoringContext.authoringAppBaseUri + "/static-assets/components/cstudio-preview-tools/mods/agent-plugins/ipad/object-rotate-right.png')"; rotateControlEl.style.width = '30px'; rotateControlEl.style.height = '32px'; rotateControlEl.style.position = 'absolute'; rotateControlEl.style.top = '5px'; rotateControlEl.style.left = '850px'; rotateControlEl.style.cursor = 'pointer'; rotateControlEl.mode = 'vert'; } else { emulateEl.style.position = 'absolute'; emulateEl.style.width = '1100px'; emulateEl.style.height = '850px'; emulateEl.style.top = '32px'; emulateEl.style.background = "url('" + CStudioAuthoringContext.authoringAppBaseUri + "/static-assets/components/cstudio-preview-tools/mods/agent-plugins/ipad/ipad-hozbg.gif') repeat scroll 0 0pt transparent"; emulateEl.style.marginLeft = '' + (CStudioAuthoring.Utils.viewportWidth() / 2 - 540) + 'px'; var iframeEl = document.createElement('iframe'); emulateEl.appendChild(iframeEl); iframeEl.style.border = 'none'; iframeEl.style.height = '663px'; iframeEl.style.marginLeft = '110px'; iframeEl.style.marginTop = '92px'; iframeEl.style.width = '884px'; iframeEl.style.background = 'white'; iframeEl.style.scrolling = 'no'; var rotateControlEl = document.createElement('div'); emulateEl.appendChild(rotateControlEl); rotateControlEl.style.background = "url('" + CStudioAuthoringContext.authoringAppBaseUri + "/static-assets/components/cstudio-preview-tools/mods/agent-plugins/ipad/object-rotate-left.png')"; rotateControlEl.style.width = '30px'; rotateControlEl.style.height = '32px'; rotateControlEl.style.position = 'absolute'; rotateControlEl.style.top = '5px'; rotateControlEl.style.left = '1100px'; rotateControlEl.style.cursor = 'pointer'; rotateControlEl.mode = 'horiz'; } rotateControlEl.control = emulateEl; rotateControlEl.controller = this; rotateControlEl.onclick = function () { if (this.mode == 'vert') { this.control.mode = 'horiz'; } else { this.control.mode = 'vert'; } this.controller.render(); }; var location = document.location.href; if (location.indexOf('?') != -1) { location += '&cstudio-useragent=ipad'; } else { location += '?cstudio-useragent=ipad'; } iframeEl.onload = function () { var els = YAHOO.util.Dom.getElementsBy( function (el) { return true; }, 'a', this.contentDocument.body, function (el) { return true; } ); for (var k = 0; k < els.length; k++) { var link = els[k].href; if (link.indexOf('#') == -1) { if (link.indexOf('?') != -1) { link += '&cstudio-useragent=ipad'; } else { link += '?cstudio-useragent=ipad'; } els[k].href = '' + link; } } }; iframeEl.src = location; } }; CStudioAuthoring.Module.moduleLoaded('medium-panel-ipad', CStudioAuthoring.MediumPanel.IPad);
rart/studio-ui
static-assets/components/cstudio-preview-tools/mods/agent-plugins/ipad/ipad.js
JavaScript
gpl-3.0
5,567
define(function(require) { var QuestionView = require('coreViews/questionView'); var Adapt = require('coreJS/adapt'); var Slider = QuestionView.extend({ events: { 'click .slider-sliderange': 'onSliderSelected', 'click .slider-handle': 'preventEvent', 'click .slider-scale-number': 'onNumberSelected', 'touchstart .slider-handle':'onHandlePressed', 'mousedown .slider-handle': 'onHandlePressed', 'focus .slider-handle':'onHandleFocus', 'blur .slider-handle':'onHandleBlur' }, // Used by the question to reset the question when revisiting the component resetQuestionOnRevisit: function() { this.setAllItemsEnabled(true); this.deselectAllItems(); this.resetQuestion(); }, // Used by question to setup itself just before rendering setupQuestion: function() { if(!this.model.get('_items')) { this.setupModelItems(); } this.model.set({ _selectedItem: {} }); this.restoreUserAnswers(); if (this.model.get('_isSubmitted')) return; this.selectItem(0); }, setupModelItems: function() { var items = []; var answer = this.model.get('_correctAnswer'); var range = this.model.get('_correctRange'); var start = this.model.get('_scaleStart'); var end = this.model.get('_scaleEnd'); for (var i = start; i <= end; i++) { if (answer) { items.push({value: i, selected: false, correct: (i == answer)}); } else { items.push({value: i, selected: false, correct: (i >= range._bottom && i <= range._top)}); } } this.model.set('_items', items); }, restoreUserAnswers: function() { if (!this.model.get('_isSubmitted')) return; var items = this.model.get('_items'); var userAnswer = this.model.get('_userAnswer'); for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (item.value == userAnswer) { this.model.set('_selectedItem', item); this.selectItem(this.getIndexFromValue(item.value)); break; } } this.setQuestionAsSubmitted(); this.markQuestion(); this.setScore(); this.showMarking(); this.setupFeedback(); }, // Used by question to disable the question during submit and complete stages disableQuestion: function() { this.setAllItemsEnabled(false); }, // Used by question to enable the question during interactions enableQuestion: function() { this.setAllItemsEnabled(true); }, setAllItemsEnabled: function(isEnabled) { if (isEnabled) { this.$('.slider-widget').removeClass('disabled'); } else { this.$('.slider-widget').addClass('disabled'); } }, // Used by question to setup itself just after rendering onQuestionRendered: function() { this.setScalePositions(); this.onScreenSizeChanged(); this.showScaleMarker(true); this.listenTo(Adapt, 'device:resize', this.onScreenSizeChanged); this.setAltText(this.model.get('_scaleStart')); this.setReadyStatus(); }, // this should make the slider handle, slider marker and slider bar to animate to give position animateToPosition: function(newPosition) { this.$('.slider-handle').stop(true).animate({ left: newPosition + 'px' },200); this.$('.slider-bar').stop(true).animate({width:newPosition + 'px'}); this.$('.slider-scale-marker').stop(true).animate({ left: newPosition + 'px' },200); this.$('.slider-bar').stop(true).animate({width:newPosition + 'px'}); }, // this shoud give the index of item using given slider value getIndexFromValue: function(itemValue) { var scaleStart = this.model.get('_scaleStart'), scaleEnd = this.model.get('_scaleEnd'); return Math.floor(this.mapValue(itemValue, scaleStart, scaleEnd, 0, this.model.get('_items').length - 1)); }, // this should set given value to slider handle setAltText: function(value) { this.$('.slider-handle').attr('aria-valuenow', value); }, mapIndexToPixels: function(value, $widthObject) { var numberOfItems = this.model.get('_items').length, width = $widthObject ? $widthObject.width() : this.$('.slider-sliderange').width(); return Math.round(this.mapValue(value, 0, numberOfItems - 1, 0, width)); }, mapPixelsToIndex: function(value) { var numberOfItems = this.model.get('_items').length, width = this.$('.slider-sliderange').width(); return Math.round(this.mapValue(value, 0, width, 0, numberOfItems - 1)); }, normalise: function(value, low, high) { var range = high - low; return (value - low) / range; }, mapValue: function(value, inputLow, inputHigh, outputLow, outputHigh) { var normal = this.normalise(value, inputLow, inputHigh); return normal * (outputHigh - outputLow) + outputLow; }, onDragReleased: function (event) { event.preventDefault(); if (Modernizr.touch) { this.$('.slider-handle').off('touchmove'); } else { $(document).off('mousemove.adapt-contrib-slider'); } var itemValue = this.model.get('_selectedItem').value; var itemIndex = this.getIndexFromValue(itemValue); this.animateToPosition(this.mapIndexToPixels(itemIndex)); this.setAltText(itemValue); }, onHandleDragged: function (event) { event.preventDefault(); var left = (event.pageX || event.originalEvent.touches[0].pageX) - event.data.offsetLeft; left = Math.max(Math.min(left, event.data.width), 0); this.$('.slider-handle').css({ left: left + 'px' }); this.$('.slider-scale-marker').css({ left: left + 'px' }); this.selectItem(this.mapPixelsToIndex(left)); }, onHandleFocus: function(event) { event.preventDefault(); this.$('.slider-handle').on('keydown', _.bind(this.onKeyDown, this)); }, onHandleBlur: function(event) { event.preventDefault(); this.$('.slider-handle').off('keydown'); }, onHandlePressed: function (event) { event.preventDefault(); if (!this.model.get('_isEnabled') || this.model.get('_isSubmitted')) return; this.showScaleMarker(true); var eventData = { width:this.$('.slider-sliderange').width(), offsetLeft: this.$('.slider-sliderange').offset().left }; if(Modernizr.touch) { this.$('.slider-handle').on('touchmove', eventData, _.bind(this.onHandleDragged, this)); this.$('.slider-handle').one('touchend', eventData, _.bind(this.onDragReleased, this)); } else { $(document).on('mousemove.adapt-contrib-slider', eventData, _.bind(this.onHandleDragged, this)); $(document).one('mouseup', eventData, _.bind(this.onDragReleased, this)); } }, onKeyDown: function(event) { if(event.which == 9) return; // tab key event.preventDefault(); var newItemIndex = this.getIndexFromValue(this.model.get('_selectedItem').value); switch (event.which) { case 40: // ↓ down case 37: // ← left newItemIndex = Math.max(newItemIndex - 1, 0); break; case 38: // ↑ up case 39: // → right newItemIndex = Math.min(newItemIndex + 1, this.model.get('_items').length - 1); break; } this.selectItem(newItemIndex); if(typeof newItemIndex == 'number') this.showScaleMarker(true); this.animateToPosition(this.mapIndexToPixels(newItemIndex)); this.setAltText(this.getValueFromIndex(newItemIndex)); }, onSliderSelected: function (event) { event.preventDefault(); if (!this.model.get('_isEnabled') || this.model.get('_isSubmitted')) { return; } this.showScaleMarker(true); var offsetLeft = this.$('.slider-sliderange').offset().left; var width = this.$('.slider-sliderange').width(); var left = (event.pageX || event.originalEvent.touches[0].pageX) - offsetLeft; left = Math.max(Math.min(left, width), 0); var itemIndex = this.mapPixelsToIndex(left); this.selectItem(itemIndex); this.animateToPosition(this.mapIndexToPixels(itemIndex)); this.setAltText(this.getValueFromIndex(itemIndex)); }, onNumberSelected: function(event) { event.preventDefault(); if (this.model.get('_isComplete')) { return; } var itemValue = parseInt($(event.currentTarget).attr('data-id')); var index = this.getIndexFromValue(itemValue); var $scaler = this.$('.slider-scaler'); this.selectItem(index); this.animateToPosition(this.mapIndexToPixels(index, $scaler)); this.setAltText(itemValue); }, getValueFromIndex: function(index) { return this.model.get('_items')[index].value; }, preventEvent: function(event) { event.preventDefault(); }, resetControlStyles: function() { this.$('.slider-handle').empty(); this.showScaleMarker(false); this.$('.slider-bar').animate({width:'0px'}); }, /** * allow the user to submit immediately; the slider handle may already be in the position they want to choose */ canSubmit: function() { return true; }, // Blank method for question to fill out when the question cannot be submitted onCannotSubmit: function() {}, //This preserves the state of the users answers for returning or showing the users answer storeUserAnswer: function() { this.model.set('_userAnswer', this.model.get('_selectedItem').value); }, isCorrect: function() { var numberOfCorrectAnswers = 0; _.each(this.model.get('_items'), function(item, index) { if(item.selected && item.correct) { this.model.set('_isAtLeastOneCorrectSelection', true); numberOfCorrectAnswers++; } }, this); this.model.set('_numberOfCorrectAnswers', numberOfCorrectAnswers); return this.model.get('_isAtLeastOneCorrectSelection') ? true : false; }, // Used to set the score based upon the _questionWeight setScore: function() { var numberOfCorrectAnswers = this.model.get('_numberOfCorrectAnswers'); var questionWeight = this.model.get('_questionWeight'); var score = questionWeight * numberOfCorrectAnswers; this.model.set('_score', score); }, // This is important and should give the user feedback on how they answered the question // Normally done through ticks and crosses by adding classes showMarking: function() { this.$('.slider-item').removeClass('correct incorrect') .addClass(this.model.get('_selectedItem').correct ? 'correct' : 'incorrect'); }, isPartlyCorrect: function() { return this.model.get('_isAtLeastOneCorrectSelection'); }, // Used by the question view to reset the stored user answer resetUserAnswer: function() { this.model.set({ _selectedItem: {}, _userAnswer: undefined }); }, // Used by the question view to reset the look and feel of the component. // This could also include resetting item data resetQuestion: function() { this.selectItem(0); this.animateToPosition(0); this.resetControlStyles(); this.showScaleMarker(true); this.setAltText(this.model.get('_scaleStart')); }, setScalePositions: function() { var numberOfItems = this.model.get('_items').length; _.each(this.model.get('_items'), function(item, index) { var normalisedPosition = this.normalise(index, 0, numberOfItems -1); this.$('.slider-scale-number').eq(index).data('normalisedPosition', normalisedPosition); }, this); }, showScale: function () { this.$('.slider-markers').empty(); if (this.model.get('_showScale') === false) { this.$('.slider-markers').eq(0).css({display: 'none'}); this.model.get('_showScaleIndicator') ? this.$('.slider-scale-numbers').eq(0).css({visibility: 'hidden'}) : this.$('.slider-scale-numbers').eq(0).css({display: 'none'}); } else { var $scaler = this.$('.slider-scaler'); var $markers = this.$('.slider-markers'); for (var i = 0, count = this.model.get('_items').length; i < count; i++) { $markers.append("<div class='slider-line component-item-color'>"); $('.slider-line', $markers).eq(i).css({left: this.mapIndexToPixels(i, $scaler) + 'px'}); } var scaleWidth = $scaler.width(), $numbers = this.$('.slider-scale-number'); for (var i = 0, count = this.model.get('_items').length; i < count; i++) { var $number = $numbers.eq(i), newLeft = Math.round($number.data('normalisedPosition') * scaleWidth); $number.css({left: newLeft}); } } }, //Labels are enabled in slider.hbs. Here we manage their containing div. showLabels: function () { if(!this.model.get('labelStart') && !this.model.get('labelEnd')) { this.$('.slider-scale-labels').eq(0).css({display: 'none'}); } }, remapSliderBar: function() { var $scaler = this.$('.slider-scaler'); var currentIndex = this.getIndexFromValue(this.model.get('_selectedItem').value); this.$('.slider-handle').css({left: this.mapIndexToPixels(currentIndex, $scaler) + 'px'}); this.$('.slider-scale-marker').css({left: this.mapIndexToPixels(currentIndex, $scaler) + 'px'}); this.$('.slider-bar').width(this.mapIndexToPixels(currentIndex, $scaler)); }, onScreenSizeChanged: function() { this.showScale(); this.showLabels(); this.remapSliderBar(); if (this.$('.slider-widget.user .button.model').css('display') === 'inline-block') { this.hideCorrectAnswer(); } else if (this.$('.slider-widget.model .button.user ').css('display') === 'inline-block') { this.showCorrectAnswer(); } }, showCorrectAnswer: function() { var answers = []; var bottom = this.model.get('_correctRange')._bottom; var top = this.model.get('_correctRange')._top; var range = top - bottom; var correctAnswer = this.model.get('_correctAnswer'); this.showScaleMarker(false); if (correctAnswer) { // Check that correctAnswer is neither undefined nor empty answers.push(correctAnswer); } else if (bottom !== undefined) { for (var i = 0; i <= range; i++) { answers.push(this.model.get('_items')[this.getIndexFromValue(bottom) + i].value); } } else { console.log(this.constructor + "::WARNING: no correct answer or correct range set in JSON") } var middleAnswer = answers[Math.floor(answers.length / 2)]; this.animateToPosition(this.mapIndexToPixels(this.getIndexFromValue(middleAnswer))); this.showModelAnswers(answers); }, showModelAnswers: function(correctAnswerArray) { var $parentDiv = this.$('.slider-modelranges'); _.each(correctAnswerArray, function(correctAnswer, index) { $parentDiv.append($("<div class='slider-model-answer component-item-color component-item-text-color'>")); var $element = $(this.$('.slider-modelranges .slider-model-answer')[index]), startingLeft = this.mapIndexToPixels(this.getIndexFromValue(this.model.get('_selectedItem').value)); if(this.model.get('_showNumber')) $element.html(correctAnswer); $element.css({left:startingLeft}).fadeIn(0, _.bind(function() { $element.animate({left: this.mapIndexToPixels(this.getIndexFromValue(correctAnswer))}); }, this)); }, this); }, // Used by the question to display the users answer and // hide the correct answer // Should use the values stored in storeUserAnswer hideCorrectAnswer: function() { var userAnswerIndex = this.getIndexFromValue(this.model.get('_userAnswer')); this.$('.slider-modelranges').empty(); this.showScaleMarker(true); this.selectItem(userAnswerIndex); this.animateToPosition(this.mapIndexToPixels(userAnswerIndex)); }, // according to given item index this should make the item as selected selectItem: function(itemIndex) { this.$el.a11y_selected(false); _.each(this.model.get('_items'), function(item, index) { item.selected = (index == itemIndex); if(item.selected) { this.model.set('_selectedItem', item); this.$('.slider-scale-number[data-id="'+(itemIndex+1)+'"]').a11y_selected(true); } }, this); this.showNumber(true); }, // this should reset the selected state of each item deselectAllItems: function() { _.each(this.model.get('_items'), function(item) { item.selected = false; }, this); }, // this makes the marker visible or hidden showScaleMarker: function(show) { var $scaleMarker = this.$('.slider-scale-marker'); if (this.model.get('_showScaleIndicator')) { this.showNumber(show); if(show) { $scaleMarker.addClass('display-block'); } else { $scaleMarker.removeClass('display-block'); } } }, // this should add the current slider value to the marker showNumber: function(show) { var $scaleMarker = this.$('.slider-scale-marker'); if(this.model.get('_showNumber')) { if(show) { $scaleMarker.html(this.model.get('_selectedItem').value); } else { $scaleMarker.html = ""; } } }, /** * Used by adapt-contrib-spoor to get the user's answers in the format required by the cmi.interactions.n.student_response data field */ getResponse:function() { return this.model.get('_userAnswer').toString(); }, /** * Used by adapt-contrib-spoor to get the type of this question in the format required by the cmi.interactions.n.type data field */ getResponseType:function() { return "numeric"; } }); Adapt.register('slider', Slider); return Slider; });
lc-thomasberger/mlTest
src/components/adapt-contrib-slider/js/adapt-contrib-slider.js
JavaScript
gpl-3.0
20,869
// start of file /** Object > Glyph A single collection of outlines that could either represent a character, or be used as part of another character through components. The following objects are stored as Glyph Objects: Glyphs (Characters) Ligatures Components **/ //------------------------------------------------------- // GLYPH OBJECT //------------------------------------------------------- function Glyph(oa){ // debug('\n Glyph - START'); oa = oa || {}; this.objtype = 'glyph'; this.hex = oa.glyphhex || false; this.name = oa.name || getGlyphName(oa.glyphhex) || false; this.glyphhtml = oa.glyphhtml || hexToHTML(oa.glyphhex) || false; this.isautowide = isval(oa.isautowide)? oa.isautowide : true; this.glyphwidth = isval(oa.glyphwidth)? oa.glyphwidth : 0; this.leftsidebearing = isval(oa.leftsidebearing)? oa.leftsidebearing : false; this.rightsidebearing = isval(oa.rightsidebearing)? oa.rightsidebearing : false; this.ratiolock = isval(oa.ratiolock)? oa.ratiolock : false; this.maxes = oa.maxes || makeUIMins(); this.shapes = oa.shapes || []; this.usedin = oa.usedin || []; this.contextglyphs = ''; this.rotationreferenceshapes = false; // debug('\t name: ' + this.name); var lc = 0; var cs = 0; if(oa.shapes && oa.shapes.length){ for(var i=0; i<oa.shapes.length; i++) { if(oa.shapes[i].objtype === 'componentinstance'){ // debug('\t hydrating ci ' + oa.shapes[i].name); this.shapes[i] = new ComponentInstance(clone(oa.shapes[i])); lc++; } else { // debug('\t hydrating sh ' + oa.shapes[i].name); this.shapes[i] = new Shape(clone(oa.shapes[i])); cs++; } } } if(this.getMaxes) this.getMaxes(); // cache oa.cache = oa.cache || {}; this.cache = {}; this.cache.svg = oa.cache.svg || false; // debug(' Glyph - END\n'); } //------------------------------------------------------- // TRANSFORM & MOVE //------------------------------------------------------- Glyph.prototype.setGlyphPosition = function(nx, ny, force){ // debug('Glyph.setGlyphPosition - START'); // debug('\t nx/ny/force: ' + nx + ' ' + ny + ' ' + force); var m = this.getMaxes(); if(nx !== false) nx = parseFloat(nx); if(ny !== false) ny = parseFloat(ny); var dx = (nx !== false)? (nx - m.xmin) : 0; var dy = (ny !== false)? (ny - m.ymax) : 0; this.updateGlyphPosition(dx, dy, force); // debug(' Glyph.setGlyphPosition - END\n'); }; Glyph.prototype.updateGlyphPosition = function(dx, dy, force){ // debug('\n Glyph.updateGlyphPosition - START ' + this.name); // debug('\t dx/dy/force: ' + dx + ' ' + dy + ' ' + force); // debug('\t number of shapes: ' + this.shapes.length); dx = parseFloat(dx) || 0; dy = parseFloat(dy) || 0; var cs = this.shapes; for(var i=0; i<cs.length; i++){ cs[i].updateShapePosition(dx, dy, force); } this.changed(); // debug(' Glyph.updateGlyphPosition - END ' + this.name + '\n\n'); }; Glyph.prototype.setGlyphSize = function(nw, nh, ratiolock){ // debug('SET GLYPHSIZE ---- nw/nh/ra:\t' + nw + '\t ' + nh + '\t ' + ratiolock); // debug('\t maxes: ' + json(this.maxes)); var m = this.getMaxes(); if(nw !== false) nw = parseFloat(nw); if(nh !== false) nh = parseFloat(nh); var ch = (m.ymax - m.ymin); var cw = (m.xmax - m.xmin); var dw = (nw !== false)? (nw - cw) : 0; var dh = (nh !== false)? (nh - ch) : 0; if(ratiolock){ if(Math.abs(nh) > Math.abs(nw)) dw = (cw*(nh/ch)) - cw; else dh = (ch*(nw/cw)) - ch; } this.updateGlyphSize(dw, dh, false); }; Glyph.prototype.updateGlyphSize = function(dw, dh, ratiolock, dontscalecomponentinstances){ // debug('\n Glyph.updateGlyphSize - START ' + this.name); // debug('\t number of shapes: ' + this.shapes.length); // debug('\t dw dh rl:\t' + dw + '/' + dh + '/' + ratiolock); var m = this.getMaxes(); if(dw !== false) dw = parseFloat(dw) || 0; if(dh !== false) dh = parseFloat(dh) || 0; // debug('\t adjust dw/dh:\t' + dw + '/' + dh); var oldw = m.xmax - m.xmin; var oldh = m.ymax - m.ymin; var neww = (oldw + dw); var newh = (oldh + dh); if(Math.abs(neww) < 1) neww = 1; if(Math.abs(newh) < 1) newh = 1; // debug('\t new w/h:\t' + neww + '/' + newh); var ratiodh = (newh/oldh); var ratiodw = (neww/oldw); // debug('\t ratio dw/dh:\t' + ratiodw + '/' + ratiodh); if(ratiolock){ // Assuming only one will be nonzero // if(Math.abs(ratiodh) > Math.abs(ratiodw)) ratiodw = ratiodh; // else ratiodh = ratiodw; if(dw !== 0 && dh === 0) ratiodh = ratiodw; else ratiodw = ratiodh; } // debug('\t ratio dw/dh:\t' + ratiodw + '/' + ratiodh); var cs = this.shapes; var s, smaxes, oldsw, oldsh, oldsx, oldsy, newsw, newsh, newsx, newsy, sdw, sdh, sdx, sdy; // debug('\t Before Maxes ' + json(m, true)); for(var i=0; i<cs.length; i++){ s = cs[i]; // debug('\t >>> Updating ' + s.objtype + ' ' + i + '/' + cs.length + ' : ' + s.name); smaxes = s.getMaxes(); // scale oldsw = smaxes.xmax - smaxes.xmin; newsw = oldsw * ratiodw; if(ratiodw === 0) sdw = false; else sdw = newsw - oldsw; oldsh = smaxes.ymax - smaxes.ymin; newsh = oldsh * ratiodh; if(ratiodh === 0) sdh = false; else sdh = newsh - oldsh; // debug('\t Shape ' + i + ' dw dh ' + sdw + ' ' + sdh); if(s.objtype === 'componentinstance' && dontscalecomponentinstances) { // Special case skipping scaling of CIs for Global Actions // debug(`\t Skipped this shape because it's a component instance`); } else { // It's a regular shape, or we're scaling everything s.updateShapeSize(sdw, sdh, false); } // move oldsx = smaxes.xmin - m.xmin; newsx = oldsx * ratiodw; if(ratiodw === 0) sdx = false; else sdx = newsx - oldsx; oldsy = smaxes.ymin - m.ymin; newsy = oldsy * ratiodh; if(ratiodh === 0) sdy = false; else sdy = newsy - oldsy; // debug('\t Shape Pos ' + i + ' dx dy ' + sdx + ' ' + sdy); s.updateShapePosition(sdx, sdy, true); } this.changed(); // debug('\t Afters Maxes ' + json(this.maxes, true)); // debug(' Glyph.updateGlyphSize - END ' + this.name + '\n'); }; Glyph.prototype.flipEW = function(mid){ // debug('\n Glyph.flipEW - START'); // debug('\t ' + this.name); // debug('\t passed mid = ' + mid); var m = this.getMaxes(); mid = isval(mid)? mid : ((m.xmax - m.xmin) / 2) + m.xmin; // debug('\t mid = ' + mid); // debug('\t maxes = ' + json(m, true)); for(var s=0; s < this.shapes.length; s++){ this.shapes[s].flipEW(mid); } this.changed(); // debug('\t maxes = ' + json(this.maxes, true)); }; Glyph.prototype.flipNS = function(mid){ var m = this.getMaxes(); mid = isval(mid)? mid : ((m.ymax - m.ymin) / 2) + m.ymin; for(var s=0; s < this.shapes.length; s++){ this.shapes[s].flipNS(mid); } this.changed(); }; Glyph.prototype.startRotationPreview = function() { // debug(`\n\n Glyph.startRotationPreview - START`); // debug(`\t shapes ${this.shapes.length}`); this.rotationreferenceshapes = []; for(var i=0; i<this.shapes.length; i++) { if(this.shapes[i].objtype === 'componentinstance'){ this.rotationreferenceshapes[i] = new ComponentInstance(this.shapes[i]); } else { this.rotationreferenceshapes[i] = new Shape(this.shapes[i]); } // debug(this.rotationreferenceshapes[i]); } // debug(` Glyph.startRotationPreview - END\n`); }; Glyph.prototype.rotationPreview = function(deltaRad, about, snap) { // debug(`\n\n Glyph.rotationPreview - START`); var tempshape; for(var i=0; i<this.shapes.length; i++) { if(this.shapes[i].objtype === 'componentinstance'){ this.shapes[i].rotate(deltaRad - niceAngleToRadians(this.shapes[i].rotation), about, snap); } else { tempshape = new Shape(clone(this.rotationreferenceshapes[i])); tempshape.rotate(deltaRad, about, snap); this.shapes[i].path = tempshape.path; } this.shapes[i].changed(); } // debug(` Glyph.rotationPreview - END\n`); }; Glyph.prototype.endRotationPreview = function() { this.rotationreferenceshapes = false; }; Glyph.prototype.rotate = function(deltaRad, about, snap) { about = about || this.getCenter(); for(var s=0; s < this.shapes.length; s++){ this.shapes[s].rotate(deltaRad, about, snap); } this.changed(); }; Glyph.prototype.reverseWinding = function() { for(var s=0; s<this.shapes.length; s++){ this.shapes[s].reverseWinding(); } this.changed(); }; Glyph.prototype.alignShapes = function(edge, target) { // debug('\n Glyph.alignShapes - START'); // debug('\t edge: ' + edge); var offset; if(edge === 'top'){ target = -999999; this.shapes.forEach(function(v) { target = Math.max(target, v.getMaxes().ymax); }); // debug('\t found TOP: ' + target); this.shapes.forEach(function(v) { v.setShapePosition(false, target); }); } else if (edge === 'middle'){ target = this.getCenter().y; // debug('\t found MIDDLE: ' + target); this.shapes.forEach(function(v) { offset = v.getCenter().y; v.updateShapePosition(false, (target - offset)); }); } else if (edge === 'bottom'){ target = 999999; this.shapes.forEach(function(v) { target = Math.min(target, v.getMaxes().ymin); }); // debug('\t found BOTTOM: ' + target); this.shapes.forEach(function(v) { offset = v.getMaxes().ymin; v.updateShapePosition(false, (target - offset)); }); } else if (edge === 'left'){ target = 999999; this.shapes.forEach(function(v) { target = Math.min(target, v.getMaxes().xmin); }); // debug('\t found LEFT: ' + target); this.shapes.forEach(function(v) { v.setShapePosition(target, false); }); } else if (edge === 'center'){ target = this.getCenter().x; // debug('\t found CENTER: ' + target); this.shapes.forEach(function(v) { offset = v.getCenter().x; v.updateShapePosition((target - offset), false); }); } else if (edge === 'right'){ target = -999999; this.shapes.forEach(function(v) { target = Math.max(target, v.getMaxes().xmax); }); // debug('\t found RIGHT: ' + target); this.shapes.forEach(function(v) { offset = v.getMaxes().xmax; v.updateShapePosition((target - offset), false); }); } this.changed(); // debug(' Glyph.alignShapes - END\n'); }; //------------------------------------------------------- // GETTERS //------------------------------------------------------- Glyph.prototype.getName = function() { return this.name; }; Glyph.prototype.getChar = function() { return getGlyphName(this.hex); }; Glyph.prototype.getHTML = function() { return this.glyphhtml || ''; }; Glyph.prototype.getLSB = function() { if(this.leftsidebearing === false) return _GP.projectsettings.defaultlsb; else return this.leftsidebearing; }; Glyph.prototype.getRSB = function() { if(this.rightsidebearing === false) return _GP.projectsettings.defaultrsb; else return this.rightsidebearing; }; Glyph.prototype.getCenter = function() { var m = this.getMaxes(); var re = {}; re.x = ((m.xmax - m.xmin) / 2) + m.xmin; re.y = ((m.ymax - m.ymin) / 2) + m.ymin; return re; }; //------------------------------------------------------- // CALCULATING SIZE //------------------------------------------------------- Glyph.prototype.calcGlyphMaxes = function(){ // debug('\n Glyph.calcGlyphMaxes - START ' + this.name); this.maxes = makeUIMins(); var tm; if(this.shapes.length > 0){ for(var jj=0; jj<this.shapes.length; jj++) { // debug('\t ++++++ START shape ' + jj); // debug(this.shapes[jj]); if(this.shapes[jj].getMaxes){ tm = this.shapes[jj].getMaxes(); // debug('\t before ' + json(tm, true)); this.maxes = getOverallMaxes([tm, this.maxes]); // debug('\t afters ' + json(tm, true)); // debug('\t ++++++ END shape ' + jj + ' - ' + this.shapes[jj].name); } } } else { this.maxes = { 'xmax': 0, 'xmin': 0, 'ymax': 0, 'ymin': 0 }; } this.calcGlyphWidth(); // debug(' Glyph.calcGlyphMaxes - END ' + this.name + '\n'); return clone(this.maxes, 'Glyph.calcGlyphMaxes'); }; Glyph.prototype.calcGlyphWidth = function(){ if(!this.isautowide) return; this.glyphwidth = Math.max(this.maxes.xmax, 0); }; Glyph.prototype.getAdvanceWidth = function() { this.calcGlyphWidth(); if(!this.isautowide) return this.glyphwidth; else return this.glyphwidth + this.getLSB() + this.getRSB(); }; Glyph.prototype.getMaxes = function() { // debug('\n Glyph.getMaxes - START ' + this.name); if(hasNonValues(this.maxes)){ // debug('\t ^^^^^^ maxes found NaN, calculating...'); this.calcGlyphMaxes(); // debug('\t ^^^^^^ maxes found NaN, DONE calculating...'); } if(this.shapes.length){ if( this.maxes.xmin === _UI.maxes.xmin || this.maxes.xmin === _UI.mins.xmin || this.maxes.xmax === _UI.maxes.xmax || this.maxes.xmax === _UI.mins.xmax || this.maxes.ymin === _UI.maxes.ymin || this.maxes.ymin === _UI.mins.ymin || this.maxes.ymax === _UI.maxes.ymax || this.maxes.ymax === _UI.mins.ymax ){ this.calcGlyphMaxes(); } } // debug('\t returning ' + json(this.maxes)); // debug(' Glyph.getMaxes - END ' + this.name + '\n'); return clone(this.maxes, 'Glyph.getMaxes'); }; function hasNonValues(obj) { if(!obj) return true; for(var v in obj){ if(obj.hasOwnProperty(v)){ if(!isval(obj[v])) return true; }} return false; } //------------------------------------------------------- // COMPONENT STUFF //------------------------------------------------------- Glyph.prototype.containsComponents = function(){ for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype === 'componentinstance'){ return true; } } return false; }; Glyph.prototype.canAddComponent = function(cid) { // debug('\n Glyph.canAddComponent - START'); var myid = ''+getMyID(this); // debug('\t adding ' + cid + ' to (me) ' + myid); if(myid === cid) return false; if(this.usedin.length === 0) return true; var downlinks = this.collectAllDownstreamLinks([], true); downlinks = downlinks.filter(function(elem, pos) { return downlinks.indexOf(elem) === pos;}); var uplinks = this.collectAllUpstreamLinks([]); uplinks = uplinks.filter(function(elem, pos) { return uplinks.indexOf(elem) === pos;}); // debug('\t downlinks: ' + downlinks); // debug('\t uplinks: ' + uplinks); if(downlinks.indexOf(cid) > -1) return false; if(uplinks.indexOf(cid) > -1) return false; return true; }; Glyph.prototype.collectAllDownstreamLinks = function(re, excludepeers) { re = re || []; for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype === 'componentinstance'){ re = re.concat(getGlyph(this.shapes[s].link).collectAllDownstreamLinks(re)); if(!excludepeers) re.push(this.shapes[s].link); } } return re; }; Glyph.prototype.collectAllUpstreamLinks = function(re) { re = re || []; for(var g=0; g<this.usedin.length; g++){ re = re.concat(getGlyph(this.usedin[g]).collectAllUpstreamLinks(re)); re.push(this.usedin[g]); } return re; }; // This method is called on Glyphs just before they are deleted // to clean up all the component instance linking Glyph.prototype.deleteLinks = function(thisid) { // debug('\n Glyph.deleteLinks - START'); // debug(`\t passed this as id: ${thisid}`); // Delete upstream Component Instances var upstreamglyph; for(var c=0; c<this.usedin.length; c++){ upstreamglyph = getGlyph(this.usedin[c]); // debug(`\t removing upstream from ${upstreamglyph.name}`); // debug(upstreamglyph.shapes); for(var u=0; u<upstreamglyph.shapes.length; u++){ if(upstreamglyph.shapes[u].objtype === 'componentinstance' && upstreamglyph.shapes[u].link === thisid){ upstreamglyph.shapes.splice(u, 1); upstreamglyph.changed(); u--; } } // debug(upstreamglyph.shapes); } // Delete downstream usedin array values for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype === 'componentinstance'){ // debug(`\t removing downstream from ${this.shapes[s].link}`); removeFromUsedIn(this.shapes[s].link, thisid); } } // debug(` Glyph.deleteLinks - END\n\n`); }; // Returns a boolian that tells if the specified component has // more than one instances in this single glyph Glyph.prototype.hasMultipleInstancesOf = function(linkID) { // debug(`\n Glyph.hasMultipleInstancesOf - START`); var count = 0; for(var i=0; i<this.shapes.length; i++) { if(this.shapes[i].link && this.shapes[i].link === linkID){ count++; // debug(`\t found match ${count} for ${linkID}`); } } // debug(` Glyph.hasMultipleInstancesOf - END - returning ${count > 1}\n\n`); return count > 1; }; //------------------------------------------------------- // DRAWING AND EXPORTING //------------------------------------------------------- Glyph.prototype.drawGlyph = function(lctx, view, alpha, addLSB){ // debug('\n Glyph.drawGlyph - START ' + this.name); // debug('\t view ' + json(view, true)); var sl = this.shapes; var shape, drewshape; if(isNaN(alpha) || alpha > 1 || alpha < 0) alpha = 1; if(addLSB && this.isautowide) view.dx += (this.getLSB() * view.dz); lctx.beginPath(); for(var j=0; j<sl.length; j++) { shape = sl[j]; if(shape.visible) { // debug('\t ' + this.name + ' drawing ' + shape.objtype + ' ' + j + ' ' + shape.name); drewshape = shape.drawShape(lctx, view); if(!drewshape){ console.warn('Could not draw shape ' + shape.name + ' in Glyph ' + this.name); if(shape.objtype === 'componentinstance' && !getGlyph(shape.link)){ console.warn('>>> Component Instance has bad link: ' + shape.link); var i = this.shapes.indexOf(shape); if(i > -1){ this.shapes.splice(i, 1); console.warn('>>> Deleted the Instance'); } } } } } lctx.closePath(); // lctx.fillStyle = RGBAtoRGB(_GP.projectsettings.colors.glyphfill, alpha); lctx.fillStyle = _GP.projectsettings.colors.glyphfill; lctx.globalAlpha = alpha; lctx.fill('nonzero'); lctx.globalAlpha = 1; // debug(' Glyph.drawGlyph - END ' + this.name + '\n'); return (this.getAdvanceWidth()*view.dz); }; Glyph.prototype.makeSVG = function(size, gutter) { // debug('\n Glyph.makeSVG - START'); var ps = _GP.projectsettings; size = size || _UI.thumbsize; gutter = gutter || _UI.thumbgutter; var emsquare = Math.max(ps.upm, (ps.ascent - ps.descent)); var desc = Math.abs(ps.descent); var charscale = (size-(gutter*2)) / size; var gutterscale = (gutter / size) * emsquare; var vbsize = emsquare - (gutter*2); var pathdata = this.getSVGpathData(); // Assemble SVG var re = '<svg version="1.1" '; re += 'xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '; re += 'width="'+size+'" height="'+size+'" viewBox="0,0,'+vbsize+','+vbsize+'">'; re += '<g transform="translate('+(gutterscale)+','+(emsquare-desc-(gutterscale/2))+') scale('+charscale+',-'+charscale+')">'; // re += '<rect x="0" y="-'+desc+'" height="'+desc+'" width="1000" fill="lime"/>'; // re += '<rect x="0" y="0" height="'+(emsquare-desc)+'" width="1000" fill="cyan"/>'; re += '<path d="' + pathdata + '"/>'; re += '</g>'; re += '</svg>'; // debug(' Glyph.makeSVG - END\n'); return re; }; Glyph.prototype.getSVGpathData = function() { if(this.cache.svg) return this.cache.svg; this.cache.svg = this.makeSVGpathData(); return this.cache.svg; }; Glyph.prototype.makeSVGpathData = function() { // SVG will not include LSB var sl = this.shapes; // Make Pathdata var pathdata = ''; var shape; for(var j=0; j<sl.length; j++) { shape = sl[j]; if(shape.visible) { pathdata += shape.getSVGpathData(); if(j < sl.length-1) pathdata += ' '; } } if(trim(pathdata) === '') pathdata = 'M0,0Z'; this.cache.svg = pathdata; return pathdata; }; Glyph.prototype.makeOpenTypeJSpath = function(otpath) { otpath = otpath || new opentype.Path(); for(var s=0; s < this.shapes.length; s++){ otpath = this.shapes[s].makeOpenTypeJSpath(otpath); } return otpath; }; Glyph.prototype.draw_MultiSelectAffordances = function() { var allpoints = []; for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype !== 'componentinstance'){ allpoints = allpoints.concat(this.shapes[s].path.pathpoints); this.shapes[s].draw_PathOutline(_UI.colors.blue, 1); } } draw_PathPoints(allpoints, _UI.colors.blue); }; Glyph.prototype.isOverControlPoint = function(x, y, nohandles) { var re = false; for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype !== 'componentinstance'){ re = this.shapes[s].path.isOverControlPoint(x, y, nohandles); if(re) return re; } } return false; }; Glyph.prototype.findWinding = function() { for(var s=0; s<this.shapes.length; s++){ this.shapes[s].findWinding(); } }; Glyph.prototype.flattenGlyph = function() { var reshapes = []; var ts, tg; for(var s=0; s<this.shapes.length; s++){ ts = this.shapes[s]; if(ts.objtype === 'shape'){ reshapes.push(new Shape(clone(ts, 'Glyph.flattenGlyph'))); } else if (ts.objtype === 'componentinstance'){ tg = ts.getTransformedGlyph(); tg = tg.flattenGlyph(); reshapes = reshapes.concat(tg.shapes); } else { // debug('\n Glyph.flattenGlyph - ERROR - none shape or ci in shapes array'); } } this.shapes = reshapes; // this.calcGlyphMaxes(); return this; }; Glyph.prototype.combineAllShapes = function(donttoast, dontresolveoverlaps) { // debug('\n Glyph.combineAllShapes - START - ' + this.name); if(this.shapes.length < 2) return this; this.flattenGlyph(); var cs = combineShapes(this.shapes, donttoast, dontresolveoverlaps); if(cs){ // debug('\t new shapes'); this.shapes = cs; // debug(this.shapes); this.changed(); } // debug(this.name + ' \t\t ' + this.shapes.length); // debug(' Glyph.combineAllShapes - END - ' + this.name + '\n'); return this; }; Glyph.prototype.resolveOverlapsForAllShapes = function() { var newshapes = []; for(var ts=0; ts<this.shapes.length; ts++){ newshapes = newshapes.concat(this.shapes[ts].resolveSelfOverlaps()); } this.shapes = newshapes; this.changed(); }; //------------------------------------------------------- // METHODS //------------------------------------------------------- Glyph.prototype.changed = function(descend, ascend) { this.cache = {}; var usedGlyph; if(ascend){ for(var g=0; g<this.usedin.length; g++){ usedGlyph = getGlyph(this.usedin[g]); if(usedGlyph && usedGlyph.changed) usedGlyph.changed(descend, ascend); } } if(descend){ for(var s=0; s<this.shapes.length; s++) this.shapes[s].changed(descend, ascend); } this.calcGlyphMaxes(); }; Glyph.prototype.map = function(indents) { indents = indents || ' '; var re = (indents + 'GLYPH ' + this.name + '\n'); var ts; for(var s=0; s < this.shapes.length; s++){ ts = this.shapes[s]; if(ts.objtype === 'shape'){ re += (indents + '-' + s + '-' + ts.name + ' ' + json(ts.path.maxes, true) + '\n'); } else if(ts.objtype === 'componentinstance'){ re += (indents+ '~' + s + '~' + ts.name + '\n'); re += getGlyph(ts.link).map(indents + ' '); } } return re; }; Glyph.prototype.copyShapesTo = function(destinationID, copyGlyphAttributes, selectNewShapes) { // debug('\n Glyph.copyShapesTo - START'); copyGlyphAttributes = copyGlyphAttributes || { srcAutoWidth: false, srcWidth: false, srcLSB: false, srcRSB: false}; selectNewShapes = selectNewShapes || false; var destinationGlyph = getGlyph(destinationID, true); var tc; if(selectNewShapes) _UI.ms.shapes.clear(); for(var c=0; c<this.shapes.length; c++){ tc = this.shapes[c]; if(tc.objtype === 'componentinstance'){ addToUsedIn(tc.link, destinationID); tc = new ComponentInstance(clone(tc, 'Glyph.copyShapesTo')); } else if(tc.objtype === 'shape'){ tc = new Shape(clone(tc, 'Glyph.copyShapesTo')); } destinationGlyph.shapes.push(tc); if(selectNewShapes) _UI.ms.shapes.add(tc); } if(copyGlyphAttributes.srcAutoWidth) destinationGlyph.isautowide = this.isautowide; if(copyGlyphAttributes.srcWidth) destinationGlyph.glyphwidth = this.glyphwidth; if(copyGlyphAttributes.srcLSB) destinationGlyph.leftsidebearing = this.leftsidebearing; if(copyGlyphAttributes.srcRSB) destinationGlyph.rightsidebearing = this.rightsidebearing; if(!selectNewShapes) showToast('Copied ' + this.shapes.length + ' shapes'); destinationGlyph.changed(); // debug('\t new shapes'); // debug(destinationGlyph.shapes); // debug(' Glyph.copyShapesTo - END\n'); }; Glyph.prototype.isHere = function(x, y) { for(var s=0; s < this.shapes.length; s++){ if(this.shapes[s].isHere(x, y)) return true; } return false; }; Glyph.prototype.hasShapes = function() { var tg; for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].objtype !== 'componentinstance') return true; else { tg = this.shapes[s].getTransformedGlyph(); if(tg.hasShapes()) return true; } } return false; }; Glyph.prototype.removeShapesWithZeroLengthPaths = function() { for(var s=0; s<this.shapes.length; s++){ if(this.shapes[s].path && this.shapes[s].path.pathpoints.length === 0){ this.shapes.splice(s, 1); s--; } } }; Glyph.prototype.getPathPoints = function() { var points = []; this.shapes.forEach(function(shape, i) { points = points.concat(shape.path.pathpoints); }); return points; }; Glyph.prototype.getShapes = function() { return this.shapes; }; Glyph.prototype.roundAll = function(precision) { for(var s=0; s<this.shapes.length; s++){ this.shapes[s].roundAll(precision); } this.changed(); }; //------------------------------------------------------- // GLYPH FUNCTIONS //------------------------------------------------------- // GET function getGlyph(id, create) { // debug('\n getGlyph - START'); // debug('\t passed: ' + id + ' create: ' + create); if(!id){ // debug('\t Not passed an ID, returning false'); return false; } if(_GP === {}){ // debug('\t _GP is uninitialized, returning false'); return false; } id = ''+id; var rechar; if (id.indexOf('0x', 2) > -1){ rechar = _GP.ligatures[id]; // debug('\t retrieved ' + rechar + ' from ligatures.'); if(rechar){ return rechar; } else if(create){ // debug('\t create was true, returning a new ligature.'); _GP.ligatures[id] = new Glyph({'glyphhex':id}); return _GP.ligatures[id]; } } else if(id.indexOf('0x') > -1){ rechar = _GP.glyphs[id]; // debug('\t retrieved ' + rechar + ' from glyphs.'); if(rechar){ return rechar; } else if(create){ // debug('\t create was true, returning a new char.'); _GP.glyphs[id] = new Glyph({'glyphhex':id}); return _GP.glyphs[id]; } } else { // debug('\t component, retrieved'); // debug(_GP.components[id]); return _GP.components[id] || false; } // debug('getGlyph - returning FALSE\n'); return false; } function getGlyphType(id) { if (id.indexOf('0x', 2) > -1) return 'ligature'; else if(id.indexOf('0x') > -1) return 'glyph'; else return 'component'; } function getGlyphName(ch) { ch = ''+ch; // debug('\n getGlyphName'); // debug('\t passed ' + ch); // not passed an id if(!ch){ // debug('\t not passed an ID, returning false'); return false; } // known unicode names var un = getUnicodeName(ch); if(un && un !== '[name not found]'){ // debug('\t got unicode name: ' + un); return escapeXMLValues(un); } var cobj = getGlyph(ch); if(ch.indexOf('0x',2) > -1){ // ligature // debug('\t ligature - returning ' + hexToHTML(ch)); return escapeXMLValues(cobj.name) || hexToHTML(ch); } else { // Component // debug('getGlyphName - inexplicably fails, returning [name not found]\n'); return escapeXMLValues(cobj.name) || '[name not found]'; } // debug(' getGlyphName - returning nothing - END\n'); } function getFirstGlyphID() { if(_GP.glyphs['0x0041']) return '0x0041'; else return getFirstID(_GP.glyphs); } // GET SELECTED function getSelectedGlyphLeftSideBearing(){ //debug('getSelectedGlyphLeftSideBearing'); var sc = getSelectedWorkItem(); if(!sc) return 0; if(sc.objtype === 'component') return 0; if(!sc.isautowide) return 0; if(sc.leftsidebearing === true) sc.leftsidebearing = _GP.projectsettings.defaultlsb; return sc.leftsidebearing !== false? sc.leftsidebearing : _GP.projectsettings.defaultlsb; } function getSelectedGlyphRightSideBearing(){ //debug('getSelectedGlyphLeftSideBearing'); var sc = getSelectedWorkItem(); if(!sc) return 0; if(sc.objtype === 'component') return 0; if(!sc.isautowide) return 0; if(sc.rightsidebearing === true) sc.rightsidebearing = _GP.projectsettings.defaultrsb; return sc.rightsidebearing !== false? sc.rightsidebearing : _GP.projectsettings.defaultrsb; } function updateCurrentGlyphWidth() { var sc = getSelectedWorkItem(); if(!sc) return; if(_UI.current_page === 'glyph edit'){ sc.changed(); } else if (_UI.current_page === 'components' && sc) { var lsarr = sc.usedin; if(lsarr) for(var c=0; c<lsarr.length; c++) getGlyph(lsarr[c]).changed(); } } // Delete function deleteGlyph(id) { // debug('\n deleteGlyph'); // debug('\t passed: ' + id); if(!id){ // debug('\t Not passed an ID, returning false'); return false; } if(_GP === {}){ // debug('\t _GP is uninitialized, returning false'); return false; } id = ''+id; if(_GP.glyphs[id]){ _GP.glyphs[id].deleteLinks(id); delete _GP.glyphs[id]; // debug(`\t deleted glyph, it is now:`); // debug(_GP.glyphs[id]); return true; } return false; } // end of file
glyphr-studio/Glyphr-Studio-1
dev/js/obj_glyph.js
JavaScript
gpl-3.0
30,023
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.9.0pr1', {"requires": ["selector-native"]});
rochestb/Adventurly
node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/selector-css2/selector-css2.js
JavaScript
gpl-3.0
16,813
// JavaScript Document /* Copyright (C) 2005 Ilya S. Lyubinskiy. All rights reserved. Technical support: http://www.php-development.ru/ YOU MAY NOT (1) Remove or modify this copyright notice. (2) Distribute this code, any part or any modified version of it. Instead, you can link to the homepage of this code: http://www.php-development.ru/javascripts/tabview.php. YOU MAY (1) Use this code on your website. (2) Use this code as a part of another product. NO WARRANTY This code is provided "as is" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. You expressly acknowledge and agree that use of this code is at your own risk. If you find my script useful, you can support my site in the following ways: 1. Vote for the script at HotScripts.com (you can do it on my site) 2. Link to the homepage of this script or to the homepage of my site: http://www.php-development.ru/javascripts/tabview.php http://www.php-development.ru/ You will get 50% commission on all orders made by your referrals. More information can be found here: http://www.php-development.ru/affiliates.php */ // ----- Auxiliary ------------------------------------------------------------- function tabview_aux(TabViewId, id) { var TabView = document.getElementById(TabViewId); // ----- Tabs ----- var Tabs = TabView.firstChild; while (Tabs.className != "Tabs" ) Tabs = Tabs.nextSibling; var Tab = Tabs.firstChild; var i = 0; do { if (Tab.tagName == "A") { i++; if (Tab.href == null || Tab.href ==""){ Tab.href = "javascript:tabview_switch('"+TabViewId+"', "+i+");"; } Tab.className = (i == id) ? "Active" : ""; Tab.blur(); } } while (Tab = Tab.nextSibling); // ----- Pages ----- var Pages = TabView.firstChild; if(Pages == null) return; while (Pages.className != 'Pages') Pages = Pages.nextSibling; var Page = Pages.firstChild; var i = 0; do { if (Page.className == 'Page') { i++; Page.style.overflow = "auto"; //Page.style.position = "absolute"; Page.style.display = (i == id) ? 'block' : 'none'; //Page.style.top = (i == id) ? 0 :1000; //Page.style.left = (i == id) ? 0 :-1000; } } while (Page = Page.nextSibling); } function getTabId(TabViewId,tabName){ var TabView = document.getElementById(TabViewId); var Tabs = TabView.firstChild; while (Tabs.className != "Tabs" ) Tabs = Tabs.nextSibling; var Tab = Tabs.firstChild; var i = 0; do{ if (Tab.tagName == "A"){ i++; if(Tab.firstChild.nodeValue==tabName) return i; } }while (Tab = Tab.nextSibling); return -1; } // ----- Functions ------------------------------------------------------------- function tabview_switch(TabViewId, id) { tabview_aux(TabViewId, id); } function tabview_switch_by_name(TabViewId, tabName) { var id=getTabId(TabViewId,tabName); if(id!=-1){ tabview_aux(TabViewId, id); } } function tabview_initialize(TabViewId) { tabview_aux(TabViewId, 1); }
Squishymedia/feedingdb
src/feeddb/feed/static/js/tabview.js
JavaScript
gpl-3.0
3,244
var status = -1; function action(mode, type, selection) { if (mode == 1) { status++; } else { if (status == 0) { cm.dispose(); } status--; } if (status == 0) { cm.sendSimple("#b#L0#Pokemon Rankings (by Wins)#l\r\n#L1#Pokemon Rankings (by Caught)#l\r\n#L2#Pokemon Rankings (by Ratio)#l\r\n"); } else if (status == 1) { if (selection == 0) { cm.sendNext(cm.getPokemonRanking()); } else if (selection == 1) { cm.sendNext(cm.getPokemonRanking_Caught()); } else if (selection == 2) { cm.sendNext(cm.getPokemonRanking_Ratio()); } cm.dispose(); } }
swordiemen/Mushy
scripts/npc/9040004.js
JavaScript
gpl-3.0
596
/* ************************************************************************ Copyright: 2009 OETIKER+PARTNER AG License: GPLv3 or later Authors: Tobi Oetiker <tobi@oetiker.ch> Utf8Check: äöü ************************************************************************ */ /** * A container that looks a bit like a PostIt */ qx.Class.define("remocular.ui.TaskLogo", { extend : qx.ui.container.Composite, /** * @param title {String} title of the Logo * @param byline {String} byline * @param about {String} text about the plugin * @param url {String} url to link to */ construct : function(title, byline, about, link) { this.base(arguments); this.setLayout(new qx.ui.layout.VBox(3)); this.set({ margin : 4, padding : 15, maxWidth : 300, allowGrowX : true, alignX : 'center', alignY : 'middle', shadow : new qx.ui.decoration.Grid("decoration/shadow/shadow.png", [ 2, 4, 4, 2 ]), decorator : new qx.ui.decoration.Single(1, 'solid', '#ddd'), backgroundColor : '#fff', opacity : 1 }); if (link) { this.setCursor('pointer'); this.addListener('click', function(e) { qx.bom.Window.open(link, '_blank'); }); } var t = new qx.ui.container.Composite(new qx.ui.layout.VBox(3)).set({ opacity : 0.5 }); t.addListener('mouseover', function(e) { this.setOpacity(1); }, t); t.addListener('mouseout', function(e) { this.setOpacity(0.5); }, t); t.add(new qx.ui.basic.Label(title).set({ font : 'smallTitle' })); t.add(new qx.ui.basic.Label(byline).set({ font : 'bold' })); t.add(new qx.ui.basic.Label(about).set({ rich : true, paddingTop : 4 })); this.add(t); } });
rplessl/remOcular
frontend/source/class/remocular/ui/TaskLogo.js
JavaScript
gpl-3.0
2,037
dojo.declare("gamelena.gfx.FlowChart", null, { id: null, surface: null, domPrefix: null, group: null, circles: [], circlesLabels: [], moves: [], groups: [], lines: [], linesGroups: [], linesHelpers: [], linesPointers: [], linesLabels: [], events: [], radio: 50, nodeComponent: null, connectorComponent: null, constructor: function(args) { dojo.declare.safeMixin(this, args); }, init : function() { var self = this; require(['gamelena/gfx'], function(gfx){ console.debug(self.domPrefix + "gfx_holder"); var container = dojo.byId(self.domPrefix + "gfx_holder"); self.surface = gfx.createSurface(container, 4800, 2400); dojo.connect(self.surface, "ondragstart", dojo, function(e) { console.debug(e) }); dojo.connect(self.surface, "onselectstart", dojo, function(e) { console.debug(e) }); }); this.group = this.surface.createGroup(); }, addNode: function(data, x1, y1) { var self = this; require(['gamelena/gfx/chart/Node'], function(Node){ var label = data[self.labelName]; var node = new Node({ component: self.nodeComponent, }); node.add(data, x1, x2); }) }, addConnector: function (originShape, destinyShape, data) { var self = this; require(['gamelena/gfx/chart/Connector'], function(Connector){ var connector = new Connector( ); connector.add() }); }, highLightShape: function(myShape) { var self = this; require(['dojox/gfx/fx'], function(fx){ myShape.moveToFront(); var stroke = myShape.getStroke(); var color = stroke != null ? stroke.color : 'green'; var width = stroke != null ? stroke.width : 1; self.animation = new fx.animateStroke({ duration : 2400, shape : myShape, color : { start : "#FFA600", end : "yellow" }, width : { end : 60, start : 60 }, join : { values : [ "outer", "bevel", "radial" ] }, onAnimate : function() { // onAnimate myShape.moveToFront(); }, onEnd : function() { myShape.moveToFront(); new fx.animateStroke({ duration : 1200, shape : myShape, color : { end : color }, width : { end : width } }).play(); myShape.moveToFront(); } }); self.animation.play(); myShape.moveToFront(); }); } });
DonMostro/tangerine
public/js/libs/gamelena/gfx/FlowChart.js
JavaScript
gpl-3.0
2,314
'use strict'; define(['angular', 'lodash', 'moment'], function(angular, _, moment) { var dependencies = []; var InterventionService = function() { var LOWER_BOUND_OPTIONS = [{ value: 'AT_LEAST', label: 'At least (>=)', shortLabel: '>=' }, { value: 'MORE_THAN', label: 'More than (>)', shortLabel: '>' }, { value: 'EXACTLY', label: 'Exactly (=)', shortLabel: '=' }]; var UPPER_BOUND_OPTIONS = [{ value: 'LESS_THAN', label: 'Less than (<)', shortLabel: '<' }, { value: 'AT_MOST', label: 'At most (<=)', shortLabel: '<=' }]; function typeValueToObject(typeValue) { return _.find(UPPER_BOUND_OPTIONS.concat(LOWER_BOUND_OPTIONS), function(option) { return option.value === typeValue; }); } function createUnitLabel(unitName, unitPeriod) { var periodLabel = moment.duration(unitPeriod).humanize(); periodLabel = periodLabel === 'a day' ? 'day' : periodLabel; return unitName + '/' + periodLabel; } function addBoundsToLabel(lowerBound, upperBound) { var label = ''; if (lowerBound) { label += typeValueToObject(lowerBound.type).shortLabel + ' ' + lowerBound.value + ' ' + createUnitLabel(lowerBound.unitName, lowerBound.unitPeriod); } if (lowerBound && upperBound) { label += ' AND '; } if (upperBound) { label += typeValueToObject(upperBound.type).shortLabel + ' ' + upperBound.value + ' ' + createUnitLabel(upperBound.unitName, upperBound.unitPeriod); } return label; } function makeMultiTreatmentLabel(intervention, interventions, joinStr) { var interventionsById = _.keyBy(interventions, 'id'); return intervention.interventionIds .map(function(interventionId) { return interventionsById[interventionId].name; }) .join(joinStr); } function generateDescriptionLabel(intervention, interventions) { var label = ''; if (intervention.type === 'fixed' || intervention.type === 'titrated' || intervention.type === 'both') { label += ': '; label += intervention.type === 'both' ? '' : intervention.type + ' dose; '; if (intervention.type === 'fixed') { label += 'dose '; label += addBoundsToLabel(intervention.constraint.lowerBound, intervention.constraint.upperBound); } else { if (intervention.minConstraint) { label += 'min dose '; label += addBoundsToLabel(intervention.minConstraint.lowerBound, intervention.minConstraint.upperBound); } if (intervention.minConstraint && intervention.maxConstraint) { label += '; '; } if (intervention.maxConstraint) { label += 'max dose '; label += addBoundsToLabel(intervention.maxConstraint.lowerBound, intervention.maxConstraint.upperBound); } } } else if (intervention.type === 'combination') { label = makeMultiTreatmentLabel(intervention, interventions, ' + '); } else if (intervention.type === 'class') { label = makeMultiTreatmentLabel(intervention, interventions, ' OR '); } return label; } function omitEmptyBounds(constraint) { if (!constraint) { return; } var omitList = []; if (!constraint.lowerBound || !constraint.lowerBound.isEnabled) { omitList.push('lowerBound'); } if (!constraint.upperBound || !constraint.upperBound.isEnabled) { omitList.push('upperBound'); } return _.omit(constraint, omitList); } function omitEmptyConstraints(constraint, minConstraintName, maxConstraintName) { if (!constraint) { return; } var emptyConstraints = _.filter([minConstraintName, maxConstraintName], function(constraintName) { return _.isEmpty(constraint[constraintName]); }); return _.omit(constraint, emptyConstraints); } function cleanUpBounds(createInterventionCommand) { var cleanedCommand = angular.copy(createInterventionCommand); if (cleanedCommand.type === 'fixed') { cleanedCommand.fixedDoseConstraint = omitEmptyBounds(cleanedCommand.fixedDoseConstraint); } else if (cleanedCommand.type === 'titrated') { cleanedCommand.titratedDoseMinConstraint = omitEmptyBounds(cleanedCommand.titratedDoseMinConstraint); cleanedCommand.titratedDoseMaxConstraint = omitEmptyBounds(cleanedCommand.titratedDoseMaxConstraint); cleanedCommand = omitEmptyConstraints(cleanedCommand, 'titratedDoseMinConstraint', 'titratedDoseMaxConstraint'); } else if (cleanedCommand.type === 'both') { cleanedCommand.bothDoseTypesMinConstraint = omitEmptyBounds(cleanedCommand.bothDoseTypesMinConstraint); cleanedCommand.bothDoseTypesMaxConstraint = omitEmptyBounds(cleanedCommand.bothDoseTypesMaxConstraint); cleanedCommand = omitEmptyConstraints(cleanedCommand, 'bothDoseTypesMinConstraint', 'bothDoseTypesMaxConstraint'); } return cleanedCommand; } return { LOWER_BOUND_OPTIONS: LOWER_BOUND_OPTIONS, UPPER_BOUND_OPTIONS: UPPER_BOUND_OPTIONS, generateDescriptionLabel: generateDescriptionLabel, cleanUpBounds: cleanUpBounds }; }; return dependencies.concat(InterventionService); });
DanielReid/addis-core
src/main/webapp/resources/app/js/intervention/interventionService.js
JavaScript
gpl-3.0
5,425
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'print', 'is', { toolbar: 'Prenta' } );
Mediawiki-wysiwyg/WYSIWYG-CKeditor
WYSIWYG/ckeditor_source/plugins/print/lang/is.js
JavaScript
gpl-3.0
210
angular.module('openITCOCKPIT') .service('QueryStringService', function(){ return { getCakeId: function(){ var url = window.location.href; url = url.split('/'); var id = url[url.length - 1]; id = parseInt(id, 10); return id; }, getCakeIds: function(){ var url = window.location.href; var ids = []; url = url.split('/'); if(url.length > 5){ //Ignore protocol, controller and action //[ "https:", "", "example.com", "commands", "copy", "39", "31" ] for(var i = 5; i < url.length; i++){ if(isNaN(url[i]) === false && url[i] !== null && url[i] !== ''){ ids.push(parseInt(url[i], 10)); } } } return ids; }, getValue: function(varName, defaultReturn){ defaultReturn = (typeof defaultReturn === 'undefined') ? null : defaultReturn; var sourceUrl = parseUri(decodeURIComponent(window.location.href)).source; if(sourceUrl.includes('/#!/')){ sourceUrl = sourceUrl.replace('/#!', ''); } var query = parseUri(sourceUrl).queryKey; if(query.hasOwnProperty(varName)){ return query[varName]; } return defaultReturn; }, getIds: function(varName, defaultReturn){ defaultReturn = (typeof defaultReturn === 'undefined') ? null : defaultReturn; try{ //&filter[Service.id][]=861&filter[Service.id][]=53&filter[Service.id][]=860 var sourceUrl = parseUri(decodeURIComponent(window.location.href)).source; if(sourceUrl.includes('/#!/')){ sourceUrl = sourceUrl.replace('/#!', ''); } var url = new URL(sourceUrl); var serviceIds = url.searchParams.getAll(varName); //getAll('filter[Service.id][]'); returns [861, 53, 860] if(serviceIds.length > 0){ return serviceIds; } return defaultReturn; }catch(e){ //IE or Edge?? ////&filter[Service.id][]=861&filter[Service.id][]=53&filter[Service.id][]=860&bert=123 var sourceUrl = parseUri(decodeURIComponent(window.location.href)).source; if(sourceUrl.includes('/#!/')){ sourceUrl = sourceUrl.replace('/#!', ''); } var urlString = sourceUrl; var peaces = urlString.split(varName); //split returns [ "https://foo.bar/services/index?angular=true&", "=861&", "=53&", "=860&", "=865&", "=799&", "=802&bert=123" ] var ids = []; for(var i = 0; i < peaces.length; i++){ if(peaces[i].charAt(0) === '='){ //Read from = to next & var currentId = ''; for(var k = 0; k < peaces[i].length; k++){ var currentChar = peaces[i].charAt(k); if(currentChar !== '='){ if(currentChar === '&'){ //Next variable in GET break; } currentId = currentId + currentChar; } } ids.push(currentId); } } if(ids.length > 0){ return ids; } return defaultReturn; } }, hasValue: function(varName){ var sourceUrl = parseUri(decodeURIComponent(window.location.href)).source; if(sourceUrl.includes('/#!/')){ sourceUrl = sourceUrl.replace('/#!', ''); } var query = parseUri(sourceUrl).queryKey; return query.hasOwnProperty(varName); }, hoststate: function(stateParams){ var states = { up: false, down: false, unreachable: false }; if(typeof stateParams === "undefined"){ return states; } if(typeof stateParams.hoststate === "undefined"){ return states; } for(var index in stateParams.hoststate){ switch(stateParams.hoststate[index]){ case 0: case '0': states.up = true; break; case 1: case '1': states.down = true; break; case 2: case '2': states.unreachable = true; break; } } return states; }, servicestate: function(stateParams){ var states = { ok: false, warning: false, critical: false, unknown: false }; if(typeof stateParams === "undefined"){ return states; } if(typeof stateParams.servicestate === "undefined"){ return states; } for(var index in stateParams.servicestate){ switch(stateParams.servicestate[index]){ case 0: case '0': states.ok = true; break; case 1: case '1': states.warning = true; break; case 2: case '2': states.critical = true; break; case 3: case '3': states.unknown = true; break; } } return states; }, getStateValue: function(stateParams, varName, defaultReturn){ defaultReturn = (typeof defaultReturn === 'undefined') ? null : defaultReturn; if(typeof stateParams[varName] !== "undefined"){ if(stateParams[varName] === null){ return defaultReturn; } return stateParams[varName]; } return defaultReturn; } } });
trevrobwhite/openITCOCKPIT
webroot/js/scripts/services/QueryStringService.js
JavaScript
gpl-3.0
7,438
import React, { Component } from 'react'; import { PanResponder, StyleSheet, TextInput, ToastAndroid, View } from 'react-native'; import { Body, Button, Card, CardItem, Container, Content, Footer, FooterTab, Header, Icon, Left, Right, Text, Title } from 'native-base'; import SideMenu from 'react-native-side-menu'; import SideMenuDomicilio from './SideMenuDomicilio'; import ReplyInputCurrency from './reply/ReplyInputCurrency'; import ReplyInputNumeric from './reply/ReplyInputNumeric'; import ReplyMultiSelect from './reply/ReplyMultiSelect'; import ReplyRadio from './reply/ReplyRadio'; import ReplyText from './reply/ReplyText'; import ReplyTime from './reply/ReplyTime'; import { passQuestion } from './business/PassQuestionDomicilio'; import FileStore from './../../FileStore'; import DomicilioData from './../../data/DomicilioData'; import { questoes } from './../../data/QuestoesDomicilio'; import { styles } from './../../Styles'; var type = (function(global) { var cache = {}; return function(obj) { var key; return obj === null ? 'null' : obj === global ? 'global' : (key = typeof obj) !== 'object' ? key : obj.nodeType ? 'object' : cache[key = ({}).toString.call(obj)] || (cache[key] = key.slice(8, -1).toLowerCase()); }; }(this)); export default class Domicilio extends Component { constructor(props) { super(props); this.state = { admin: this.props.admin, quiz: this.props.quiz }; } componentWillMount(){ if(this.state.quiz.domicilio === null){ this.state.quiz.domicilio = new DomicilioData(this.state.admin.id); } FileStore.saveFileDomicilio(this.state.quiz.domicilio); let questao = questoes[this.state.admin.indexPage].id.replace(/\D/g,''); for(key in passQuestion){ if(questao == passQuestion[key].questao){ //this.state.admin.maxQuestion = passQuestion[key].passe; for (i = questao + 1; i < passQuestion[key].passe; i++) { for(key in this.state.quiz){ if(key.replace(/\D/g,'') == i){ this.state.quiz[key] = -1; } } } break; } } idQuestao = 'questao_' + questoes[this.state.admin.indexPage].id; numeroQuestao = questoes[this.state.admin.indexPage].id.replace(/\D/g,''); } popQuizScreen(){ if(this.state.admin.indexPage === 0 && this.state.quiz['questao_1'] === null){ this.state.quiz.domicilio = null; FileStore.deleteDomicilio(this.state.admin.id); }; this.props.navigator.replacePreviousAndPop({ name: 'quiz', admin: this.state.admin, quiz: this.state.quiz, isOpen: false }); } popScreen(){ if(this.state.admin.indexPage > 0){ this.state.admin.indexPage = Number(this.state.admin.indexPage) - 1; this.props.navigator.replacePreviousAndPop({ name: 'domicilio', admin: this.state.admin, quiz: this.state.quiz }); }else{ ToastAndroid.showWithGravity('Não há como voltar mais', ToastAndroid.SHORT, ToastAndroid.CENTER); } } pushScreen(){ let flagResponse = true; if(type(this.state.quiz.domicilio[idQuestao]) == 'array'){ if(this.state.quiz.domicilio[idQuestao].length == 0){ flagResponse = false; } }else{ if(this.state.quiz.domicilio[idQuestao] == null){ flagResponse = false; } } if(flagResponse || Number(numeroQuestao) + 1 <= this.state.admin.maxQuestion){ if(Number(numeroQuestao) + 1 <= this.state.admin.maxQuestion){ this.state.admin.indexPage = Number(this.state.admin.indexPage) + 1; FileStore.saveFileDomicilio(this.state.quiz.domicilio); if(this.state.admin.indexPage >= questoes.length){ ToastAndroid.showWithGravity('Questionário Finalizado\nNão há como avançar mais', ToastAndroid.SHORT, ToastAndroid.CENTER); }else{ this.props.navigator.push({ name: 'domicilio', admin: this.state.admin, quiz: this.state.quiz }); } }else{ ToastAndroid.showWithGravity('Responda a questão ' + numeroQuestao, ToastAndroid.SHORT, ToastAndroid.CENTER); } }else{ ToastAndroid.showWithGravity('Responda a questão', ToastAndroid.SHORT, ToastAndroid.CENTER); } } updateMenuState() { this.setState({ isOpen: !this.state.isOpen, }); } setMenuState(isOpen) { this.setState({ isOpen: isOpen }); } render() { let isOpen = this.state.isOpen; let admin = this.state.admin; let quiz = this.state.quiz; let questao = questoes[admin.indexPage]; let pergunta_extensao = questao.pergunta_extensao; const menu = <SideMenuDomicilio admin={admin} quiz={quiz} navigator={this.props.navigator} />; function renderIf(condition, contentIf, contentElse = null) { if (condition) { return contentIf; } else { return contentElse; } } return ( <Container style={styles.container}> <Header style={styles.header}> <Left> <Button transparent onPress={() => {this.popQuizScreen()}}> <Icon name='ios-arrow-back' /> </Button> </Left> <Body style={styles.bodyHeader}> <Title>{questao.titulo}</Title> </Body> <Right> <Button transparent onPress={() => {this.updateMenuState()}}> <Text></Text> </Button> </Right> </Header> <Content> <Card> <CardItem style={styles.cardItemQuestao}> <Text style={styles.questao}>{questao.id.replace(/\D/g,'') + '. ' + questao.pergunta}</Text> <Text style={styles.observacaoQuestao}>{questao.observacao_pergunta}</Text> </CardItem> {renderIf(questao.pergunta_secundaria !== '', <CardItem style={styles.pergunta_secundaria}> <Text style={styles.questao_secundaria}>{questao.id.replace(/[0-9]/g, '').toUpperCase() + ') ' + questao.pergunta_secundaria.pergunta}</Text> <Text note>{questao.pergunta_secundaria.observacao_pergunta}</Text> </CardItem> )} <CardItem cardBody style={{justifyContent: 'center'}}> {renderIf(questao.tipo === 'input_currency', <ReplyInputCurrency admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} {renderIf(questao.tipo === 'input_numeric', <ReplyInputNumeric admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} {renderIf(questao.tipo === 'multiple', <ReplyMultiSelect admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} {renderIf(questao.tipo === 'radio', <ReplyRadio admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} {renderIf(questao.tipo === 'text', <ReplyText admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} {renderIf(questao.tipo === 'input_time', <ReplyTime admin={admin} quiz={quiz.domicilio} questao={questao} passQuestion={passQuestion} /> )} </CardItem> {renderIf(pergunta_extensao != '', <CardItem> <Text style={styles.observacaoQuestao}>{pergunta_extensao.pergunta}</Text> <TextInput style={{width: 500, fontSize: 20}} keyboardType = 'default' onChangeText = {(value) => { if(quiz.domicilio[idQuestao] != null){ if(quiz.domicilio[idQuestao] == pergunta_extensao.referencia){ quiz.domicilio[idQuestao + '_secundaria'] = value; }else if(quiz.domicilio[idQuestao].indexOf(Number(pergunta_extensao.referencia)) > -1){ quiz.domicilio[idQuestao + '_secundaria'] = value; } } }} defaultValue = {quiz.domicilio[idQuestao + '_secundaria']} maxLength = {500} /> </CardItem> )} </Card> </Content> <Footer> <FooterTab> <Button style={{backgroundColor: '#005376'}} onPress={() => {this.popScreen()}}> <Icon name='ios-arrow-back' /> </Button> <Button style={{backgroundColor: '#005376'}} onPress={() => {this.pushScreen()}}> <Icon name='ios-arrow-forward' /> </Button> </FooterTab> </Footer> </Container> ); } }
vagnerpraia/ipeasurvey
app/component/quiz/Domicilio.js
JavaScript
gpl-3.0
10,707
/* * File: app/view/MyViewportViewModel.js * * This file was generated by Sencha Architect version 3.1.0. * http://www.sencha.com/products/architect/ * * This file requires use of the Ext JS 5.0.x library, under independent license. * License of Sencha Architect does not include license for Ext JS 5.0.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('W3D3_Homework.view.MyViewportViewModel', { extend: 'Ext.app.ViewModel', alias: 'viewmodel.myviewport' });
MNLBC/Group2Projects
6. Ziegfreid Morissey Flameno/W3D3_Homework/Codes/app/view/MyViewportViewModel.js
JavaScript
gpl-3.0
644
/** * Created by elastetic.dev on 19/08/2017. * copyright 2017 elastetic.dev * See the COPYRIGHT file at the top-level directory of this distribution */ angular.module("elastetic").controller('MySqlPoiDataConfigController', ['$scope', '$controller', 'messages', '$mdDialog', '$http', '$stateParams', function($scope, $controller, messages, $mdDialog, $http, $stateParams) { //angular.extend(this, $controller('adminConnectionsController', {$scope: $scope})); -> no longer needed, configs are now rapped inside pluginConfigurator directive. $scope.tables = []; //get data from site for scope //-------------------------------------------------------------------------------------- $http({method: 'GET', url: '/api/site/' + $stateParams.site + '/connection'}) //get the list of projects for this user, for the dlgopen (not ideal location, for proto only .then(function (response) { $scope.tables.push.apply($scope.tables, response.data); }, function (response) { messages.error(response.data); } ); }]);
deebobo/deebobo
public/plugins/_common/my_sql_poi_data/js/my_sql_poi_data_config_controller.js
JavaScript
gpl-3.0
1,238
/******************************************************************************* * Copyright 2012, 2013 CNES - CENTRE NATIONAL d'ETUDES SPATIALES * * This file is part of SITools2. * * SITools2 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. * * SITools2 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 SITools2. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /*global define: false */ /** * Animated button */ define( [ "jquery", "jquery.ui"], function($) { var AnimatedButton = function(element, options) { this.$element = $(element).button(); this.stopped = true; if ( options ) { this.$element.on('click', $.proxy( options.onclick, this )); } }; /**************************************************************************************************************/ /** * Start animation */ AnimatedButton.prototype.startAnimation = function() { this.stopped = false; this.iterateAnimation(); }; /**************************************************************************************************************/ /** * Stop animation */ AnimatedButton.prototype.stopAnimation = function() { this.stopped = true; }; /**************************************************************************************************************/ /** * Loading animation */ AnimatedButton.prototype.iterateAnimation = function() { var self = this; this.$element.children('span').animate({ backgroundColor: "rgb(255, 165, 0);" }, 300, function(){ $(this).animate({ backgroundColor: "transparent" }, 300, function(){ if ( !self.stopped ) { self.iterateAnimation(); } }); }); }; /**************************************************************************************************************/ return AnimatedButton; });
TPZF/RTWeb3D
src/mizar/js/AnimatedButton.js
JavaScript
gpl-3.0
2,280
function Locations(){var a=this;a.id="locations",a.map=jQuery("#"+a.id),a.markers=[],a.initAddresAndMap=function(b){a.map.length&&jQuery.ajax({type:"GET",dataType:"json",url:"http://maps.googleapis.com/maps/api/geocode/json?address="+b,success:function(b){"OK"==b.status?a.initMap(b.results[0].geometry.location.lat,b.results[0].geometry.location.lng):a.initMap(40.4778838,-74.290702)}})},a.initMap=function(b,c){var d={zoom:15,center:new google.maps.LatLng(b,c),scrollwheel:!1,draggable:!1},e=new google.maps.Map(document.getElementById(a.id),d),f=new google.maps.Marker({position:new google.maps.LatLng(b,c),map:e,title:"Click to zoom"});google.maps.event.addListener(f,"click",function(){e.setZoom(8),e.setCenter(f.getPosition())})}}jQuery(document).ready(function(){var a=new Locations;a.map.length&&a.initAddresAndMap(a.map.data("address"))});
RDSergij/tm-real-estate
assets/js/locations.min.js
JavaScript
gpl-3.0
848
/*! * Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ define([ './UnmanagedComponent', '../dashboard/Utils', '../Logger', '../lib/jquery', 'amd!../lib/underscore', 'amd!../lib/mustache-wax', '../addIns/templateTypes', 'css!./TemplateComponent' ], function(UnmanagedComponent, Utils, Logger, $, _, Mustache) { return UnmanagedComponent.extend({ defaults: { templateType: 'mustache', template: '<div>{{items}}</div>', rootElement: 'items', formatters: {}, events: [], postProcess: function() {} }, messages: { error: { noData: "No data available.", invalidTemplate: "Invalid template.", invalidTemplateType: "Invalid template type.", generic: "Invalid options defined. Please check the template component properties." }, success: {}, warning: {}, info: {}, config: { style: { success: {icon: "comment", type: "success"}, error: {icon: "remove-sign", type: "danger"}, info: {icon: "info-sign", type: "info"}, warning: {icon: "exclamation-sign", style: "warning"} }, template: "<div class='alert alert-<%=type%>' role='alert'>" + " <span class='glyphicon glyphicon-<%=icon%>' aria-hidden='true'></span> " + " <span> <%=msg%> </span>" + "</div>" } }, init: function() { $.extend(true, this, Utils.ev(this.extendableOptions)); $.extend(true, this.defaults, Utils.ev(this.options)); }, update: function() { _.bindAll(this, 'redraw', 'init', 'processData', 'renderTemplate', 'attachEvents', 'processMessage', 'template', 'applyFormatter', 'applyAddin', 'processAddins'); this.init(); this.triggerQuery(this.chartDefinition, this.redraw); }, redraw: function(data) { this.model = this.processData(data); var htmlResult = this.renderTemplate(this.template, this.templateType, this.model); var $target = this.placeholder(); $target.empty().append(htmlResult); this.processAddins($target, data); if(!_.isEmpty(this.events)) { this.attachEvents(this.eventSelector, this.eventType, this.eventHandler); } }, getUID: function() { return 'xxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }, applyFormatter: function(model, formatter, id) { var formatHandler = Utils.propertiesArrayToObject(this.formatters)[formatter]; if(_.isFunction(formatHandler)) { return formatHandler.call(this, model, id); } else { return model; } }, applyAddin: function(model, addin, id) { var UID = this.name + "_" + addin + this.getUID(); this.addins = this.addins || []; this.addins.push({uid: UID, model: model, addin: addin, id: id}); return '<div id="' + UID + '" class="' + addin + '"/>'; }, processAddins: function($target, data) { var myself = this; _.each(this.addins, function(elem) { myself.handleAddin(_.first($target.find('#' + elem.uid)), elem.model, elem.addin, data, elem.id); }); }, handleAddin: function(target, model, addInName, data, id) { var addIn = this.getAddIn("templateType", addInName); var state = {value: model, data: data, id: id}; addIn.call(target, state, this.getAddInOptions("templateType", addIn.getName())); }, // Transform qyeryResult.dataset to JSON format to be used in Templates processData: function(queryResult) { if(!_.isFunction(this.modelHandler)) { var hasData = queryResult.queryInfo != null ? queryResult.queryInfo.totalRows > 0 : queryResult.resultset.length > 0; if(hasData) { var data = []; _.each(queryResult.resultset, function(row) { data.push(_.extend({}, row)); }); var model = {}; model[this.rootElement] = data; return model; } else { return ""; } } else { return this.modelHandler(queryResult); } }, // Apply template based on the result of a query. Creates a template based (mustache or underscore) view data object and apply columns format renderTemplate: function(template, templateType, model) { var html = ""; var myself = this; if((!_.isEmpty(model))) { var helpers = { formatter: function(data, formatter, id) { return myself.applyFormatter(data, formatter, id); }, addin: function(data, addin, id) { return myself.applyAddin(data, addin, id); } }; try { switch(templateType.toUpperCase()) { case 'UNDERSCORE': model = _.defaults({}, model, Utils.propertiesArrayToObject(helpers)); html = _.template(Utils.ev(template), model); break; case 'MUSTACHE': Mustache.Formatters = helpers; html = Mustache.render(Utils.ev(template), model); break; default: html = this.processMessage('invalidTemplateType', 'error'); break; } } catch(e) { html = this.processMessage('invalidTemplate', 'error'); } } else { html = this.processMessage('noData', 'error'); } return html; }, // bind click to created cards attachEvents: function() { var myself = this; _.each(this.events, function(elem) { var separator = ',', handler = _.first(elem).split(separator), eventHandler = _.last(elem), event = _.first(handler).trim(), selector = _.last(handler).trim(); if(_.isFunction(eventHandler)) { myself.placeholder(selector).on(event, _.bind(eventHandler, myself)); } }); }, processMessage: function(message, type) { var completeMsg = { msg: this.messages[type][message] || message || "", type: this.messages.config.style[type].type || "info", icon: this.messages.config.style[type].icon || "comment" }; Logger.log(completeMsg.msg, type); return _.template(this.messages.config.template, completeMsg); } }); });
bytekast/cdf
core-js/src/main/javascript/cdf/components/TemplateComponent.js
JavaScript
mpl-2.0
7,041
'use strict'; module.exports = function (grunt) { grunt.registerTask('server', [ 'clean:server', 'configureProxies:livereload', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); grunt.registerTask('server:open', [ 'clean:server', 'configureProxies:livereload', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'open:server', 'watch' ]); grunt.registerTask('server:dist', [ 'connect:dist', 'open:dist', 'watch' ]); grunt.registerTask('server:doc', [ 'connect:doc', 'open:doc', 'watch:doc' ]); };
uripro1/portfolio
tasks/server.js
JavaScript
mpl-2.0
716