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
// moment.js locale configuration // locale : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function( factory ) { if (typeof define === 'function' && define.amd) { define( ['moment'], factory ); // AMD } else { if (typeof exports === 'object') { module.exports = factory( require( '../moment' ) ); // Node } else { factory( (typeof global !== 'undefined' ? global : this).moment ); // node or other global } } }( function( moment ) { return moment.defineLocale( 'gl', { months: 'Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro'.split( '_' ), monthsShort: 'Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.'.split( '_' ), weekdays: 'Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado'.split( '_' ), weekdaysShort: 'Dom._Lun._Mar._Mér._Xov._Ven._Sáb.'.split( '_' ), weekdaysMin: 'Do_Lu_Ma_Mé_Xo_Ve_Sá'.split( '_' ), longDateFormat: { LT: 'H:mm', LTS: 'LT:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY LT', LLLL: 'dddd D MMMM YYYY LT' }, calendar: { sameDay: function() { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay: function() { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek: function() { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay: function() { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek: function() { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse: 'L' }, relativeTime: { future: function( str ) { if (str === 'uns segundos') { return 'nuns segundos'; } return 'en ' + str; }, past: 'hai %s', s: 'uns segundos', m: 'un minuto', mm: '%d minutos', h: 'unha hora', hh: '%d horas', d: 'un día', dd: '%d días', M: 'un mes', MM: '%d meses', y: 'un ano', yy: '%d anos' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } } ); } ));
hannesk001/SPHERE-Framework
Library/Moment.Js/2.8.4/locale/gl.js
JavaScript
agpl-3.0
2,839
/** * Kendo UI v2018.1.221 (http://www.telerik.com/kendo-ui) * Copyright 2018 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f){ if (typeof define === 'function' && define.amd) { define(["kendo.core"], f); } else { f(); } }(function(){ (function( window, undefined ) { kendo.cultures["bg"] = { name: "bg", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { name: "", abbr: "", pattern: ["-n $","n $"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "лв." } }, calendars: { standard: { days: { names: ["неделя","понеделник","вторник","сряда","четвъртък","петък","събота"], namesAbbr: ["нед","пон","вт","ср","четв","пет","съб"], namesShort: ["нд","пн","вт","ср","чт","пт","сб"] }, months: { names: ["януари","февруари","март","април","май","юни","юли","август","септември","октомври","ноември","декември"], namesAbbr: ["яну","фев","мар","апр","май","юни","юли","авг","сеп","окт","ное","дек"] }, AM: [""], PM: [""], patterns: { d: "d.M.yyyy 'г.'", D: "dd MMMM yyyy 'г.'", F: "dd MMMM yyyy 'г.' H:mm:ss", g: "d.M.yyyy 'г.' H:mm", G: "d.M.yyyy 'г.' H:mm:ss", m: "d MMMM", M: "d MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "H:mm", T: "H:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy 'г.'", Y: "MMMM yyyy 'г.'" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); }));
Memba/Memba-Widgets
src/js/vendor/kendo/cultures/kendo.culture.bg.js
JavaScript
agpl-3.0
6,694
(function (requirejs, require, define) { // Main module. require( [ 'video/01_initialize.js', 'video/025_focus_grabber.js', 'video/04_video_control.js', 'video/05_video_quality_control.js', 'video/06_video_progress_slider.js', 'video/07_video_volume_control.js', 'video/08_video_speed_control.js', 'video/09_video_caption.js' ], function ( Initialize, FocusGrabber, VideoControl, VideoQualityControl, VideoProgressSlider, VideoVolumeControl, VideoSpeedControl, VideoCaption ) { var previousState, youtubeXhr = null; // Because this constructor can be called multiple times on a single page (when // the user switches verticals, the page doesn't reload, but the content changes), we must // will check each time if there is a previous copy of 'state' object. If there is, we // will make sure that copy exists cleanly. We have to do this because when verticals switch, // the code does not handle any Xmodule JS code that is running - it simply removes DOM // elements from the page. Any functions that were running during this, and that will run // afterwards (expecting the DOM elements to be present) must be stopped by hand. previousState = null; window.Video = function (element) { var state; // Stop bufferization of previous video on sequence change. // Problem: multiple video tags with the same src cannot // play together. The second tag waiting when first video will be fully loaded. // That's why we abort bufferization forcibly. $(element).closest('.sequence').bind('sequence:change', function(e){ if (previousState !== null && typeof previousState.videoPlayer !== 'undefined') { previousState.stopBuffering(); $(e.currentTarget).unbind('sequence:change'); } }); // Check for existance of previous state, uninitialize it if necessary, and create a new state. // Store new state for future invocation of this module consturctor function. if (previousState !== null && typeof previousState.videoPlayer !== 'undefined') { previousState.videoPlayer.onPause(); } state = {}; previousState = state; state.youtubeXhr = youtubeXhr; Initialize(state, element); if (!youtubeXhr) { youtubeXhr = state.youtubeXhr; } FocusGrabber(state); VideoControl(state); VideoQualityControl(state); VideoProgressSlider(state); VideoVolumeControl(state); VideoSpeedControl(state); VideoCaption(state); // Because the 'state' object is only available inside this closure, we will also make // it available to the caller by returning it. This is necessary so that we can test // Video with Jasmine. return state; }; window.Video.clearYoutubeXhr = function () { youtubeXhr = null; }; }); }(RequireJS.requirejs, RequireJS.require, RequireJS.define));
syjeon/new_edx
lms/static/xmodule_js/src/video/10_main.js
JavaScript
agpl-3.0
3,079
odoo.define('hr/static/src/bugfix/bugfix_tests.js', function (require) { 'use strict'; /** * This file allows introducing new QUnit test modules without contaminating * other test files. This is useful when bug fixing requires adding new * components for instance in stable versions of Odoo. Any test that is defined * in this file should be isolated in its own file in master. */ QUnit.module('hr', {}, function () { QUnit.module('bugfix', {}, function () { QUnit.module('bugfix_tests.js', { }); }); }); });
rven/odoo
addons/hr/static/src/bugfix/bugfix_tests.js
JavaScript
agpl-3.0
517
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {dev, devAssert, userAssert} from '../../src/log'; import {validateData} from '../../3p/3p'; /** * A fake ad network integration that is mainly used for testing * and demo purposes. This implementation gets stripped out in compiled * production code. * @param {!Window} global * @param {!Object} data */ export function _ping_(global, data) { // for testing only. see #10628 global.networkIntegrationDataParamForTesting = data; validateData(data, ['url'], ['valid', 'adHeight', 'adWidth', 'enableIo']); userAssert(!data['error'], 'Fake user error!'); global.document.getElementById('c').textContent = data.ping; global.ping = Object.create(null); if (data.ad_container) { devAssert(global.context.container == data.ad_container, 'wrong container'); } if (data.valid == 'false') { // Immediately send no-content for visual diff test global.context.noContentAvailable(); } if (data.valid && data.valid == 'true') { const img = document.createElement('img'); if (data.url) { img.setAttribute('src', data.url); img.setAttribute('width', data.width); img.setAttribute('height', data.height); } let width, height; if (data.adHeight) { img.setAttribute('height', data.adHeight); height = Number(data.adHeight); } if (data.adWidth) { img.setAttribute('width', data.adWidth); width = Number(data.adWidth); } document.body.appendChild(img); if (width || height) { global.context.renderStart({width, height}); } else { global.context.renderStart(); } if (data.enableIo) { global.context.observeIntersection(function (changes) { /** @type {!Array} */ (changes).forEach(function (c) { dev().info( 'AMP-AD', 'Intersection: (WxH)' + `${c.intersectionRect.width}x${c.intersectionRect.height}` ); }); // store changes to global.lastIO for testing purpose global.ping.lastIO = changes[changes.length - 1]; }); } global.context.getHtml('a', ['href'], function (html) { dev().info('GET-HTML', html); }); global.context.getConsentState(function (consentState) { dev().info('GET-CONSENT-STATE', consentState); }); if (global.context.consentSharedData) { const TAG = 'consentSharedData'; dev().info(TAG, global.context.consentSharedData); } if (global.context.initialConsentValue) { const TAG = 'consentStringValue'; dev().info(TAG, global.context.initialConsentValue); } if (global.context.initialConsentMetadata) { const TAG = 'consentMetadata'; dev().info(TAG, global.context.initialConsentMetadata); } } else { global.setTimeout(() => { global.context.noContentAvailable(); }, 1000); } }
prateekbh/amphtml
ads/vendors/_ping_.js
JavaScript
apache-2.0
3,466
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionEject = _react2.default.createClass({ displayName: 'ActionEject', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M5 17h14v2H5zm7-12L5.33 15h13.34z' }) ); } }); exports.default = ActionEject; module.exports = exports['default'];
Maxwelloff/react-football
node_modules/material-ui/lib/svg-icons/action/eject.js
JavaScript
apache-2.0
934
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fab'; var iconName = 'ideal'; var width = 576; var height = 512; var ligatures = []; var unicode = 'e013'; var svgPathData = 'M125.61,165.48a49.07,49.07,0,1,0,49.06,49.06A49.08,49.08,0,0,0,125.61,165.48ZM86.15,425.84h78.94V285.32H86.15Zm151.46-211.6c0-20-10-22.53-18.74-22.53H204.82V237.5h14.05C228.62,237.5,237.61,234.69,237.61,214.24Zm201.69,46V168.93h22.75V237.5h33.69C486.5,113.08,388.61,86.19,299.67,86.19H204.84V169h14c25.6,0,41.5,17.35,41.5,45.26,0,28.81-15.52,46-41.5,46h-14V425.88h94.83c144.61,0,194.94-67.16,196.72-165.64Zm-109.75,0H273.3V169h54.43v22.73H296v10.58h30V225H296V237.5h33.51Zm74.66,0-5.16-17.67H369.31l-5.18,17.67H340.47L368,168.92h32.35l27.53,91.34ZM299.65,32H32V480H299.65c161.85,0,251-79.73,251-224.52C550.62,172,518,32,299.65,32Zm0,426.92H53.07V53.07H299.65c142.1,0,229.9,64.61,229.9,202.41C529.55,389.57,448.55,458.92,299.65,458.92Zm83.86-264.85L376,219.88H392.4l-7.52-25.81Z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faIdeal = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
googleforgames/open-match-docs
site/themes/docsy/assets/vendor/Font-Awesome/js-packages/@fortawesome/free-brands-svg-icons/faIdeal.js
JavaScript
apache-2.0
1,377
//// [baseIndexSignatureResolution.ts] class Base { private a: string; } class Derived extends Base { private b: string; } // Note - commmenting "extends Foo" prevents the error interface Foo { [i: number]: Base; } interface FooOf<TBase extends Base> extends Foo { [i: number]: TBase; } var x: FooOf<Derived> = null; var y: Derived = x[0]; /* // Note - the equivalent for normal interface methods works fine: interface A { foo(): Base; } interface B<TBase extends Base> extends A { foo(): TBase; } var b: B<Derived> = null; var z: Derived = b.foo(); */ //// [baseIndexSignatureResolution.js] var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Base = /** @class */ (function () { function Base() { } return Base; }()); var Derived = /** @class */ (function (_super) { __extends(Derived, _super); function Derived() { return _super !== null && _super.apply(this, arguments) || this; } return Derived; }(Base)); var x = null; var y = x[0]; /* // Note - the equivalent for normal interface methods works fine: interface A { foo(): Base; } interface B<TBase extends Base> extends A { foo(): TBase; } var b: B<Derived> = null; var z: Derived = b.foo(); */
kitsonk/TypeScript
tests/baselines/reference/baseIndexSignatureResolution.js
JavaScript
apache-2.0
1,974
/************************************工具函数************************************/ function jsTrim(str) { return str.replace(/(^\s*)|(\s*$)/g,""); } //将小数点清零 function returnFloat0(value) { value = Math.round(parseFloat(value)); return value; } //保留一位小数点 function returnFloat1(value) { value = Math.round(parseFloat(value) * 10) / 10; if (value.toString().indexOf(".") < 0) value = value.toString() + ".0"; return value; } //保留两位小数点 function returnFloat(value) { value = Math.round(parseFloat(value) * 100) / 100; if (value.toString().indexOf(".") < 0) { value = value.toString() + ".00"; } return value; } /************************************ 全局js ***********************************/ //显示加载器 function showLoader() { $.mobile.loading('show', { text: '加载中...', //加载器中显示的文字 textVisible: false, //是否显示文字 theme: 'a', //加载器主题样式a-e textonly: false, //是否只显示文字 html: "" //要显示的html内容,如图片等 }); } //隐藏加载器 function hideLoader() { //隐藏加载器 $.mobile.loading('hide'); } /********************************* 购物界面js **************************************/ function initCarInfo(destUrl){ function onCarSuccess(data, status) { document.getElementById('order-info').innerHTML = data; } function onCarError(data, status) { document.getElementById('order_totalnum').innerHTML = "0"; document.getElementById('order_totalprice').innerHTML = "0"; } $.ajax({ type: "GET", url: destUrl, dataType : "html", cache : false, success: onCarSuccess, error: onCarError, }); } function initCarTotalPrice(destUrl){ function onCarSuccess(data, status) { document.getElementById('cart_totalprice').innerHTML = data; } function onCarError(data, status) { document.getElementById('cart_totalprice').innerHTML = "0"; } $.ajax({ type: "GET", url: destUrl, dataType : "html", cache : false, success: onCarSuccess, error: onCarError, }); } function foodtypeClick(foodtypeId, destUrl) { if (foodtypeId == curTypeId) { return; } function onFoodtypeSuccess(data, status) { hideLoader(); //先更新右侧内容 myScroll2.scrollTo(0, 0, 200, 0); $("#scroller2").empty(); $("#scroller2").html(data); myScroll2.refresh(); //再更新左侧选中按钮 document.getElementById('foodtype_' + curTypeId).className = ""; curTypeId = foodtypeId; document.getElementById('foodtype_' + curTypeId).className = "active"; curFoodId = 0; //更新curFoodId防止切换的时候,详情点击展示出错 } function onFoodtypeError(data, status) { hideLoader(); // handle an error } if(foodtypeId !=2){ showLoader(); } $.ajax({ type: "GET", url: destUrl, dataType : "html", cache : false, success: onFoodtypeSuccess, error: onFoodtypeError, }); } function foodtitleClick(food_id) { var fooddetailObj = document.getElementById('fooddetail_' + food_id); if (fooddetailObj.style.display == "none") { fooddetailObj.style.display = ""; } else { fooddetailObj.style.display = "none"; } myScroll2.refresh(); if (curFoodId == food_id) { return; } if (curFoodId != 0) { document.getElementById('fooddetail_' + curFoodId).style.display = "none"; } curFoodId = food_id; } function OnOrderAddfoodSuccess(data, status) { if (data.status == "error") { if(data.errorcode == -1) { } if(data.errorcode == -2) { } if(data.errorcode == -3) { } showAttention(data.message); return; } //好吧,没有错误的话,就开始更新显示界面 var food_id = data.data.food_id; var food_num = data.data.food_num; var totalNum = data.data.totalNum; var totalPrice = data.data.totalPrice; //先改变数值 document.getElementById('order_totalnum').innerHTML = totalNum; document.getElementById('order_totalprice').innerHTML = totalPrice; document.getElementById('order_foodnum_' + food_id).innerHTML = food_num; //再改变显示 if (food_num > 0) { document.getElementById('foodattention_' + food_id).className = "foodattention-active"; } else { document.getElementById('foodattention_' + food_id).className = "foodattention"; } } function OnOrderAddfoodFailed(data, status) { } function order_plus_onclick(food_id, destUrl) { var curNum = parseInt(document.getElementById('order_foodnum_' + food_id).innerHTML); if(curNum >= 99) { return; } $.ajax({ type: "GET", url: destUrl, dataType : "json", cache : false, success: OnOrderAddfoodSuccess, error: OnOrderAddfoodFailed, }); } function OnOrderReducefoodSuccess(data, status) { if (data.status == "error") { if(data.errorcode == -1) { } if(data.errorcode == -2) { } alert(data.message); return; } //好吧,没有错误的话,就开始更新显示界面 var food_id = data.data.food_id; var food_num = data.data.food_num; var totalNum = data.data.totalNum; var totalPrice = data.data.totalPrice; document.getElementById('order_totalnum').innerHTML = totalNum; document.getElementById('order_totalprice').innerHTML = totalPrice; document.getElementById('order_foodnum_' + food_id).innerHTML = food_num; //再改变显示 if (food_num > 0) { document.getElementById('foodattention_' + food_id).className = "foodattention-active"; } else { document.getElementById('foodattention_' + food_id).className = "foodattention"; } } function OnOrderReducefoodFailed(data, status) { } function order_dec_onclick(food_id, destUrl) { var curNum = parseInt(document.getElementById('order_foodnum_' + food_id).innerHTML); if(curNum <= 0) { return; } $.ajax({ type: "GET", url: destUrl, dataType : "json", cache : false, success: OnOrderReducefoodSuccess, error: OnOrderReducefoodFailed, }); } /**************************** 购物车选项 ************************************/ function OnCartAddfoodSuccess(data, status) { if (data.status == "error") { if(data.errorcode == -1) { } if(data.errorcode == -2) { } if(data.errorcode == -3) { } showAttention(data.message); return; } //好吧,没有错误的话,就开始更新显示界面 var food_id = data.data.food_id; var food_num = data.data.food_num; var totalNum = data.data.totalNum; totalPrice = parseFloat(data.data.totalPrice); document.getElementById('cart_totalnum').innerHTML = totalNum; var totalShowPrice; if ((delivery_fee_valid == 1 && totalPrice < basicprice) || always_delivery_fee == 1) { totalShowPrice = totalPrice + delivery_fee; document.getElementById('delivery_fee').style.display = ""; } else { totalShowPrice = totalPrice; document.getElementById('delivery_fee').style.display = "none"; } //改变总价 document.getElementById('cart_totalprice').innerHTML = totalShowPrice; //如果有会员价,改变会员价 if (isShowMemberPrice == 1) { var memberShowPrice = totalPrice * mebmerPriceCount/10; if ((delivery_fee_valid == 1 && totalPrice < basicprice) || always_delivery_fee == 1) { memberShowPrice = memberShowPrice + delivery_fee; } //取1位小数 memberShowPrice = returnFloat1(memberShowPrice); document.getElementById('cart_memberprice').innerHTML = memberShowPrice; } document.getElementById('cart_foodnum_' + food_id).innerHTML = food_num; if (food_num > 0) { document.getElementById('foodname_' + food_id).style.textDecoration = ""; } } function OnCartAddfoodFailed(data, status) { } function cart_plus_onclick(food_id, destUrl) { var curNum = parseInt(document.getElementById('cart_foodnum_' + food_id).innerHTML); if(curNum >= 99) { return; } $.ajax({ type: "GET", url: destUrl, dataType : "json", cache : false, success: OnCartAddfoodSuccess, error: OnCartAddfoodFailed, }); } function OnCartReducefoodSuccess(data, status) { if (data.status == "error") { if(data.errorcode == -1) { } if(data.errorcode == -2) { } showAttention(data.message); return; } //好吧,没有错误的话,就开始更新显示界面 var food_id = data.data.food_id; var food_num = data.data.food_num; var totalNum = data.data.totalNum; totalPrice = parseFloat(data.data.totalPrice); document.getElementById('cart_totalnum').innerHTML = totalNum; var totalShowPrice; if ((delivery_fee_valid == 1 && totalPrice < basicprice) || always_delivery_fee == 1) { totalShowPrice = totalPrice + delivery_fee; document.getElementById('delivery_fee').style.display = ""; } else { totalShowPrice = totalPrice; document.getElementById('delivery_fee').style.display = "none"; } //改变总价 document.getElementById('cart_totalprice').innerHTML = totalShowPrice; //如果有会员价,改变会员价 if (isShowMemberPrice == 1) { var memberShowPrice = totalPrice * mebmerPriceCount/10; if ((delivery_fee_valid == 1 && totalPrice < basicprice) || always_delivery_fee == 1) { memberShowPrice = memberShowPrice + delivery_fee; } //取1位小数 memberShowPrice = returnFloat1(memberShowPrice); document.getElementById('cart_memberprice').innerHTML = memberShowPrice; } document.getElementById('cart_foodnum_' + food_id).innerHTML = food_num; if (food_num == 0) { document.getElementById('foodname_' + food_id).style.textDecoration = "line-through"; } } function OnCartReducefoodFailed(data, status) { } function cart_dec_onclick(food_id, destUrl) { var curNum = parseInt(document.getElementById('cart_foodnum_' + food_id).innerHTML); if(curNum <= 0) { return; } $.ajax({ type: "GET", url: destUrl, dataType : "json", cache : false, success: OnCartReducefoodSuccess, error: OnCartReducefoodFailed, }); } function valiForm(){ var mobilePattern = /^1\d{10}$/; var phonePattern = /^(1(([35][0-9])|(47)|[8][0123456789]))\d{8}$/; var flag = false; var name = jsTrim(document.getElementById("name").value); var phone = jsTrim(document.getElementById("phone").value); var address = jsTrim(document.getElementById("address").value); document.getElementById("name").value = name; document.getElementById("phone").value = phone; document.getElementById("address").value = address; if(name.length < 1){ document.getElementById("nameinfo-layout").style.display = ""; document.getElementById("nameinfo").innerHTML = "亲,留下您的大名吧!"; flag = true; } else{ document.getElementById("nameinfo-layout").style.display = "none"; } var phoneShowInfo = false; if(phone.length !=11) { document.getElementById("phoneinfo-layout").style.display = ""; document.getElementById("phoneinfo").innerHTML = "亲,电话长度不对哦!"; flag = true; phoneShowInfo = true; } if(!(phonePattern.test(phone))){ document.getElementById("phoneinfo-layout").style.display = ""; document.getElementById("phoneinfo").innerHTML = "亲,您的电话格式有误,电话只能包含数字或横线-"; flag = true; phoneShowInfo = true; } if (phoneShowInfo == false) { document.getElementById("phoneinfo-layout").style.display = "none"; } if(address.length < 1){ document.getElementById("addressinfo-layout").style.display = ""; document.getElementById("addressinfo").innerHTML = "亲,地址不能为空的哦!"; flag = true; } else{ document.getElementById("addressinfo-layout").style.display = "none"; } return flag; } function hsorry() { $("#sorryx").fadeOut("slow"); } function showAttention(info) { document.getElementById("attention-content").innerHTML = info; $("#sorryx").fadeIn("slow", function(){setTimeout("hsorry()", 1500); }) } function time(btn) { if(wait == 0) { btn.text("重新获取"); btn.button('enable'); btn.button('refresh'); wait = 180; } else { //btn.setAttribute("disabled", true); btn.text(wait+"秒后重发"); btn.button('disable'); btn.button('refresh'); //document.getElementById("cart-captchainfo").innerHTML = "您的验证码已经成功发送,请输入您收到的短信验证码完成手机号码验证。"; wait--; setTimeout(function() { time(btn); }, 1000) } } function sendCaptcha(customer_id, wxusername, admin_id, shop_id) { var phone = jsTrim(document.getElementById("phone").value); $.ajax({ type: "GET", url: "/index.php?r=sms/sendcaptcha&phone=" + phone + "&customer_id=" + customer_id + "&wxusername=" + wxusername + "&admin_id=" + admin_id + "&shop_id=" + shop_id, cache : false, success: function(data){ if (data == "true") { document.getElementById("cart-captchainfo").innerHTML = "您的验证码已经成功发送,请输入您收到的短信验证码完成手机号码验证。"; } else if (data == "false") { document.getElementById("cart-captchainfo").innerHTML = "您的短信验证码发送失败,请稍后重试。"; } else { //验证次数超过3次的情况 document.getElementById("cart-captchainfo").innerHTML = "您今天获取验证码次数已超过3次,请明天再试!"; return false; } }, }); $("#getcaptcha").button('disable'); time($("#getcaptcha")); return true; } function submitOnclick(token,wecha_id) { //先判断购物车是否为空 var totalNum = parseInt(document.getElementById('cart_totalprice').innerHTML); if (totalNum <= 0||totalNum=='NaN') { showAttention("您的购物车为空,不能提交订单!"); return; } //先判断格式是否错误 if (valiForm() == true) { return; } //开始正式提交订单 showLoader(); $('#submit-btn').addClass('ui-disabled'); //如果都验证通过了,判断是否需要短信验证 var phone = jsTrim(document.getElementById("phone").value); // $.ajax({ // type: "GET", // url: "/index.php?", // cache : false, // success: function(data){ // } // }); var name = document.getElementById("name").value; var address = document.getElementById("address").value; var note = document.getElementById("note").value; var diningtype = 0 var radios = document.getElementsByName("diningtypes"); for(var i=0;i<radios.length;i++){ if(radios[i].checked){ diningtype =radios[i].value; break; } } var tableid = 0 var tableids = document.getElementsByName("tableid"); if(tableids!=null){ for(var i=0;i<tableids.length;i++){ if(tableids[i].checked){ tableid =tableids[i].value; break; } } } var buytimestamp = document.getElementById("buytimestamp").value; var hour = document.getElementById("hour").value; window.location.href="/index.php?g=Wap&m=Mall&a=submitorders&token="+token+"&wecha_id="+wecha_id+"&truename="+name+"&address="+address+"&tel="+phone+"&diningtype="+diningtype+"&tableid="+tableid+"&buytime="+buytimestamp+"&hour="+hour+"&note="+note; }
royalwang/saivi
tpl/static/dining/js/shoporder.js
JavaScript
apache-2.0
15,526
//// [tests/cases/compiler/aliasUsageInOrExpression.ts] //// //// [aliasUsageInOrExpression_backbone.ts] export class Model { public someData: string; } //// [aliasUsageInOrExpression_moduleA.ts] import Backbone = require("./aliasUsageInOrExpression_backbone"); export class VisualizationModel extends Backbone.Model { // interesting stuff here } //// [aliasUsageInOrExpression_main.ts] import Backbone = require("./aliasUsageInOrExpression_backbone"); import moduleA = require("./aliasUsageInOrExpression_moduleA"); interface IHasVisualizationModel { VisualizationModel: typeof Backbone.Model; } var i: IHasVisualizationModel; var d1 = i || moduleA; var d2: IHasVisualizationModel = i || moduleA; var d2: IHasVisualizationModel = moduleA || i; var e: { x: IHasVisualizationModel } = <{ x: IHasVisualizationModel }>null || { x: moduleA }; var f: { x: IHasVisualizationModel } = <{ x: IHasVisualizationModel }>null ? { x: moduleA } : null; //// [aliasUsageInOrExpression_backbone.js] "use strict"; exports.__esModule = true; exports.Model = void 0; var Model = /** @class */ (function () { function Model() { } return Model; }()); exports.Model = Model; //// [aliasUsageInOrExpression_moduleA.js] "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); exports.__esModule = true; exports.VisualizationModel = void 0; var Backbone = require("./aliasUsageInOrExpression_backbone"); var VisualizationModel = /** @class */ (function (_super) { __extends(VisualizationModel, _super); function VisualizationModel() { return _super !== null && _super.apply(this, arguments) || this; } return VisualizationModel; }(Backbone.Model)); exports.VisualizationModel = VisualizationModel; //// [aliasUsageInOrExpression_main.js] "use strict"; exports.__esModule = true; var moduleA = require("./aliasUsageInOrExpression_moduleA"); var i; var d1 = i || moduleA; var d2 = i || moduleA; var d2 = moduleA || i; var e = null || { x: moduleA }; var f = null ? { x: moduleA } : null;
microsoft/TypeScript
tests/baselines/reference/aliasUsageInOrExpression.js
JavaScript
apache-2.0
2,791
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _index = _interopRequireDefault(require("../../parse/index.js")); var _index2 = _interopRequireDefault(require("../_lib/convertToFP/index.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. var parse = (0, _index2.default)(_index.default, 3); var _default = parse; exports.default = _default; module.exports = exports.default;
BigBoss424/portfolio
v8/development/node_modules/date-fns/fp/parse/index.js
JavaScript
apache-2.0
582
/* * Copyright 2012 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Aria.classDefinition({ $classpath : "test.aria.html.element.ElementBindingsTest", $extends : "aria.jsunit.TestCase", $dependencies : ["aria.html.Element", "aria.utils.Json", "aria.utils.Array"], $prototype : { /** * Verify that onbind is called with the correct parameters */ testBindings : function () { var basket = {}; var shopping = { bags : [{ hand : "left", content : null }, { hand : "right", content : null }] }; var cfg = { tagName : "span", bind : { "apple" : { inside : basket, to : "apples" }, "pear" : { inside : basket, to : "pears" }, "coffe" : { inside : shopping.bags[0], to : "content" }, "sugar" : { inside : shopping.bags[1], to : "content" } } }; var widget = new aria.html.Element(cfg, { tplClasspath : "Element" }); var name, value, old; widget.onbind = function (property, newValue, oldValue) { // Simply put them in the closure name = property; value = newValue; old = oldValue; }; // Change a value with listener aria.utils.Json.setValue(basket, "apples", 3); this.assertEquals(name, "apple", "Expecting name %2, got %1"); this.assertEquals(value, 3, "Expecting value %2, got %1"); this.assertTrue(old == null, "Expecting old value null, got " + old); // Change it again aria.utils.Json.setValue(basket, "apples", 0); this.assertEquals(name, "apple", "Expecting name %2, got %1"); this.assertEquals(value, 0, "Expecting value %2, got %1"); this.assertEquals(old, 3, "Expecting old value %2, got %1"); // Change a different value aria.utils.Json.setValue(basket, "pears", ["abate"]); this.assertEquals(name, "pear", "Expecting name %2, got %1"); this.assertEquals(value.length, 1, "Expecting value length %2, got %1"); this.assertEquals(value[0], "abate", "Expecting value %2, got %1"); this.assertTrue(old == null, "Expecting old value null, got " + old); // And cahnge again the previous one aria.utils.Json.setValue(basket, "apples", { type : "golden" }); this.assertEquals(name, "apple", "Expecting name %2, got %1"); this.assertEquals(value.type, "golden", "Expecting value %2, got %1"); this.assertEquals(old, 0, "Expecting old value %2, got %1"); // Change a value with no listeners aria.utils.Json.setValue(shopping.bags[0], "hand", "middle"); this.assertEquals(name, "apple", "Expecting name %2, got %1"); this.assertEquals(value.type, "golden", "Expecting value %2, got %1"); this.assertEquals(old, 0, "Expecting old value %2, got %1"); // And now one with a listener aria.utils.Json.setValue(shopping.bags[1], "content", false); this.assertEquals(name, "sugar", "Expecting name %2, got %1"); this.assertEquals(value, false, "Expecting value false, got %1"); this.assertEquals(old, null, "Expecting old value null, got %1"); widget.$dispose(); }, /** * Check that listeners are removed when the widget is disposed */ testDestroy : function () { var internet = {}; var cfg = { tagName : "img", bind : { "src" : { inside : internet, to : "image" }, "alt" : { inside : internet, to : "text" } } }; var widget = new aria.html.Element(cfg, { tplClasspath : "Element" }); // Value and old value are already tested var name; widget.onbind = function (property) { name = property; }; aria.utils.Json.setValue(internet, "image", "something"); this.assertEquals(name, "src", "The listener on src should be called"); // Dispose the widget, this is the important part widget.$dispose(); aria.utils.Json.setValue(internet, "text", "something"); this.assertEquals(name, "src", "The listener on src shouldn't be called again"); }, /** * Just to be sure that two listener on the same value are called correctly */ testMultipleBind : function () { var internet = {}; var cfg = { tagName : "img", bind : { "src" : { inside : internet, to : "same" }, "alt" : { inside : internet, to : "same" } } }; var widget = new aria.html.Element(cfg, { tplClasspath : "Element" }); // Value and old value are already tested var names = []; widget.onbind = function (property) { names.push(property); }; aria.utils.Json.setValue(internet, "same", "something"); this.assertEquals(names.length, 2, "Two listeners should be called"); this.assertTrue(aria.utils.Array.contains(names, "src"), "src callback not called"); this.assertTrue(aria.utils.Array.contains(names, "alt"), "alt callback not called"); widget.$dispose(); }, /** * This is a bit of paranoia, but check that when there are more widgets, the correct callback is called */ testMultipleWidgets : function () { var container = {}; var first = { tagName : "img", bind : { "me" : { inside : container, to : "one" } } }; var second = { tagName : "ul", bind : { "you" : { inside : container, to : "two" } } }; var third = { tagName : "iframe", bind : { "me" : { inside : container, to : "two" } } }; var one = new aria.html.Element(first, { tplClasspath : "Element" }); var two = new aria.html.Element(second, { tplClasspath : "Element" }); var three = new aria.html.Element(third, { tplClasspath : "Element" }); var names = []; one.onbind = function (property) { names.push("one_" + property); }; two.onbind = function (property) { names.push("two_" + property); }; three.onbind = function (property) { names.push("three_" + property); }; aria.utils.Json.setValue(container, "one", 1); this.assertEquals(names.length, 1, "One listener should be called"); this.assertEquals(names[0], "one_me", "One listener should be called"); names = []; aria.utils.Json.setValue(container, "two", 2); this.assertEquals(names.length, 2, "Two listeners should be called"); this.assertTrue(aria.utils.Array.contains(names, "two_you"), "Second listener not called"); this.assertTrue(aria.utils.Array.contains(names, "three_me"), "Third listener not called"); one.$dispose(); two.$dispose(); three.$dispose(); } } });
flongo/ariatemplates
test/aria/html/element/ElementBindingsTest.js
JavaScript
apache-2.0
9,393
/** @license React v16.13.1 * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var _assign = require('object-assign'); var checkPropTypes = require('prop-types/checkPropTypes'); var ReactVersion = '16.13.1'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current batch's configuration such as how long an update * should suspend for if it needs to. */ var ReactCurrentBatchConfig = { suspense: null }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function describeComponentFrame (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; } var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_BLOCK_TYPE: return getComponentName(type.render); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } var ReactDebugCurrentFrame = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } { // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentlyValidatingElement) { var name = getComponentName(currentlyValidatingElement.type); var owner = currentlyValidatingElement._owner; stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type)); } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } /** * Used by act() to track whether you're inside an act() scope. */ var IsSomeRendererActing = { current: false }; var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentBatchConfig: ReactCurrentBatchConfig, ReactCurrentOwner: ReactCurrentOwner, IsSomeRendererActing: IsSomeRendererActing, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: _assign }; { _assign(ReactSharedInternals, { // These should not be included in production. ReactDebugCurrentFrame: ReactDebugCurrentFrame, // Shim for React DOM 16.0.0 which still destructured (but not used) this. // TODO: remove in React 17.0. ReactComponentTreeHook: {} }); } // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0; if (!hasExistingStack) { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) { { throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." ); } } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. _assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentName(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { if (!!(element === null || element === undefined)) { { throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." ); } } var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } var POOL_SIZE = 10; var traverseContextPool = []; function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) { if (traverseContextPool.length) { var traverseContext = traverseContextPool.pop(); traverseContext.result = mapResult; traverseContext.keyPrefix = keyPrefix; traverseContext.func = mapFunction; traverseContext.context = mapContext; traverseContext.count = 0; return traverseContext; } else { return { result: mapResult, keyPrefix: keyPrefix, func: mapFunction, context: mapContext, count: 0 }; } } function releaseTraverseContext(traverseContext) { traverseContext.result = null; traverseContext.keyPrefix = null; traverseContext.func = null; traverseContext.context = null; traverseContext.count = 0; if (traverseContextPool.length < POOL_SIZE) { traverseContextPool.push(traverseContext); } } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { { // Warn about using Maps as children if (iteratorFn === children.entries) { if (!didWarnAboutMaps) { warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(children); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else if (type === 'object') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum(); } var childrenString = '' + children; { { throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + ")." + addendum ); } } } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); releaseTraverseContext(traverseContext); } function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); releaseTraverseContext(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { return traverseAllChildren(children, function () { return null; }, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, function (child) { return child; }); return result; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { if (!isValidElement(children)) { { throw Error( "React.Children.only expected to receive a single React element child." ); } } return children; } function createContext(defaultValue, calculateChangedBits) { if (calculateChangedBits === undefined) { calculateChangedBits = null; } else { { if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') { error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits); } } } var context = { $$typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } function lazy(ctor) { var lazyType = { $$typeof: REACT_LAZY_TYPE, _ctor: ctor, // React uses these fields to store the result. _status: -1, _result: null }; { // In production, this would just set it on the object. var defaultProps; var propTypes; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); } } } return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; } function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE); } function memo(type, compare) { { if (!isValidElementType(type)) { error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } return { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; if (!(dispatcher !== null)) { { throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." ); } } return dispatcher; } function useContext(Context, unstable_observedBits) { var dispatcher = resolveDispatcher(); { if (unstable_observedBits !== undefined) { error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : ''); } // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context, unstable_observedBits); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentName(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(source) { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== undefined) { return getSourceInfoErrorAddendum(elementProps.__source); } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; } setCurrentlyValidatingElement(element); { error('Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner); } setCurrentlyValidatingElement(null); } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var name = getComponentName(type); var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { setCurrentlyValidatingElement(element); checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum); setCurrentlyValidatingElement(null); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { setCurrentlyValidatingElement(fragment); var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); break; } } if (fragment.ref !== null) { error('Invalid attribute `ref` supplied to `React.Fragment`.'); } setCurrentlyValidatingElement(null); } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } { error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); } // Legacy hook: remove it Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } { try { var frozenObject = Object.freeze({}); var testMap = new Map([[frozenObject, null]]); var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. testMap.set(0, 0); testSet.add(0); } catch (e) { } } var createElement$1 = createElementWithValidation ; var cloneElement$1 = cloneElementWithValidation ; var createFactory = createFactoryWithValidation ; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useEffect = useEffect; exports.useImperativeHandle = useImperativeHandle; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.version = ReactVersion; })(); }
BigBoss424/portfolio
v8/development/node_modules/react/cjs/react.development.js
JavaScript
apache-2.0
60,645
var Linq = (function () { function Linq() { } Linq.select = function (values, func) { var result = new Array(values.length); for (var i = 0; i < values.length; i++) { result[i] = func(values[i]); } return result; }; return Linq; })();
hippich/typescript
tests/baselines/reference/unknownSymbolInGenericReturnType.js
JavaScript
apache-2.0
315
//// [intersectionWithUnionConstraint.ts] function f1<T extends string | number, U extends string | number>(x: T & U) { // Combined constraint of 'T & U' is 'string | number' let y: string | number = x; } function f2<T extends string | number | undefined, U extends string | null | undefined>(x: T & U) { let y1: string | number = x; // Error let y2: string | null = x; // Error let y3: string | undefined = x; let y4: number | null = x; // Error let y5: number | undefined = x; // Error let y6: null | undefined = x; // Error } type T1 = (string | number | undefined) & (string | null | undefined); // string | undefined function f3<T extends string | number | undefined>(x: T & (number | object | undefined)) { const y: number | undefined = x; } function f4<T extends string | number>(x: T & (number | object)) { const y: number = x; } function f5<T, U extends keyof T>(x: keyof T & U) { let y: keyof any = x; } // Repro from #23648 type Example<T, U> = { [K in keyof T]: K extends keyof U ? UnexpectedError<K> : NoErrorHere<K> } type UnexpectedError<T extends PropertyKey> = T type NoErrorHere<T extends PropertyKey> = T //// [intersectionWithUnionConstraint.js] "use strict"; function f1(x) { // Combined constraint of 'T & U' is 'string | number' var y = x; } function f2(x) { var y1 = x; // Error var y2 = x; // Error var y3 = x; var y4 = x; // Error var y5 = x; // Error var y6 = x; // Error } function f3(x) { var y = x; } function f4(x) { var y = x; } function f5(x) { var y = x; }
donaldpipowitch/TypeScript
tests/baselines/reference/intersectionWithUnionConstraint.js
JavaScript
apache-2.0
1,636
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n) { return 5; } export default [ 'lkt', [ ['AM', 'PM'], , ], , [ ['A', 'W', 'N', 'Y', 'T', 'Z', 'O'], [ 'Aŋpétuwakȟaŋ', 'Aŋpétuwaŋži', 'Aŋpétunuŋpa', 'Aŋpétuyamni', 'Aŋpétutopa', 'Aŋpétuzaptaŋ', 'Owáŋgyužažapi' ], , ], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], [ 'Aŋpétuwakȟaŋ', 'Aŋpétuwaŋži', 'Aŋpétunuŋpa', 'Aŋpétuyamni', 'Aŋpétutopa', 'Aŋpétuzaptaŋ', 'Owáŋgyužažapi' ], , ], [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], [ 'Wiótheȟika Wí', 'Thiyóȟeyuŋka Wí', 'Ištáwičhayazaŋ Wí', 'Pȟežítȟo Wí', 'Čhaŋwápetȟo Wí', 'Wípazukȟa-wašté Wí', 'Čhaŋpȟásapa Wí', 'Wasútȟuŋ Wí', 'Čhaŋwápeǧi Wí', 'Čhaŋwápe-kasná Wí', 'Waníyetu Wí', 'Tȟahékapšuŋ Wí' ], ], , [ ['BCE', 'CE'], , ], 0, [6, 0], ['y-MM-dd', 'y MMM d', 'y MMMM d', 'y MMMM d, EEEE'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], [ '{1} {0}', , , ], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], '$', 'USD', plural ]; //# sourceMappingURL=lkt.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/@angular/common/locales/lkt.js
JavaScript
apache-2.0
1,713
/* * Copyright (C) 2011 Google Inc. 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. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 * OWNER 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. */ /** * @constructor */ WebInspector.ExtensionServer = function() { this._clientObjects = {}; this._handlers = {}; this._subscribers = {}; this._subscriptionStartHandlers = {}; this._subscriptionStopHandlers = {}; this._extraHeaders = {}; this._requests = {}; this._lastRequestId = 0; this._registeredExtensions = {}; this._status = new WebInspector.ExtensionStatus(); var commands = WebInspector.extensionAPI.Commands; this._registerHandler(commands.AddAuditCategory, this._onAddAuditCategory.bind(this)); this._registerHandler(commands.AddAuditResult, this._onAddAuditResult.bind(this)); this._registerHandler(commands.AddConsoleMessage, this._onAddConsoleMessage.bind(this)); this._registerHandler(commands.AddRequestHeaders, this._onAddRequestHeaders.bind(this)); this._registerHandler(commands.CreatePanel, this._onCreatePanel.bind(this)); this._registerHandler(commands.CreateSidebarPane, this._onCreateSidebarPane.bind(this)); this._registerHandler(commands.CreateStatusBarButton, this._onCreateStatusBarButton.bind(this)); this._registerHandler(commands.EvaluateOnInspectedPage, this._onEvaluateOnInspectedPage.bind(this)); this._registerHandler(commands.GetHAR, this._onGetHAR.bind(this)); this._registerHandler(commands.GetConsoleMessages, this._onGetConsoleMessages.bind(this)); this._registerHandler(commands.GetPageResources, this._onGetPageResources.bind(this)); this._registerHandler(commands.GetRequestContent, this._onGetRequestContent.bind(this)); this._registerHandler(commands.GetResourceContent, this._onGetResourceContent.bind(this)); this._registerHandler(commands.Log, this._onLog.bind(this)); this._registerHandler(commands.Reload, this._onReload.bind(this)); this._registerHandler(commands.SetOpenResourceHandler, this._onSetOpenResourceHandler.bind(this)); this._registerHandler(commands.SetResourceContent, this._onSetResourceContent.bind(this)); this._registerHandler(commands.SetSidebarHeight, this._onSetSidebarHeight.bind(this)); this._registerHandler(commands.SetSidebarContent, this._onSetSidebarContent.bind(this)); this._registerHandler(commands.SetSidebarPage, this._onSetSidebarPage.bind(this)); this._registerHandler(commands.ShowPanel, this._onShowPanel.bind(this)); this._registerHandler(commands.StopAuditCategoryRun, this._onStopAuditCategoryRun.bind(this)); this._registerHandler(commands.Subscribe, this._onSubscribe.bind(this)); this._registerHandler(commands.Unsubscribe, this._onUnsubscribe.bind(this)); this._registerHandler(commands.UpdateButton, this._onUpdateButton.bind(this)); this._registerHandler(commands.UpdateAuditProgress, this._onUpdateAuditProgress.bind(this)); window.addEventListener("message", this._onWindowMessage.bind(this), false); } WebInspector.ExtensionServer.prototype = { hasExtensions: function() { return !!Object.keys(this._registeredExtensions).length; }, notifySearchAction: function(panelId, action, searchString) { this._postNotification(WebInspector.extensionAPI.Events.PanelSearch + panelId, action, searchString); }, notifyViewShown: function(identifier, frameIndex) { this._postNotification(WebInspector.extensionAPI.Events.ViewShown + identifier, frameIndex); }, notifyViewHidden: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ViewHidden + identifier); }, notifyButtonClicked: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ButtonClicked + identifier); }, _inspectedURLChanged: function(event) { this._requests = {}; var url = event.data; this._postNotification(WebInspector.extensionAPI.Events.InspectedURLChanged, url); }, startAuditRun: function(category, auditRun) { this._clientObjects[auditRun.id] = auditRun; this._postNotification("audit-started-" + category.id, auditRun.id); }, stopAuditRun: function(auditRun) { delete this._clientObjects[auditRun.id]; }, /** * @param {...*} vararg */ _postNotification: function(type, vararg) { var subscribers = this._subscribers[type]; if (!subscribers) return; var message = { command: "notify-" + type, arguments: Array.prototype.slice.call(arguments, 1) }; for (var i = 0; i < subscribers.length; ++i) subscribers[i].postMessage(message); }, _onSubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (subscribers) subscribers.push(port); else { this._subscribers[message.type] = [ port ]; if (this._subscriptionStartHandlers[message.type]) this._subscriptionStartHandlers[message.type](); } }, _onUnsubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (!subscribers) return; subscribers.remove(port); if (!subscribers.length) { delete this._subscribers[message.type]; if (this._subscriptionStopHandlers[message.type]) this._subscriptionStopHandlers[message.type](); } }, _onAddRequestHeaders: function(message) { var id = message.extensionId; if (typeof id !== "string") return this._status.E_BADARGTYPE("extensionId", typeof id, "string"); var extensionHeaders = this._extraHeaders[id]; if (!extensionHeaders) { extensionHeaders = {}; this._extraHeaders[id] = extensionHeaders; } for (var name in message.headers) extensionHeaders[name] = message.headers[name]; var allHeaders = /** @type NetworkAgent.Headers */ ({}); for (var extension in this._extraHeaders) { var headers = this._extraHeaders[extension]; for (name in headers) { if (typeof headers[name] === "string") allHeaders[name] = headers[name]; } } NetworkAgent.setExtraHTTPHeaders(allHeaders); }, _onCreatePanel: function(message, port) { var id = message.id; // The ids are generated on the client API side and must be unique, so the check below // shouldn't be hit unless someone is bypassing the API. if (id in this._clientObjects || id in WebInspector.panels) return this._status.E_EXISTS(id); var page = this._expandResourcePath(port._extensionOrigin, message.page); var panelDescriptor = new WebInspector.PanelDescriptor(id, message.title, undefined, undefined, new WebInspector.ExtensionPanel(id, page)); panelDescriptor.setIconURL(this._expandResourcePath(port._extensionOrigin, message.icon)); this._clientObjects[id] = panelDescriptor.panel(); WebInspector.inspectorView.addPanel(panelDescriptor); return this._status.OK(); }, _onShowPanel: function(message) { // Note: WebInspector.showPanel already sanitizes input. WebInspector.showPanel(message.id); }, _onCreateStatusBarButton: function(message, port) { var panel = this._clientObjects[message.panel]; if (!panel || !(panel instanceof WebInspector.ExtensionPanel)) return this._status.E_NOTFOUND(message.panel); var button = new WebInspector.ExtensionButton(message.id, this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); this._clientObjects[message.id] = button; panel.addStatusBarItem(button.element); return this._status.OK(); }, _onUpdateButton: function(message, port) { var button = this._clientObjects[message.id]; if (!button || !(button instanceof WebInspector.ExtensionButton)) return this._status.E_NOTFOUND(message.id); button.update(this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); return this._status.OK(); }, _onCreateSidebarPane: function(message) { var panel = WebInspector.panel(message.panel); if (!panel) return this._status.E_NOTFOUND(message.panel); if (!panel.addExtensionSidebarPane) return this._status.E_NOTSUPPORTED(); var id = message.id; var sidebar = new WebInspector.ExtensionSidebarPane(message.title, message.id); this._clientObjects[id] = sidebar; panel.addExtensionSidebarPane(id, sidebar); return this._status.OK(); }, _onSetSidebarHeight: function(message) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setHeight(message.height); return this._status.OK(); }, _onSetSidebarContent: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); function callback(error) { var result = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, result); } if (message.evaluateOnPage) return sidebar.setExpression(message.expression, message.rootTitle, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); sidebar.setObject(message.expression, message.rootTitle, callback.bind(this)); }, _onSetSidebarPage: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setPage(this._expandResourcePath(port._extensionOrigin, message.page)); }, _onSetOpenResourceHandler: function(message, port) { var name = this._registeredExtensions[port._extensionOrigin].name || ("Extension " + port._extensionOrigin); if (message.handlerPresent) WebInspector.openAnchorLocationRegistry.registerHandler(name, this._handleOpenURL.bind(this, port)); else WebInspector.openAnchorLocationRegistry.unregisterHandler(name); }, _handleOpenURL: function(port, details) { var url = /** @type {string} */ (details.url); var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return false; var lineNumber = details.lineNumber; if (typeof lineNumber === "number") lineNumber += 1; port.postMessage({ command: "open-resource", resource: this._makeResource(contentProvider), lineNumber: lineNumber }); return true; }, _onLog: function(message) { WebInspector.log(message.message); }, _onReload: function(message) { var options = /** @type ExtensionReloadOptions */ (message.options || {}); NetworkAgent.setUserAgentOverride(typeof options.userAgent === "string" ? options.userAgent : ""); var injectedScript; if (options.injectedScript) { // Wrap client script into anonymous function, return another anonymous function that // returns empty object for compatibility with InjectedScriptManager on the backend. injectedScript = "((function(){" + options.injectedScript + "})(),function(){return {}})"; } PageAgent.reload(!!options.ignoreCache, injectedScript); return this._status.OK(); }, _onEvaluateOnInspectedPage: function(message, port) { /** * @param {?Protocol.Error} error * @param {RuntimeAgent.RemoteObject} resultPayload * @param {boolean=} wasThrown */ function callback(error, resultPayload, wasThrown) { var result; if (error) result = this._status.E_PROTOCOLERROR(error.toString()); else if (wasThrown) result = { isException: true, value: resultPayload.description }; else result = { value: resultPayload.value }; this._dispatchCallback(message.requestId, port, result); } return this.evaluate(message.expression, true, true, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); }, _onGetConsoleMessages: function() { return WebInspector.console.messages.map(this._makeConsoleMessage); }, _onAddConsoleMessage: function(message) { function convertSeverity(level) { switch (level) { case WebInspector.extensionAPI.console.Severity.Tip: return WebInspector.ConsoleMessage.MessageLevel.Tip; case WebInspector.extensionAPI.console.Severity.Log: return WebInspector.ConsoleMessage.MessageLevel.Log; case WebInspector.extensionAPI.console.Severity.Warning: return WebInspector.ConsoleMessage.MessageLevel.Warning; case WebInspector.extensionAPI.console.Severity.Error: return WebInspector.ConsoleMessage.MessageLevel.Error; case WebInspector.extensionAPI.console.Severity.Debug: return WebInspector.ConsoleMessage.MessageLevel.Debug; } } var level = convertSeverity(message.severity); if (!level) return this._status.E_BADARG("message.severity", message.severity); var consoleMessage = WebInspector.ConsoleMessage.create( WebInspector.ConsoleMessage.MessageSource.JS, level, message.text, WebInspector.ConsoleMessage.MessageType.Log, message.url, message.line); WebInspector.console.addMessage(consoleMessage); }, _makeConsoleMessage: function(message) { function convertLevel(level) { if (!level) return; switch (level) { case WebInspector.ConsoleMessage.MessageLevel.Tip: return WebInspector.extensionAPI.console.Severity.Tip; case WebInspector.ConsoleMessage.MessageLevel.Log: return WebInspector.extensionAPI.console.Severity.Log; case WebInspector.ConsoleMessage.MessageLevel.Warning: return WebInspector.extensionAPI.console.Severity.Warning; case WebInspector.ConsoleMessage.MessageLevel.Error: return WebInspector.extensionAPI.console.Severity.Error; case WebInspector.ConsoleMessage.MessageLevel.Debug: return WebInspector.extensionAPI.console.Severity.Debug; default: return WebInspector.extensionAPI.console.Severity.Log; } } var result = { severity: convertLevel(message.level), text: message.text, }; if (message.url) result.url = message.url; if (message.line) result.line = message.line; return result; }, _onGetHAR: function() { var requests = WebInspector.networkLog.requests; var harLog = (new WebInspector.HARLog(requests)).build(); for (var i = 0; i < harLog.entries.length; ++i) harLog.entries[i]._requestId = this._requestId(requests[i]); return harLog; }, /** * @param {WebInspector.ContentProvider} contentProvider */ _makeResource: function(contentProvider) { return { url: contentProvider.contentURL(), type: contentProvider.contentType().name() }; }, _onGetPageResources: function() { var resources = {}; function pushResourceData(contentProvider) { if (!resources[contentProvider.contentURL()]) resources[contentProvider.contentURL()] = this._makeResource(contentProvider); } var uiSourceCodes = WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.Network); uiSourceCodes.forEach(pushResourceData.bind(this)); WebInspector.resourceTreeModel.forAllResources(pushResourceData.bind(this)); return Object.values(resources); }, /** * @param {WebInspector.ContentProvider} contentProvider */ _getResourceContent: function(contentProvider, message, port) { /** * @param {?string} content * @param {boolean} contentEncoded * @param {string} mimeType */ function onContentAvailable(content, contentEncoded, mimeType) { var response = { encoding: contentEncoded ? "base64" : "", content: content }; this._dispatchCallback(message.requestId, port, response); } contentProvider.requestContent(onContentAvailable.bind(this)); }, _onGetRequestContent: function(message, port) { var request = this._requestById(message.id); if (!request) return this._status.E_NOTFOUND(message.id); this._getResourceContent(request, message, port); }, _onGetResourceContent: function(message, port) { var url = /** @type {string} */ (message.url); var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return this._status.E_NOTFOUND(url); this._getResourceContent(contentProvider, message, port); }, _onSetResourceContent: function(message, port) { /** * @param {?Protocol.Error} error */ function callbackWrapper(error) { var response = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, response); } var url = /** @type {string} */ (message.url); var uiSourceCode = WebInspector.workspace.uiSourceCodeForOriginURL(url); if (!uiSourceCode) { var resource = WebInspector.resourceTreeModel.resourceForURL(url); if (!resource) return this._status.E_NOTFOUND(url); return this._status.E_NOTSUPPORTED("Resource is not editable") } uiSourceCode.setWorkingCopy(message.content); if (message.commit) uiSourceCode.commitWorkingCopy(callbackWrapper.bind(this)); else callbackWrapper.call(this, null); }, _requestId: function(request) { if (!request._extensionRequestId) { request._extensionRequestId = ++this._lastRequestId; this._requests[request._extensionRequestId] = request; } return request._extensionRequestId; }, _requestById: function(id) { return this._requests[id]; }, _onAddAuditCategory: function(message, port) { var category = new WebInspector.ExtensionAuditCategory(port._extensionOrigin, message.id, message.displayName, message.resultCount); if (WebInspector.panel("audits").getCategory(category.id)) return this._status.E_EXISTS(category.id); this._clientObjects[message.id] = category; WebInspector.panel("audits").addCategory(category); }, _onAddAuditResult: function(message) { var auditResult = this._clientObjects[message.resultId]; if (!auditResult) return this._status.E_NOTFOUND(message.resultId); try { auditResult.addResult(message.displayName, message.description, message.severity, message.details); } catch (e) { return e; } return this._status.OK(); }, _onUpdateAuditProgress: function(message) { var auditResult = this._clientObjects[message.resultId]; if (!auditResult) return this._status.E_NOTFOUND(message.resultId); auditResult.updateProgress(Math.min(Math.max(0, message.progress), 1)); }, _onStopAuditCategoryRun: function(message) { var auditRun = this._clientObjects[message.resultId]; if (!auditRun) return this._status.E_NOTFOUND(message.resultId); auditRun.done(); }, _dispatchCallback: function(requestId, port, result) { if (requestId) port.postMessage({ command: "callback", requestId: requestId, result: result }); }, initExtensions: function() { this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ConsoleMessageAdded, WebInspector.console, WebInspector.ConsoleModel.Events.MessageAdded, this._notifyConsoleMessageAdded); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.NetworkRequestFinished, WebInspector.networkManager, WebInspector.NetworkManager.EventTypes.RequestFinished, this._notifyRequestFinished); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceAdded, WebInspector.workspace, WebInspector.UISourceCodeProvider.Events.UISourceCodeAdded, this._notifyResourceAdded); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ElementsPanelObjectSelected, WebInspector.notifications, WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged); this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceContentCommitted, WebInspector.workspace, WebInspector.Workspace.Events.UISourceCodeContentCommitted, this._notifyUISourceCodeContentCommitted); function onTimelineSubscriptionStarted() { WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._notifyTimelineEventRecorded, this); WebInspector.timelineManager.start(); } function onTimelineSubscriptionStopped() { WebInspector.timelineManager.stop(); WebInspector.timelineManager.removeEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, this._notifyTimelineEventRecorded, this); } this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.TimelineEventRecorded, onTimelineSubscriptionStarted.bind(this), onTimelineSubscriptionStopped.bind(this)); WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this); this._initDone = true; if (this._pendingExtensions) { this._pendingExtensions.forEach(this._innerAddExtension, this); delete this._pendingExtensions; } InspectorExtensionRegistry.getExtensionsAsync(); }, _notifyConsoleMessageAdded: function(event) { this._postNotification(WebInspector.extensionAPI.Events.ConsoleMessageAdded, this._makeConsoleMessage(event.data)); }, _notifyResourceAdded: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); this._postNotification(WebInspector.extensionAPI.Events.ResourceAdded, this._makeResource(uiSourceCode)); }, _notifyUISourceCodeContentCommitted: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data.uiSourceCode); var content = /** @type {string} */ (event.data.content); this._postNotification(WebInspector.extensionAPI.Events.ResourceContentCommitted, this._makeResource(uiSourceCode), content); }, _notifyRequestFinished: function(event) { var request = /** @type {WebInspector.NetworkRequest} */ (event.data); this._postNotification(WebInspector.extensionAPI.Events.NetworkRequestFinished, this._requestId(request), (new WebInspector.HAREntry(request)).build()); }, _notifyElementsSelectionChanged: function() { this._postNotification(WebInspector.extensionAPI.Events.ElementsPanelObjectSelected); }, _notifyTimelineEventRecorded: function(event) { this._postNotification(WebInspector.extensionAPI.Events.TimelineEventRecorded, event.data); }, /** * @param {Array.<ExtensionDescriptor>} extensions */ _addExtensions: function(extensions) { extensions.forEach(this._addExtension, this); }, _addExtension: function(extensionInfo) { if (this._initDone) { this._innerAddExtension(extensionInfo); return; } if (this._pendingExtensions) this._pendingExtensions.push(extensionInfo); else this._pendingExtensions = [extensionInfo]; }, _innerAddExtension: function(extensionInfo) { const urlOriginRegExp = new RegExp("([^:]+:\/\/[^/]*)\/"); // Can't use regexp literal here, MinJS chokes on it. var startPage = extensionInfo.startPage; var name = extensionInfo.name; try { var originMatch = urlOriginRegExp.exec(startPage); if (!originMatch) { console.error("Skipping extension with invalid URL: " + startPage); return false; } var extensionOrigin = originMatch[1]; if (!this._registeredExtensions[extensionOrigin]) { // See ExtensionAPI.js and ExtensionCommon.js for details. InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin, buildExtensionAPIInjectedScript(extensionInfo)); this._registeredExtensions[extensionOrigin] = { name: name }; } var iframe = document.createElement("iframe"); iframe.src = startPage; iframe.style.display = "none"; document.body.appendChild(iframe); } catch (e) { console.error("Failed to initialize extension " + startPage + ":" + e); return false; } return true; }, _onWindowMessage: function(event) { if (event.data === "registerExtension") this._registerExtension(event.origin, event.ports[0]); }, _registerExtension: function(origin, port) { if (!this._registeredExtensions.hasOwnProperty(origin)) { if (origin !== window.location.origin) // Just ignore inspector frames. console.error("Ignoring unauthorized client request from " + origin); return; } port._extensionOrigin = origin; port.addEventListener("message", this._onmessage.bind(this), false); port.start(); }, _onmessage: function(event) { var message = event.data; var result; if (message.command in this._handlers) result = this._handlers[message.command](message, event.target); else result = this._status.E_NOTSUPPORTED(message.command); if (result && message.requestId) this._dispatchCallback(message.requestId, event.target, result); }, _registerHandler: function(command, callback) { this._handlers[command] = callback; }, _registerSubscriptionHandler: function(eventTopic, onSubscribeFirst, onUnsubscribeLast) { this._subscriptionStartHandlers[eventTopic] = onSubscribeFirst; this._subscriptionStopHandlers[eventTopic] = onUnsubscribeLast; }, _registerAutosubscriptionHandler: function(eventTopic, eventTarget, frontendEventType, handler) { this._registerSubscriptionHandler(eventTopic, eventTarget.addEventListener.bind(eventTarget, frontendEventType, handler, this), eventTarget.removeEventListener.bind(eventTarget, frontendEventType, handler, this)); }, _expandResourcePath: function(extensionPath, resourcePath) { if (!resourcePath) return; return extensionPath + this._normalizePath(resourcePath); }, _normalizePath: function(path) { var source = path.split("/"); var result = []; for (var i = 0; i < source.length; ++i) { if (source[i] === ".") continue; // Ignore empty path components resulting from //, as well as a leading and traling slashes. if (source[i] === "") continue; if (source[i] === "..") result.pop(); else result.push(source[i]); } return "/" + result.join("/"); }, /** * @param {string} expression * @param {boolean} exposeCommandLineAPI * @param {boolean} returnByValue * @param {Object} options * @param {string} securityOrigin * @param {function(?string, ?RuntimeAgent.RemoteObject, boolean=)} callback */ evaluate: function(expression, exposeCommandLineAPI, returnByValue, options, securityOrigin, callback) { var contextId; if (typeof options === "object" && options["useContentScriptContext"]) { var mainFrame = WebInspector.resourceTreeModel.mainFrame; if (!mainFrame) return this._status.E_FAILED("main frame not available yet"); var context = WebInspector.runtimeModel.contextByFrameAndSecurityOrigin(mainFrame, securityOrigin); if (!context) return this._status.E_NOTFOUND(securityOrigin); contextId = context.id; } RuntimeAgent.evaluate(expression, "extension", exposeCommandLineAPI, true, contextId, returnByValue, false, callback); } } /** * @constructor */ WebInspector.ExtensionStatus = function() { function makeStatus(code, description) { var details = Array.prototype.slice.call(arguments, 2); var status = { code: code, description: description, details: details }; if (code !== "OK") { status.isError = true; console.log("Extension server error: " + String.vsprintf(description, details)); } return status; } this.OK = makeStatus.bind(null, "OK", "OK"); this.E_EXISTS = makeStatus.bind(null, "E_EXISTS", "Object already exists: %s"); this.E_BADARG = makeStatus.bind(null, "E_BADARG", "Invalid argument %s: %s"); this.E_BADARGTYPE = makeStatus.bind(null, "E_BADARGTYPE", "Invalid type for argument %s: got %s, expected %s"); this.E_NOTFOUND = makeStatus.bind(null, "E_NOTFOUND", "Object not found: %s"); this.E_NOTSUPPORTED = makeStatus.bind(null, "E_NOTSUPPORTED", "Object does not support requested operation: %s"); this.E_PROTOCOLERROR = makeStatus.bind(null, "E_PROTOCOLERROR", "Inspector protocol error: %s"); this.E_FAILED = makeStatus.bind(null, "E_FAILED", "Operation failed: %s"); } WebInspector.addExtensions = function(extensions) { WebInspector.extensionServer._addExtensions(extensions); } WebInspector.extensionAPI = {}; defineCommonExtensionSymbols(WebInspector.extensionAPI); WebInspector.extensionServer = new WebInspector.ExtensionServer(); window.addExtension = function(page, name) { WebInspector.extensionServer._addExtension({ startPage: page, name: name, }); }
VikingsYip/webkitdotnet
webkit/WebKit.resources/inspector/ExtensionServer.js
JavaScript
bsd-2-clause
33,321
/* YUI 3.6.0 (build 5521) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("lang/datatype-date-format_en-MY",function(a){a.Intl.add("datatype-date-format","en-MY",{"a":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"A":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"b":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"B":["January","February","March","April","May","June","July","August","September","October","November","December"],"c":"%a, %b %d, %Y %l:%M:%S %p %Z","p":["AM","PM"],"P":["am","pm"],"x":"%m/%d/%y","X":"%l:%M:%S %p"});},"3.6.0");
bretkikehara/wattdepot-visualization
src/main/webapp/yui/3.6.0/build/datatype-date-format/lang/datatype-date-format_en-MY.js
JavaScript
bsd-3-clause
669
// Copyright (c) 2014 The crouton Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* Constants */ var URL = "ws://localhost:30001/"; var VERSION = 2; /* Note: the extension must always be backward compatible */ var MAXLOGGERLEN = 20; var RETRY_TIMEOUT = 5; var UPDATE_CHECK_INTERVAL = 15*60; /* Check for updates every 15' at most */ var WINDOW_UPDATE_INTERVAL = 15; /* Update window list every 15" at most */ /* String to copy to the clipboard if it should be empty */ var DUMMY_EMPTYSTRING = "%"; LogLevel = { ERROR : "error", INFO : "info", DEBUG : "debug" } /* Global variables */ var clipboardholder_; /* textarea used to hold clipboard content */ var timeout_ = null; /* Set if a timeout is active */ var websocket_ = null; /* Active connection */ /* State variables */ var debug_ = false; var showlog_ = false; /* true if extension log should be shown */ var hidpi_ = false; /* true if kiwi windows should be opened in HiDPI mode */ var enabled_ = true; /* true if we are trying to connect */ var active_ = false; /* true if we are connected to a server */ var error_ = false; /* true if there was an error during the last connection */ var dummystr_ = false; /* true if the last string we copied was the dummy string */ var update_ = false; /* true if an update to the extension is available */ var lastupdatecheck_ = null; var lastwindowlistupdate_ = null; var status_ = ""; var sversion_ = 0; /* Version of the websocket server */ var logger_ = []; /* Array of status messages: [LogLevel, time, message] */ var windows_ = []; /* Array of windows. (.display, .name) */ var kiwi_win_ = {}; /* Map of kiwi windows. Key is display, value is object (.id, .window: window element) */ var focus_win_ = -1; /* Focused kiwi window. -1 if no kiwi window focused. */ var notifications_ = {}; /* Map of notification id to function to be called when the notification is clicked. */ /* Set the current status string. * active is a boolean, true if the WebSocket connection is established. */ function setStatus(status, active) { active_ = active; status_ = status; /* Apply update if the extension is not active */ if (update_ && !active_) chrome.runtime.reload(); refreshUI(); } function showHelp() { window.open("first.html", '_blank'); } function updateAvailable(version) { printLog("A new version of the extension is available (" + version + ")", LogLevel.INFO); /* Apply update immediately if the extension is not active */ if (!active_) chrome.runtime.reload(); else update_ = true; } function checkUpdate(force) { var currenttime = new Date().getTime(); if (force || lastupdatecheck_ == null || (currenttime-lastupdatecheck_) > 1000*UPDATE_CHECK_INTERVAL) { chrome.runtime.requestUpdateCheck(function (status, details) { printLog("Update status=" + status, LogLevel.DEBUG); if (status == "update_available") { updateAvailable(details.version); } }); lastupdatecheck_ = currenttime; } } function updateWindowList(force) { if (!active_ || sversion_ < 2) { windows_ = []; return; } var currenttime = new Date().getTime(); if (force || lastwindowlistupdate_ == null || (currenttime-lastwindowlistupdate_) > 1000*WINDOW_UPDATE_INTERVAL) { lastwindowlistupdate_ = currenttime; printLog("Sending window list request", LogLevel.DEBUG); websocket_.send("Cs" + focus_win_); websocket_.send("Cl"); } } /* Called from kiwi (window.js), so we can directly access each window */ function registerKiwi(displaynum, window) { display = ":" + displaynum if (kiwi_win_[display] && kiwi_win_[display].id >= 0) { kiwi_win_[display].window = window; } } /* Close the popup window */ function closePopup() { var views = chrome.extension.getViews({type: "popup"}); for (var i = 0; i < views.length; views++) { views[i].close(); } } /* Update the icon, and refresh the popup page */ function refreshUI() { updateWindowList(false); if (error_) icon = "error" else if (!enabled_) icon = "disabled" else if (active_) icon = "connected"; else icon = "disconnected"; chrome.browserAction.setIcon( {path: {'19': icon + '-19.png', '38': icon + '-38.png'}} ); chrome.browserAction.setTitle({title: 'crouton: ' + icon}); var views = chrome.extension.getViews({type: "popup"}); for (var i = 0; i < views.length; views++) { var view = views[i]; /* Make sure page is ready */ if (document.readyState === "complete") { /* Update "help" link */ helplink = view.document.getElementById("help"); helplink.onclick = showHelp; /* Update enable/disable link. */ enablelink = view.document.getElementById("enable"); if (enabled_) { enablelink.textContent = "Disable"; enablelink.onclick = function() { console.log("Disable click"); enabled_ = false; if (websocket_ != null) websocket_.close(); else websocketConnect(); /* Clear timeout and display message */ refreshUI(); } } else { enablelink.textContent = "Enable"; enablelink.onclick = function() { console.log("Enable click"); enabled_ = true; if (websocket_ == null) websocketConnect(); refreshUI(); } } /* Update debug mode according to checkbox state. */ debugcheck = view.document.getElementById("debugcheck"); debugcheck.onclick = function() { debug_ = debugcheck.checked; refreshUI(); var disps = Object.keys(kiwi_win_); for (var i = 0; i < disps.length; i++) { if (kiwi_win_[disps[i]].window) kiwi_win_[disps[i]].window.setDebug(debug_?1:0); } } debugcheck.checked = debug_; /* Update hidpi mode according to checkbox state. */ hidpicheck = view.document.getElementById("hidpicheck"); if (window.devicePixelRatio > 1) { hidpicheck.onclick = function() { hidpi_ = hidpicheck.checked; refreshUI(); var disps = Object.keys(kiwi_win_); for (var i = 0; i < disps.length; i++) { if (kiwi_win_[disps[i]].window) kiwi_win_[disps[i]].window.setHiDPI(hidpi_?1:0); } } hidpicheck.disabled = false; } else { hidpicheck.disabled = true; } hidpicheck.checked = hidpi_; /* Update status box */ view.document.getElementById("info").textContent = status_; /* Update window table */ /* FIXME: Improve UI */ windowlist = view.document.getElementById("windowlist"); while (windowlist.rows.length > 0) { windowlist.deleteRow(0); } for (var i = 0; i < windows_.length; i++) { var row = windowlist.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.className = "display"; cell1.innerHTML = windows_[i].display; cell2.className = "name"; cell2.innerHTML = windows_[i].name; cell2.onclick = (function(i) { return function() { if (active_) { websocket_.send("C" + windows_[i].display); closePopup(); } } })(i); } /* Update logger table */ loggertable = view.document.getElementById("logger"); /* FIXME: only update needed rows */ while (loggertable.rows.length > 0) { loggertable.deleteRow(0); } /* Only update if "show log" is enabled */ logcheck = view.document.getElementById("logcheck"); logcheck.onclick = function() { showlog_ = logcheck.checked; refreshUI(); } logcheck.checked = showlog_; if (showlog_) { for (var i = 0; i < logger_.length; i++) { value = logger_[i]; if (value[0] == LogLevel.DEBUG && !debug_) continue; var row = loggertable.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var levelclass = value[0]; cell1.className = "time " + levelclass; cell2.className = "value " + levelclass; cell1.innerHTML = value[1]; cell2.innerHTML = value[2]; } } } } } /* Start the extension */ function clipboardStart() { printLog("Extension started (" + chrome.runtime.getManifest().version + ")", LogLevel.INFO); setStatus("Started...", false); /* Monitor window focus changes/removals and report to croutonclip */ chrome.windows.onFocusChanged.addListener(windowFocusChanged) chrome.windows.onRemoved.addListener(windowRemoved) clipboardholder_ = document.getElementById("clipboardholder"); /* Notification event handlers */ chrome.notifications.onClosed.addListener(notificationClosed); chrome.notifications.onClicked.addListener(notificationClicked); websocketConnect(); } /* Connect to the server */ function websocketConnect() { /* Clear timeout if we were called manually. */ if (timeout_ != null) { clearTimeout(timeout_); timeout_ = null; } if (!enabled_) { setStatus("No connection (extension disabled)", false); printLog("Extension is disabled", LogLevel.INFO); return; } if (websocket_ != null) { printLog("Socket already open", LogLevel.DEBUG); return; } console.log("websocketConnect: " + websocket_); printLog("Opening a web socket", LogLevel.DEBUG); error_ = false; setStatus("Connecting...", false); websocket_ = new WebSocket(URL); websocket_.onopen = websocketOpen; websocket_.onmessage = websocketMessage; websocket_.onclose = websocketClose; } /* Connection was established */ function websocketOpen() { printLog("Connection established", LogLevel.INFO); setStatus("Connected: checking version...", false); } function readClipboard() { clipboardholder_.value = ""; clipboardholder_.select(); document.execCommand("Paste"); return clipboardholder_.value; } function writeClipboard(str) { clipboardholder_.value = str; clipboardholder_.select(); document.execCommand("Copy"); } /* Received a message from the server */ function websocketMessage(evt) { var received_msg = evt.data; var cmd = received_msg[0]; var payload = received_msg.substring(1); printLog("Message received (" + received_msg + ")", LogLevel.DEBUG); /* Only accept version packets until we have received one. */ if (!active_) { if (cmd == 'V') { /* Version */ sversion_ = payload; if (sversion_ < 1 || sversion_ > VERSION) { websocket_.send("EInvalid version (> " + VERSION + ")"); error("Invalid server version " + sversion_ + " > " + VERSION, false); } websocket_.send("VOK"); /* Set active_ to true */ setStatus(sversion_ >= 2 ? "" : "Connected", true); /* Force a window list update */ updateWindowList(true); return; } else { error("Received frame while waiting for version", false); } } switch(cmd) { case 'W': /* Write */ var clip = readClipboard(); dummystr_ = false; /* Do not erase identical clipboard content */ if (clip != payload) { /* We cannot write an empty string: Write DUMMY instead */ if (payload == "") { writeClipboard(DUMMY_EMPTYSTRING); dummystr_ = true; } else { writeClipboard(payload); } } else if (payload == DUMMY_EMPTYSTRING) { /* Unlikely case where DUMMY string comes from the other side */ writeClipboard(payload); } else { printLog("Not erasing content (identical)", LogLevel.DEBUG); } websocket_.send("WOK"); break; case 'R': /* Read */ var clip = readClipboard(); if (clip == DUMMY_EMPTYSTRING && dummystr_) { websocket_.send("R"); } else { websocket_.send("R" + clip); } break; case 'U': /* Open an URL */ /* URL must be absolute: see RFC 3986 for syntax (section 3.1) */ if (match = (/^([a-z][a-z0-9+-.]*):/i).exec(payload)) { /* FIXME: we could blacklist schemes using match[1] here */ window.open(payload, '_blank'); websocket_.send("UOK"); } else { printLog("Received invalid URL: " + payload, LogLevel.ERROR); websocket_.send("EError: URL must be absolute"); } break; case 'N': /* Raise a notification */ /* Payload in JSON format, compatible with chrome.extensions specifications */ try { var data = JSON.parse(payload); if (!data.type) data.type = "basic"; if (!data.iconUrl) data.iconUrl = "icon-128.png"; /* Strip off crouton fields */ var id = ""; var display = null; if (data.crouton_id) { id = data.crouton_id; } delete data.crouton_id; /* Set context message with chroot name/display */ delete data.contextMessage; if (data.crouton_display) { display = data.crouton_display; var win = windows_.filter(function(x) { return x.display == display })[0]; var name = win ? (win.name + " (" + display + ")") : display; data.contextMessage = "Switch to " + name; } delete data.crouton_display; chrome.notifications.create(id, data, function(id) { printLog("Raised notification " + id, LogLevel.DEBUG); notifications_[id] = function() { if (display) websocket_.send("C" + display); /* Remove the notification. */ chrome.notifications.clear(id, function(_) {}); } }); websocket_.send("NOK"); } catch(e) { printLog("Notification parsing error: " + e + " (payload: '" + payload + "').", LogLevel.ERROR); websocket_.send("EError: invalid payload."); } break; case 'C': /* Returned data from a croutoncycle command */ /* Non-zero length has a window list; otherwise it's a cycle signal */ if (payload.length > 0) { windows_ = payload.split('\n').map( function(x) { m = x.match(/^([^ *]*)\*? +(.*)$/) if (!m) return null; /* Only display cros and X11 servers (no window) */ if (m[1] != "cros" && !m[1].match(/^:([0-9]+)$/)) return null; k = new Object() k.display = m[1]; k.name = m[2]; return k; } ).filter( function(x) { return !!x; } ) windows_.forEach(function(k) { if (kiwi_win_[k.display] && kiwi_win_[k.display].window) { kiwi_win_[k.display].window.setTitle(k.name); } }) } refreshUI(); break; case 'X': /* Ask to open a crouton-in-a-tab window */ display = payload match = display.match(/^:([0-9]+)$/) displaynum = match ? match[1] : null if (!displaynum) { /* Minimize all kiwi windows */ var disps = Object.keys(kiwi_win_); for (var i = 0; i < disps.length; i++) { var winid = kiwi_win_[disps[i]].id; chrome.windows.update(winid, {focused: false}); minimize = function(win) { chrome.windows.update(winid, {'state': 'minimized'}, function(win) {})} chrome.windows.get(winid, function(win) { /* To make restore nicer, first exit full screen, * then minimize */ if (win.state == "fullscreen") { chrome.windows.update(winid, {'state': 'maximized'}, minimize) } else { minimize() } }) } } else if (kiwi_win_[display] && kiwi_win_[display].id >= 0 && (!kiwi_win_[display].window || !kiwi_win_[display].window.closing)) { /* focus/full screen an existing window */ var winid = kiwi_win_[display].id; chrome.windows.update(winid, {focused: true}); chrome.windows.get(winid, function(win) { if (win.state == "maximized") chrome.windows.update(winid, {'state': 'fullscreen'}, function(win) {}) }) } else { /* Open a new window */ kiwi_win_[display] = new Object(); kiwi_win_[display].id = -1; kiwi_win_[display].window = null; win = windows_.filter(function(x){ return x.display == display })[0] name = win ? win.name : "crouton in a tab"; chrome.windows.create({ 'url': "window.html?display=" + displaynum + "&debug=" + (debug_ ? 1 : 0) + "&hidpi=" + (hidpi_ ? 1 : 0) + "&title=" + encodeURIComponent(name), 'type': "popup" }, function(newwin) { kiwi_win_[display].id = newwin.id; focus_win_ = display; if (active_ && sversion_ >= 2) websocket_.send("Cs" + focus_win_); }); } websocket_.send("XOK"); closePopup(); /* Force a window list update */ updateWindowList(true); break; case 'P': /* Ping */ websocket_.send(received_msg); break; case 'E': error("Server error: " + payload, 1); break; default: error("Invalid packet from server: " + received_msg, 1); break; } } /* Connection was closed (or never established) */ function websocketClose() { if (websocket_ == null) { console.log("websocketClose: null!"); return; } printLog("Connection closed", active_ ? LogLevel.INFO : LogLevel.DEBUG); if (enabled_) { setStatus("Disconnected (retrying every " + RETRY_TIMEOUT + " seconds)", false); /* Retry in RETRY_TIMEOUT seconds */ if (timeout_ == null) { timeout_ = setTimeout(websocketConnect, RETRY_TIMEOUT*1000); } } else { setStatus("Disconnected (extension disabled)", false); } websocket_ = null; /* Check for update on every disconnect */ checkUpdate(false); } /* Called when window in focus changes: feeback to the extension so the * clipboard can be transfered. */ function windowFocusChanged(windowid) { var disps = Object.keys(kiwi_win_); nextfocus_win_ = "cros"; for (var i = 0; i < disps.length; i++) { if (kiwi_win_[disps[i]].id == windowid) { nextfocus_win_ = disps[i]; break; } } if (focus_win_ != nextfocus_win_) { focus_win_ = nextfocus_win_; if (active_ && sversion_ >= 2) websocket_.send("Cs" + focus_win_); printLog("Window " + focus_win_ + " focused", LogLevel.DEBUG); } } /* Called when a window is removed, so we can delete its reference. */ function windowRemoved(windowid) { var disps = Object.keys(kiwi_win_); for (var i = 0; i < disps.length; i++) { if (kiwi_win_[disps[i]].id == windowid) { kiwi_win_[disps[i]].id = -1; kiwi_win_[disps[i]].window = null; printLog("Window " + disps[i] + " removed", LogLevel.DEBUG); } } } /* Called when a notification is clicked */ function notificationClicked(id) { printLog("Notification " + id + " clicked.", LogLevel.DEBUG); if (notifications_[id]) { notifications_[id](); } } /* Called when a notification is closed */ function notificationClosed(id, byUser) { printLog("Notification " + id + " closed (byUser: " + byUser + ").", LogLevel.DEBUG); delete notifications_[id]; } function padstr0(i) { var s = i + ""; if (s.length < 2) return "0" + s; else return s; } /* Add a message in the log. */ function printLog(str, level) { date = new Date; datestr = padstr0(date.getHours()) + ":" + padstr0(date.getMinutes()) + ":" + padstr0(date.getSeconds()); if (str.length > 200) str = str.substring(0, 197) + "..."; console.log(datestr + ": " + str); /* Add messages to logger */ if (level != LogLevel.DEBUG || debug_) { logger_.unshift([level, datestr, str]); if (logger_.length > MAXLOGGERLEN) { logger_.pop(); } refreshUI(); } } /* Display an error, and prevent retries if enabled is false */ function error(str, enabled) { printLog(str, LogLevel.ERROR); enabled_ = enabled; error_ = true; refreshUI(); if (websocket != null) websocket_.close(); /* Force check for extension update (possible reason for the error) */ checkUpdate(true); } /* Open help tab on first install on Chromium OS */ chrome.runtime.onInstalled.addListener(function(details) { if (details.reason == "install") { chrome.runtime.getPlatformInfo(function(platforminfo) { if (platforminfo.os == 'cros') { showHelp(); } }); } }); /* Initialize, taking into account the platform */ chrome.runtime.getPlatformInfo(function(platforminfo) { if (platforminfo.os == 'cros') { /* On error: disconnect WebSocket, then log errors */ onerror = function(msg, url, line) { if (websocket_) websocket_.close(); error("Uncaught JS error: " + msg, false); return true; } /* Start the extension as soon as the background page is loaded */ if (document.readyState == 'complete') { clipboardStart(); } else { document.addEventListener('DOMContentLoaded', clipboardStart); } chrome.runtime.onUpdateAvailable.addListener(function(details) { updateAvailable(details.version); }); } else { /* Disable the icon on non-Chromium OS. */ chrome.browserAction.setTitle( {title: 'crouton is not available on this platform'} ); chrome.browserAction.disable(); } });
JDGBOLT/chroagh
host-ext/crouton/background.js
JavaScript
bsd-3-clause
24,630
/*! * @package ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause (see accompanying LICENSE.txt file) * * This file contains code covered by: * copyright: 2011 Simple Machines (http://www.simplemachines.org) * * @version 2.0 dev */ /** * This file contains javascript associated with the displaying statistics and the like */ /** * Stats object for expanding / collapsing the forum year/month stats section * * @param {object} oOptions */ function elk_StatsCenter(oOptions) { this.opt = oOptions; this.oTable = null; this.oYears = {}; this.bIsLoading = false; this.init(); } // Start up the stats area, current year/month expanded, all others collapsed and ready for action elk_StatsCenter.prototype.init = function () { this.oTable = document.getElementById(this.opt.sTableId); // Is the table actually present? if (typeof (this.oTable) !== 'object') { return; } // Find all months and years defined in the table. var aRows = this.oTable.getElementsByTagName('tr'), aResults = [], sYearId = null, oCurYear = null, sMonthId = null, oCurMonth = null; for (var i = 0, n = aRows.length; i < n; i++) { // Check if the current row represents a year. if ((aResults = this.opt.reYearPattern.exec(aRows[i].id)) !== null) { // The id is part of the pattern match. sYearId = aResults[1]; // Setup the object that'll have the state information of the year. this.oYears[sYearId] = { oCollapseImage: document.getElementById(this.opt.sYearImageIdPrefix + sYearId), oMonths: {} }; // Create a shortcut, makes things more readable. oCurYear = this.oYears[sYearId]; // Use the collapse image to determine the current state. oCurYear.bIsCollapsed = oCurYear.oCollapseImage.src.indexOf(this.opt.sYearImageCollapsed) >= 0; // Setup the toggle element for the year. oCurYear.oToggle = new elk_Toggle({ bToggleEnabled: true, bCurrentlyCollapsed: oCurYear.bIsCollapsed, instanceRef: this, sYearId: sYearId, funcOnBeforeCollapse: function () { this.opt.instanceRef.onBeforeCollapseYear(this); }, aSwappableContainers: [], aSwapImages: [ { sId: this.opt.sYearImageIdPrefix + sYearId, srcExpanded: elk_images_url + '/' + this.opt.sYearImageExpanded, altExpanded: '-', srcCollapsed: elk_images_url + '/' + this.opt.sYearImageCollapsed, altCollapsed: '+' } ], aSwapLinks: [ { sId: this.opt.sYearLinkIdPrefix + sYearId, msgExpanded: sYearId, msgCollapsed: sYearId } ] }); } // Or maybe the current row represents a month. else if ((aResults = this.opt.reMonthPattern.exec(aRows[i].id)) !== null) { // Set the id to the matched pattern. sMonthId = aResults[1]; // Initialize the month as a child object of the year. oCurYear.oMonths[sMonthId] = { oCollapseImage: document.getElementById(this.opt.sMonthImageIdPrefix + sMonthId) }; // Create a shortcut to the current month. oCurMonth = oCurYear.oMonths[sMonthId]; // Determine whether the month is currently collapsed or expanded.. oCurMonth.bIsCollapsed = oCurMonth.oCollapseImage.src.indexOf(this.opt.sMonthImageCollapsed) >= 0; var sLinkText = document.getElementById(this.opt.sMonthLinkIdPrefix + sMonthId).innerHTML; // Setup the toggle element for the month. oCurMonth.oToggle = new elk_Toggle({ bToggleEnabled: true, bCurrentlyCollapsed: oCurMonth.bIsCollapsed, instanceRef: this, sMonthId: sMonthId, funcOnBeforeCollapse: function () { this.opt.instanceRef.onBeforeCollapseMonth(this); }, funcOnBeforeExpand: function () { this.opt.instanceRef.onBeforeExpandMonth(this); }, aSwappableContainers: [], aSwapImages: [ { sId: this.opt.sMonthImageIdPrefix + sMonthId, srcExpanded: elk_images_url + '/' + this.opt.sMonthImageExpanded, altExpanded: '-', srcCollapsed: elk_images_url + '/' + this.opt.sMonthImageCollapsed, altCollapsed: '+' } ], aSwapLinks: [ { sId: this.opt.sMonthLinkIdPrefix + sMonthId, msgExpanded: sLinkText, msgCollapsed: sLinkText } ] }); oCurYear.oToggle.opt.aSwappableContainers[oCurYear.oToggle.opt.aSwappableContainers.length] = aRows[i].id; } // Must be a day then else if ((aResults = this.opt.reDayPattern.exec(aRows[i].id)) !== null) { oCurMonth.oToggle.opt.aSwappableContainers[oCurMonth.oToggle.opt.aSwappableContainers.length] = aRows[i].id; oCurYear.oToggle.opt.aSwappableContainers[oCurYear.oToggle.opt.aSwappableContainers.length] = aRows[i].id; } } // Collapse all collapsed years! for (i = 0; i < this.opt.aCollapsedYears.length; i++) this.oYears[this.opt.aCollapsedYears[i]].oToggle.toggle(); }; // Helper function for year collapsing, close the months first elk_StatsCenter.prototype.onBeforeCollapseYear = function (oToggle) { // Tell ElkArte that all underlying months have disappeared. for (var sMonth in this.oYears[oToggle.opt.sYearId].oMonths) if (this.oYears[oToggle.opt.sYearId].oMonths[sMonth].oToggle.opt.aSwappableContainers.length > 0) { this.oYears[oToggle.opt.sYearId].oMonths[sMonth].oToggle.changeState(true); } }; // Helper function, called before the month is collapsed elk_StatsCenter.prototype.onBeforeCollapseMonth = function (oToggle) { if (!oToggle.bCollapsed) { // Tell ElkArte that it the state has changed. getXMLDocument(elk_prepareScriptUrl(elk_scripturl) + 'action=stats;collapse=' + oToggle.opt.sMonthId + ';api=xml'); // Remove the month rows from the year toggle. var aNewContainers = [], oYearToggle = this.oYears[oToggle.opt.sMonthId.substr(0, 4)].oToggle; for (var i = 0, n = oYearToggle.opt.aSwappableContainers.length; i < n; i++) if (!in_array(oYearToggle.opt.aSwappableContainers[i], oToggle.opt.aSwappableContainers)) { aNewContainers[aNewContainers.length] = oYearToggle.opt.aSwappableContainers[i]; } oYearToggle.opt.aSwappableContainers = aNewContainers; } }; // Helper function, called before the month is expanded out, makes the ajax call to get the data elk_StatsCenter.prototype.onBeforeExpandMonth = function (oToggle) { // Ignore if we're still loading the previous batch. if (this.bIsLoading) { return; } if (oToggle.opt.aSwappableContainers.length === 0) { // Make the xml call sendXMLDocument.call(this, elk_prepareScriptUrl(elk_scripturl) + 'action=stats;expand=' + oToggle.opt.sMonthId + ';api=xml', '', this.onDocReceived); if ('ajax_indicator' in window) { ajax_indicator(true); } this.bIsLoading = true; } // Silently let ElkArte know this one is expanded. else { getXMLDocument(elk_prepareScriptUrl(elk_scripturl) + 'action=stats;expand=' + oToggle.opt.sMonthId + ';api=xml'); } }; // Callback for the xml call to get the stats information for the expanded section elk_StatsCenter.prototype.onDocReceived = function (oXMLDoc) { // Loop through all the months we got from the XML. var aMonthNodes = oXMLDoc.getElementsByTagName('month'); for (var iMonthIndex = 0, iNumMonths = aMonthNodes.length; iMonthIndex < iNumMonths; iMonthIndex++) { var sMonthId = aMonthNodes[iMonthIndex].getAttribute('id'), iStart = document.getElementById('tr_month_' + sMonthId).rowIndex + 1, sYearId = sMonthId.substr(0, 4); // Within the current months, check out all the days. var aDayNodes = aMonthNodes[iMonthIndex].getElementsByTagName('day'); for (var iDayIndex = 0, iNumDays = aDayNodes.length; iDayIndex < iNumDays; iDayIndex++) { var oCurRow = this.oTable.insertRow(iStart + iDayIndex); oCurRow.className = this.opt.sDayRowClassname; oCurRow.id = this.opt.sDayRowIdPrefix + aDayNodes[iDayIndex].getAttribute('date'); for (var iCellIndex = 0, iNumCells = this.opt.aDataCells.length; iCellIndex < iNumCells; iCellIndex++) { var oCurCell = oCurRow.insertCell(-1); if (this.opt.aDataCells[iCellIndex] === 'date') { oCurCell.style.paddingLeft = '6ex'; } else { oCurCell.style.textAlign = 'center'; } var sCurData = aDayNodes[iDayIndex].getAttribute(this.opt.aDataCells[iCellIndex]); oCurCell.appendChild(document.createTextNode(sCurData)); } // Add these day rows to the toggle objects in case of collapse. this.oYears[sYearId].oMonths[sMonthId].oToggle.opt.aSwappableContainers[this.oYears[sYearId].oMonths[sMonthId].oToggle.opt.aSwappableContainers.length] = oCurRow.id; this.oYears[sYearId].oToggle.opt.aSwappableContainers[this.oYears[sYearId].oToggle.opt.aSwappableContainers.length] = oCurRow.id; } } this.bIsLoading = false; if (typeof (window.ajax_indicator) === 'function') { ajax_indicator(false); } };
elkarte/Elkarte
themes/default/scripts/stats.js
JavaScript
bsd-3-clause
8,815
//>>built define( ({ invalidMessage: "Η τιμή που καταχωρήσατε δεν είναι έγκυρη.", missingMessage: "Η τιμή αυτή πρέπει απαραίτητα να καθοριστεί.", rangeMessage: "Η τιμή αυτή δεν ανήκει στο εύρος έγκυρων τιμών." }) );
NCIP/cabio
software/cabio-api/system/web/dijit/form/nls/el/validate.js
JavaScript
bsd-3-clause
328
require("should"); var helper = require("../../helper"); var accountDataUtil = require("../../data-util/auth/account-data-util"); var validateAccount = require("dl-models").validator.auth.account; var AccountManager = require("../../../src/managers/auth/account-manager"); var accountManager = null; var account; var roleDataUtil = require("../../data-util/auth/role-data-util"); var validateRole = require("dl-models").validator.auth.role; var RoleManager = require("../../../src/managers/auth/role-manager"); var roleManager = null; var role; before('#00. connect db', function(done) { helper.getDb() .then(db => { roleManager = new RoleManager(db, { username: 'dev' }); accountManager = new AccountManager(db, { username: 'dev' }); roleDataUtil.getNewTestData() .then(_role => { role = _role; validateRole(role); return Promise.resolve(role) }) .then((role) => { return accountDataUtil.getNewTestData(role); }) .then((_account) => { account = _account; validateAccount(account); done(); }) .catch(e => { done(e); }); }) .catch(e => { done(e); }); }); it('#01. role permissions.permission should updated when update permissions.permission', function(done) { var oldPermission = role.permissions[0]; oldPermission.permission = 0; roleManager.update(role) .then((roleId) => { return roleManager.getSingleById(roleId); }) .then((updatedRole) => { var newPermission = updatedRole.permissions[0]; oldPermission.permission.should.equal(newPermission.permission); role = updatedRole; done(); }) .catch(e => { done(e); }); }); it('#02. assigned users.role.permissions should same with role.permissions', function(done) { accountManager.getSingleById(account._id) .then((targetAccount) => { var userRole = targetAccount.roles.find((r) => r._id.toString() === role._id.toString()); userRole.should.not.equal(null); for (var rolePermission of role.permissions) { var userPermission = userRole.permissions.find((p) => p.unitId.toString() === rolePermission.unitId.toString()) userPermission.should.not.equal(null); userPermission.permission.should.equal(rolePermission.permission); } done(); }) .catch(e => { done(e); }); });
indriHutabalian/dl-module
test/auth/role/update.js
JavaScript
mit
2,841
{ return str.replace(hyphenateRE, "-$1").toLowerCase(); }
stas-vilchik/bdd-ml
data/9944.js
JavaScript
mit
60
import _extends from 'babel-runtime/helpers/extends'; import moment from 'moment'; var defaultDisabledTime = { disabledHours: function disabledHours() { return []; }, disabledMinutes: function disabledMinutes() { return []; }, disabledSeconds: function disabledSeconds() { return []; } }; export function getTodayTime(value) { var today = moment(); today.locale(value.locale()).utcOffset(value.utcOffset()); return today; } export function getTitleString(value) { return value.format('L'); } export function getTodayTimeStr(value) { var today = getTodayTime(value); return getTitleString(today); } export function getMonthName(month) { var locale = month.locale(); var localeData = month.localeData(); return localeData[locale === 'zh-cn' ? 'months' : 'monthsShort'](month); } export function syncTime(from, to) { if (!moment.isMoment(from) || !moment.isMoment(to)) return; to.hour(from.hour()); to.minute(from.minute()); to.second(from.second()); } export function getTimeConfig(value, disabledTime) { var disabledTimeConfig = disabledTime ? disabledTime(value) : {}; disabledTimeConfig = _extends({}, defaultDisabledTime, disabledTimeConfig); return disabledTimeConfig; } export function isTimeValidByConfig(value, disabledTimeConfig) { var invalidTime = false; if (value) { var hour = value.hour(); var minutes = value.minute(); var seconds = value.second(); var disabledHours = disabledTimeConfig.disabledHours(); if (disabledHours.indexOf(hour) === -1) { var disabledMinutes = disabledTimeConfig.disabledMinutes(hour); if (disabledMinutes.indexOf(minutes) === -1) { var disabledSeconds = disabledTimeConfig.disabledSeconds(hour, minutes); invalidTime = disabledSeconds.indexOf(seconds) !== -1; } else { invalidTime = true; } } else { invalidTime = true; } } return !invalidTime; } export function isTimeValid(value, disabledTime) { var disabledTimeConfig = getTimeConfig(value, disabledTime); return isTimeValidByConfig(value, disabledTimeConfig); } export function isAllowedDate(value, disabledDate, disabledTime) { if (disabledDate) { if (disabledDate(value)) { return false; } } if (disabledTime) { if (!isTimeValid(value, disabledTime)) { return false; } } return true; }
prodigalyijun/demo-by-antd
node_modules/rc-calendar/es/util/index.js
JavaScript
mit
2,378
const BaseChecker = require('./../base-checker') const ruleId = 'visibility-modifier-order' const meta = { type: 'order', docs: { description: `Visibility modifier must be first in list of modifiers.`, category: 'Style Guide Rules', examples: { good: [ { description: 'Visibility modifier placed first', code: require('../../../test/fixtures/order/visibility-modifier-first') } ], bad: [ { description: 'Visibility modifier not placed first', code: require('../../../test/fixtures/order/visibility-modifier-not-first') } ] } }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class VisibilityModifierOrderChecker extends BaseChecker { constructor(reporter, tokens) { super(reporter, ruleId, meta) this.tokens = tokens } getTokensWithoutFunctionParams(node) { const parametersCount = node.parameters.length const nodeStart = parametersCount ? node.parameters[parametersCount - 1].loc.end : node.loc.start const lastParamIndex = this.tokens.findIndex( token => token.loc.start.line === nodeStart.line && token.loc.start.column === nodeStart.column ) // discard parameters return this.tokens.slice(lastParamIndex + 1) } FunctionDefinition(node) { if (node.visibility !== 'default' && (node.stateMutability || node.modifiers.length)) { const functionTokens = [] const nodeEnd = node.loc.end const tokens = this.getTokensWithoutFunctionParams(node) for (let i = 0, n = tokens.length; i < n; ++i) { const token = tokens[i] if (functionTokens.length && token.value === '{') break const { type, loc: { start } } = token if (start.line <= nodeEnd.line && ['Keyword', 'Identifier'].includes(type)) { functionTokens.push(token) } } const visibilityIndex = functionTokens.findIndex(t => t.value === node.visibility) const stateMutabilityIndex = functionTokens.findIndex(t => t.value === node.stateMutability) const modifierIndex = node.modifiers.length ? functionTokens.findIndex(t => t.value === node.modifiers[0].name) : -1 if ( (stateMutabilityIndex > -1 && visibilityIndex > stateMutabilityIndex) || (modifierIndex > -1 && visibilityIndex > modifierIndex) ) { this._error(functionTokens[visibilityIndex]) } } } _error(node) { const message = 'Visibility modifier must be first in list of modifiers' this.error(node, message) } } module.exports = VisibilityModifierOrderChecker
protofire/solhint
lib/rules/order/visibility-modifier-order.js
JavaScript
mit
2,711
// Find all <input type="file"> elements with a data-uploadto attribute // and register an onchange handler so that any selected file is // automatically POSTED to the specified "uploadto" URL. The server's // response is ignored. whenReady(function() { // Run when the document is ready var elts = document.getElementsByTagName("input"); // All input elements for(var i = 0; i < elts.length; i++) { // Loop through them var input = elts[i]; if (input.type !== "file") continue; // Skip all but file upload elts var url = input.getAttribute("data-uploadto"); // Get upload URL if (!url) continue; // Skip any without a url input.addEventListener("change", function() { // When user selects file var file = this.files[0]; // Assume a single file selection if (!file) return; // If no file, do nothing var xhr = new XMLHttpRequest(); // Create a new request xhr.open("POST", url); // POST to the URL xhr.send(file); // Send the file as body }, false); } });
yangjunjun/examples
source-from-book/codes_of_JavaScript_the_Definitive_Guide/examples/18.09.autoUpload.js
JavaScript
mit
1,187
/*! jQuery UI - v1.10.3 - 2013-09-09 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.fi={closeText:"Sulje",prevText:"&#xAB;Edellinen",nextText:"Seuraava&#xBB;",currentText:"Tänään",monthNames:["Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu","Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu"],monthNamesShort:["Tammi","Helmi","Maalis","Huhti","Touko","Kesä","Heinä","Elo","Syys","Loka","Marras","Joulu"],dayNamesShort:["Su","Ma","Ti","Ke","To","Pe","La"],dayNames:["Sunnuntai","Maanantai","Tiistai","Keskiviikko","Torstai","Perjantai","Lauantai"],dayNamesMin:["Su","Ma","Ti","Ke","To","Pe","La"],weekHeader:"Vk",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.fi)});
hillst/spirobase
web/includes/jquery-ui-1.10.3.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-fi.min.js
JavaScript
mit
872
import { ArrayTests } from 'ember-runtime/tests/suites/array'; import insertAtTests from 'ember-runtime/tests/suites/mutable_array/insertAt'; import popObjectTests from 'ember-runtime/tests/suites/mutable_array/popObject'; import pushObjectTests from 'ember-runtime/tests/suites/mutable_array/pushObject'; import pushObjectsTest from 'ember-runtime/tests/suites/mutable_array/pushObjects'; import removeAtTests from 'ember-runtime/tests/suites/mutable_array/removeAt'; import replaceTests from 'ember-runtime/tests/suites/mutable_array/replace'; import shiftObjectTests from 'ember-runtime/tests/suites/mutable_array/shiftObject'; import unshiftObjectTests from 'ember-runtime/tests/suites/mutable_array/unshiftObject'; import reverseObjectsTests from 'ember-runtime/tests/suites/mutable_array/reverseObjects'; const MutableArrayTests = ArrayTests.extend(); MutableArrayTests.importModuleTests(insertAtTests); MutableArrayTests.importModuleTests(popObjectTests); MutableArrayTests.importModuleTests(pushObjectTests); MutableArrayTests.importModuleTests(pushObjectsTest); MutableArrayTests.importModuleTests(removeAtTests); MutableArrayTests.importModuleTests(replaceTests); MutableArrayTests.importModuleTests(shiftObjectTests); MutableArrayTests.importModuleTests(unshiftObjectTests); MutableArrayTests.importModuleTests(reverseObjectsTests); export default MutableArrayTests;
vikram7/ember.js
packages/ember-runtime/tests/suites/mutable_array.js
JavaScript
mit
1,381
'use strict'; describe('Controller: LoginCtrl', function () { // load the controller's module beforeEach(module('quiverInvoiceApp')); var LoginCtrl, scope, q, generic = function () { var deferred = q.defer(); deferred.resolve(arguments); return deferred.promise; }; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope, $q) { q = $q; scope = $rootScope.$new(); LoginCtrl = $controller('LoginCtrl', { $scope: scope, userService: { logIn: generic, create: generic, reset: generic }, notificationService: { success: generic, error: generic }, $state: { go: generic } }); })); var user = {email: 'test@quiver.is', password: 'user'}; it('should call userService.logIn', inject(function ($timeout) { var result; scope.logIn(user).then(function (res) { result = res; }); $timeout.flush(); expect(result[0]).toEqual(user); })); it('should call userService.create', inject(function ($timeout) { var result; scope.create(user).then(function (res) { result = res; }); $timeout.flush(); expect(result[0]).toEqual(user); })); it('should call userService.reset', inject(function ($timeout) { var result; scope.resetPassword(user).then(function (res) { result = res; }); $timeout.flush(); expect(result[0]).toEqual(user.email); })); });
deltaepsilon/quiver-invoice
test/spec/controllers/Login.js
JavaScript
mit
1,521
export const Types = { Startup: 'Startup' } export const Actions = { startup: () => ({ type: Types.Startup }) }
rmevans9/reactotron
packages/demo-react-native/App/Redux/StartupRedux.js
JavaScript
mit
117
'use strict'; angular.module('ngQuantum.modalBox', ['ngQuantum.modal']) .provider('$modalBox', function () { var defaults = this.defaults = { effect: 'slit', boxType: 'alert', typeClass: 'modalbox', instanceName: 'modal', prefixEvent: 'modalbox', directive: 'nqModalBox', placement: 'near-top', uniqueId: 'nq-modalbox', trigger: 'click', okText: 'OK', cancelText: 'Cancel', confirmText: 'Confirm', template:false, showIcon: true, promptModel: '$promptValue', alertTemplate: 'modalbox/alertbox.tpl.html', confirmTemplate: 'modalbox/confirmbox.tpl.html', promptTemplate: 'modalbox/promptbox.tpl.html' }; this.$get = ['$modal', '$parse', '$helpers', function ($modal, $parse, $helpers) { function ModalBoxFactory(config, attr) { findTemplate() var $modalBox = {}, element = config.element, $buttons; var options = angular.extend({}, defaults, config); attr && angular.forEach(['afterOk', 'afterConfirm', 'afterCancel', 'afterCustom'], function (key) { if (angular.isDefined(attr[key])) { options[key] = $parse(attr[key]); } }) $modalBox = new $modal(options, attr); options = config = $modalBox.$options; var scope = $modalBox.$scope angular.forEach(['okText', 'cancelText', 'confirmText', 'promptLabel'], function (key) { scope[key] = options[key] }) var init = $modalBox.init; $modalBox.init = function () { init(); if (!options.showIcon) { $modalBox.$target.addClass('no-icon') } }; var show = $modalBox.show; $modalBox.show = function () { if (options.boxType == 'prompt') scope.promptModel = ''; var promise = show(); if ($buttons) $buttons.on('click', $modalBox.hide); return promise; }; var hide = $modalBox.hide; $modalBox.hide = function () { if (angular.isFunction(options.afterOk) && !$buttons) { options.afterOk(scope) } if ($buttons) { if (angular.isFunction(options.afterCustom)) options.afterCustom(scope) $buttons.off('click', $modalBox.hide) } return hide(); }; var footerCheck = $modalBox.footerCheck; $modalBox.footerCheck = function () { footerCheck(arguments); if ($modalBox.customFooter && $modalBox.customFooter.length) $buttons = $modalBox.customFooter.find('button'); }; scope.$confirm = function () { scope.$$postDigest(function () { $modalBox.hide(); if (angular.isFunction(options.afterConfirm)) { scope.$parent.$apply(function () { if (options.boxType == 'prompt') scope.$parent[options.promptModel] = scope.promptModel; }) options.afterConfirm(scope); } }); } scope.$cancel = function () { scope.$$postDigest(function () { $modalBox.hide(); if (angular.isFunction(options.afterCancel)) { options.afterCancel(scope) } }); } scope.$on('$destroy', function () { $modalBox && !$modalBox.isDestroyed && $modalBox.destroy(); $modalBox = null; }); function findTemplate() { switch (config.boxType) { case 'alert': config.template = config.alertTemplate || defaults.alertTemplate break; case 'confirm': config.template = config.confirmTemplate || defaults.confirmTemplate break; case 'prompt': config.template = config.promptTemplate || defaults.promptTemplate break; default: config.template = config.template || defaults.alertTemplate break; } } return $modalBox; } return ModalBoxFactory; } ]; }) .directive('nqModalBox', ['$modalBox','$helpers', function ($modalBox, $helpers) { return { restrict: 'EAC', scope:true, link: function postLink(scope, element, attr, transclusion) { var options = { $scope: scope }; angular.forEach(['boxType', 'promptLabel', 'promptModel', 'alertTemplate', 'confirmTemplate', 'promptTemplate', 'showIcon', 'okText', 'cancelText', 'confirmText'], function (key) { if (angular.isDefined(attr[key])) options[key] = $helpers.parseConstant(attr[key]); }) options.uniqueId = attr.uniqueId || attr.id || scope.$id; options.element = element; var modalBox = {} if (angular.isDefined(attr.contentTarget)) { var content = angular.element(attr.contentTarget) if (!content.length) { content = angular.element('<span><span class="label label-warning">Warning :</span> No content element find</span>') } options.htmlObject = true; options.buildOnShow = false; scope.content = content; modalBox =new $modalBox(options, attr); } else { options.element = element; options.html = true; modalBox =new $modalBox(options, attr); } scope.$on('$destroy', function () { modalBox = null; }) element.data('$nqModalBox', modalBox) } }; } ])
nagyistoce/quantumui
src/components/modalbox.js
JavaScript
mit
7,811
(function() { 'use strict'; angular .module('lumx.ripple') .directive('lxRipple', lxRipple); lxRipple.$inject = ['$timeout']; function lxRipple($timeout) { return { restrict: 'A', link: link, }; function link(scope, element, attrs) { var timer; element .css( { position: 'relative', overflow: 'hidden' }) .on('mousedown', function(e) { var ripple; if (element.find('.ripple').length === 0) { ripple = angular.element('<span/>', { class: 'ripple' }); if (attrs.lxRipple) { ripple.addClass('bgc-' + attrs.lxRipple); } element.prepend(ripple); } else { ripple = element.find('.ripple'); } ripple.removeClass('ripple--is-animated'); if (!ripple.height() && !ripple.width()) { var diameter = Math.max(element.outerWidth(), element.outerHeight()); ripple.css( { height: diameter, width: diameter }); } var x = e.pageX - element.offset().left - ripple.width() / 2; var y = e.pageY - element.offset().top - ripple.height() / 2; ripple.css( { top: y + 'px', left: x + 'px' }).addClass('ripple--is-animated'); timer = $timeout(function() { ripple.removeClass('ripple--is-animated'); }, 651); }); scope.$on('$destroy', function() { $timeout.cancel(timer); element.off(); }); } } })();
jefvel/lumX
modules/ripple/js/ripple_directive.js
JavaScript
mit
2,372
function RowConfigController($scope) { $scope.currentRow = $scope.model.currentRow; $scope.editors = $scope.model.editors; $scope.columns = $scope.model.columns; $scope.scaleUp = function(section, max, overflow) { var add = 1; if (overflow !== true) { add = (max > 1) ? 1 : max; } //var add = (max > 1) ? 1 : max; section.grid = section.grid + add; }; $scope.scaleDown = function(section) { var remove = (section.grid > 1) ? 1 : section.grid; section.grid = section.grid - remove; }; $scope.percentage = function(spans) { return ((spans / $scope.columns) * 100).toFixed(8); }; $scope.toggleCollection = function(collection, toggle) { if (toggle) { collection = []; } else { delete collection; } }; /**************** area *****************/ $scope.configureCell = function(cell, row) { if ($scope.currentCell && $scope.currentCell === cell) { delete $scope.currentCell; } else { if (cell === undefined) { var available = $scope.availableRowSpace; var space = 4; if (available < 4 && available > 0) { space = available; } cell = { grid: space }; row.areas.push(cell); } $scope.currentCell = cell; } }; $scope.deleteArea = function(index) { $scope.currentRow.areas.splice(index, 1); }; $scope.closeArea = function() { $scope.currentCell = undefined; }; $scope.nameChanged = false; var originalName = $scope.currentRow.name; $scope.$watch("currentRow", function(row) { if (row) { var total = 0; _.forEach(row.areas, function(area) { total = (total + area.grid); }); $scope.availableRowSpace = $scope.columns - total; if (originalName) { if (originalName != row.name) { $scope.nameChanged = true; } else { $scope.nameChanged = false; } } } }, true); } angular.module("umbraco").controller("Umbraco.PropertyEditors.GridPrevalueEditor.RowConfigController", RowConfigController);
neilgaietto/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/dialogs/rowconfig.controller.js
JavaScript
mit
2,477
((function(){ var rainbow = this.MooRainbow = new Class({ Implements: [Options, Events], options: { data: 'moorainbow', startColor: '#f00', transparency: 1, activeForm: 'hsb', forms: { 'rgb': ['red', 'green', 'blue'], 'hsb': ['hue', 'saturation', 'brightness'] }, defaults: { relative: null, position: 'right', offset: {x: 10, y: 0} }, onChange: function(sets, element){ if (!element) return; var trigger; if (element.get('data-moorainbow-trigger')) { trigger = element; element = document.id(element.get('data-moorainbow-trigger')); } else { trigger = document.getElements('[data-moorainbow-trigger='+element.get('id')+']'); } element.set('value', this.sets.hex); if (this.sets.hex != 'transparent') trigger.getElement('.overlay').removeClass('overlay-transparent'); trigger.getElement('.overlay').setStyle('backgroundColor', this.sets.hex); }, onComplete: function(){} }, initialize: function(options){ this.setOptions(options); this.data = 'data-' + this.options.data; this.sets = {rgb: [], hsb: [], hex: ''}; this.coords = {overlay: {x: 0, y: 0}, slider: 0}; this.offsets = {overlay: 0, slider: 0}; if (!this.layout) this.build(); this.attach(); this.setColor(this.options.startColor.hexToRgb().rgbToHsb(), 'force'); this.hide(); }, attach: function(){ var buttonType = this.layout.retrieve('moor:buttontype:click', function(event, element){ this.buttonTypeClick.call(this, event, element); }.bind(this)), trigger = this.layout.retrieve('moor:trigger:click', function(event, element){ this.toggle.call(this, event, element); }.bind(this)), smartToggle = document.retrieve('moor:smarttoggle:click', function(event, element){ this.smartToggle.call(this, event, element); }.bind(this)), overlayMouseDown = this.layout.retrieve('moor:overlay:mousedown', function(event, element){ this.overlayMouseDown.call(this, event, element); }.bind(this)), sliderMouseDown = this.layout.retrieve('moor:slider:mousedown', function(event, element){ this.sliderMouseDown.call(this, event, element); }.bind(this)), backupColor = this.layout.retrieve('moor:backupcolor:click', function(event, element){ var color = element.retrieve('moor:backup:color', this.options.startColor); if (color != 'transparent') this.setColor.call(this, color, 'force'); else this.triggerTransparent.call(this, event, element); }.bind(this)), elementKeyup = this.layout.retrieve('moor:element:keyup', function(event, element){ this.keyup.call(this, event, element); }.bind(this)); this.layout.addEvents({ 'click:relay([data-moorainbow-button-type])': buttonType, 'click:relay(.moor-colorsbox-selected)': backupColor, 'keyup:relay([data-moorainbow-input] input)': elementKeyup, 'mousedown:relay([data-moorainbow-overlay])': overlayMouseDown, 'mousedown:relay([data-moorainbow-slider])': sliderMouseDown }); document.addEvents({ 'mousedown:relay([data-moorainbow-trigger])': trigger, 'focus:relay([data-moorainbow])': trigger, 'keyup:relay([data-moorainbow])': elementKeyup }); if (!document.retrieve('moor:document:events')){ document.addEvent('click', smartToggle); document.store('moor:document:events', true); } this.attachDrag(); }, attachDrag: function(){ var overlay = this.layout.getElement('[data-moorainbow-overlay]'), slider = this.layout.getElement('[data-moorainbow-slider]'), overlaySize = overlay.getComputedSize(), sliderSize = slider.getComputedSize(), events; this.overlayDragInstance = new Drag(this.overlayCursor, { limit: { x: [0 - this.offsets.overlay, overlaySize.width - this.offsets.overlay], y: [0 - this.offsets.overlay, overlaySize.height - this.offsets.overlay] }, //onBeforeStart: this.overlayDrag.bind(this), //onStart: this.overlayDrag.bind(this), //onDrag: this.overlayDrag.bind(this), snap: 0 }); this.sliderDragInstance = new Drag(this.sliderCursor, { limit: { y: [0 - this.offsets.slider, sliderSize.height - this.offsets.slider] }, modifiers: {x: false}, //onBeforeStart: this.sliderDrag.bind(this), //onStart: this.sliderDrag.bind(this), //onDrag: this.sliderDrag.bind(this), snap: 0 }); events = { onBeforeStart: this.setColor.bind(this), onStart: this.setColor.bind(this), onDrag: this.setColor.bind(this) }; this.overlayDragInstance.addEvents(events); this.sliderDragInstance.addEvents(events); }, overlayMouseDown: function(event, element){ var overlay = this.layout.getElement('[data-moorainbow-overlay]'), overlayPosition = overlay.getPosition(), overlayBorders = { x: overlay.getStyle('border-left').toInt() + overlay.getStyle('border-right').toInt(), y: overlay.getStyle('border-top').toInt() + overlay.getStyle('border-bottom').toInt() }; this.overlayCursor.style.left = event.page.x - overlayPosition.x - this.offsets.overlay - overlayBorders.x + 'px'; this.overlayCursor.style.top = event.page.y - overlayPosition.y - this.offsets.overlay - overlayBorders.y + 'px'; this.overlayDragInstance.start(event); }, sliderMouseDown: function(event, element){ var slider = this.layout.getElement('[data-moorainbow-slider]'), sliderPosition = slider.getPosition().y; sliderBorders = slider.getStyle('border-top').toInt() + slider.getStyle('border-bottom').toInt() this.sliderCursor.style.top = event.page.y - sliderPosition - this.offsets.slider - sliderBorders + 'px'; this.sliderDragInstance.start(event); }, toggle: function(event, element){ var color = null, activeTrigger = this.active ? this.active.get('data-moorainbow-trigger') : null, elementTrigger = element.get('data-moorainbow-trigger'); if (this.isShown && this.active == element) return; if (this.isShown && activeTrigger && activeTrigger == element.get('id')) return; if (this.isShown && this.active && elementTrigger && elementTrigger == this.active.get('id')) return; this.active = element; this.show(); if (!element.get('data-moorainbow-trigger') && document.getElement('[data-moorainbow-trigger=' + element.get('id') + ']')){ color = element.get('value'); element = document.getElement('[data-moorainbow-trigger=' + element.get('id') + ']'); } if (!color) color = document.id(element.get('data-moorainbow-trigger')).get('value'); this.backupColor.setStyle('background-color', color).store('moor:backup:color', color); this.reposition({relative: element}); if (color != 'transparent') this.setColor(color, 'force'); }, smartToggle: function(event, element){ if (event){ var target = event.target; if (target.get('data-moorainbow') !== null || target.get('data-moorainbow-trigger') !== null || target.get('data-moorainbow-layout') !== null || target.getParent('[data-moorainbow]') || target.getParent('[data-moorainbow-trigger]') || target.getParent('[data-moorainbow-layout]')) return; else this.hide(); } }, reposition: function(options){ var element, position, offset, axis = {x: 0, y: 0}, defaults = this.options.defaults; defaults = Object.merge(defaults, options); element = defaults.relative; position = defaults.position; offset = defaults.offset; if (!element) return; switch(position){ case 'left': axis.x = 0 - this.layout.getSize().x; offset.x *= -1; break; case 'right': axis.x = element.getSize().x; offset.x *= 1; break; case 'top': axis.y = 0 - this.layout.getSize().y; offset.x *= -1; break; case 'bottom': axis.y = element.getSize().y; offset.x *= 1; break; } this.layout.style.left = element.getPosition().x + axis.x + offset.x + 'px'; this.layout.style.top = element.getPosition().y + axis.y + offset.y + 'px'; }, setColor: function(color, updateCursors){ var isSlider, hue, type = 'hsb'; if (typeOf(color) == 'element'){ if (color.hasClass('moor-slider-cursor')) isSlider = true; color = this._getHSB(); } if (!color) color = this._getHSB(); if (color[0] == '#'){ type = 'rgb'; color = color.hexToRgb(true); } if (updateCursors) this._updateCursors(color, type); this.updateData(color, type); }, updateData: function(color, type){ type = type || 'hsb'; var input, hue, hsb, rgb, hex, data; switch(type){ case 'rgb': rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); break; case 'hsb': hsb = color || this._getHSB(); rgb = hsb.hsbToRgb(true); hex = this._hsbToHex(hsb); } data = { red: rgb[0], green: rgb[1], blue: rgb[2], hue: hsb[0], saturation: hsb[1], brightness: hsb[2], hex: hex }; this.sets = {rgb: rgb, hsb: hsb, hex: hex}; if (Color.prototype.toHsv){ hue = new Color({h: hsb[0], s: 100, v: 100}).toString(); } else { hue = new Color([this.sets.hsb[0], 100, 100]).hsbToRgb(true); } ['red', 'green', 'blue', 'hue', 'saturation', 'brightness', 'hex'].each(function(set, i){ input = this.layout.getElement('[data-moorainbow-input-'+set+']'); input.set('value', data[set]); }, this); this.selectedColor.setStyle('backgroundColor', this.sets.hex); this.layout.getElement('[data-moorainbow-overlay]').setStyle('backgroundColor', hue); this.fireEvent('onChange', [this.sets, this.active], 1); }, hide: function(){ this.layout.setStyles({display: 'none', visibility: 'hidden'}); this.isShown = false; }, show: function(){ this.layout.setStyles({display: 'block', visibility: 'visible'}); this.isShown = true; }, keyup: function(event, element){ var parent, data, dataKey, dataElement, dataColor = [], match = element.value.match(/^(#[a-f0-9]{6}|[0-9]{1,3})$/ig), color; if (!match) return; parent = element.getParent('[data-moorainbow-input]:not([data-moorainbow-input=hex])'); if (!this._validateData(event, element) && null === element.get('data-moorainbow')) return false; color = match[0]; if (parent){ data = parent.get('data-moorainbow-input'); Object.each(this.options.forms, function(value, key){ if (value.contains(data)) dataKey = key; }, this); } if (dataKey){ this.options.forms[dataKey].each(function(type){ dataElement = this.layout.getElement('[data-moorainbow-input-' + type + ']'); dataColor.push(dataElement.get('value').toInt()); }, this); if (dataKey == 'rgb') color = dataColor.rgbToHex(); else color = dataColor; } this.setColor(color, 'force'); }, build: function(){ var input, label, suffix; var layout = new Element('div.moor-layout[data-moorainbow-layout]').inject(document.body), colorwheel = new Element('div.moor-overlay[data-moorainbow-overlay]').adopt( new Element('div.moor-overlay-white'), new Element('div.moor-overlay-black'), new Element('div.moor-overlay-cursor') ).inject(layout), sliderwheel = new Element('div.moor-slider[data-moorainbow-slider]').adopt( new Element('div.moor-slider-colors'), new Element('div.moor-slider-cursor') ).inject(layout), colorsbox = new Element('div.moor-colorsbox[data-moorainbow-colorsbox]').adopt( new Element('div.moor-colorsbox-current'), new Element('div.moor-colorsbox-selected') ).inject(layout), inputs = new Element('div.moor-inputs').inject(layout), buttons = new Element('div.moor-buttons').inject(layout), indicator = new Element('span.rt-arrow').inject(layout); ['red', 'green', 'blue', 'hue', 'saturation', 'brightness', 'hex'].each(function(type){ label = (type != 'hex') ? type[0].capitalize() : '# ' + type; suffix = ['saturation', 'brightness'].contains(type) ? '%' : (type == 'hue') ? '&deg;' : ''; input = new Element('div.moor-inputs-block.moor-inputs-' + type + '[data-moorainbow-input=' + type + ']').adopt( new Element('span', {html: label}), new Element('input[data-moorainbow-input-' + type + ']') ); if (suffix) input.adopt(new Element('span', {html: suffix})); inputs.adopt(input); }); ['close', 'transparent', 'RGB', 'HSB'].each(function(button){ label = button == 'close' ? '&times;' : button == 'transparent' ? '' : button; new Element('div.moor-button.moor-button-' + button.toLowerCase() + '[data-moorainbow-button-type=' + button.toLowerCase() + ']', {html: label}).inject(buttons); }); // offsets this.overlayCursor = colorwheel.getElement('.moor-overlay-cursor'); this.sliderCursor = sliderwheel.getElement('.moor-slider-cursor'); // selected / backup colors this.selectedColor = layout.getElement('div.moor-colorsbox-current'); this.backupColor = layout.getElement('div.moor-colorsbox-selected'); this.offsets = { overlay: this.overlayCursor.getSize().x / 2, slider: this.sliderCursor.getSize().y / 2 }; this.layout = layout; this.buttonTypeClick.call(this); }, buttonTypeClick: function(event, element){ var type = element ? element.get('data-moorainbow-button-type') || this.options.activeForm : this.options.activeForm; if (!this.options.forms[type]){ var method = this['trigger' + type.capitalize()]; return method ? method.call(this, event, element) : false; } Object.each(this.options.forms, function(inputs, key){ if (key == type){ this.layout.getElement('[data-moorainbow-button-type=' + key + ']').addClass('moor-button-active'); inputs.each(function(input){ this.layout.getElement('[data-moorainbow-input=' + input + ']').addClass('moor-inputs-block-active'); }, this); } else { this.layout.getElement('[data-moorainbow-button-type=' + key + ']').removeClass('moor-button-active'); inputs.each(function(input){ this.layout.getElement('[data-moorainbow-input=' + input + ']').removeClass('moor-inputs-block-active'); }, this); } }, this); }, triggerClose: function(event, element){ this.hide(); }, triggerTransparent: function(event, element){ element = this.active; if (!element) return; var trigger, value = 'transparent'; if (element.get('data-moorainbow-trigger')) { trigger = element; element = document.id(element.get('data-moorainbow-trigger')); } else { trigger = document.getElements('[data-moorainbow-trigger='+element.get('id')+']'); } element.set('value', value); trigger.getElement('.overlay').addClass('overlay-' + value).setStyle('backgroundColor', value); this.hide(); }, _hsbToHex: function(hsb){ hsb = hsb || this._getHSB(); var toRgb = hsb.hsbToRgb() || hsb.toRgb(), toHex = toRgb.rgbToHex() || toRgb.toString(); return toHex; }, _hexToHsb: function(hex){ return hex.hexToRgb().rgbToHsb(); }, _getHSB: function(){ var coords = this._getCoordinates(), overlayElement = this.layout.getElement('[data-moorainbow-overlay]'), sliderElement = this.layout.getElement('[data-moorainbow-slider]'), overlaySize = overlayElement.getComputedSize(), sliderSize = sliderElement.getComputedSize(); var s = Math.round((coords.overlay.x * 100) / overlaySize.width), b = 100 - Math.round((coords.overlay.y * 100) / overlaySize.height), h = 360 - Math.round((coords.slider.y * 360) / sliderSize.height); h = (h >= 360) ? 0 : (h < 0) ? 0 : h; s = (s > 100) ? 100 : (s < 0) ? 0 : s; b = (b > 100) ? 100 : (b < 0) ? 0 : b; return [h, s, b]; }, _updateCursors: function(hsb, type){ var overlayCursor = this.overlayCursor, sliderCursor = this.sliderCursor, overlayElement = this.layout.getElement('[data-moorainbow-overlay]'), sliderElement = this.layout.getElement('[data-moorainbow-slider]'), overlaySize = overlayElement.getComputedSize(), sliderSize = sliderElement.getComputedSize(); if (type == 'rgb') hsb = hsb.rgbToHsb(); var coordinates = { x: Math.round(((overlaySize.width * hsb[1]) / 100) - this.offsets.overlay), y: Math.round(- ((overlaySize.height * hsb[2]) / 100) + overlaySize.height - this.offsets.overlay), z: Math.round((sliderSize.height * hsb[0]) / 360) }; if (coordinates.z == 360) coordinates.z = 0; coordinates.z = sliderSize.height - coordinates.z - this.offsets.slider; //sliH - c + this.snippet('slider') - arwH; overlayCursor.style.top = coordinates.y + 'px'; overlayCursor.style.left = coordinates.x + 'px'; sliderCursor.style.top = coordinates.z + 'px'; }, _getCoordinates: function(){ var overlayCursor = this.overlayCursor, sliderCursor = this.sliderCursor, overlayElement = this.layout.getElement('[data-moorainbow-overlay]'), sliderElement = this.layout.getElement('[data-moorainbow-slider]'); return { overlay: { x: overlayCursor.getPosition(overlayElement).x + this.offsets.overlay, y: overlayCursor.getPosition(overlayElement).y + this.offsets.overlay }, slider: { y: sliderCursor.getPosition(sliderElement).y + this.offsets.slider } }; }, _validateData: function(event, element){ var parent = element.getParent('[data-moorainbow-input]'), value = element.get('value'), data; if (!parent) return false; data = parent.get('data-moorainbow-input'); switch(data){ case 'hue': if (!value.match(/^[0-9]{1,3}$/) || value.toInt() >= 360){ element.set('value', 0); return true; } break; case 'saturation': case 'brightness': if (!value.match(/^[0-9]{1,3}$/) || value.toInt() > 100){ element.set('value', 100); return true; } break; case 'red': case 'green': case 'blue': if (!value.match(/^[0-9]{1,3}$/) || value.toInt() > 255){ element.set('value', 0); return true; } break; } return true; } }); window.addEvent('domready', function(){ this.moorainbow = new MooRainbow(); }); })());
Dwightgnjohnson/corcoranpruett.com
wp-content/themes/gantry/admin/widgets/colorchooser/js/mooRainbow-2.0.js
JavaScript
gpl-2.0
18,068
jQuery(function($) { $('div.inline-group').sortable({ /*containment: 'parent', zindex: 10, */ items: 'div.inline-related', handle: 'h3:first', update: function() { $(this).find('div.inline-related').each(function(i) { if ($(this).find('input[id$=id]').val()) { $(this).find('input[id$=order]').val(i+1); } }); } }); $('div.inline-related h3').css('cursor', 'move'); $('div.inline-related').find('input[id$=order]').parent('div').hide(); });
alirizakeles/tendenci
tendenci/apps/base/static/js/admin/sortable_inline/stacked-sort.js
JavaScript
gpl-3.0
581
// Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor // tutao: a = bitlength (1024) // b = number of miller rabin test * 2 // c = SecureRandom function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<<dbits)-1); BigInteger.prototype.DV = (1<<dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2,BI_FP); BigInteger.prototype.F1 = BI_FP-dbits; BigInteger.prototype.F2 = 2*dbits-BI_FP; // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; var BI_RC = new Array(); var rr,vv; rr = "0".charCodeAt(0); for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; rr = "a".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; rr = "A".charCodeAt(0); for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; function int2char(n) { return BI_RM.charAt(n); } function intAt(s,i) { var c = BI_RC[s.charCodeAt(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpCopyTo(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh; this[this.t++] = (x>>(this.DB-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh; } this.clamp(); if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) clamp off excess high words function bnpClamp() { var c = this.s&this.DM; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1<<k)-1, d, m = false, r = "", i = this.t; var p = this.DB-(i*this.DB)%k; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<cbs)-1; var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpSubTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlShiftTo(j,t); if(r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1<<i)) > 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0]; } // (public) return value as byte function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor // tutao: on first invocation: // a = bitlength (1024) // b = number of miller rabin test * 2 // c = SecureRandom // on second invocation: // a = bitlength (1024) // b = SecureRandom // c == undefined function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; this.fromString(x,256); } } // (public) convert to bigendian byte array function bnToByteArray() { var i = this.t, r = new Array(); r[0] = this.s; var p = this.DB-(i*this.DB)%8, d, k = 0; if(i-- > 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<<p)-1))<<(8-p); d |= this[--i]>>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<<n) function bnpChangeBit(n,op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r,op,r); return r; } // (public) this | (1<<n) function bnSetBit(n) { return this.changeBit(n,op_or); } // (public) this & ~(1<<n) function bnClearBit(n) { return this.changeBit(n,op_andnot); } // (public) this ^ (1<<n) function bnFlipBit(n) { return this.changeBit(n,op_xor); } // (protected) r = this + a function bnpAddTo(a,r) { var i = 0, c = 0, m = Math.min(a.t,this.t); while(i < m) { c += this[i]+a[i]; r[i++] = c&this.DM; c >>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { // we switched to leemons bigint lib for modpow, as this is faster on safari browsers (reduced the decryption times: 9s -> 3,4s) // TODO introduce switch for other browsers, as they are slower (by factor 0.5) because of the conversion overhead var xHex = this.toString(16); var eHex = e.toString(16); var mHex = m.toString(16); var result = powMod(str2bigInt(xHex,16),str2bigInt(eHex,16),str2bigInt(mHex,16)); return new BigInteger(bigInt2str(result,16),16); // var i = e.bitLength(), k, r = nbv(1), z; // if(i <= 0) return r; // else if(i < 18) k = 1; // else if(i < 48) k = 3; // else if(i < 144) k = 4; // else if(i < 768) k = 5; // else k = 6; // if(i < 8) // z = new Classic(m); // else if(m.isEven()) // z = new Barrett(m); // else // z = new Montgomery(m); // // // precomputation // var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1; // g[1] = z.convert(this); // if(k > 1) { // var g2 = nbi(); // z.sqrTo(g[1],g2); // while(n <= km) { // g[n] = nbi(); // z.mulTo(g2,g[n-2],g[n]); // n += 2; // } // } // // var j = e.t-1, w, is1 = true, r2 = nbi(), t; // i = nbits(e[j])-1; // while(j >= 0) { // if(i >= k1) w = (e[j]>>(i-k1))&km; // else { // w = (e[j]&((1<<(i+1))-1))<<(k1-i); // if(j > 0) w |= e[j-1]>>(this.DB+i-k1); // } // // n = k; // while((w&1) == 0) { w >>= 1; --n; } // if((i -= n) < 0) { i += this.DB; --j; } // if(is1) { // ret == 1, don't bother squaring or multiplying it // g[w].copyTo(r); // is1 = false; // } // else { // while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } // if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } // z.mulTo(r2,g[w],r); // } // // while(j >= 0 && (e[j]&(1<<i)) == 0) { // z.sqrTo(r,r2); t = r; r = r2; r2 = t; // if(--i < 0) { i = this.DB-1; --j; } // } // } // return z.revert(r); } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s<0)?this.negate():this.clone(); var y = (a.s<0)?a.negate():a.clone(); if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(), g = y.getLowestSetBit(); if(g < 0) return x; if(i < g) g = i; if(g > 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 // TUTAO: It is fine to use Math.random() instead secure random here because it is only used for checking if the number is a prime. The number itself is generated with the secure random number generator. a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Depends on jsbn.js and rng.js // Version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object function parseBigInt(str,r) { return new BigInteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2Hex(b) { if(b < 0x10) return "0" + b.toString(16); else return b.toString(16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { // TODO: fix for utf-8 alert("Message too long for RSA"); return null; } var ba = new Array(); var i = s.length - 1; while(i >= 0 && n > 0) { var c = s.charCodeAt(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new SecureRandom(); var x = new Array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextBytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // Set the public key fields N and e from hex strings function RSASetPublic(N,E) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); } else alert("Invalid RSA public key"); } // Perform raw public operation on "x": return x^e (mod n) function RSADoPublic(x) { return x.modPowInt(this.e, this.n); } // Return the PKCS#1 RSA encryption of "text" as an even-length hex string function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string //function RSAEncryptB64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; //} // protected RSAKey.prototype.doPublic = RSADoPublic; // public RSAKey.prototype.setPublic = RSASetPublic; RSAKey.prototype.encrypt = RSAEncrypt; //RSAKey.prototype.encrypt_b64 = RSAEncryptB64; // Depends on rsa.js and jsbn2.js // Version 1.1: support utf-8 decoding in pkcs1unpad2 // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext function pkcs1unpad2(d,n) { var b = d.toByteArray(); var i = 0; while(i < b.length && b[i] == 0) ++i; if(b.length-i != n-1 || b[i] != 2) return null; ++i; while(b[i] != 0) if(++i >= b.length) return null; var ret = ""; while(++i < b.length) { var c = b[i] & 255; if(c < 128) { // utf-8 decode ret += String.fromCharCode(c); } else if((c > 191) && (c < 224)) { ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63)); ++i; } else { ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63)); i += 2; } } return ret; } // Set the private key fields N, e, and d from hex strings function RSASetPrivate(N,E,D) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); this.d = parseBigInt(D,16); } else alert("Invalid RSA private key"); } // Set the private key fields N, e, d and CRT params from hex strings function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); this.d = parseBigInt(D,16); this.p = parseBigInt(P,16); this.q = parseBigInt(Q,16); this.dmp1 = parseBigInt(DP,16); this.dmq1 = parseBigInt(DQ,16); this.coeff = parseBigInt(C,16); } else alert("Invalid RSA private key"); } // Generate a new random private key B bits long, using public expt E function RSAGenerate(B,E) { var rng = new SecureRandom(); var qs = B>>1; this.e = parseInt(E,16); var ee = new BigInteger(E,16); for(;;) { for(;;) { this.p = new BigInteger(B-qs,10,rng); // tutao: changed parameter b from 1 to 10 (=> 5 rounds); according to HAC 4.49, we only need 2 rounds && discussion: https://github.com/digitalbazaar/forge/issues/28 // tutao: the prime probability is already guaranteed by the BigInteger constructor above; if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break; if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0) break; } for(;;) { // tutao: same changes as above this.q = new BigInteger(qs,10,rng); if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0) break; } if(this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } } // Perform raw private operation on "x": return x^d (mod n) function RSADoPrivate(x) { if(this.p == null || this.q == null) return x.modPow(this.d, this.n); // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while(xp.compareTo(xq) < 0) xp = xp.add(this.p); return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); } // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is an even-length hex string and the output is a plain string. function RSADecrypt(ctext) { var c = parseBigInt(ctext, 16); var m = this.doPrivate(c); if(m == null) return null; return pkcs1unpad2(m, (this.n.bitLength()+7)>>3); } // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is a Base64-encoded string and the output is a plain string. //function RSAB64Decrypt(ctext) { // var h = b64tohex(ctext); // if(h) return this.decrypt(h); else return null; //} // protected RSAKey.prototype.doPrivate = RSADoPrivate; // public RSAKey.prototype.setPrivate = RSASetPrivate; RSAKey.prototype.setPrivateEx = RSASetPrivateEx; RSAKey.prototype.generate = RSAGenerate; RSAKey.prototype.decrypt = RSADecrypt; //RSAKey.prototype.b64_decrypt = RSAB64Decrypt; //////////////////////////////////////////////////////////////////////////////////////// // Big Integer Library v. 5.4 // Created 2000, last modified 2009 // Leemon Baird // www.leemon.com // // Version history: // v 5.4 3 Oct 2009 // - added "var i" to greaterShift() so i is not global. (Thanks to PŽter Szab— for finding that bug) // // v 5.3 21 Sep 2009 // - added randProbPrime(k) for probable primes // - unrolled loop in mont_ (slightly faster) // - millerRabin now takes a bigInt parameter rather than an int // // v 5.2 15 Sep 2009 // - fixed capitalization in call to int2bigInt in randBigInt // (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug) // // v 5.1 8 Oct 2007 // - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters // - added functions GCD and randBigInt, which call GCD_ and randBigInt_ // - fixed a bug found by Rob Visser (see comment with his name below) // - improved comments // // This file is public domain. You can use it for any purpose without restriction. // I do not guarantee that it is correct, so use it at your own risk. If you use // it for something interesting, I'd appreciate hearing about it. If you find // any bugs or make any improvements, I'd appreciate hearing about those too. // It would also be nice if my name and URL were left in the comments. But none // of that is required. // // This code defines a bigInt library for arbitrary-precision integers. // A bigInt is an array of integers storing the value in chunks of bpe bits, // little endian (buff[0] is the least significant word). // Negative bigInts are stored two's complement. Almost all the functions treat // bigInts as nonnegative. The few that view them as two's complement say so // in their comments. Some functions assume their parameters have at least one // leading zero element. Functions with an underscore at the end of the name put // their answer into one of the arrays passed in, and have unpredictable behavior // in case of overflow, so the caller must make sure the arrays are big enough to // hold the answer. But the average user should never have to call any of the // underscored functions. Each important underscored function has a wrapper function // of the same name without the underscore that takes care of the details for you. // For each underscored function where a parameter is modified, that same variable // must not be used as another argument too. So, you cannot square x by doing // multMod_(x,x,n). You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n). // Or simply use the multMod(x,x,n) function without the underscore, where // such issues never arise, because non-underscored functions never change // their parameters; they always allocate new memory for the answer that is returned. // // These functions are designed to avoid frequent dynamic memory allocation in the inner loop. // For most functions, if it needs a BigInt as a local variable it will actually use // a global, and will only allocate to it only when it's not the right size. This ensures // that when a function is called repeatedly with same-sized parameters, it only allocates // memory on the first call. // // Note that for cryptographic purposes, the calls to Math.random() must // be replaced with calls to a better pseudorandom number generator. // // In the following, "bigInt" means a bigInt with at least one leading zero element, // and "integer" means a nonnegative integer less than radix. In some cases, integer // can be negative. Negative bigInts are 2s complement. // // The following functions do not modify their inputs. // Those returning a bigInt, string, or Array will dynamically allocate memory for that value. // Those returning a boolean will return the integer 0 (false) or 1 (true). // Those returning boolean or int will not allocate memory except possibly on the first // time they're called with a given parameter size. // // bigInt add(x,y) //return (x+y) for bigInts x and y. // bigInt addInt(x,n) //return (x+n) where x is a bigInt and n is an integer. // string bigInt2str(x,base) //return a string form of bigInt x in a given base, with 2 <= base <= 95 // int bitSize(x) //return how many bits long the bigInt x is, not counting leading zeros // bigInt dup(x) //return a copy of bigInt x // boolean equals(x,y) //is the bigInt x equal to the bigint y? // boolean equalsInt(x,y) //is bigint x equal to integer y? // bigInt expand(x,n) //return a copy of x with at least n elements, adding leading zeros if needed // Array findPrimes(n) //return array of all primes less than integer n // bigInt GCD(x,y) //return greatest common divisor of bigInts x and y (each with same number of elements). // boolean greater(x,y) //is x>y? (x and y are nonnegative bigInts) // boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y? // bigInt int2bigInt(t,n,m) //return a bigInt equal to integer t, with at least n bits and m array elements // bigInt inverseMod(x,n) //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null // int inverseModInt(x,n) //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse // boolean isZero(x) //is the bigInt x equal to zero? // boolean millerRabin(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x) // boolean millerRabinInt(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int, 1<b<x) // bigInt mod(x,n) //return a new bigInt equal to (x mod n) for bigInts x and n. // int modInt(x,n) //return x mod n for bigInt x and integer n. // bigInt mult(x,y) //return x*y for bigInts x and y. This is faster when y<x. // bigInt multMod(x,y,n) //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x. // boolean negative(x) //is bigInt x negative? // bigInt powMod(x,y,n) //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n. // bigInt randBigInt(n,s) //return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1. // bigInt randTruePrime(k) //return a new, random, k-bit, true prime bigInt using Maurer's algorithm. // bigInt randProbPrime(k) //return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). // bigInt str2bigInt(s,b,n,m) //return a bigInt for number represented in string s in base b with at least n bits and m array elements // bigInt sub(x,y) //return (x-y) for bigInts x and y. Negative answers will be 2s complement // bigInt trim(x,k) //return a copy of x with exactly k leading zero elements // // // The following functions each have a non-underscored version, which most users should call instead. // These functions each write to a single parameter, and the caller is responsible for ensuring the array // passed in is large enough to hold the result. // // void addInt_(x,n) //do x=x+n where x is a bigInt and n is an integer // void add_(x,y) //do x=x+y for bigInts x and y // void copy_(x,y) //do x=y on bigInts x and y // void copyInt_(x,n) //do x=n on bigInt x and integer n // void GCD_(x,y) //set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). // boolean inverseMod_(x,n) //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist // void mod_(x,n) //do x=x mod n for bigInts x and n. (This never overflows its array). // void mult_(x,y) //do x=x*y for bigInts x and y. // void multMod_(x,y,n) //do x=x*y mod n for bigInts x,y,n. // void powMod_(x,y,n) //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. // void randBigInt_(b,n,s) //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. // void randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. // void sub_(x,y) //do x=x-y for bigInts x and y. Negative answers will be 2s complement. // // The following functions do NOT have a non-underscored version. // They each write a bigInt result to one or more parameters. The caller is responsible for // ensuring the arrays passed in are large enough to hold the results. // // void addShift_(x,y,ys) //do x=x+(y<<(ys*bpe)) // void carry_(x) //do carries and borrows so each element of the bigInt x fits in bpe bits. // void divide_(x,y,q,r) //divide x by y giving quotient q and remainder r // int divInt_(x,n) //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). // int eGCD_(x,y,d,a,b) //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y // void halve_(x) //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). // void leftShift_(x,n) //left shift bigInt x by n bits. n<bpe. // void linComb_(x,y,a,b) //do x=a*x+b*y for bigInts x and y and integers a and b // void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys // void mont_(x,y,n,np) //Montgomery multiplication (see comments where the function is defined) // void multInt_(x,n) //do x=x*n where x is a bigInt and n is an integer. // void rightShift_(x,n) //right shift bigInt x by n bits. 0 <= n < bpe. (This never overflows its array). // void squareMod_(x,n) //do x=x*x mod n for bigInts x,n // void subShift_(x,y,ys) //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement. // // The following functions are based on algorithms from the _Handbook of Applied Cryptography_ // powMod_() = algorithm 14.94, Montgomery exponentiation // eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_ // GCD_() = algorothm 14.57, Lehmer's algorithm // mont_() = algorithm 14.36, Montgomery multiplication // divide_() = algorithm 14.20 Multiple-precision division // squareMod_() = algorithm 14.16 Multiple-precision squaring // randTruePrime_() = algorithm 4.62, Maurer's algorithm // millerRabin() = algorithm 4.24, Miller-Rabin algorithm // // Profiling shows: // randTruePrime_() spends: // 10% of its time in calls to powMod_() // 85% of its time in calls to millerRabin() // millerRabin() spends: // 99% of its time in calls to powMod_() (always with a base of 2) // powMod_() spends: // 94% of its time in calls to mont_() (almost always with x==y) // // This suggests there are several ways to speed up this library slightly: // - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window) // -- this should especially focus on being fast when raising 2 to a power mod n // - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test // - tune the parameters in randTruePrime_(), including c, m, and recLimit // - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking // within the loop when all the parameters are the same length. // // There are several ideas that look like they wouldn't help much at all: // - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway) // - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32) // - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square // followed by a Montgomery reduction. The intermediate answer will be twice as long as x, so that // method would be slower. This is unfortunate because the code currently spends almost all of its time // doing mont_(x,x,...), both for randTruePrime_() and powMod_(). A faster method for Montgomery squaring // would have a large impact on the speed of randTruePrime_() and powMod_(). HAC has a couple of poorly-worded // sentences that seem to imply it's faster to do a non-modular square followed by a single // Montgomery reduction, but that's obviously wrong. //////////////////////////////////////////////////////////////////////////////////////// //globals bpe=0; //bits stored per array element mask=0; //AND this with an array element to chop it down to bpe bits radix=mask+1; //equals 2^bpe. A single 1 bit to the left of the last bit of mask. //the digits for converting to different bases digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-'; //initialize the global variables for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++); //bpe=number of bits in the mantissa on this platform bpe>>=1; //bpe=number of bits in one element of the array representing the bigInt mask=(1<<bpe)-1; //AND the mask with an integer to get its bpe least significant bits radix=mask+1; //2^bpe. a single 1 bit to the left of the first bit of mask one=int2bigInt(1,1,1); //constant used in powMod_() //the following global variables are scratchpad memory to //reduce dynamic memory allocation in the inner loop t=new Array(0); ss=t; //used in mult_() s0=t; //used in multMod_(), squareMod_() s1=t; //used in powMod_(), multMod_(), squareMod_() s2=t; //used in powMod_(), multMod_() s3=t; //used in powMod_() s4=t; s5=t; //used in mod_() s6=t; //used in bigInt2str() s7=t; //used in powMod_() T=t; //used in GCD_() sa=t; //used in mont_() mr_x1=t; mr_r=t; mr_a=t; //used in millerRabin() eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t; //used in eGCD_(), inverseMod_() md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_() primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t; s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_() rpprb=t; //used in randProbPrimeRounds() (which also uses "primes") //////////////////////////////////////////////////////////////////////////////////////// //return array of all primes less than integer n function findPrimes(n) { var i,s,p,ans; s=new Array(n); for (i=0;i<n;i++) s[i]=0; s[0]=2; p=0; //first p elements of s are primes, the rest are a sieve for(;s[p]<n;) { //s[p] is the pth prime for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p] s[i]=1; p++; s[p]=s[p-1]+1; for(; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0) } ans=new Array(p); for(i=0;i<p;i++) ans[i]=s[i]; return ans; } //does a single round of Miller-Rabin base b consider x to be a possible prime? //x is a bigInt, and b is an integer, with b<x function millerRabinInt(x,b) { if (mr_x1.length!=x.length) { mr_x1=dup(x); mr_r=dup(x); mr_a=dup(x); } copyInt_(mr_a,b); return millerRabin(x,mr_a); } //does a single round of Miller-Rabin base b consider x to be a possible prime? //x and b are bigInts with b<x function millerRabin(x,b) { var i,j,k,s; if (mr_x1.length!=x.length) { mr_x1=dup(x); mr_r=dup(x); mr_a=dup(x); } copy_(mr_a,b); copy_(mr_r,x); copy_(mr_x1,x); addInt_(mr_r,-1); addInt_(mr_x1,-1); //s=the highest power of two that divides mr_r k=0; for (i=0;i<mr_r.length;i++) for (j=1;j<mask;j<<=1) if (x[i] & j) { s=(k<mr_r.length+bpe ? k : 0); i=mr_r.length; j=mask; } else k++; if (s) rightShift_(mr_r,s); powMod_(mr_a,mr_r,x); if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) { j=1; while (j<=s-1 && !equals(mr_a,mr_x1)) { squareMod_(mr_a,x); if (equalsInt(mr_a,1)) { return 0; } j++; } if (!equals(mr_a,mr_x1)) { return 0; } } return 1; } //returns how many bits long the bigInt is, not counting leading zeros. function bitSize(x) { var j,z,w; for (j=x.length-1; (x[j]==0) && (j>0); j--); for (z=0,w=x[j]; w; (w>>=1),z++); z+=bpe*j; return z; } //return a copy of x with at least n elements, adding leading zeros if needed function expand(x,n) { var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0); copy_(ans,x); return ans; } //return a k-bit true random prime using Maurer's algorithm. function randTruePrime(k) { var ans=int2bigInt(0,k,0); randTruePrime_(ans,k); return trim(ans,1); } //return a k-bit random probable prime with probability of error < 2^-80 function randProbPrime(k) { if (k>=600) return randProbPrimeRounds(k,2); //numbers from HAC table 4.3 if (k>=550) return randProbPrimeRounds(k,4); if (k>=500) return randProbPrimeRounds(k,5); if (k>=400) return randProbPrimeRounds(k,6); if (k>=350) return randProbPrimeRounds(k,7); if (k>=300) return randProbPrimeRounds(k,9); if (k>=250) return randProbPrimeRounds(k,12); //numbers from HAC table 4.4 if (k>=200) return randProbPrimeRounds(k,15); if (k>=150) return randProbPrimeRounds(k,18); if (k>=100) return randProbPrimeRounds(k,27); return randProbPrimeRounds(k,40); //number from HAC remark 4.26 (only an estimate) } //return a k-bit probable random prime using n rounds of Miller Rabin (after trial division with small primes) function randProbPrimeRounds(k,n) { var ans, i, divisible, B; B=30000; //B is largest prime to use in trial division ans=int2bigInt(0,k,0); //optimization: try larger and smaller B to find the best limit. if (primes.length==0) primes=findPrimes(30000); //check for divisibility by primes <=30000 if (rpprb.length!=ans.length) rpprb=dup(ans); for (;;) { //keep trying random values for ans until one appears to be prime //optimization: pick a random number times L=2*3*5*...*p, plus a // random element of the list of all numbers in [0,L) not divisible by any prime up to p. // This can reduce the amount of random number generation. randBigInt_(ans,k,0); //ans = a random odd number to check ans[0] |= 1; divisible=0; //check ans for divisibility by small primes up to B for (i=0; (i<primes.length) && (primes[i]<=B); i++) if (modInt(ans,primes[i])==0 && !equalsInt(ans,primes[i])) { divisible=1; break; } //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here. //do n rounds of Miller Rabin, with random bases less than ans for (i=0; i<n && !divisible; i++) { randBigInt_(rpprb,k,0); while(!greater(ans,rpprb)) //pick a random rpprb that's < ans randBigInt_(rpprb,k,0); if (!millerRabin(ans,rpprb)) divisible=1; } if(!divisible) return ans; } } //return a new bigInt equal to (x mod n) for bigInts x and n. function mod(x,n) { var ans=dup(x); mod_(ans,n); return trim(ans,1); } //return (x+n) where x is a bigInt and n is an integer. function addInt(x,n) { var ans=expand(x,x.length+1); addInt_(ans,n); return trim(ans,1); } //return x*y for bigInts x and y. This is faster when y<x. function mult(x,y) { var ans=expand(x,x.length+y.length); mult_(ans,y); return trim(ans,1); } //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n. function powMod(x,y,n) { var ans=expand(x,n.length); powMod_(ans,trim(y,2),trim(n,2),0); //this should work without the trim, but doesn't return trim(ans,1); } //return (x-y) for bigInts x and y. Negative answers will be 2s complement function sub(x,y) { var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); sub_(ans,y); return trim(ans,1); } //return (x+y) for bigInts x and y. function add(x,y) { var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1)); add_(ans,y); return trim(ans,1); } //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null function inverseMod(x,n) { var ans=expand(x,n.length); var s; s=inverseMod_(ans,n); return s ? trim(ans,1) : null; } //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x. function multMod(x,y,n) { var ans=expand(x,n.length); multMod_(ans,y,n); return trim(ans,1); } /* TUTAO: not used //generate a k-bit true random prime using Maurer's algorithm, //and put it into ans. The bigInt ans must be large enough to hold it. function randTruePrime_(ans,k) { var c,m,pm,dd,j,r,B,divisible,z,zz,recSize; if (primes.length==0) primes=findPrimes(30000); //check for divisibility by primes <=30000 if (pows.length==0) { pows=new Array(512); for (j=0;j<512;j++) { pows[j]=Math.pow(2,j/511.-1.); } } //c and m should be tuned for a particular machine and value of k, to maximize speed c=0.1; //c=0.1 in HAC m=20; //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits recLimit=20; //stop recursion when k <=recLimit. Must have recLimit >= 2 if (s_i2.length!=ans.length) { s_i2=dup(ans); s_R =dup(ans); s_n1=dup(ans); s_r2=dup(ans); s_d =dup(ans); s_x1=dup(ans); s_x2=dup(ans); s_b =dup(ans); s_n =dup(ans); s_i =dup(ans); s_rm=dup(ans); s_q =dup(ans); s_a =dup(ans); s_aa=dup(ans); } if (k <= recLimit) { //generate small random primes by trial division up to its square root pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k) copyInt_(ans,0); for (dd=1;dd;) { dd=0; ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k)); //random, k-bit, odd integer, with msb 1 for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k) if (0==(ans[0]%primes[j])) { dd=1; break; } } } carry_(ans); return; } B=c*k*k; //try small primes up to B (or all the primes[] array if the largest is less than B). if (k>2*m) //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits for (r=1; k-k*r<=m; ) r=pows[Math.floor(Math.random()*512)]; //r=Math.pow(2,Math.random()-1); else r=.5; //simulation suggests the more complex algorithm using r=.333 is only slightly faster. recSize=Math.floor(r*k)+1; randTruePrime_(s_q,recSize); copyInt_(s_i2,0); s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe)); //s_i2=2^(k-2) divide_(s_i2,s_q,s_i,s_rm); //s_i=floor((2^(k-1))/(2q)) z=bitSize(s_i); for (;;) { for (;;) { //generate z-bit numbers until one falls in the range [0,s_i-1] randBigInt_(s_R,z,0); if (greater(s_i,s_R)) break; } //now s_R is in the range [0,s_i-1] addInt_(s_R,1); //now s_R is in the range [1,s_i] add_(s_R,s_i); //now s_R is in the range [s_i+1,2*s_i] copy_(s_n,s_q); mult_(s_n,s_R); multInt_(s_n,2); addInt_(s_n,1); //s_n=2*s_R*s_q+1 copy_(s_r2,s_R); multInt_(s_r2,2); //s_r2=2*s_R //check s_n for divisibility by small primes up to B for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++) if (modInt(s_n,primes[j])==0 && !equalsInt(s_n,primes[j])) { divisible=1; break; } if (!divisible) //if it passes small primes check, then try a single Miller-Rabin base 2 if (!millerRabinInt(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_ divisible=1; if (!divisible) { //if it passes that test, continue checking s_n addInt_(s_n,-3); for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--); //strip leading zeros for (zz=0,w=s_n[j]; w; (w>>=1),zz++); zz+=bpe*j; //zz=number of bits in s_n, ignoring leading zeros for (;;) { //generate z-bit numbers until one falls in the range [0,s_n-1] randBigInt_(s_a,zz,0); if (greater(s_n,s_a)) break; } //now s_a is in the range [0,s_n-1] addInt_(s_n,3); //now s_a is in the range [0,s_n-4] addInt_(s_a,2); //now s_a is in the range [2,s_n-2] copy_(s_b,s_a); copy_(s_n1,s_n); addInt_(s_n1,-1); powMod_(s_b,s_n1,s_n); //s_b=s_a^(s_n-1) modulo s_n addInt_(s_b,-1); if (isZero(s_b)) { copy_(s_b,s_a); powMod_(s_b,s_r2,s_n); addInt_(s_b,-1); copy_(s_aa,s_n); copy_(s_d,s_b); GCD_(s_d,s_n); //if s_b and s_n are relatively prime, then s_n is a prime if (equalsInt(s_d,1)) { copy_(ans,s_aa); return; //if we've made it this far, then s_n is absolutely guaranteed to be prime } } } } } */ //Return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1. function randBigInt(n,s) { var a,b; a=Math.floor((n-1)/bpe)+2; //# array elements to hold the BigInt with a leading 0 element b=int2bigInt(0,0,a); randBigInt_(b,n,s); return b; } /* TUTAO: not used //Set b to an n-bit random BigInt. If s=1, then the most significant of those n bits is set to 1. //Array b must be big enough to hold the result. Must have n>=1 function randBigInt_(b,n,s) { var i,a; for (i=0;i<b.length;i++) b[i]=0; a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt for (i=0;i<a;i++) { b[i]=Math.floor(Math.random()*(1<<(bpe-1))); } b[a-1] &= (2<<((n-1)%bpe))-1; if (s==1) b[a-1] |= (1<<((n-1)%bpe)); } */ //Return the greatest common divisor of bigInts x and y (each with same number of elements). function GCD(x,y) { var xc,yc; xc=dup(x); yc=dup(y); GCD_(xc,yc); return xc; } //set x to the greatest common divisor of bigInts x and y (each with same number of elements). //y is destroyed. function GCD_(x,y) { var i,xp,yp,A,B,C,D,q,sing; if (T.length!=x.length) T=dup(x); sing=1; while (sing) { //while y has nonzero elements other than y[0] sing=0; for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0 if (y[i]) { sing=1; break; } if (!sing) break; //quit when y all zero elements except possibly y[0] for (i=x.length;!x[i] && i>=0;i--); //find most significant element of x xp=x[i]; yp=y[i]; A=1; B=0; C=0; D=1; while ((yp+C) && (yp+D)) { q =Math.floor((xp+A)/(yp+C)); qp=Math.floor((xp+B)/(yp+D)); if (q!=qp) break; t= A-q*C; A=C; C=t; // do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp) t= B-q*D; B=D; D=t; t=xp-q*yp; xp=yp; yp=t; } if (B) { copy_(T,x); linComb_(x,y,A,B); //x=A*x+B*y linComb_(y,T,D,C); //y=D*y+C*T } else { mod_(x,y); copy_(T,x); copy_(x,y); copy_(y,T); } } if (y[0]==0) return; t=modInt(x,y[0]); copyInt_(x,y[0]); y[0]=t; while (y[0]) { x[0]%=y[0]; t=x[0]; x[0]=y[0]; y[0]=t; } } //do x=x**(-1) mod n, for bigInts x and n. //If no inverse exists, it sets x to zero and returns 0, else it returns 1. //The x array must be at least as large as the n array. function inverseMod_(x,n) { var k=1+2*Math.max(x.length,n.length); if(!(x[0]&1) && !(n[0]&1)) { //if both inputs are even, then inverse doesn't exist copyInt_(x,0); return 0; } if (eg_u.length!=k) { eg_u=new Array(k); eg_v=new Array(k); eg_A=new Array(k); eg_B=new Array(k); eg_C=new Array(k); eg_D=new Array(k); } copy_(eg_u,x); copy_(eg_v,n); copyInt_(eg_A,1); copyInt_(eg_B,0); copyInt_(eg_C,0); copyInt_(eg_D,1); for (;;) { while(!(eg_u[0]&1)) { //while eg_u is even halve_(eg_u); if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2 halve_(eg_A); halve_(eg_B); } else { add_(eg_A,n); halve_(eg_A); sub_(eg_B,x); halve_(eg_B); } } while (!(eg_v[0]&1)) { //while eg_v is even halve_(eg_v); if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2 halve_(eg_C); halve_(eg_D); } else { add_(eg_C,n); halve_(eg_C); sub_(eg_D,x); halve_(eg_D); } } if (!greater(eg_v,eg_u)) { //eg_v <= eg_u sub_(eg_u,eg_v); sub_(eg_A,eg_C); sub_(eg_B,eg_D); } else { //eg_v > eg_u sub_(eg_v,eg_u); sub_(eg_C,eg_A); sub_(eg_D,eg_B); } if (equalsInt(eg_u,0)) { if (negative(eg_C)) //make sure answer is nonnegative add_(eg_C,n); copy_(x,eg_C); if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse copyInt_(x,0); return 0; } return 1; } } } //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse function inverseModInt(x,n) { var a=1,b=0,t; for (;;) { if (x==1) return a; if (x==0) return 0; b-=a*Math.floor(n/x); n%=x; if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to += if (n==0) return 0; a-=b*Math.floor(x/n); x%=n; } } //this deprecated function is for backward compatibility only. function inverseModInt_(x,n) { return inverseModInt(x,n); } //Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that: // v = GCD_(x,y) = a*x-b*y //The bigInts v, a, b, must have exactly as many elements as the larger of x and y. function eGCD_(x,y,v,a,b) { var g=0; var k=Math.max(x.length,y.length); if (eg_u.length!=k) { eg_u=new Array(k); eg_A=new Array(k); eg_B=new Array(k); eg_C=new Array(k); eg_D=new Array(k); } while(!(x[0]&1) && !(y[0]&1)) { //while x and y both even halve_(x); halve_(y); g++; } copy_(eg_u,x); copy_(v,y); copyInt_(eg_A,1); copyInt_(eg_B,0); copyInt_(eg_C,0); copyInt_(eg_D,1); for (;;) { while(!(eg_u[0]&1)) { //while u is even halve_(eg_u); if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2 halve_(eg_A); halve_(eg_B); } else { add_(eg_A,y); halve_(eg_A); sub_(eg_B,x); halve_(eg_B); } } while (!(v[0]&1)) { //while v is even halve_(v); if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2 halve_(eg_C); halve_(eg_D); } else { add_(eg_C,y); halve_(eg_C); sub_(eg_D,x); halve_(eg_D); } } if (!greater(v,eg_u)) { //v<=u sub_(eg_u,v); sub_(eg_A,eg_C); sub_(eg_B,eg_D); } else { //v>u sub_(v,eg_u); sub_(eg_C,eg_A); sub_(eg_D,eg_B); } if (equalsInt(eg_u,0)) { if (negative(eg_C)) { //make sure a (C)is nonnegative add_(eg_C,y); sub_(eg_D,x); } multInt_(eg_D,-1); ///make sure b (D) is nonnegative copy_(a,eg_C); copy_(b,eg_D); leftShift_(v,g); return; } } } //is bigInt x negative? function negative(x) { return ((x[x.length-1]>>(bpe-1))&1); } //is (x << (shift*bpe)) > y? //x and y are nonnegative bigInts //shift is a nonnegative integer function greaterShift(x,y,shift) { var i, kx=x.length, ky=y.length; k=((kx+shift)<ky) ? (kx+shift) : ky; for (i=ky-1-shift; i<kx && i>=0; i++) if (x[i]>0) return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger for (i=kx-1+shift; i<ky; i++) if (y[i]>0) return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger for (i=k-1; i>=shift; i--) if (x[i-shift]>y[i]) return 1; else if (x[i-shift]<y[i]) return 0; return 0; } //is x > y? (x and y both nonnegative) function greater(x,y) { var i; var k=(x.length<y.length) ? x.length : y.length; for (i=x.length;i<y.length;i++) if (y[i]) return 0; //y has more digits for (i=y.length;i<x.length;i++) if (x[i]) return 1; //x has more digits for (i=k-1;i>=0;i--) if (x[i]>y[i]) return 1; else if (x[i]<y[i]) return 0; return 0; } //divide x by y giving quotient q and remainder r. (q=floor(x/y), r=x mod y). All 4 are bigints. //x must have at least one leading zero element. //y must be nonzero. //q and r must be arrays that are exactly the same length as x. (Or q can have more). //Must have x.length >= y.length >= 2. function divide_(x,y,q,r) { var kx, ky; var i,j,y1,y2,c,a,b; copy_(r,x); for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros //normalize: ensure the most significant element of y has its highest bit set b=y[ky-1]; for (a=0; b; a++) b>>=1; a=bpe-a; //a is how many bits to shift so that the high order bit of y is leftmost in its array element leftShift_(y,a); //multiply both by 1<<a now, then divide both by that at the end leftShift_(r,a); //Rob Visser discovered a bug: the following line was originally just before the normalization. for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros copyInt_(q,0); // q=0 while (!greaterShift(y,r,kx-ky)) { // while (leftShift_(y,kx-ky) <= r) { subShift_(r,y,kx-ky); // r=r-leftShift_(y,kx-ky) q[kx-ky]++; // q[kx-ky]++; } // } for (i=kx-1; i>=ky; i--) { if (r[i]==y[ky-1]) q[i-ky]=mask; else q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]); //The following for(;;) loop is equivalent to the commented while loop, //except that the uncommented version avoids overflow. //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0 // while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2]) // q[i-ky]--; for (;;) { y2=(ky>1 ? y[ky-2] : 0)*q[i-ky]; c=y2>>bpe; y2=y2 & mask; y1=c+q[i-ky]*y[ky-1]; c=y1>>bpe; y1=y1 & mask; if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i]) q[i-ky]--; else break; } linCombShift_(r,y,-q[i-ky],i-ky); //r=r-q[i-ky]*leftShift_(y,i-ky) if (negative(r)) { addShift_(r,y,i-ky); //r=r+leftShift_(y,i-ky) q[i-ky]--; } } rightShift_(y,a); //undo the normalization step rightShift_(r,a); //undo the normalization step } //do carries and borrows so each element of the bigInt x fits in bpe bits. function carry_(x) { var i,k,c,b; k=x.length; c=0; for (i=0;i<k;i++) { c+=x[i]; b=0; if (c<0) { b=-(c>>bpe); c+=b*radix; } x[i]=c & mask; c=(c>>bpe)-b; } } //return x mod n for bigInt x and integer n. function modInt(x,n) { var i,c=0; for (i=x.length-1; i>=0; i--) c=(c*radix+x[i])%n; return c; } //convert the integer t into a bigInt with at least the given number of bits. //the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word) //Pad the array with leading zeros so that it has at least minSize elements. //There will always be at least one leading 0 element. function int2bigInt(t,bits,minSize) { var i,k; k=Math.ceil(bits/bpe)+1; k=minSize>k ? minSize : k; buff=new Array(k); copyInt_(buff,t); return buff; } //return the bigInt given a string representation in a given base. //Pad the array with leading zeros so that it has at least minSize elements. //If base=-1, then it reads in a space-separated list of array elements in decimal. //The array will always have at least one leading zero, unless base=-1. function str2bigInt(s,base,minSize) { var d, i, j, x, y, kk; var k=s.length; if (base==-1) { //comma-separated list of array elements in decimal x=new Array(0); for (;;) { y=new Array(x.length+1); for (i=0;i<x.length;i++) y[i+1]=x[i]; y[0]=parseInt(s,10); x=y; d=s.indexOf(',',0); if (d<1) break; s=s.substring(d+1); if (s.length==0) break; } if (x.length<minSize) { y=new Array(minSize); copy_(y,x); return y; } return x; } x=int2bigInt(0,base*k,0); for (i=0;i<k;i++) { d=digitsStr.indexOf(s.substring(i,i+1),0); if (base<=36 && d>=36) //convert lowercase to uppercase if base<=36 d-=26; if (d>=base || d<0) { //stop at first illegal character break; } multInt_(x,base); addInt_(x,d); } for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros k=minSize>k+1 ? minSize : k+1; y=new Array(k); kk=k<x.length ? k : x.length; for (i=0;i<kk;i++) y[i]=x[i]; for (;i<k;i++) y[i]=0; return y; } //is bigint x equal to integer y? //y must have less than bpe bits function equalsInt(x,y) { var i; if (x[0]!=y) return 0; for (i=1;i<x.length;i++) if (x[i]) return 0; return 1; } //are bigints x and y equal? //this works even if x and y are different lengths and have arbitrarily many leading zeros function equals(x,y) { var i; var k=x.length<y.length ? x.length : y.length; for (i=0;i<k;i++) if (x[i]!=y[i]) return 0; if (x.length>y.length) { for (;i<x.length;i++) if (x[i]) return 0; } else { for (;i<y.length;i++) if (y[i]) return 0; } return 1; } //is the bigInt x equal to zero? function isZero(x) { var i; for (i=0;i<x.length;i++) if (x[i]) return 0; return 1; } //convert a bigInt into a string in a given base, from base 2 up to base 95. //Base -1 prints the contents of the array representing the number. function bigInt2str(x,base) { var i,t,s=""; if (s6.length!=x.length) s6=dup(x); else copy_(s6,x); if (base==-1) { //return the list of array contents for (i=x.length-1;i>0;i--) s+=x[i]+','; s+=x[0]; } else { //return it in the given base while (!isZero(s6)) { t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base); s=digitsStr.substring(t,t+1)+s; } } if (s.length==0) s="0"; return s; } //returns a duplicate of bigInt x function dup(x) { var i; buff=new Array(x.length); copy_(buff,x); return buff; } //do x=y on bigInts x and y. x must be an array at least as big as y (not counting the leading zeros in y). function copy_(x,y) { var i; var k=x.length<y.length ? x.length : y.length; for (i=0;i<k;i++) x[i]=y[i]; for (i=k;i<x.length;i++) x[i]=0; } //do x=y on bigInt x and integer y. function copyInt_(x,n) { var i,c; for (c=n,i=0;i<x.length;i++) { x[i]=c & mask; c>>=bpe; } } //do x=x+n where x is a bigInt and n is an integer. //x must be large enough to hold the result. function addInt_(x,n) { var i,k,c,b; x[0]+=n; k=x.length; c=0; for (i=0;i<k;i++) { c+=x[i]; b=0; if (c<0) { b=-(c>>bpe); c+=b*radix; } x[i]=c & mask; c=(c>>bpe)-b; if (!c) return; //stop carrying as soon as the carry is zero } } //right shift bigInt x by n bits. 0 <= n < bpe. function rightShift_(x,n) { var i; var k=Math.floor(n/bpe); if (k) { for (i=0;i<x.length-k;i++) //right shift x by k elements x[i]=x[i+k]; for (;i<x.length;i++) x[i]=0; n%=bpe; } for (i=0;i<x.length-1;i++) { x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n)); } x[i]>>=n; } //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement function halve_(x) { var i; for (i=0;i<x.length-1;i++) { x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1)); } x[i]=(x[i]>>1) | (x[i] & (radix>>1)); //most significant bit stays the same } //left shift bigInt x by n bits. function leftShift_(x,n) { var i; var k=Math.floor(n/bpe); if (k) { for (i=x.length; i>=k; i--) //left shift x by k elements x[i]=x[i-k]; for (;i>=0;i--) x[i]=0; n%=bpe; } if (!n) return; for (i=x.length-1;i>0;i--) { x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n))); } x[i]=mask & (x[i]<<n); } //do x=x*n where x is a bigInt and n is an integer. //x must be large enough to hold the result. function multInt_(x,n) { var i,k,c,b; if (!n) return; k=x.length; c=0; for (i=0;i<k;i++) { c+=x[i]*n; b=0; if (c<0) { b=-(c>>bpe); c+=b*radix; } x[i]=c & mask; c=(c>>bpe)-b; } } //do x=floor(x/n) for bigInt x and integer n, and return the remainder function divInt_(x,n) { var i,r=0,s; for (i=x.length-1;i>=0;i--) { s=r*radix+x[i]; x[i]=Math.floor(s/n); r=s%n; } return r; } //do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b. //x must be large enough to hold the answer. function linComb_(x,y,a,b) { var i,c,k,kk; k=x.length<y.length ? x.length : y.length; kk=x.length; for (c=0,i=0;i<k;i++) { c+=a*x[i]+b*y[i]; x[i]=c & mask; c>>=bpe; } for (i=k;i<kk;i++) { c+=a*x[i]; x[i]=c & mask; c>>=bpe; } } //do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys. //x must be large enough to hold the answer. function linCombShift_(x,y,b,ys) { var i,c,k,kk; k=x.length<ys+y.length ? x.length : ys+y.length; kk=x.length; for (c=0,i=ys;i<k;i++) { c+=x[i]+b*y[i-ys]; x[i]=c & mask; c>>=bpe; } for (i=k;c && i<kk;i++) { c+=x[i]; x[i]=c & mask; c>>=bpe; } } //do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys. //x must be large enough to hold the answer. function addShift_(x,y,ys) { var i,c,k,kk; k=x.length<ys+y.length ? x.length : ys+y.length; kk=x.length; for (c=0,i=ys;i<k;i++) { c+=x[i]+y[i-ys]; x[i]=c & mask; c>>=bpe; } for (i=k;c && i<kk;i++) { c+=x[i]; x[i]=c & mask; c>>=bpe; } } //do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys. //x must be large enough to hold the answer. function subShift_(x,y,ys) { var i,c,k,kk; k=x.length<ys+y.length ? x.length : ys+y.length; kk=x.length; for (c=0,i=ys;i<k;i++) { c+=x[i]-y[i-ys]; x[i]=c & mask; c>>=bpe; } for (i=k;c && i<kk;i++) { c+=x[i]; x[i]=c & mask; c>>=bpe; } } //do x=x-y for bigInts x and y. //x must be large enough to hold the answer. //negative answers will be 2s complement function sub_(x,y) { var i,c,k,kk; k=x.length<y.length ? x.length : y.length; for (c=0,i=0;i<k;i++) { c+=x[i]-y[i]; x[i]=c & mask; c>>=bpe; } for (i=k;c && i<x.length;i++) { c+=x[i]; x[i]=c & mask; c>>=bpe; } } //do x=x+y for bigInts x and y. //x must be large enough to hold the answer. function add_(x,y) { var i,c,k,kk; k=x.length<y.length ? x.length : y.length; for (c=0,i=0;i<k;i++) { c+=x[i]+y[i]; x[i]=c & mask; c>>=bpe; } for (i=k;c && i<x.length;i++) { c+=x[i]; x[i]=c & mask; c>>=bpe; } } //do x=x*y for bigInts x and y. This is faster when y<x. function mult_(x,y) { var i; if (ss.length!=2*x.length) ss=new Array(2*x.length); copyInt_(ss,0); for (i=0;i<y.length;i++) if (y[i]) linCombShift_(ss,x,y[i],i); //ss=1*ss+y[i]*(x<<(i*bpe)) copy_(x,ss); } //do x=x mod n for bigInts x and n. function mod_(x,n) { if (s4.length!=x.length) s4=dup(x); else copy_(s4,x); if (s5.length!=x.length) s5=dup(x); divide_(s4,n,s5,x); //x = remainder of s4 / n } //do x=x*y mod n for bigInts x,y,n. //for greater speed, let y<x. function multMod_(x,y,n) { var i; if (s0.length!=2*x.length) s0=new Array(2*x.length); copyInt_(s0,0); for (i=0;i<y.length;i++) if (y[i]) linCombShift_(s0,x,y[i],i); //s0=1*s0+y[i]*(x<<(i*bpe)) mod_(s0,n); copy_(x,s0); } //do x=x*x mod n for bigInts x,n. function squareMod_(x,n) { var i,j,d,c,kx,kn,k; for (kx=x.length; kx>0 && !x[kx-1]; kx--); //ignore leading zeros in x k=kx>n.length ? 2*kx : 2*n.length; //k=# elements in the product, which is twice the elements in the larger of x and n if (s0.length!=k) s0=new Array(k); copyInt_(s0,0); for (i=0;i<kx;i++) { c=s0[2*i]+x[i]*x[i]; s0[2*i]=c & mask; c>>=bpe; for (j=i+1;j<kx;j++) { c=s0[i+j]+2*x[i]*x[j]+c; s0[i+j]=(c & mask); c>>=bpe; } s0[i+kx]=c; } mod_(s0,n); copy_(x,s0); } //return x with exactly k leading zero elements function trim(x,k) { var i,y; for (i=x.length; i>0 && !x[i-1]; i--); y=new Array(i+k); copy_(y,x); return y; } //do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation. 0**0=1. //this is faster when n is odd. x usually needs to have as many elements as n. function powMod_(x,y,n) { var k1,k2,kn,np; if(s7.length!=n.length) s7=dup(n); //for even modulus, use a simple square-and-multiply algorithm, //rather than using the more complex Montgomery algorithm. if ((n[0]&1)==0) { copy_(s7,x); copyInt_(x,1); while(!equalsInt(y,0)) { if (y[0]&1) multMod_(x,s7,n); divInt_(y,2); squareMod_(s7,n); } return; } //calculate np from n for the Montgomery multiplications copyInt_(s7,0); for (kn=n.length;kn>0 && !n[kn-1];kn--); np=radix-inverseModInt(modInt(n,radix),radix); s7[kn]=1; multMod_(x ,s7,n); // x = x * 2**(kn*bp) mod n if (s3.length!=x.length) s3=dup(x); else copy_(s3,x); for (k1=y.length-1;k1>0 & !y[k1]; k1--); //k1=first nonzero element of y if (y[k1]==0) { //anything to the 0th power is 1 copyInt_(x,1); return; } for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1); //k2=position of first 1 bit in y[k1] for (;;) { if (!(k2>>=1)) { //look at next bit of y k1--; if (k1<0) { mont_(x,one,n,np); return; } k2=1<<(bpe-1); } mont_(x,x,n,np); if (k2 & y[k1]) //if next bit is a 1 mont_(x,s3,n,np); } } //do x=x*y*Ri mod n for bigInts x,y,n, // where Ri = 2**(-kn*bpe) mod n, and kn is the // number of elements in the n array, not // counting leading zeros. //x array must have at least as many elemnts as the n array //It's OK if x and y are the same variable. //must have: // x,y < n // n is odd // np = -(n^(-1)) mod radix function mont_(x,y,n,np) { var i,j,c,ui,t,ks; var kn=n.length; var ky=y.length; if (sa.length!=kn) sa=new Array(kn); copyInt_(sa,0); for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y ks=sa.length-1; //sa will never have more than this many nonzero elements. //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers for (i=0; i<kn; i++) { t=sa[0]+x[i]*y[0]; ui=((t & mask) * np) & mask; //the inner "& mask" was needed on Safari (but not MSIE) at one time c=(t+ui*n[0]) >> bpe; t=x[i]; //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed j=1; for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; } for (;j<ky;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; } for (;j<kn-4;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; } for (;j<kn;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; } for (;j<ks;) { c+=sa[j]; sa[j-1]=c & mask; c>>=bpe; j++; } sa[j-1]=c & mask; } if (!greater(n,sa)) sub_(sa,n); copy_(x,sa); }
msoftware/tutanota-1
web/lib/worker/crypto-jsbn-2012-08-09_1.js
JavaScript
gpl-3.0
90,904
/********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2014 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2014. All rights reserved". ********************************************************************************/ function processAjaxSuccessError(id, data) { if(data == 'failure') { alert('An error has occurred. You have attempted to access a page you do not have access to.'); return false; } } function processListViewSummaryClone(listViewId, summaryCssClass, summaryCloneId) { listViewSelector = $('#' + listViewId); replacementContent = $(listViewSelector).find('.' + summaryCssClass).html(); if (typeof(replacementContent) == 'undefined') { replacementContent = null; } summaryClone = $('#' + summaryCloneId); summaryClone.html(replacementContent); } function updateListViewSelectedIds(gridViewId, selectedId, selectedValue) { var array = new Array (); var processed = false; jQuery.each($('#' + gridViewId + "-selectedIds").val().split(','), function(i, value) { if(selectedId == value) { if(selectedValue) { array.push(value); } processed = true; } else { if(value != '') { array.push(value); } } } ); if(!processed && selectedValue) { array.push(selectedId); } $('#' + gridViewId + "-selectedIds").val(array.toString()); } function addListViewSelectedIdsToUrl(id, options) { options.url = $.param.querystring(options.url, 'selectedIds=' + $('#' + id + "-selectedIds").val()); } function resetSelectedListAttributes(selectedListAttributesId, hiddenListAttributesId, defaultSelectedAttributes) { $('#' + selectedListAttributesId + ' option').remove().appendTo('#' + hiddenListAttributesId); defaults = eval(defaultSelectedAttributes); for (i = 0; i < defaults.length; ++i) { $('#' + hiddenListAttributesId).find('option[value="' + defaults[i] + '"]').remove().appendTo('#' + selectedListAttributesId); }; $('#' + hiddenListAttributesId).find("option").each(function(){ if(jQuery.inArray($(this).val(), defaults) != -1) { $(this).remove().appendTo('#' + selectedListAttributesId); } }); return false; }
maruthisivaprasad/zurmo
app/themes/default/js/ListViewUtils.js
JavaScript
agpl-3.0
4,206
define( //begin v1.x content ({ loadingState: "טעינה...‏", errorState: "אירעה שגיאה" }) //end v1.x content );
sulistionoadi/belajar-springmvc-dojo
training-web/src/main/webapp/js/dojotoolkit/dijit/nls/he/loading.js
JavaScript
apache-2.0
129
"use strict"; var f = require('util').format, fs = require('fs'); exports['Correctly receive the APM events for an insert'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var started = []; var succeeded = []; var failed = []; var callbackTriggered = false; var listener = require('../..').instrument(function(err, instrumentations) { callbackTriggered = true; }); listener.on('started', function(event) { if(event.commandName == 'insert') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'insert') succeeded.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { test.equal(null, err); db.collection('apm_test').insertOne({a:1}).then(function(r) { test.equal(1, r.insertedCount); test.equal(1, started.length); test.equal(1, succeeded.length); test.ok(callbackTriggered); listener.uninstrument(); db.close(); test.done(); }); }); } } exports['Correctly receive the APM events for an insert using custom operationId and time generator'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var started = []; var succeeded = []; var failed = []; var callbackTriggered = false; var listener = require('../..').instrument({ operationIdGenerator: { next: function() { return 10000; } }, timestampGenerator: { current: function() { return 1; }, duration: function(start, end) { return end - start; } } }, function(err, instrumentations) { callbackTriggered = true; }); listener.on('started', function(event) { if(event.commandName == 'insert') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'insert') succeeded.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { db.collection('apm_test_1').insertOne({a:1}).then(function(r) { test.equal(1, started.length); test.equal(1, succeeded.length); test.equal(10000, started[0].operationId); test.equal(0, succeeded[0].duration); test.ok(callbackTriggered); listener.uninstrument(); db.close(); test.done(); }); }); } } var validateExpecations = function(test, expectation, results) { if(expectation.command_started_event) { // Get the command var obj = expectation.command_started_event; // Unpack the expectation var command = obj.command; var databaseName = obj.database_name; var commandName = obj.command_name; // Get the result var result = results.starts.shift(); // Validate the test test.equal(commandName, result.commandName) } else if(expectation.command_succeeded_event) { var obj = expectation.command_succeeded_event; // Unpack the expectation var reply = obj.reply; var databaseName = obj.database_name; var commandName = obj.command_name; // Get the result var result = results.successes.shift(); // Validate the test test.equal(commandName, result.commandName); // test.deepEqual(reply[0], result.reply.result); } else if(expectation.command_failed_event) { var obj = expectation.command_failed_event; // Unpack the expectation var reply = obj.reply; var databaseName = obj.database_name; var commandName = obj.command_name; // Get the result var result = results.failures.shift(); // Validate the test test.equal(commandName, result.commandName); } } var executeOperation = function(assert, client, listener, scenario, test, callback) { var successes = []; var failures = []; var starts = []; // Get the operation var operation = test.operation; // Get the command name var commandName = operation.name; // Get the arguments var args = operation.arguments || {}; // Get the database instance var db = client.db(scenario.database_name); // Get the collection var collection = db.collection(scenario.collection_name); // Parameters var params = []; // Get the data var data = scenario.data; // Drop the collection collection.drop(function(err) { // Insert the data collection.insertMany(data, function(err, r) { assert.equal(null, err); assert.equal(data.length, r.insertedCount); // Set up the listeners listener.on('started', function(event) { starts.push(event); }); listener.on('succeeded', function(event) { successes.push(event); }); listener.on('failed', function(event) { failures.push(event); }); // Cleanup the listeners var cleanUpListeners = function(_listener) { _listener.removeAllListeners('started'); _listener.removeAllListeners('succeeded'); _listener.removeAllListeners('failed'); } // Unpack the operation if(args.filter) { params.push(args.filter); } if(args.deletes) { params.push(args.deletes); } if(args.document) { params.push(args.document); } if(args.documents) { params.push(args.documents); } if(args.update) { params.push(args.update); } if(args.requests) { params.push(args.requests); } // Find command is special needs to executed using toArray if(operation.name == 'find') { var cursor = collection[commandName](); if(args.filter) { cursor = cursor.filter(args.filter); } if(args.batchSize) { cursor = cursor.batchSize(args.batchSize); } if(args.limit) { cursor = cursor.limit(args.limit); } // Execute find cursor.toArray(function(err, r) { // Validate the expectations test.expectations.forEach(function(x, index) { validateExpecations(assert, x, { successes: successes, failures: failures, starts: starts }); }); // Cleanup listeners cleanUpListeners(listener); // Finish the operation callback(); }); } else { params.push(function(err, result) { // Validate the expectations test.expectations.forEach(function(x, index) { validateExpecations(assert, x, { successes: successes, failures: failures, starts: starts }); }); // Cleanup listeners cleanUpListeners(listener); // Finish the operation callback(); }); // Execute the operation collection[commandName].apply(collection, params); } }); }); } var executeTests = function(assert, client, listener, scenario, tests, callback) { if(tests.length == 0) return callback(); // Get the scenario var test = tests.shift(); // Execute the test console.log(f('execute test [%s]', test.description)); // Setup and execute the operation executeOperation(assert, client, listener, scenario, test, function() { // Execute the next test executeTests(assert, client, listener, scenario, tests, callback); }); } var executeSuite = function(assert, client, listener, scenarios, callback) { if(scenarios.length == 0) return callback(); // Get the scenario var scenario = scenarios.shift(); // Get the data var data = scenario.data; // Get the database var db = client.db(scenario.database_name); // Insert into the db var collection = db.collection(scenario.collection_name); // Execute the tests executeTests(assert, client, listener, scenario, scenario.tests.slice(0), function() { // Execute the next suite executeSuite(assert, client, listener, scenarios, callback); }); } exports['Correctly run all JSON APM Tests'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { // Read all the json files for the APM spec var scenarios = fs.readdirSync(__dirname + '/apm').filter(function(x) { return x.indexOf('.json') != -1; }).map(function(x) { return JSON.parse(fs.readFileSync(__dirname + '/apm/' + x)); }); // Get the methods var MongoClient = require('../..'); var listener = require('../../').instrument(); // Connect to the db MongoClient.connect(configuration.url(), function(err, client) { test.equal(null, err); // Execute each group of tests executeSuite(test, client, listener, scenarios.slice(0), function(err) { test.equal(null, err); listener.uninstrument(); client.close(); test.done(); }); }); } } exports['Correctly receive the APM events for a find with getmore and killcursor'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var ReadPreference = configuration.require.ReadPreference; var started = []; var succeeded = []; var failed = []; var listener = require('../..').instrument(); listener.on('started', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') succeeded.push(event); }); listener.on('failed', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') failed.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { test.equal(null, err); // Drop the collection db.collection('apm_test_2').drop(function(err, r) { // Insert test documents db.collection('apm_test_2').insertMany([{a:1}, {a:1}, {a:1}, {a:1}, {a:1}, {a:1}], {w:1}).then(function(r) { test.equal(6, r.insertedCount); db.collection('apm_test_2').find({a:1}) .project({_id: 1, a:1}) .hint({'_id':1}) .skip(1) .limit(100) .batchSize(2) .comment('some comment') .maxScan(1000) .maxTimeMS(5000) .setReadPreference(ReadPreference.PRIMARY) .addCursorFlag('noCursorTimeout', true) .toArray().then(function(docs) { // Assert basic documents test.equal(5, docs.length); test.equal(3, started.length); test.equal(3, succeeded.length); test.equal(0, failed.length); // Success messages test.equal(2, succeeded[0].reply.length); test.equal(succeeded[0].operationId, succeeded[1].operationId); test.equal(succeeded[0].operationId, succeeded[2].operationId); test.equal(2, succeeded[1].reply.length); test.equal(1, succeeded[2].reply.length); // Started test.equal(started[0].operationId, started[1].operationId); test.equal(started[0].operationId, started[2].operationId); listener.uninstrument(); db.close(); test.done(); }).catch(function(err) { console.log(err.stack) }); }).catch(function(e) { console.log(err.stack) }); }); }); } } exports['Correctly receive the APM failure event for find'] = { metadata: { requires: { topology: ['single'], mongodb: ">=2.6.0" } }, // The actual test we wish to run test: function(configuration, test) { var ReadPreference = configuration.require.ReadPreference; var started = []; var succeeded = []; var failed = []; var listener = require('../..').instrument(); listener.on('started', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') succeeded.push(event); }); listener.on('failed', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors') failed.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { test.equal(null, err); // Drop the collection db.collection('apm_test_2').drop(function(err, r) { // Insert test documents db.collection('apm_test_2').insertMany([{a:1}, {a:1}, {a:1}, {a:1}, {a:1}, {a:1}]).then(function(r) { test.equal(6, r.insertedCount); db.collection('apm_test_2').find({$illegalfield:1}) .project({_id: 1, a:1}) .hint({'_id':1}) .skip(1) .limit(100) .batchSize(2) .comment('some comment') .maxScan(1000) .maxTimeMS(5000) .setReadPreference(ReadPreference.PRIMARY) .addCursorFlag('noCursorTimeout', true) .toArray().then(function(docs) { }).catch(function(err) { test.equal(1, failed.length); listener.uninstrument(); db.close(); test.done(); }); }).catch(function(e) { console.dir(e) }); }); }); } } var cleanup = function(overrides) { overrides.forEach(function(x) { x.obj[x.method] = x.func; }); } exports['Correctly receive the APM events for a bulk operation'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var started = []; var succeeded = []; var failed = []; var listener = require('../..').instrument(); listener.on('started', function(event) { if(event.commandName == 'insert' || event.commandName == 'update' || event.commandName == 'delete') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'insert' || event.commandName == 'update' || event.commandName == 'delete') succeeded.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { db.collection('apm_test_3').bulkWrite([ { insertOne: { a: 1 } } , { updateOne: { q: {a:2}, u: {$set: {a:2}}, upsert:true } } , { deleteOne: { q: {c:1} } } ], {ordered:true}).then(function(r) { test.equal(3, started.length); test.equal(3, succeeded.length); test.equal(started[0].operationId, started[1].operationId); test.equal(started[0].operationId, started[2].operationId); test.equal(succeeded[0].operationId, succeeded[1].operationId); test.equal(succeeded[0].operationId, succeeded[2].operationId); listener.uninstrument(); db.close(); test.done(); }).catch(function(err) { console.dir(err) }); }); } } exports['Correctly receive the APM explain command'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var ReadPreference = configuration.require.ReadPreference; var started = []; var succeeded = []; var failed = []; var listener = require('../..').instrument(); listener.on('started', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors' || event.commandName == 'explain') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors' || event.commandName == 'explain') succeeded.push(event); }); listener.on('failed', function(event) { if(event.commandName == 'find' || event.commandName == 'getMore' || event.commandName == 'killCursors' || event.commandName == 'explain') failed.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { test.equal(null, err); // Drop the collection db.collection('apm_test_2').drop(function(err, r) { // Insert test documents db.collection('apm_test_2').insertMany([{a:1}, {a:1}, {a:1}, {a:1}, {a:1}, {a:1}], {w:1}).then(function(r) { test.equal(6, r.insertedCount); db.collection('apm_test_2').find({a:1}) .explain().then(function(explain) { test.ok(explain != null); test.equal(1, started.length); test.equal('explain', started[0].commandName); test.equal('apm_test_2', started[0].command.explain.find); test.equal(1, succeeded.length); test.equal('explain', succeeded[0].commandName); // Started test.equal(started[0].operationId, succeeded[0].operationId); // Remove instrumentation listener.uninstrument(); db.close(); test.done(); }).catch(function(err) { console.log(err.stack) }); }).catch(function(e) { console.log(err.stack) }); }); }); } } exports['Correctly filter out sensitive commands'] = { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(configuration, test) { var ReadPreference = configuration.require.ReadPreference; var started = []; var succeeded = []; var failed = []; var listener = require('../..').instrument(); listener.on('started', function(event) { if(event.commandName == 'getnonce') started.push(event); }); listener.on('succeeded', function(event) { if(event.commandName == 'getnonce') succeeded.push(event); }); listener.on('failed', function(event) { if(event.commandName == 'getnonce') failed.push(event); }); var db = configuration.newDbInstance({w:1}, {poolSize:1, auto_reconnect:false}); db.open(function(err, db) { test.equal(null, err); db.command({getnonce:true}, function(err, r) { test.equal(null, err); test.ok(r != null); test.equal(1, started.length); test.equal(1, succeeded.length); test.equal(0, failed.length); test.deepEqual({getnonce:true}, started[0].commandObj); test.deepEqual({}, succeeded[0].reply); // Remove instrumentation listener.uninstrument(); db.close(); test.done(); }); }); } }
capaj/node-mongodb-native
test/functional/apm_tests.js
JavaScript
apache-2.0
19,537
'use strict'; var fs = require('fs'); var utils = require('./utils'); /** * Add the `contents` property to a `file` object. * * @param {Object} `options` * @return {Object} File object. * @api public */ module.exports = function(options) { return utils.through.obj(function(file, enc, next) { contentsAsync(file, options, next); }); }; /** * Async method for getting `file.contents`. * * @param {Object} `file` * @param {Object} `options` * @param {Function} `cb` * @return {Object} */ function contentsAsync(file, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (typeof cb !== 'function') { throw new TypeError('expected a callback function'); } if (!utils.isObject(file)) { cb(new TypeError('expected file to be an object')); return; } contentsSync(file, options); cb(null, file); } /** * Sync method for getting `file.contents`. * * @param {Object} `file` * @param {Object} `options` * @return {Object} */ function contentsSync(file, options) { if (!utils.isObject(file)) { throw new TypeError('expected file to be an object'); } try { // ideally we want to stat the real, initial filepath file.stat = fs.lstatSync(file.history[0]); } catch (err) { try { // if that doesn't work, try again file.stat = fs.lstatSync(file.path); } catch (err) { file.stat = new fs.Stats(); } } utils.syncContents(file, options); return file; } /** * Expose `async` method */ module.exports.async = contentsAsync; /** * Expose `sync` method */ module.exports.sync = contentsSync;
mrtequino/JSW
nodejs/pos-server/node_modules/base-config-schema/node_modules/file-contents/index.js
JavaScript
apache-2.0
1,645
//>>built define("dojox/gantt/GanttChart","./GanttProjectItem ./GanttResourceItem ./GanttProjectControl ./GanttTaskControl ./GanttTaskItem ./TabMenu dijit/Tooltip dojo/_base/declare dojo/_base/array dojo/_base/lang dojo/date/locale dojo/request dojo/request/util dojo/on dojo/dom dojo/dom-class dojo/dom-construct dojo/dom-style dojo/dom-attr dojo/dom-geometry dojo/keys dojo/has dojo/_base/window dojo/json dojo/domReady!".split(" "),function(w,C,v,x,y,D,K,E,k,l,q,z,F,n,G,r,h,f,p,A,s,H,I,B){return E("dojox.gantt.GanttChart", [],{constructor:function(b,a){this.resourceChartHeight=void 0!==b.resourceChartHeight?b.resourceChartHeight:!1;this.withResource=void 0!==b.withResource?b.withResource:!0;this.correctError=void 0!==b.autoCorrectError?b.autoCorrectError:!1;this.isShowConMenu=this.isContentEditable=!b.readOnly;this.withTaskId=void 0!==b.withTaskId?b.withTaskId:!b.readOnly;this.animation=void 0!==b.animation?b.animation:!0;this.saveProgramPath=b.saveProgramPath||"saveGanttData.php";this.dataFilePath=b.dataFilePath|| "gantt_default.json";this.contentHeight=b.height||400;this.contentWidth=b.width||600;this.content=G.byId(a);this.scrollBarWidth=18;this.panelTimeHeight=102;this.maxWidthTaskNames=this.maxWidthPanelNames=150;this.minWorkLength=8;this.heightTaskItem=12;this.heightTaskItemExtra=11;this.pixelsPerDay=24;this.hsPerDay=8;this.pixelsPerWorkHour=this.pixelsPerDay/this.hsPerDay;this.pixelsPerHour=this.pixelsPerDay/24;this.totalDays=this.countDays=0;this.startDate=null;this.contentDataHeight=this.initialPos= 0;this.panelTimeExpandDelta=20;this.tabMenu=this.contentData=this.panelTime=this.panelNames=this.divTimeInfo=null;this.project=[];this.arrProjects=[];this.xmlLoader=null;this.isResizing=this.isMoving=!1;this.animationNodes=[];this.scale=1;this.tempDayInPixels=0;this.resource=null;this.months=q.getNames("months","wide");this._events=[]},getProject:function(b){return k.filter(this.arrProjects,function(a){return a.project.id==b},this)[0]},checkPosPreviousTask:function(b,a){var c=this.getWidthOnDuration(b.duration), d=this.getPosOnDate(b.startTime),e=this.getPosOnDate(a.startTime);return c+d<=e},correctPosPreviousTask:function(b,a,c){var d=new Date(b.startTime);d.setHours(d.getHours()+24*(b.duration/this.hsPerDay));0<d.getHours()&&(d.setHours(0),d.setDate(d.getDate()+1));c?c.setStartTime(d,!0):a.startTime=d;a.parentTask&&!this.checkPosParentTask(a.parentTask,a)&&(b=new Date(a.parentTask.startTime),b.setHours(b.getHours()+24*(a.parentTask.duration/this.hsPerDay)),a.duration=parseInt(parseInt((b-a.startTime)/36E5)* this.hsPerDay/24))},correctPosParentTask:function(b,a){a.previousTask?this.correctPosPreviousTask(a.previousTask,a):(b.startTime>a.startTime&&(a.startTime=new Date(b.startTime)),this.checkPosParentTask(b,a)||(a.duration=b.duration))},checkPosParentTaskInTree:function(b){for(var a=!1,c=0;c<b.cldTasks.length;c++){var d=b.cldTasks[c];if(!this.checkPosParentTask(b,d))if(this.correctError)this.correctPosParentTask(b,d);else return!0;if(b.startTime>d.startTime)if(this.correctError)this.correctPosParentTask(b, d);else return!0;0<d.cldTasks.length&&(a=this.checkPosParentTaskInTree(d))}return a},setPreviousTask:function(b){for(var a=!1,c=0;c<b.parentTasks.length;c++){a=b.parentTasks[c];if(a.previousTaskId){a.previousTask=b.getTaskById(a.previousTaskId);if(!a.previousTask&&!this.correctError)return!0;a.previousTask.cldPreTasks.push(a)}if(a.previousTask&&!this.checkPosPreviousTask(a.previousTask,a))if(this.correctError)this.correctPosPreviousTask(a.previousTask,a);else return!0;a=this.setPreviousTaskInTree(a)}return a}, setPreviousTaskInTree:function(b){for(var a=!1,c=0;c<b.cldTasks.length;c++){var d=b.cldTasks[c];if(d.previousTaskId){d.previousTask=b.project.getTaskById(d.previousTaskId);if(!d.previousTask&&!this.correctError)return!0;if(!this.checkPosPreviousTask(d.previousTask,d))if(this.correctError)this.correctPosPreviousTask(d.previousTask,d);else return!0;d.previousTask.cldPreTasks.push(d)}0<d.cldTasks.length&&(a=this.setPreviousTaskInTree(d))}return a},checkPosParentTask:function(b,a){var c=this.getWidthOnDuration(b.duration), d=this.getPosOnDate(b.startTime),e=this.getPosOnDate(a.startTime),g=this.getWidthOnDuration(a.duration);return c+d>=e+g},addProject:function(b){this.project.push(b)},deleteProject:function(b){var a=this.getProject(b);if(a){if(0<a.arrTasks.length)for(;0<a.arrTasks.length;)a.deleteChildTask(a.arrTasks[0]);var c=this.heightTaskItemExtra+this.heightTaskItem;a.nextProject&&a.shiftNextProject(a,-c);this.project=k.filter(this.project,function(b){return b.id!=a.project.id},this);a.previousProject&&a.nextProject&& (c=a.previousProject,c.nextProject=a.nextProject);a.previousProject&&!a.nextProject&&(c=a.previousProject,c.nextProject=null);!a.previousProject&&a.nextProject&&(a.nextProject.previousProject=null);for(c=0;c<this.arrProjects.length;c++)this.arrProjects[c].project.id==b&&this.arrProjects.splice(c,1);a.projectItem[0].parentNode.removeChild(a.projectItem[0]);a.descrProject.parentNode.removeChild(a.descrProject);a.projectNameItem.parentNode.removeChild(a.projectNameItem);this.contentDataHeight-=this.heightTaskItemExtra+ this.heightTaskItem;0==this.project.length&&(b=new Date(this.startDate),b=new Date(b.setDate(b.getDate()+1)),b=new w({id:1,name:"New Project",startDate:b}),this.project.push(b),a=new v(this,b),a.create(),this.arrProjects.push(a),this.contentDataHeight+=this.heightTaskItemExtra+this.heightTaskItem);this.checkPosition()}},insertProject:function(b,a,c){if(this.startDate>=c||this.getProject(b))return!1;this.checkHeighPanelTasks();b=new w({id:b,name:a,startDate:c});this.project.push(b);b=new v(this,b); for(a=0;a<this.arrProjects.length;a++){var d=this.arrProjects[a-1],e=this.arrProjects[a+1];if(c<this.arrProjects[a].project.startDate)return this.arrProjects.splice(a,0,b),0<a&&(b.previousProject=d,d.nextProject=b),a+1<=this.arrProjects.length&&(b.nextProject=e,e.previousProject=b,b.shiftNextProject(b,this.heightTaskItem+this.heightTaskItemExtra)),b.create(),b.hideDescrProject(),this.checkPosition(),b}0<this.arrProjects.length&&(this.arrProjects[this.arrProjects.length-1].nextProject=b,b.previousProject= this.arrProjects[this.arrProjects.length-1]);this.arrProjects.push(b);b.create();b.hideDescrProject();this.checkPosition();return b},openTree:function(b){var a=this.getLastCloseParent(b);this.openNode(a);b.taskItem.id!=a.taskItem.id&&this.openTree(b)},openNode:function(b){b.isExpanded||(r.remove(b.cTaskNameItem[2],"ganttImageTreeExpand"),r.add(b.cTaskNameItem[2],"ganttImageTreeCollapse"),b.isExpanded=!0,b.shiftCurrentTasks(b,b.hideTasksHeight),b.showChildTasks(b,b.isExpanded),b.hideTasksHeight=0)}, getLastCloseParent:function(b){return b.parentTask?!b.parentTask.isExpanded||"none"==b.parentTask.cTaskNameItem[2].style.display?this.getLastCloseParent(b.parentTask):b:b},getProjectItemById:function(b){return k.filter(this.project,function(a){return a.id==b},this)[0]},clearAll:function(){this.contentDataHeight=0;this.startDate=null;this.clearData();this.clearItems();this.clearEvents()},clearEvents:function(){k.forEach(this._events,function(b){b.remove()});this._events=[]},clearData:function(){this.project= [];this.arrProjects=[]},clearItems:function(){this.contentData.removeChild(this.contentData.firstChild);this.contentData.appendChild(this.createPanelTasks());this.panelNames.removeChild(this.panelNames.firstChild);this.panelNames.appendChild(this.createPanelNamesTasks());this.panelTime.removeChild(this.panelTime.firstChild)},buildUIContent:function(){this.project.sort(this.sortProjStartDate);this.startDate=this.getStartDate();this.panelTime.appendChild(this.createPanelTime());for(var b=0;b<this.project.length;b++){for(var a= this.project[b],c=0;c<a.parentTasks.length;c++){var d=a.parentTasks[c];if(d.startTime)this.setStartTimeChild(d);else return;if(this.setPreviousTask(a))return}for(c=0;c<a.parentTasks.length;c++)if(d=a.parentTasks[c],d.startTime<a.startDate||this.checkPosParentTaskInTree(d))return;this.sortTasksByStartTime(a)}for(b=0;b<this.project.length;b++)a=this.project[b],a=new v(this,a),0<this.arrProjects.length&&(c=this.arrProjects[this.arrProjects.length-1],a.previousProject=c,c.nextProject=a),a.create(),this.checkHeighPanelTasks(), this.arrProjects.push(a),this.createTasks(a);this.resource&&this.resource.reConstruct();this.postLoadData();this.postBindEvents()},loadJSONData:function(b){var a=this;a.dataFilePath=b||a.dataFilePath;z.get(a.dataFilePath,{sync:!0}).then(function(b){a.loadJSONString(b.text);a.buildUIContent();console.log("Successfully! Loaded data from: "+a.dataFilePath)},function(){console.log("Failed! Load error: "+a.dataFilePath)})},loadJSONString:function(b){b&&(this.clearAll(),b=B.parse(b).items,k.forEach(b,function(a){var b= a.startdate.split("-"),d=new w({id:a.id,name:a.name,startDate:new Date(b[0],parseInt(b[1])-1,b[2])});k.forEach(a.tasks,function(a){var b=a.id,c=a.name,f=a.starttime.split("-"),h=a.duration,k=a.percentage,J=a.previousTaskId,l=a.taskOwner,b=new y({id:b,name:c,startTime:new Date(f[0],parseInt(f[1])-1,f[2]),duration:h,percentage:k,previousTaskId:J,taskOwner:l});a=a.children;0!=a.length&&this.buildChildTasksData(b,a);d.addTask(b)},this);this.addProject(d)},this))},buildChildTasksData:function(b,a){a&& k.forEach(a,function(a){var d=a.id,e=a.name,g=a.starttime.split("-"),m=a.duration,f=a.percentage,h=a.previousTaskId,k=a.taskOwner,d=new y({id:d,name:e,startTime:new Date(g[0],parseInt(g[1])-1,g[2]),duration:m,percentage:f,previousTaskId:h,taskOwner:k});d.parentTask=b;b.addChildTask(d);a=a.children;0!=a.length&&this.buildChildTasksData(d,a)},this)},getJSONData:function(){var b={identifier:"id",items:[]};k.forEach(this.project,function(a){var c={id:a.id,name:a.name,startdate:a.startDate.getFullYear()+ "-"+(a.startDate.getMonth()+1)+"-"+a.startDate.getDate(),tasks:[]};b.items.push(c);k.forEach(a.parentTasks,function(a){a={id:a.id,name:a.name,starttime:a.startTime.getFullYear()+"-"+(a.startTime.getMonth()+1)+"-"+a.startTime.getDate(),duration:a.duration,percentage:a.percentage,previousTaskId:a.previousTaskId||"",taskOwner:a.taskOwner||"",children:this.getChildTasksData(a.cldTasks)};c.tasks.push(a)},this)},this);return b},getChildTasksData:function(b){var a=[];b&&0<b.length&&k.forEach(b,function(b){b= {id:b.id,name:b.name,starttime:b.startTime.getFullYear()+"-"+(b.startTime.getMonth()+1)+"-"+b.startTime.getDate(),duration:b.duration,percentage:b.percentage,previousTaskId:b.previousTaskId||"",taskOwner:b.taskOwner||"",children:this.getChildTasksData(b.cldTasks)};a.push(b)},this);return a},saveJSONData:function(b){var a=this;a.dataFilePath=b&&0<l.trim(b).length?b:this.dataFilePath;try{z.post(a.saveProgramPath,{query:{filename:a.dataFilePath,data:B.stringify(a.getJSONData())}}).response.then(function(b){F.checkStatus(b.options.status)|| 405==b.options.status?console.log("Successfully! Saved data to "+a.dataFilePath):console.log("Failed! Saved error")})}catch(c){console.log("exception: "+c.message)}},sortTaskStartTime:function(b,a){return b.startTime<a.startTime?-1:b.startTime>a.startTime?1:0},sortProjStartDate:function(b,a){return b.startDate<a.startDate?-1:b.startDate>a.startDate?1:0},setStartTimeChild:function(b){k.forEach(b.cldTasks,function(a){a.startTime||(a.startTime=b.startTime);0!=a.cldTasks.length&&this.setStartTimeChild(a)}, this)},createPanelTasks:function(){var b=h.create("div",{className:"ganttTaskPanel"});f.set(b,{height:this.contentHeight-this.panelTimeHeight-this.scrollBarWidth+"px"});return b},refreshParams:function(b){this.pixelsPerDay=b;this.pixelsPerWorkHour=this.pixelsPerDay/this.hsPerDay;this.pixelsPerHour=this.pixelsPerDay/24},createPanelNamesTasksHeader:function(){var b=h.create("div",{className:"ganttPanelHeader"}),a=h.create("table",{cellPadding:"0px",border:"0px",cellSpacing:"0px",bgColor:"#FFFFFF",className:"ganttToolbar"}, b),c=a.insertRow(a.rows.length),d=a.insertRow(a.rows.length),e=a.insertRow(a.rows.length);a.insertRow(a.rows.length);var a=h.create("td",{align:"center",vAlign:"middle",className:"ganttToolbarZoomIn"},c),g=l.hitch(this,function(){5<2*this.scale||(this.scale*=2,this.switchTeleMicroView(this.pixelsPerDay*this.scale))});this.zoomInClickEvent&&this.zoomInClickEvent.remove();this.zoomInClickEvent=n(a,"click",l.hitch(this,g));this.zoomInKeyEvent&&this.zoomInKeyEvent.remove();this.zoomInKeyEvent=n(a,"keydown", l.hitch(this,function(a){a.keyCode==s.ENTER&&g()}));p.set(a,"tabIndex",0);var c=h.create("td",{align:"center",vAlign:"middle",className:"ganttToolbarZoomOut"},c),f=l.hitch(this,function(){0.2>0.5*this.scale||(this.scale*=0.5,this.switchTeleMicroView(this.pixelsPerDay*this.scale))});this.zoomOutClickEvent&&this.zoomOutClickEvent.remove();this.zoomOutClickEvent=n(c,"click",l.hitch(this,f));this.zoomOutKeyEvent&&this.zoomOutKeyEvent.remove();this.zoomOutKeyEvent=n(c,"keydown",l.hitch(this,function(a){a.keyCode== s.ENTER&&f()}));p.set(c,"tabIndex",0);var t=h.create("td",{align:"center",vAlign:"middle",className:"ganttToolbarMicro"},d);this.microClickEvent&&this.microClickEvent.remove();this.microClickEvent=n(t,"click",l.hitch(this,this.refresh,this.animation?15:1,0,2));this.microKeyEvent&&this.microKeyEvent.remove();this.microKeyEvent=n(t,"keydown",l.hitch(this,function(a){a.keyCode==s.ENTER&&(t.blur(),this.refresh(this.animation?15:1,0,2))}));p.set(t,"tabIndex",0);var u=h.create("td",{align:"center",vAlign:"middle", className:"ganttToolbarTele"},d);this.teleClickEvent&&this.teleClickEvent.remove();this.teleClickEvent=n(u,"click",l.hitch(this,this.refresh,this.animation?15:1,0,0.5));this.teleKeyEvent&&this.teleKeyEvent.remove();this.teleKeyEvent=n(u,"keydown",l.hitch(this,function(a){a.keyCode==s.ENTER&&(u.blur(),this.refresh(this.animation?15:1,0,0.5))}));p.set(u,"tabIndex",0);d=h.create("td",{align:"center",vAlign:"middle",className:"ganttToolbarSave"},e);this.saveClickEvent&&this.saveClickEvent.remove();this.saveClickEvent= n(d,"click",l.hitch(this,this.saveJSONData,""));this.saveKeyEvent&&this.saveKeyEvent.remove();this.saveKeyEvent=n(d,"keydown",l.hitch(this,function(a){a.keyCode==s.ENTER&&this.saveJSONData("")}));p.set(d,"tabIndex",0);e=h.create("td",{align:"center",vAlign:"middle",className:"ganttToolbarLoad"},e);this.loadClickEvent&&this.loadClickEvent.remove();this.loadClickEvent=n(e,"click",l.hitch(this,this.loadJSONData,""));this.loadKeyEvent&&this.loadKeyEvent.remove();this.loadKeyEvent=n(e,"keydown",l.hitch(this, function(a){a.keyCode==s.ENTER&&this.loadJSONData("")}));p.set(e,"tabIndex",0);var q="Enlarge timeline;Shrink timeline;Zoom in time zone(microscope view);Zoom out time zone(telescope view);Save gantt data to json file;Load gantt data from json file".split(";");k.forEach([a,c,t,u,d,e],function(a,b){var c=q[b],d=function(){r.add(a,"ganttToolbarActionHover");dijit.showTooltip(c,a,["above","below"])};a.onmouseover=d;a.onfocus=d;d=function(){r.remove(a,"ganttToolbarActionHover");a&&dijit.hideTooltip(a)}; a.onmouseout=d;a.onblur=d},this);return b},createPanelNamesTasks:function(){var b=h.create("div",{innerHTML:"\x26nbsp;",className:"ganttPanelNames"});f.set(b,{height:this.contentHeight-this.panelTimeHeight-this.scrollBarWidth+"px",width:this.maxWidthPanelNames+"px"});return b},createPanelTime:function(){var b=h.create("div",{className:"ganttPanelTime"}),a=h.create("table",{cellPadding:"0px",border:"0px",cellSpacing:"0px",bgColor:"#FFFFFF",className:"ganttTblTime"},b);this.totalDays=this.countDays; var c=a.insertRow(a.rows.length),d,e,g=0;e=d=(new Date(this.startDate)).getFullYear();for(var m=0;m<this.countDays;m++,g++)e=new Date(this.startDate),e.setDate(e.getDate()+m),e=e.getFullYear(),e!=d&&(this.addYearInPanelTime(c,g,d),g=0,d=e);this.addYearInPanelTime(c,g,e);f.set(c,"display","none");d=a.insertRow(a.rows.length);var k,c=0;e=1970;k=g=(new Date(this.startDate)).getMonth();for(m=0;m<this.countDays;m++,c++)e=new Date(this.startDate),e.setDate(e.getDate()+m),k=e.getMonth(),e=e.getFullYear(), k!=g&&(this.addMonthInPanelTime(d,c,g,11!==g?e:e-1),c=0,g=k);this.addMonthInPanelTime(d,c,k,e);d=a.insertRow(a.rows.length);c=0;e=g=q._getWeekOfYear(new Date(this.startDate));for(m=0;m<this.countDays;m++,c++)e=new Date(this.startDate),e.setDate(e.getDate()+m),e=q._getWeekOfYear(e),e!=g&&(this.addWeekInPanelTime(d,c,g),c=0,g=e);this.addWeekInPanelTime(d,c,e);e=a.insertRow(a.rows.length);for(m=0;m<this.countDays;m++)this.addDayInPanelTime(e);a=a.insertRow(a.rows.length);for(m=0;m<this.countDays;m++)this.addHourInPanelTime(a); f.set(a,"display","none");return b},adjustPanelTime:function(){var b=k.map(this.arrProjects,function(a){return parseInt(a.projectItem[0].style.left)+parseInt(a.projectItem[0].firstChild.style.width)+a.descrProject.offsetWidth+this.panelTimeExpandDelta},this).sort(function(a,b){return b-a})[0];if(this.maxTaskEndPos!=b){for(var a=this.panelTime.firstChild.firstChild.rows,c=0;4>=c;c++)this.removeCell(a[c]);var d=Math.round((b+this.panelTimeExpandDelta)/this.pixelsPerDay);this.totalDays=d;var e,g,f=0; g=e=(new Date(this.startDate)).getFullYear();for(c=0;c<d;c++,f++)g=new Date(this.startDate),g.setDate(g.getDate()+c),g=g.getFullYear(),g!=e&&(this.addYearInPanelTime(a[0],f,e),f=0,e=g);this.addYearInPanelTime(a[0],f,g);var h;e=0;g=1970;h=f=(new Date(this.startDate)).getMonth();for(c=0;c<d;c++,e++)g=new Date(this.startDate),g.setDate(g.getDate()+c),h=g.getMonth(),g=g.getFullYear(),h!=f&&(this.addMonthInPanelTime(a[1],e,f,11!==f?g:g-1),e=0,f=h);this.addMonthInPanelTime(a[1],e,h,g);e=0;g=f=q._getWeekOfYear(new Date(this.startDate)); for(c=0;c<d;c++,e++)g=new Date(this.startDate),g.setDate(g.getDate()+c),g=q._getWeekOfYear(g),g!=f&&(this.addWeekInPanelTime(a[2],e,f),e=0,f=g);this.addWeekInPanelTime(a[2],e,g);for(c=0;c<d;c++)this.addDayInPanelTime(a[3]);for(c=0;c<d;c++)this.addHourInPanelTime(a[4]);this.panelTime.firstChild.firstChild.style.width=this.pixelsPerDay*a[3].cells.length+"px";this.contentData.firstChild.style.width=this.pixelsPerDay*a[3].cells.length+"px";this.maxTaskEndPos=b}},addYearInPanelTime:function(b,a,c){c="Year "+ c;b=h.create("td",{colSpan:a,align:"center",vAlign:"middle",className:"ganttYearNumber",innerHTML:20<this.pixelsPerDay*a?c:"",innerHTMLData:c},b);f.set(b,"width",this.pixelsPerDay*a+"px")},addMonthInPanelTime:function(b,a,c,d){c=this.months[c]+(d?" of "+d:"");b=h.create("td",{colSpan:a,align:"center",vAlign:"middle",className:"ganttMonthNumber",innerHTML:30<this.pixelsPerDay*a?c:"",innerHTMLData:c},b);f.set(b,"width",this.pixelsPerDay*a+"px")},addWeekInPanelTime:function(b,a,c){c="Week "+c;b=h.create("td", {colSpan:a,align:"center",vAlign:"middle",className:"ganttWeekNumber",innerHTML:20<this.pixelsPerDay*a?c:"",innerHTMLData:c},b);f.set(b,"width",this.pixelsPerDay*a+"px")},addDayInPanelTime:function(b){var a=new Date(this.startDate);a.setDate(a.getDate()+parseInt(b.cells.length));var c=h.create("td",{align:"center",vAlign:"middle",className:"ganttDayNumber",innerHTML:20<this.pixelsPerDay?a.getDate():"",innerHTMLData:String(a.getDate()),data:b.cells.length},b);f.set(c,"width",this.pixelsPerDay+"px"); 5<=a.getDay()&&r.add(c,"ganttDayNumberWeekend");this._events.push(n(c,"mouseover",l.hitch(this,function(a){a=a.target||a.srcElement;var b=new Date(this.startDate.getTime());b.setDate(b.getDate()+parseInt(p.get(a,"data")));dijit.showTooltip(b.getFullYear()+"."+(b.getMonth()+1)+"."+b.getDate(),c,["above","below"])})));this._events.push(n(c,"mouseout",l.hitch(this,function(a){(a=a.target||a.srcElement)&&dijit.hideTooltip(a)})))},addHourInPanelTime:function(b){b=h.create("td",{align:"center",vAlign:"middle", className:"ganttHourNumber",data:b.cells.length},b);f.set(b,"width",this.pixelsPerDay+"px");b=h.create("table",{cellPadding:"0",cellSpacing:"0"},b);b=b.insertRow(b.rows.length);for(var a=0;a<this.hsPerDay;a++){var c=h.create("td",{className:"ganttHourClass"},b);f.set(c,"width",this.pixelsPerDay/this.hsPerDay+"px");p.set(c,"innerHTMLData",String(9+a));5<this.pixelsPerDay/this.hsPerDay&&p.set(c,"innerHTML",String(9+a));r.add(c,3>=a?"ganttHourNumberAM":"ganttHourNumberPM")}},incHeightPanelTasks:function(b){var a= this.contentData.firstChild;a.style.height=parseInt(a.style.height)+b+"px"},incHeightPanelNames:function(b){var a=this.panelNames.firstChild;a.style.height=parseInt(a.style.height)+b+"px"},checkPosition:function(){k.forEach(this.arrProjects,function(b){k.forEach(b.arrTasks,function(a){a.checkPosition()},this)},this)},checkHeighPanelTasks:function(){this.contentDataHeight+=this.heightTaskItemExtra+this.heightTaskItem;parseInt(this.contentData.firstChild.style.height)<=this.contentDataHeight&&(this.incHeightPanelTasks(this.heightTaskItem+ this.heightTaskItemExtra),this.incHeightPanelNames(this.heightTaskItem+this.heightTaskItemExtra))},sortTasksByStartTime:function(b){b.parentTasks.sort(this.sortTaskStartTime);for(var a=0;a<b.parentTasks.length;a++)b.parentTasks[a]=this.sortChildTasks(b.parentTasks[a])},sortChildTasks:function(b){b.cldTasks.sort(this.sortTaskStartTime);for(var a=0;a<b.cldTasks.length;a++)0<b.cldTasks[a].cldTasks.length&&this.sortChildTasks(b.cldTasks[a]);return b},refresh:function(b,a,c){if(!(0>=this.arrProjects.length)&& !(0>=this.arrProjects[0].arrTasks.length))if(!b||a>b)this.refreshController(),this.resource&&this.resource.refresh(),this.tempDayInPixels=0,this.panelNameHeadersCover&&f.set(this.panelNameHeadersCover,"display","none");else{0==this.tempDayInPixels&&(this.tempDayInPixels=this.pixelsPerDay);this.panelNameHeadersCover&&f.set(this.panelNameHeadersCover,"display","");var d=this.tempDayInPixels+this.tempDayInPixels*(c-1)*Math.pow(a/b,2);this.refreshParams(d);k.forEach(this.arrProjects,function(a){k.forEach(a.arrTasks, function(a){a.refresh()},this);a.refresh()},this);setTimeout(l.hitch(this,function(){this.refresh(b,++a,c)}),15)}},switchTeleMicroView:function(b){for(var a=this.panelTime.firstChild.firstChild,c=0;5>c;c++)40<b?f.set(a.rows[c],"display",0==c||1==c?"none":""):20>b?f.set(a.rows[c],"display",2==c||4==c?"none":""):f.set(a.rows[c],"display",0==c||4==c?"none":"")},refreshController:function(){this.contentData.firstChild.style.width=Math.max(1200,this.pixelsPerDay*this.totalDays)+"px";this.panelTime.firstChild.style.width= this.pixelsPerDay*this.totalDays+"px";this.panelTime.firstChild.firstChild.style.width=this.pixelsPerDay*this.totalDays+"px";this.switchTeleMicroView(this.pixelsPerDay);k.forEach(this.panelTime.firstChild.firstChild.rows,function(b){k.forEach(b.childNodes,function(a){var b=parseInt(p.get(a,"colSpan")||1),d=l.trim(p.get(a,"innerHTMLData")||"");0<d.length?p.set(a,"innerHTML",20>this.pixelsPerDay*b?"":d):k.forEach(a.firstChild.rows[0].childNodes,function(a){var b=l.trim(p.get(a,"innerHTMLData")||""); p.set(a,"innerHTML",10<this.pixelsPerDay/this.hsPerDay?b:"")},this);1==b&&(f.set(a,"width",this.pixelsPerDay*b+"px"),0>=d.length&&k.forEach(a.firstChild.rows[0].childNodes,function(a){f.set(a,"width",this.pixelsPerDay*b/this.hsPerDay+"px")},this))},this)},this)},init:function(){this.startDate=this.getStartDate();f.set(this.content,{width:this.contentWidth+"px",height:this.contentHeight+"px"});this.tableControl=h.create("table",{cellPadding:"0",cellSpacing:"0",className:"ganttTabelControl"});var b= this.tableControl.insertRow(this.tableControl.rows.length);this.content.appendChild(this.tableControl);this.countDays=this.getCountDays();this.panelTime=h.create("div",{className:"ganttPanelTimeContainer"});f.set(this.panelTime,"height",this.panelTimeHeight+"px");this.panelTime.appendChild(this.createPanelTime());this.contentData=h.create("div",{className:"ganttContentDataContainer"});f.set(this.contentData,"height",this.contentHeight-this.panelTimeHeight+"px");this.contentData.appendChild(this.createPanelTasks()); var a=h.create("td",{vAlign:"top"});this.panelNameHeaders=h.create("div",{className:"ganttPanelNameHeaders"},a);f.set(this.panelNameHeaders,{height:this.panelTimeHeight+"px",width:this.maxWidthPanelNames+"px"});this.panelNameHeaders.appendChild(this.createPanelNamesTasksHeader());this.panelNames=h.create("div",{className:"ganttPanelNamesContainer"},a);this.panelNames.appendChild(this.createPanelNamesTasks());b.appendChild(a);var a=h.create("td",{vAlign:"top"}),c=h.create("div",{className:"ganttDivCell"}); c.appendChild(this.panelTime);c.appendChild(this.contentData);a.appendChild(c);b.appendChild(a);f.set(this.panelNames,"height",this.contentHeight-this.panelTimeHeight-this.scrollBarWidth+"px");f.set(this.panelNames,"width",this.maxWidthPanelNames+"px");f.set(this.contentData,"width",this.contentWidth-this.maxWidthPanelNames+"px");f.set(this.contentData.firstChild,"width",this.pixelsPerDay*this.countDays+"px");f.set(this.panelTime,"width",this.contentWidth-this.maxWidthPanelNames-this.scrollBarWidth+ "px");f.set(this.panelTime.firstChild,"width",this.pixelsPerDay*this.countDays+"px");this.isShowConMenu&&(this.tabMenu=new D(this));var d=this;this.contentData.onscroll=function(){d.panelTime.scrollLeft=this.scrollLeft;d.panelNames&&(d.panelNames.scrollTop=this.scrollTop,d.isShowConMenu&&d.tabMenu.hide());d.resource&&(d.resource.contentData.scrollLeft=this.scrollLeft)};this.project.sort(this.sortProjStartDate);for(b=0;b<this.project.length;b++){a=this.project[b];for(c=0;c<a.parentTasks.length;c++){var e= a.parentTasks[c];e.startTime||(e.startTime=a.startDate);this.setStartTimeChild(e);if(this.setPreviousTask(a))return}for(c=0;c<a.parentTasks.length;c++){e=a.parentTasks[c];if(e.startTime<a.startDate)if(this.correctError)e.startTime=a.startDate;else return;if(this.checkPosParentTaskInTree(e))return}this.sortTasksByStartTime(a)}for(b=0;b<this.project.length;b++)a=this.project[b],a=new v(this,a),0<this.arrProjects.length&&(c=this.arrProjects[this.arrProjects.length-1],a.previousProject=c,c.nextProject= a),a.create(),this.checkHeighPanelTasks(),this.arrProjects.push(a),this.createTasks(a);this.withResource&&(this.resource=new C(this),this.resource.create());this.postLoadData();this.postBindEvents();return this},postLoadData:function(){k.forEach(this.arrProjects,function(a){k.forEach(a.arrTasks,function(a){a.postLoadData()},this);a.postLoadData()},this);var b=A.getMarginBox(this.panelNameHeaders);this.panelNameHeadersCover||(this.panelNameHeadersCover=h.create("div",{className:"ganttHeaderCover"}, this.panelNameHeaders.parentNode),f.set(this.panelNameHeadersCover,{left:b.l+"px",top:b.t+"px",height:b.h+"px",width:b.w+"px",display:"none"}))},postBindEvents:function(){var b=A.position(this.tableControl,!0);H("dom-addeventlistener")&&this._events.push(n(this.tableControl,"mousemove",l.hitch(this,function(a){var c=a.srcElement||a.target;if(c==this.panelNames.firstChild||c==this.contentData.firstChild)c=this.heightTaskItem+this.heightTaskItemExtra,a=parseInt(a.layerY/c)*c+this.panelTimeHeight-this.contentData.scrollTop, a!=this.oldHLTop&&a<b.h-50&&(this.highLightDiv?f.set(this.highLightDiv,"top",b.y+a+"px"):(this.highLightDiv=h.create("div",{className:"ganttRowHighlight"},I.body()),f.set(this.highLightDiv,{top:b.y+a+"px",left:b.x+"px",width:b.w-20+"px",height:c+"px"}))),this.oldHLTop=a})))},getStartDate:function(){k.forEach(this.project,function(b){this.startDate?b.startDate<this.startDate&&(this.startDate=new Date(b.startDate)):this.startDate=new Date(b.startDate)},this);this.initialPos=24*this.pixelsPerHour;return this.startDate? new Date(this.startDate.setHours(this.startDate.getHours()-24)):new Date},getCountDays:function(){return parseInt((this.contentWidth-this.maxWidthPanelNames)/(24*this.pixelsPerHour))},createTasks:function(b){k.forEach(b.project.parentTasks,function(a,c){0<c&&(b.project.parentTasks[c-1].nextParentTask=a,a.previousParentTask=b.project.parentTasks[c-1]);var d=new x(a,b,this);b.arrTasks.push(d);d.create();this.checkHeighPanelTasks();0<a.cldTasks.length&&this.createChildItemControls(a.cldTasks,b)},this)}, createChildItemControls:function(b,a){b&&k.forEach(b,function(c,d){0<d&&(c.previousChildTask=b[d-1],b[d-1].nextChildTask=c);(new x(c,a,this)).create();this.checkHeighPanelTasks();0<c.cldTasks.length&&this.createChildItemControls(c.cldTasks,a)},this)},getPosOnDate:function(b){return(b-this.startDate)/36E5*this.pixelsPerHour},getWidthOnDuration:function(b){return Math.round(this.pixelsPerWorkHour*b)},getLastChildTask:function(b){return 0<b.childTask.length?this.getLastChildTask(b.childTask[b.childTask.length- 1]):b},removeCell:function(b){for(;b.cells[0];)b.deleteCell(b.cells[0])}})});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/gantt/GanttChart.js
JavaScript
apache-2.0
28,342
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * If B = 11110xxx (n = 4) and (string.charAt(k + 4) and * string.charAt(k + 5)) or (string.charAt(k + 7) and * string.charAt(k + 8)) or (string.charAt(k + 10) and * string.charAt(k + 11)) do not represent hexadecimal digits, throw URIError * * @path ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A1.12_T3.js * @description Complex tests, string.charAt(k + 10) and string.charAt(k + 11) * do not represent hexadecimal digits */ //CHECK result = true; var interval = [[0x00, 0x29], [0x40,0x40], [0x47, 0x60], [0x67, 0xFFFF]]; for (indexI = 0; indexI < interval.length; indexI++) { for (indexJ = interval[indexI][0]; indexJ <= interval[indexI][1]; indexJ++) { try { decodeURIComponent("%F0%" + "%A0%A0" + String.fromCharCode(indexJ, indexJ)); result = false; } catch (e) { if ((e instanceof URIError) !== true) { result = false; } } } } if (result !== true) { $ERROR('#1: If B = 11110xxx (n = 4) and (string.charAt(k + 10) and string.charAt(k + 11)) do not represent hexadecimal digits, throw URIError'); }
popravich/typescript
tests/Fidelity/test262/suite/ch15/15.1/15.1.3/15.1.3.2/S15.1.3.2_A1.12_T3.js
JavaScript
apache-2.0
1,224
/** * Created by Michael on 02/04/14. */ angular.module('angularUtils.directives.uiBreadcrumbs', ['ui.router']) .directive('uiBreadcrumbs', function($interpolate, $state) { return { restrict: 'E', templateUrl: 'vendors/angularUtils/directives/uiBreadcrumbs/uiBreadcrumbs.tpl.html', scope: { displaynameProperty: '@' }, link: function(scope) { scope.breadcrumbs = []; if ($state.$current.name !== '') { updateBreadcrumbsArray(); } scope.$on('$stateChangeSuccess', function() { updateBreadcrumbsArray(); }); /** * Start with the current state and traverse up the path to build the * array of breadcrumbs that can be used in an ng-repeat in the template. */ function updateBreadcrumbsArray() { var breadcrumbs = []; var currentState = $state.$current; while(currentState && currentState.name !== '') { var displayName = getDisplayName(currentState); if (displayName !== false) { breadcrumbs.push({ displayName: displayName, route: currentState.name }); } currentState = currentState.parent; } breadcrumbs.reverse(); scope.breadcrumbs = breadcrumbs; } /** * Resolve the displayName of the specified state. Take the property specified by the `displayname-property` * attribute and look up the corresponding property on the state's config object. The specified string can be interpolated against any resolved * properties on the state config object, by using the usual {{ }} syntax. * @param currentState * @returns {*} */ function getDisplayName(currentState) { var i; var propertyReference; var propertyArray; var displayName; if (!scope.displaynameProperty) { // if the displayname-property attribute was not specified, default to the state's name return currentState.name; } propertyArray = scope.displaynameProperty.split('.'); propertyReference = currentState; for (i = 0; i < propertyArray.length; i ++) { if (angular.isDefined(propertyReference[propertyArray[i]])) { if (propertyReference[propertyArray[i]] === false) { return false; } else { propertyReference = propertyReference[propertyArray[i]]; } } else { // if the specified property was not foundm default to the state's name return currentState.name; } } // use the $interpolate service to handle any bindings in the propertyReference string. displayName = $interpolate(propertyReference)(currentState.locals.globals); return displayName; } } }; }) ;
VHAINNOVATIONS/Mental-Health-eScreening
UIResources/WYSIWYGUITestPages/vendors/angularUtils/directives/uiBreadcrumbs/uiBreadcrumbs.js
JavaScript
apache-2.0
3,722
var searchData= [ ['client_2ec',['client.c',['../client_8c.html',1,'']]], ['co_2ec',['co.c',['../co_8c.html',1,'']]], ['coap_2dobserver_2ec',['coap-observer.c',['../coap-observer_8c.html',1,'']]], ['coap_2dserver_2ec',['coap-server.c',['../coap-server_8c.html',1,'']]], ['coap_2eh',['coap.h',['../coap_8h.html',1,'']]], ['coap_5flist_2ec',['coap_list.c',['../coap__list_8c.html',1,'']]], ['coap_5flist_2eh',['coap_list.h',['../coap__list_8h.html',1,'']]], ['coap_5ftime_2eh',['coap_time.h',['../coap__time_8h.html',1,'']]], ['config_2eh',['config.h',['../config_8h.html',1,'']]] ];
SunKyu/HUFS_libcoap_gateway
doc/html/search/files_63.js
JavaScript
bsd-2-clause
600
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); var utils = require('../../lib/utils'); /** * Google Cloud Key Management Service (KMS) API * * Manages encryption for your cloud services the same way you do on-premise. You can generate, use, rotate, and destroy AES256 encryption keys. * * @example * var google = require('googleapis'); * var cloudkms = google.cloudkms('v1'); * * @namespace cloudkms * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Cloudkms */ function Cloudkms(options) { // eslint-disable-line var self = this; self._options = options || {}; self.projects = { locations: { /** * cloudkms.projects.locations.list * * @desc Lists information about the supported locations for this service. * * @alias cloudkms.projects.locations.list * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string=} params.filter The standard list filter. * @param {string} params.name The resource that owns the locations collection, if applicable. * @param {string=} params.pageToken The standard list page token. * @param {integer=} params.pageSize The standard list page size. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}/locations', method: 'GET' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.get * * @desc Get information about a location. * * @alias cloudkms.projects.locations.get * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name Resource name for the location. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'GET' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, keyRings: { /** * cloudkms.projects.locations.keyRings.list * * @desc Lists KeyRings. * * @alias cloudkms.projects.locations.keyRings.list * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.parent Required. The resource name of the location associated with the KeyRings, in the format `projects/x/locations/x`. * @param {string=} params.pageToken Optional pagination token, returned earlier via ListKeyRingsResponse.next_page_token. * @param {integer=} params.pageSize Optional limit on the number of KeyRings to include in the response. Further KeyRings can subsequently be obtained by including the ListKeyRingsResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/keyRings', method: 'GET' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.create * * @desc Create a new KeyRing in a given Project and Location. * * @alias cloudkms.projects.locations.keyRings.create * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.parent Required. The resource name of the location associated with the KeyRings, in the format `projects/x/locations/x`. * @param {string=} params.keyRingId Required. It must be unique within a location and match the regular expression `[a-zA-Z0-9_-]{1,63}` * @param {cloudkms(v1).KeyRing} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ create: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/keyRings', method: 'POST' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.setIamPolicy * * @desc Sets the access control policy on the specified resource. Replaces any existing policy. * * @alias cloudkms.projects.locations.keyRings.setIamPolicy * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. * @param {cloudkms(v1).SetIamPolicyRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ setIamPolicy: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:setIamPolicy', method: 'POST' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.getIamPolicy * * @desc Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set. * * @alias cloudkms.projects.locations.keyRings.getIamPolicy * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getIamPolicy: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:getIamPolicy', method: 'GET' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.get * * @desc Returns metadata for a given KeyRing. * * @alias cloudkms.projects.locations.keyRings.get * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The name of the KeyRing to get. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'GET' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.testIamPermissions * * @desc Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning. * * @alias cloudkms.projects.locations.keyRings.testIamPermissions * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. * @param {cloudkms(v1).TestIamPermissionsRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ testIamPermissions: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:testIamPermissions', method: 'POST' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, cryptoKeys: { /** * cloudkms.projects.locations.keyRings.cryptoKeys.decrypt * * @desc Decrypt data that was protected by Encrypt. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.decrypt * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name Required. The resource name of the CryptoKey to use for decryption. The server will choose the appropriate version. * @param {cloudkms(v1).DecryptRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ decrypt: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}:decrypt', method: 'POST' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.list * * @desc Lists CryptoKeys. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.list * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string=} params.pageToken Optional pagination token, returned earlier via ListCryptoKeysResponse.next_page_token. * @param {integer=} params.pageSize Optional limit on the number of CryptoKeys to include in the response. Further CryptoKeys can subsequently be obtained by including the ListCryptoKeysResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. * @param {string} params.parent Required. The resource name of the KeyRing to list, in the format `projects/x/locations/x/keyRings/x`. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/cryptoKeys', method: 'GET' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.encrypt * * @desc Encrypt data, so that it can only be recovered by a call to Decrypt. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.encrypt * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name Required. The resource name of the CryptoKey or CryptoKeyVersion to use for encryption. If a CryptoKey is specified, the server will use its primary version. * @param {cloudkms(v1).EncryptRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ encrypt: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}:encrypt', method: 'POST' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.setIamPolicy * * @desc Sets the access control policy on the specified resource. Replaces any existing policy. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.setIamPolicy * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. * @param {cloudkms(v1).SetIamPolicyRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ setIamPolicy: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:setIamPolicy', method: 'POST' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.create * * @desc Create a new CryptoKey within a KeyRing. CryptoKey.purpose is required. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.create * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.parent Required. The name of the KeyRing associated with the CryptoKeys. * @param {string=} params.cryptoKeyId Required. It must be unique within a KeyRing and match the regular expression `[a-zA-Z0-9_-]{1,63}` * @param {cloudkms(v1).CryptoKey} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ create: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/cryptoKeys', method: 'POST' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.updatePrimaryVersion * * @desc Update the version of a CryptoKey that will be used in Encrypt * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.updatePrimaryVersion * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The resource name of the CryptoKey to update. * @param {cloudkms(v1).UpdateCryptoKeyPrimaryVersionRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ updatePrimaryVersion: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}:updatePrimaryVersion', method: 'POST' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.getIamPolicy * * @desc Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.getIamPolicy * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ getIamPolicy: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:getIamPolicy', method: 'GET' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.patch * * @desc Update a CryptoKey. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.patch * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name Output only. The resource name for this CryptoKey in the format `projects/x/locations/x/keyRings/x/cryptoKeys/x`. * @param {string=} params.updateMask Required list of fields to be updated in this request. * @param {cloudkms(v1).CryptoKey} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'PATCH' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.get * * @desc Returns metadata for a given CryptoKey, as well as its primary CryptoKeyVersion. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.get * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The name of the CryptoKey to get. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'GET' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.testIamPermissions * * @desc Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error. Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.testIamPermissions * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.resource_ REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. * @param {cloudkms(v1).TestIamPermissionsRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ testIamPermissions: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{resource}:testIamPermissions', method: 'POST' }, options), params: params, requiredParams: ['resource'], pathParams: ['resource'], context: self }; return createAPIRequest(parameters, callback); }, cryptoKeyVersions: { /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.list * * @desc Lists CryptoKeyVersions. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.list * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string=} params.pageToken Optional pagination token, returned earlier via ListCryptoKeyVersionsResponse.next_page_token. * @param {integer=} params.pageSize Optional limit on the number of CryptoKeyVersions to include in the response. Further CryptoKeyVersions can subsequently be obtained by including the ListCryptoKeyVersionsResponse.next_page_token in a subsequent request. If unspecified, the server will pick an appropriate default. * @param {string} params.parent Required. The resource name of the CryptoKey to list, in the format `projects/x/locations/x/keyRings/x/cryptoKeys/x`. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/cryptoKeyVersions', method: 'GET' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.create * * @desc Create a new CryptoKeyVersion in a CryptoKey. The server will assign the next sequential id. If unset, state will be set to ENABLED. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.create * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.parent Required. The name of the CryptoKey associated with the CryptoKeyVersions. * @param {cloudkms(v1).CryptoKeyVersion} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ create: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{parent}/cryptoKeyVersions', method: 'POST' }, options), params: params, requiredParams: ['parent'], pathParams: ['parent'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.destroy * * @desc Schedule a CryptoKeyVersion for destruction. Upon calling this method, CryptoKeyVersion.state will be set to DESTROY_SCHEDULED and destroy_time will be set to a time 24 hours in the future, at which point the state will be changed to DESTROYED, and the key material will be irrevocably destroyed. Before the destroy_time is reached, RestoreCryptoKeyVersion may be called to reverse the process. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.destroy * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The resource name of the CryptoKeyVersion to destroy. * @param {cloudkms(v1).DestroyCryptoKeyVersionRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ destroy: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}:destroy', method: 'POST' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.restore * * @desc Restore a CryptoKeyVersion in the DESTROY_SCHEDULED, state. Upon restoration of the CryptoKeyVersion, state will be set to DISABLED, and destroy_time will be cleared. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.restore * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The resource name of the CryptoKeyVersion to restore. * @param {cloudkms(v1).RestoreCryptoKeyVersionRequest} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ restore: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}:restore', method: 'POST' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.patch * * @desc Update a CryptoKeyVersion's metadata. state may be changed between ENABLED and DISABLED using this method. See DestroyCryptoKeyVersion and RestoreCryptoKeyVersion to move between other states. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.patch * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string=} params.updateMask Required list of fields to be updated in this request. * @param {string} params.name Output only. The resource name for this CryptoKeyVersion in the format `projects/x/locations/x/keyRings/x/cryptoKeys/x/cryptoKeyVersions/x`. * @param {cloudkms(v1).CryptoKeyVersion} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'PATCH' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); }, /** * cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.get * * @desc Returns metadata for a given CryptoKeyVersion. * * @alias cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.get * @memberOf! cloudkms(v1) * * @param {object} params Parameters for request * @param {string} params.name The name of the CryptoKeyVersion to get. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); var parameters = { options: utils.extend({ url: 'https://cloudkms.googleapis.com/v1/{name}', method: 'GET' }, options), params: params, requiredParams: ['name'], pathParams: ['name'], context: self }; return createAPIRequest(parameters, callback); } } } } } }; } /** * @typedef CryptoKey * @memberOf! cloudkms(v1) * @type object * @property {string} purpose The immutable purpose of this CryptoKey. Currently, the only acceptable purpose is ENCRYPT_DECRYPT. * @property {string} nextRotationTime At next_rotation_time, the Key Management Service will automatically: 1. Create a new version of this CryptoKey. 2. Mark the new version as primary. Key rotations performed manually via CreateCryptoKeyVersion and UpdateCryptoKeyPrimaryVersion do not affect next_rotation_time. * @property {string} createTime Output only. The time at which this CryptoKey was created. * @property {string} rotationPeriod next_rotation_time will be advanced by this period when the service automatically rotates a key. Must be at least one day. If rotation_period is set, next_rotation_time must also be set. * @property {cloudkms(v1).CryptoKeyVersion} primary Output only. A copy of the &quot;primary&quot; CryptoKeyVersion that will be used by Encrypt when this CryptoKey is given in EncryptRequest.name. The CryptoKey&#39;s primary version can be updated via UpdateCryptoKeyPrimaryVersion. * @property {string} name Output only. The resource name for this CryptoKey in the format `projects/x/locations/x/keyRings/x/cryptoKeys/x. */ /** * @typedef Rule * @memberOf! cloudkms(v1) * @type object * @property {string[]} in If one or more &#39;in&#39; clauses are specified, the rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in at least one of these entries. * @property {string[]} permissions A permission is a string of form &#39;&lt;service&gt;.&lt;resource type&gt;.&lt;verb&gt;&#39; (e.g., &#39;storage.buckets.list&#39;). A value of &#39;*&#39; matches all permissions, and a verb part of &#39;*&#39; (e.g., &#39;storage.buckets.*&#39;) matches all verbs. * @property {string} action Required * @property {string[]} notIn If one or more &#39;not_in&#39; clauses are specified, the rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in none of the entries. The format for in and not_in entries is the same as for members in a Binding (see google/iam/v1/policy.proto). * @property {string} description Human-readable description of the rule. * @property {cloudkms(v1).Condition[]} conditions Additional restrictions that must be met * @property {cloudkms(v1).LogConfig[]} logConfig The config returned to callers of tech.iam.IAM.CheckPolicy for any entries that match the LOG action. */ /** * @typedef LogConfig * @memberOf! cloudkms(v1) * @type object * @property {cloudkms(v1).DataAccessOptions} dataAccess Data access options. * @property {cloudkms(v1).CloudAuditOptions} cloudAudit Cloud audit options. * @property {cloudkms(v1).CounterOptions} counter Counter options. */ /** * @typedef SetIamPolicyRequest * @memberOf! cloudkms(v1) * @type object * @property {cloudkms(v1).Policy} policy REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. * @property {string} updateMask OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: paths: &quot;bindings, etag&quot; This field is only used by Cloud IAM. */ /** * @typedef DecryptRequest * @memberOf! cloudkms(v1) * @type object * @property {string} ciphertext Required. The encrypted data originally returned in EncryptResponse.ciphertext. * @property {string} additionalAuthenticatedData Optional data that must match the data originally supplied in EncryptRequest.additional_authenticated_data. */ /** * @typedef Location * @memberOf! cloudkms(v1) * @type object * @property {object} metadata Service-specific metadata. For example the available capacity at the given location. * @property {object} labels Cross-service attributes for the location. For example {&quot;cloud.googleapis.com/region&quot;: &quot;us-east1&quot;} * @property {string} name Resource name for the location, which may vary between implementations. For example: `&quot;projects/example-project/locations/us-east1&quot;` * @property {string} locationId The canonical id for this location. For example: `&quot;us-east1&quot;`. */ /** * @typedef ListCryptoKeysResponse * @memberOf! cloudkms(v1) * @type object * @property {string} nextPageToken A token to retrieve next page of results. Pass this value in ListCryptoKeysRequest.page_token to retrieve the next page of results. * @property {cloudkms(v1).CryptoKey[]} cryptoKeys The list of CryptoKeys. * @property {integer} totalSize The total number of CryptoKeys that matched the query. */ /** * @typedef Condition * @memberOf! cloudkms(v1) * @type object * @property {string} op An operator to apply the subject with. * @property {string} svc Trusted attributes discharged by the service. * @property {string} value DEPRECATED. Use &#39;values&#39; instead. * @property {string} sys Trusted attributes supplied by any service that owns resources and uses the IAM system for access control. * @property {string} iam Trusted attributes supplied by the IAM system. * @property {string[]} values The objects of the condition. This is mutually exclusive with &#39;value&#39;. */ /** * @typedef CounterOptions * @memberOf! cloudkms(v1) * @type object * @property {string} metric The metric to update. * @property {string} field The field value to attribute. */ /** * @typedef AuditLogConfig * @memberOf! cloudkms(v1) * @type object * @property {string[]} exemptedMembers Specifies the identities that do not cause logging for this type of permission. Follows the same format of Binding.members. * @property {string} logType The log type that this config enables. */ /** * @typedef DecryptResponse * @memberOf! cloudkms(v1) * @type object * @property {string} plaintext The decrypted data originally supplied in EncryptRequest.plaintext. */ /** * @typedef TestIamPermissionsRequest * @memberOf! cloudkms(v1) * @type object * @property {string[]} permissions The set of permissions to check for the `resource`. Permissions with wildcards (such as &#39;*&#39; or &#39;storage.*&#39;) are not allowed. For more information see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). */ /** * @typedef EncryptResponse * @memberOf! cloudkms(v1) * @type object * @property {string} name The resource name of the CryptoKeyVersion used in encryption. * @property {string} ciphertext The encrypted data. */ /** * @typedef KeyRing * @memberOf! cloudkms(v1) * @type object * @property {string} name Output only. The resource name for the KeyRing in the format `projects/x/locations/x/keyRings/x. * @property {string} createTime Output only. The time at which this KeyRing was created. */ /** * @typedef ListLocationsResponse * @memberOf! cloudkms(v1) * @type object * @property {cloudkms(v1).Location[]} locations A list of locations that matches the specified filter in the request. * @property {string} nextPageToken The standard List next-page token. */ /** * @typedef Policy * @memberOf! cloudkms(v1) * @type object * @property {cloudkms(v1).Binding[]} bindings Associates a list of `members` to a `role`. Multiple `bindings` must not be specified for the same `role`. `bindings` with no members will result in an error. * @property {string} etag `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy. If no `etag` is provided in the call to `setIamPolicy`, then the existing policy is overwritten blindly. * @property {boolean} iamOwned * @property {cloudkms(v1).Rule[]} rules If more than one rule is specified, the rules are applied in the following manner: - All matching LOG rules are always applied. - If any DENY/DENY_WITH_LOG rule matches, permission is denied. Logging will be applied if one or more matching rule requires logging. - Otherwise, if any ALLOW/ALLOW_WITH_LOG rule matches, permission is granted. Logging will be applied if one or more matching rule requires logging. - Otherwise, if no rule applies, permission is denied. * @property {integer} version Version of the `Policy`. The default version is 0. * @property {cloudkms(v1).AuditConfig[]} auditConfigs Specifies cloud audit logging configuration for this policy. */ /** * @typedef UpdateCryptoKeyPrimaryVersionRequest * @memberOf! cloudkms(v1) * @type object * @property {string} cryptoKeyVersionId The id of the child CryptoKeyVersion to use as primary. */ /** * @typedef RestoreCryptoKeyVersionRequest * @memberOf! cloudkms(v1) * @type object */ /** * @typedef DataAccessOptions * @memberOf! cloudkms(v1) * @type object */ /** * @typedef ListKeyRingsResponse * @memberOf! cloudkms(v1) * @type object * @property {string} nextPageToken A token to retrieve next page of results. Pass this value in ListKeyRingsRequest.page_token to retrieve the next page of results. * @property {integer} totalSize The total number of KeyRings that matched the query. * @property {cloudkms(v1).KeyRing[]} keyRings The list of KeyRings. */ /** * @typedef AuditConfig * @memberOf! cloudkms(v1) * @type object * @property {string} service Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. * @property {cloudkms(v1).AuditLogConfig[]} auditLogConfigs The configuration for logging of each type of permission. Next ID: 4 * @property {string[]} exemptedMembers */ /** * @typedef CryptoKeyVersion * @memberOf! cloudkms(v1) * @type object * @property {string} destroyEventTime Output only. The time this CryptoKeyVersion&#39;s key material was destroyed. Only present if state is DESTROYED. * @property {string} destroyTime Output only. The time this CryptoKeyVersion&#39;s key material is scheduled for destruction. Only present if state is DESTROY_SCHEDULED. * @property {string} createTime Output only. The time at which this CryptoKeyVersion was created. * @property {string} state The current state of the CryptoKeyVersion. * @property {string} name Output only. The resource name for this CryptoKeyVersion in the format `projects/x/locations/x/keyRings/x/cryptoKeys/x/cryptoKeyVersions/x. */ /** * @typedef CloudAuditOptions * @memberOf! cloudkms(v1) * @type object */ /** * @typedef Binding * @memberOf! cloudkms(v1) * @type object * @property {string[]} members Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. * @property {string} role Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required */ /** * @typedef EncryptRequest * @memberOf! cloudkms(v1) * @type object * @property {string} additionalAuthenticatedData Optional data that, if specified, must also be provided during decryption through DecryptRequest.additional_authenticated_data. Must be no larger than 64KiB. * @property {string} plaintext Required. The data to encrypt. Must be no larger than 64KiB. */ /** * @typedef ListCryptoKeyVersionsResponse * @memberOf! cloudkms(v1) * @type object * @property {string} nextPageToken A token to retrieve next page of results. Pass this value in ListCryptoKeyVersionsRequest.page_token to retrieve the next page of results. * @property {integer} totalSize The total number of CryptoKeyVersions that matched the query. * @property {cloudkms(v1).CryptoKeyVersion[]} cryptoKeyVersions The list of CryptoKeyVersions. */ /** * @typedef TestIamPermissionsResponse * @memberOf! cloudkms(v1) * @type object * @property {string[]} permissions A subset of `TestPermissionsRequest.permissions` that the caller is allowed. */ /** * @typedef DestroyCryptoKeyVersionRequest * @memberOf! cloudkms(v1) * @type object */ module.exports = Cloudkms;
Poornakiruthika/Test
node_modules/googleapis/apis/cloudkms/v1.js
JavaScript
mit
53,015
/* * Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ /** * Initializes the global "brackets" variable and it's properties. * Modules should not access the global.brackets object until either * (a) the module requires this module, i.e. require("utils/Global") or * (b) the module receives a "appReady" callback from the utils/AppReady module. */ define(function (require, exports, module) { "use strict"; var configJSON = require("text!config.json"), UrlParams = require("utils/UrlParams").UrlParams; // Define core brackets namespace if it isn't already defined // // We can't simply do 'brackets = {}' to define it in the global namespace because // we're in "use strict" mode. Most likely, 'window' will always point to the global // object when this code is running. However, in case it isn't (e.g. if we're running // inside Node for CI testing) we use this trick to get the global object. var Fn = Function, global = (new Fn("return this"))(); if (!global.brackets) { global.brackets = {}; } // Parse URL params var params = new UrlParams(); params.parse(); // Parse src/config.json try { global.brackets.metadata = JSON.parse(configJSON); global.brackets.config = global.brackets.metadata.config; } catch (err) { console.log(err); } // Uncomment the following line to force all low level file i/o routines to complete // asynchronously. This should only be done for testing/debugging. // NOTE: Make sure this line is commented out again before committing! //brackets.forceAsyncCallbacks = true; // Load native shell when brackets is run in a native shell rather than the browser // TODO: (issue #266) load conditionally global.brackets.shellAPI = require("utils/ShellAPI"); // Determine OS/platform if (global.navigator.platform === "MacIntel" || global.navigator.platform === "MacPPC") { global.brackets.platform = "mac"; } else if (global.navigator.platform.indexOf("Linux") >= 0) { global.brackets.platform = "linux"; } else { global.brackets.platform = "win"; } global.brackets.inBrowser = !global.brackets.hasOwnProperty("fs"); // Are we in a desktop shell with a native menu bar? var hasNativeMenus = params.get("hasNativeMenus"); if (hasNativeMenus) { global.brackets.nativeMenus = (hasNativeMenus === "true"); } else { global.brackets.nativeMenus = (!global.brackets.inBrowser && (global.brackets.platform !== "linux")); } // Locale-related APIs global.brackets.isLocaleDefault = function () { return !global.localStorage.getItem("locale"); }; global.brackets.getLocale = function () { // By default use the locale that was determined in brackets.js return params.get("testEnvironment") ? "en" : (global.localStorage.getItem("locale") || global.require.s.contexts._.config.locale); }; global.brackets.setLocale = function (locale) { if (locale) { global.localStorage.setItem("locale", locale); } else { global.localStorage.removeItem("locale"); } }; // Create empty app namespace if running in-browser if (!global.brackets.app) { global.brackets.app = {}; } // Loading extensions requires creating new require.js contexts, which // requires access to the global 'require' object that always gets hidden // by the 'require' in the AMD wrapper. We store this in the brackets // object here so that the ExtensionLoader doesn't have to have access to // the global object. global.brackets.libRequire = global.require; // Also store our current require.js context (the one that loads brackets // core modules) so that extensions can use it. // Note: we change the name to "getModule" because this won't do exactly // the same thing as 'require' in AMD-wrapped modules. The extension will // only be able to load modules that have already been loaded once. global.brackets.getModule = require; exports.global = global; });
revi/brackets
src/utils/Global.js
JavaScript
mit
5,374
// - jquery.event.livehack.js (function() { var event = jQuery.event, //helper that finds handlers by type and calls back a function, this is basically handle // events - the events object // types - an array of event types to look for // callback(type, handlerFunc, selector) - a callback // selector - an optional selector to filter with, if there, matches by selector // if null, matches anything, otherwise, matches with no selector findHelper = function( events, types, callback, selector ) { var t, type, typeHandlers, all, h, handle, namespaces, namespace, match; for ( t = 0; t < types.length; t++ ) { type = types[t]; all = type.indexOf(".") < 0; if (!all ) { namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } typeHandlers = (events[type] || []).slice(0); for ( h = 0; h < typeHandlers.length; h++ ) { handle = typeHandlers[h]; match = (all || namespace.test(handle.namespace)); if(match){ if(selector){ if (handle.selector === selector ) { callback(type, handle.origHandler || handle.handler); } } else if (selector === null){ callback(type, handle.origHandler || handle.handler, handle.selector); } else if (!handle.selector ) { callback(type, handle.origHandler || handle.handler); } } } } }; /** * Finds event handlers of a given type on an element. * @param {HTMLElement} el * @param {Array} types an array of event names * @param {String} [selector] optional selector * @return {Array} an array of event handlers */ event.find = function( el, types, selector ) { var events = ( $._data(el) || {} ).events, handlers = [], t, liver, live; if (!events ) { return handlers; } findHelper(events, types, function( type, handler ) { handlers.push(handler); }, selector); return handlers; }; /** * Finds all events. Group by selector. * @param {HTMLElement} el the element * @param {Array} types event types */ event.findBySelector = function( el, types ) { var events = $._data(el).events, selectors = {}, //adds a handler for a given selector and event add = function( selector, event, handler ) { var select = selectors[selector] || (selectors[selector] = {}), events = select[event] || (select[event] = []); events.push(handler); }; if (!events ) { return selectors; } //first check live: /*$.each(events.live || [], function( i, live ) { if ( $.inArray(live.origType, types) !== -1 ) { add(live.selector, live.origType, live.origHandler || live.handler); } });*/ //then check straight binds findHelper(events, types, function( type, handler, selector ) { add(selector || "", type, handler); }, null); return selectors; }; event.supportTouch = "ontouchend" in document; $.fn.respondsTo = function( events ) { if (!this.length ) { return false; } else { //add default ? return event.find(this[0], $.isArray(events) ? events : [events]).length > 0; } }; $.fn.triggerHandled = function( event, data ) { event = (typeof event == "string" ? $.Event(event) : event); this.trigger(event, data); return event.handled; }; /** * Only attaches one event handler for all types ... * @param {Array} types llist of types that will delegate here * @param {Object} startingEvent the first event to start listening to * @param {Object} onFirst a function to call */ event.setupHelper = function( types, startingEvent, onFirst ) { if (!onFirst ) { onFirst = startingEvent; startingEvent = null; } var add = function( handleObj ) { var bySelector, selector = handleObj.selector || ""; if ( selector ) { bySelector = event.find(this, types, selector); if (!bySelector.length ) { $(this).delegate(selector, startingEvent, onFirst); } } else { //var bySelector = event.find(this, types, selector); if (!event.find(this, types, selector).length ) { event.add(this, startingEvent, onFirst, { selector: selector, delegate: this }); } } }, remove = function( handleObj ) { var bySelector, selector = handleObj.selector || ""; if ( selector ) { bySelector = event.find(this, types, selector); if (!bySelector.length ) { $(this).undelegate(selector, startingEvent, onFirst); } } else { if (!event.find(this, types, selector).length ) { event.remove(this, startingEvent, onFirst, { selector: selector, delegate: this }); } } }; $.each(types, function() { event.special[this] = { add: add, remove: remove, setup: function() {}, teardown: function() {} }; }); }; })(jQuery)
kristianmandrup/jquerypp-rails
vendor/assets/javascripts/jquery.event.livehack.js
JavaScript
mit
4,918
/** * Copyright (c) 2015-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. * * @flow */ 'use strict'; // Note(vjeux): this would be better as an interface but flow doesn't // support them yet class Animated { __attach(): void {} __detach(): void {} __getValue(): any {} __getAnimatedValue(): any { return this.__getValue(); } __addChild(child: Animated) {} __removeChild(child: Animated) {} __getChildren(): Array<Animated> { return []; } } module.exports = Animated;
DelvarWorld/react-router
website/modules/animated/Animated.js
JavaScript
mit
717
const wrapMapStateToProps = (mapStateToProps, getForm) => { if (mapStateToProps) { if (typeof mapStateToProps !== 'function') { throw new Error('mapStateToProps must be a function'); } if (mapStateToProps.length > 1) { return (state, ownProps) => ({ ...mapStateToProps(state, ownProps), form: getForm(state) }); } return state => ({ ...mapStateToProps(state), form: getForm(state) }); } return state => ({ form: getForm(state) }); }; export default wrapMapStateToProps;
mikekidder/redux-form
src/wrapMapStateToProps.js
JavaScript
mit
553
/** * @fileoverview Source code for spaced-comments rule * @author Gyandeep Singh * @copyright 2015 Toru Nagashima. All rights reserved. * @copyright 2015 Gyandeep Singh. All rights reserved. * @copyright 2014 Greg Cochard. All rights reserved. */ "use strict"; var escapeStringRegexp = require("escape-string-regexp"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Escapes the control characters of a given string. * @param {string} s - A string to escape. * @returns {string} An escaped string. */ function escape(s) { var isOneChar = s.length === 1; s = escapeStringRegexp(s); return isOneChar ? s : "(?:" + s + ")"; } /** * Escapes the control characters of a given string. * And adds a repeat flag. * @param {string} s - A string to escape. * @returns {string} An escaped string. */ function escapeAndRepeat(s) { return escape(s) + "+"; } /** * Parses `markers` option. * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. * @param {string[]|null} markers - A marker list. * @returns {string[]} A marker list. */ function parseMarkersOption(markers) { if (markers == null) { markers = []; } // `*` is a marker for JSDoc comments. if (markers.indexOf("*") === -1) { markers.push("*"); } return markers; } /** * Parses `exceptions` option. * @param {string[]|null} exceptions - An exception list. * @returns {string[]} An exception list. */ function parseExceptionsOption(exceptions) { return exceptions || []; } /** * Creates RegExp object for `always` mode. * Generated pattern is below: * * 1. First, a marker or nothing. * 2. Next, a space or an exception pattern sequence. * * @param {string[]} markers - A marker list. * @param {string[]} exceptions - A exception pattern list. * @returns {RegExp} A RegExp object for `always` mode. */ function createAlwaysStylePattern(markers, exceptions) { var pattern = "^"; // A marker or nothing. // ["*"] ==> "\*?" // ["*", "!"] ==> "(?:\*|!)?" // ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F if (markers.length === 1) { // the marker. pattern += escape(markers[0]); } else { // one of markers. pattern += "(?:"; pattern += markers.map(escape).join("|"); pattern += ")"; } pattern += "?"; // or nothing. // A space or an exception pattern sequence. // [] ==> "\s" // ["-"] ==> "(?:\s|\-+$)" // ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" // ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) if (exceptions.length === 0) { // a space. pattern += "\\s"; } else { // a space or... pattern += "(?:\\s|"; if (exceptions.length === 1) { // a sequence of the exception pattern. pattern += escapeAndRepeat(exceptions[0]); } else { // a sequence of one of exception patterns. pattern += "(?:"; pattern += exceptions.map(escapeAndRepeat).join("|"); pattern += ")"; } pattern += "(?:$|[\n\r]))"; // the sequence continues until the end. } return new RegExp(pattern); } /** * Creates RegExp object for `never` mode. * Generated pattern is below: * * 1. First, a marker or nothing (captured). * 2. Next, a space or a tab. * * @param {string[]} markers - A marker list. * @returns {RegExp} A RegExp object for `never` mode. */ function createNeverStylePattern(markers) { var pattern = "^(" + markers.map(escape).join("|") + ")?[ \t]"; return new RegExp(pattern); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { // Unless the first option is never, require a space var requireSpace = context.options[0] !== "never"; // Parse the second options. // If markers don't include `"*"`, it's added automatically for JSDoc comments. var markers = parseMarkersOption(context.options[1] && context.options[1].markers); var exceptions = parseExceptionsOption(context.options[1] && context.options[1].exceptions); // Create RegExp object for valid patterns. var stylePattern = null; if (requireSpace) { stylePattern = createAlwaysStylePattern(markers, exceptions); } else { stylePattern = createNeverStylePattern(markers); } /** * Reports a given comment if it's invalid. * @param {ASTNode} node - a comment node to check. * @returns {void} */ function checkCommentForSpace(node) { var commentIdentifier = node.type === "Block" ? "/*" : "//"; // Ignores empty comments. if (node.value.length === 0) { return; } // Checks. if (requireSpace) { if (!stylePattern.test(node.value)) { if (exceptions.length > 0) { context.report(node, "Expected exception block, space or tab after " + commentIdentifier + " in comment."); } else { context.report(node, "Expected space or tab after " + commentIdentifier + " in comment."); } } } else { var matched = stylePattern.exec(node.value); if (matched) { if (matched[1] == null) { context.report(node, "Unexpected space or tab after " + commentIdentifier + " in comment."); } else { context.report(node, "Unexpected space or tab after marker (" + matched[1] + ") in comment."); } } } } return { "LineComment": checkCommentForSpace, "BlockComment": checkCommentForSpace }; }; module.exports.schema = [ { "enum": ["always", "never"] }, { "type": "object", "properties": { "exceptions": { "type": "array", "items": { "type": "string" } }, "markers": { "type": "array", "items": { "type": "string" } } }, "additionalProperties": false } ];
Lukkub/Redux-ShopCartApp
node_modules/eslint/lib/rules/spaced-comment.js
JavaScript
mit
6,753
/*! * Less - Leaner CSS v3.5.0-beta.6 * http://lesscss.org * * Copyright (c) 2009-2018, Alexis Sellier <self@cloudhead.net> * Licensed under the Apache-2.0 License. * */ /** * @license Apache-2.0 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.less = f()}})(function(){var define,module,exports;return (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){ var addDataAttr = require('./utils').addDataAttr, browser = require('./browser'); module.exports = function(window, options) { // use options from the current script tag data attribues addDataAttr(options, browser.currentScript(window)); if (options.isFileProtocol === undefined) { options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol); } // Load styles asynchronously (default: false) // // This is set to `false` by default, so that the body // doesn't start loading before the stylesheets are parsed. // Setting this to `true` can result in flickering. // options.async = options.async || false; options.fileAsync = options.fileAsync || false; // Interval between watch polls options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500); options.env = options.env || (window.location.hostname == '127.0.0.1' || window.location.hostname == '0.0.0.0' || window.location.hostname == 'localhost' || (window.location.port && window.location.port.length > 0) || options.isFileProtocol ? 'development' : 'production'); var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash); if (dumpLineNumbers) { options.dumpLineNumbers = dumpLineNumbers[1]; } if (options.useFileCache === undefined) { options.useFileCache = true; } if (options.onReady === undefined) { options.onReady = true; } // TODO: deprecate and remove 'inlineJavaScript' thing - where it came from at all? options.javascriptEnabled = (options.javascriptEnabled || options.inlineJavaScript) ? true : false; }; },{"./browser":3,"./utils":11}],2:[function(require,module,exports){ /** * Kicks off less and compiles any stylesheets * used in the browser distributed version of less * to kick-start less using the browser api */ /* global window, document */ // TODO - consider switching this out for a recommendation for this polyfill? // <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script> // Browsers have good Promise support require('promise/polyfill'); var options = require('../less/default-options')(); if (window.less) { for (key in window.less) { if (window.less.hasOwnProperty(key)) { options[key] = window.less[key]; } } } require('./add-default-options')(window, options); options.plugins = options.plugins || []; if (window.LESS_PLUGINS) { options.plugins = options.plugins.concat(window.LESS_PLUGINS); } var less = module.exports = require('./index')(window, options); window.less = less; var css, head, style; // Always restore page visibility function resolveOrReject(data) { if (data.filename) { console.warn(data); } if (!options.async) { head.removeChild(style); } } if (options.onReady) { if (/!watch/.test(window.location.hash)) { less.watch(); } // Simulate synchronous stylesheet loading by hiding page rendering if (!options.async) { css = 'body { display: none !important }'; head = document.head || document.getElementsByTagName('head')[0]; style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); } less.registerStylesheetsImmediately(); less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject); } },{"../less/default-options":16,"./add-default-options":1,"./index":8,"promise/polyfill":101}],3:[function(require,module,exports){ var utils = require('./utils'); module.exports = { createCSS: function (document, styles, sheet) { // Strip the query-string var href = sheet.href || ''; // If there is no title set, use the filename, minus the extension var id = 'less:' + (sheet.title || utils.extractId(href)); // If this has already been inserted into the DOM, we may need to replace it var oldStyleNode = document.getElementById(id); var keepOldStyleNode = false; // Create a new stylesheet node for insertion or (if necessary) replacement var styleNode = document.createElement('style'); styleNode.setAttribute('type', 'text/css'); if (sheet.media) { styleNode.setAttribute('media', sheet.media); } styleNode.id = id; if (!styleNode.styleSheet) { styleNode.appendChild(document.createTextNode(styles)); // If new contents match contents of oldStyleNode, don't replace oldStyleNode keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 && oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue); } var head = document.getElementsByTagName('head')[0]; // If there is no oldStyleNode, just append; otherwise, only append if we need // to replace oldStyleNode with an updated stylesheet if (oldStyleNode === null || keepOldStyleNode === false) { var nextEl = sheet && sheet.nextSibling || null; if (nextEl) { nextEl.parentNode.insertBefore(styleNode, nextEl); } else { head.appendChild(styleNode); } } if (oldStyleNode && keepOldStyleNode === false) { oldStyleNode.parentNode.removeChild(oldStyleNode); } // For IE. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head if (styleNode.styleSheet) { try { styleNode.styleSheet.cssText = styles; } catch (e) { throw new Error('Couldn\'t reassign styleSheet.cssText.'); } } }, currentScript: function(window) { var document = window.document; return document.currentScript || (function() { var scripts = document.getElementsByTagName('script'); return scripts[scripts.length - 1]; })(); } }; },{"./utils":11}],4:[function(require,module,exports){ // Cache system is a bit outdated and could do with work module.exports = function(window, options, logger) { var cache = null; if (options.env !== 'development') { try { cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage; } catch (_) {} } return { setCSS: function(path, lastModified, modifyVars, styles) { if (cache) { logger.info('saving ' + path + ' to cache.'); try { cache.setItem(path, styles); cache.setItem(path + ':timestamp', lastModified); if (modifyVars) { cache.setItem(path + ':vars', JSON.stringify(modifyVars)); } } catch (e) { // TODO - could do with adding more robust error handling logger.error('failed to save "' + path + '" to local storage for caching.'); } } }, getCSS: function(path, webInfo, modifyVars) { var css = cache && cache.getItem(path), timestamp = cache && cache.getItem(path + ':timestamp'), vars = cache && cache.getItem(path + ':vars'); modifyVars = modifyVars || {}; vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object if (timestamp && webInfo.lastModified && (new Date(webInfo.lastModified).valueOf() === new Date(timestamp).valueOf()) && JSON.stringify(modifyVars) === vars) { // Use local copy return css; } } }; }; },{}],5:[function(require,module,exports){ var utils = require('./utils'), browser = require('./browser'); module.exports = function(window, less, options) { function errorHTML(e, rootHref) { var id = 'less-error-message:' + utils.extractId(rootHref || ''); var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>'; var elem = window.document.createElement('div'), timer, content, errors = []; var filename = e.filename || rootHref; var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; elem.id = id; elem.className = 'less-error-message'; content = '<h3>' + (e.type || 'Syntax') + 'Error: ' + (e.message || 'There is an error in your .less file') + '</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + '</a> '; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.line) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' + '<ul>' + errors.join('') + '</ul>'; } if (e.stack && (e.extract || options.logLevel >= 4)) { content += '<br/>Stack Trace</br />' + e.stack.split('\n').slice(1).join('<br/>'); } elem.innerHTML = content; // CSS for error messages browser.createCSS(window.document, [ '.less-error-message ul, .less-error-message li {', 'list-style-type: none;', 'margin-right: 15px;', 'padding: 4px 0;', 'margin: 0;', '}', '.less-error-message label {', 'font-size: 12px;', 'margin-right: 15px;', 'padding: 4px 0;', 'color: #cc7777;', '}', '.less-error-message pre {', 'color: #dd6666;', 'padding: 4px 0;', 'margin: 0;', 'display: inline-block;', '}', '.less-error-message pre.line {', 'color: #ff0000;', '}', '.less-error-message h3 {', 'font-size: 20px;', 'font-weight: bold;', 'padding: 15px 0 5px 0;', 'margin: 0;', '}', '.less-error-message a {', 'color: #10a', '}', '.less-error-message .error {', 'color: red;', 'font-weight: bold;', 'padding-bottom: 2px;', 'border-bottom: 1px dashed red;', '}' ].join('\n'), { title: 'error-message' }); elem.style.cssText = [ 'font-family: Arial, sans-serif', 'border: 1px solid #e00', 'background-color: #eee', 'border-radius: 5px', '-webkit-border-radius: 5px', '-moz-border-radius: 5px', 'color: #e00', 'padding: 15px', 'margin-bottom: 15px' ].join(';'); if (options.env === 'development') { timer = setInterval(function () { var document = window.document, body = document.body; if (body) { if (document.getElementById(id)) { body.replaceChild(elem, document.getElementById(id)); } else { body.insertBefore(elem, body.firstChild); } clearInterval(timer); } }, 10); } } function removeErrorHTML(path) { var node = window.document.getElementById('less-error-message:' + utils.extractId(path)); if (node) { node.parentNode.removeChild(node); } } function removeErrorConsole(path) { // no action } function removeError(path) { if (!options.errorReporting || options.errorReporting === 'html') { removeErrorHTML(path); } else if (options.errorReporting === 'console') { removeErrorConsole(path); } else if (typeof options.errorReporting === 'function') { options.errorReporting('remove', path); } } function errorConsole(e, rootHref) { var template = '{line} {content}'; var filename = e.filename || rootHref; var errors = []; var content = (e.type || 'Syntax') + 'Error: ' + (e.message || 'There is an error in your .less file') + ' in ' + filename; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.line) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += ' on line ' + e.line + ', column ' + (e.column + 1) + ':\n' + errors.join('\n'); } if (e.stack && (e.extract || options.logLevel >= 4)) { content += '\nStack Trace\n' + e.stack; } less.logger.error(content); } function error(e, rootHref) { if (!options.errorReporting || options.errorReporting === 'html') { errorHTML(e, rootHref); } else if (options.errorReporting === 'console') { errorConsole(e, rootHref); } else if (typeof options.errorReporting === 'function') { options.errorReporting('add', e, rootHref); } } return { add: error, remove: removeError }; }; },{"./browser":3,"./utils":11}],6:[function(require,module,exports){ /* global window, XMLHttpRequest */ module.exports = function(options, logger) { var AbstractFileManager = require('../less/environment/abstract-file-manager.js'); var fileCache = {}; // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load var FileManager = function() { }; FileManager.prototype = new AbstractFileManager(); FileManager.prototype.alwaysMakePathsAbsolute = function alwaysMakePathsAbsolute() { return true; }; FileManager.prototype.join = function join(basePath, laterPath) { if (!basePath) { return laterPath; } return this.extractUrlParts(laterPath, basePath).path; }; FileManager.prototype.doXHR = function doXHR(url, type, callback, errback) { var xhr = new XMLHttpRequest(); var async = options.isFileProtocol ? options.fileAsync : true; if (typeof xhr.overrideMimeType === 'function') { xhr.overrideMimeType('text/css'); } logger.debug('XHR: Getting \'' + url + '\''); xhr.open('GET', url, async); xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); xhr.send(null); function handleResponse(xhr, callback, errback) { if (xhr.status >= 200 && xhr.status < 300) { callback(xhr.responseText, xhr.getResponseHeader('Last-Modified')); } else if (typeof errback === 'function') { errback(xhr.status, url); } } if (options.isFileProtocol && !options.fileAsync) { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { callback(xhr.responseText); } else { errback(xhr.status, url); } } else if (async) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { handleResponse(xhr, callback, errback); } }; } else { handleResponse(xhr, callback, errback); } }; FileManager.prototype.supports = function(filename, currentDirectory, options, environment) { return true; }; FileManager.prototype.clearFileCache = function() { fileCache = {}; }; FileManager.prototype.loadFile = function loadFile(filename, currentDirectory, options, environment) { // TODO: Add prefix support like less-node? // What about multiple paths? if (currentDirectory && !this.isPathAbsolute(filename)) { filename = currentDirectory + filename; } filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename; options = options || {}; // sheet may be set to the stylesheet for the initial load or a collection of properties including // some context variables for imports var hrefParts = this.extractUrlParts(filename, window.location.href); var href = hrefParts.url; var self = this; return new Promise(function(resolve, reject) { if (options.useFileCache && fileCache[href]) { try { var lessText = fileCache[href]; return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() }}); } catch (e) { return reject({ filename: href, message: 'Error loading file ' + href + ' error was ' + e.message }); } } self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) { // per file cache fileCache[href] = data; // Use remote copy (re-parse) resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified }}); }, function doXHRError(status, url) { reject({ type: 'File', message: '\'' + url + '\' wasn\'t found (' + status + ')', href: href }); }); }); }; return FileManager; }; },{"../less/environment/abstract-file-manager.js":17}],7:[function(require,module,exports){ module.exports = function() { var functionRegistry = require('./../less/functions/function-registry'); function imageSize() { throw { type: 'Runtime', message: 'Image size functions are not supported in browser version of less' }; } var imageFunctions = { 'image-size': function(filePathNode) { imageSize(this, filePathNode); return -1; }, 'image-width': function(filePathNode) { imageSize(this, filePathNode); return -1; }, 'image-height': function(filePathNode) { imageSize(this, filePathNode); return -1; } }; functionRegistry.addMultiple(imageFunctions); }; },{"./../less/functions/function-registry":26}],8:[function(require,module,exports){ // // index.js // Should expose the additional browser functions on to the less object // var addDataAttr = require('./utils').addDataAttr, browser = require('./browser'); module.exports = function(window, options) { var document = window.document; var less = require('../less')(); less.options = options; var environment = less.environment, FileManager = require('./file-manager')(options, less.logger), fileManager = new FileManager(); environment.addFileManager(fileManager); less.FileManager = FileManager; less.PluginLoader = require('./plugin-loader'); require('./log-listener')(less, options); var errors = require('./error-reporting')(window, less, options); var cache = less.cache = options.cache || require('./cache')(window, options, less.logger); require('./image-size')(less.environment); // Setup user functions - Deprecate? if (options.functions) { less.functions.functionRegistry.addMultiple(options.functions); } var typePattern = /^text\/(x-)?less$/; function clone(obj) { return JSON.parse(JSON.stringify(obj || {})); } // only really needed for phantom function bind(func, thisArg) { var curryArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0)); return func.apply(thisArg, args); }; } function loadStyles(modifyVars) { var styles = document.getElementsByTagName('style'), style; for (var i = 0; i < styles.length; i++) { style = styles[i]; if (style.type.match(typePattern)) { var instanceOptions = clone(options); instanceOptions.modifyVars = modifyVars; var lessText = style.innerHTML || ''; instanceOptions.filename = document.location.href.replace(/#.*$/, ''); /* jshint loopfunc:true */ // use closure to store current style less.render(lessText, instanceOptions, bind(function(style, e, result) { if (e) { errors.add(e, 'inline'); } else { style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = result.css; } else { style.innerHTML = result.css; } } }, null, style)); } } } function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) { var instanceOptions = clone(options); addDataAttr(instanceOptions, sheet); instanceOptions.mime = sheet.type; if (modifyVars) { instanceOptions.modifyVars = modifyVars; } function loadInitialFileCallback(loadedFile) { var data = loadedFile.contents, path = loadedFile.filename, webInfo = loadedFile.webInfo; var newFileInfo = { currentDirectory: fileManager.getPath(path), filename: path, rootFilename: path, relativeUrls: instanceOptions.relativeUrls}; newFileInfo.entryPath = newFileInfo.currentDirectory; newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory; if (webInfo) { webInfo.remaining = remaining; var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars); if (!reload && css) { webInfo.local = true; callback(null, css, data, sheet, webInfo, path); return; } } // TODO add tests around how this behaves when reloading errors.remove(path); instanceOptions.rootFileInfo = newFileInfo; less.render(data, instanceOptions, function(e, result) { if (e) { e.href = path; callback(e); } else { cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css); callback(null, result.css, data, sheet, webInfo, path); } }); } fileManager.loadFile(sheet.href, null, instanceOptions, environment) .then(function(loadedFile) { loadInitialFileCallback(loadedFile); }).catch(function(err) { console.log(err); callback(err); }); } function loadStyleSheets(callback, reload, modifyVars) { for (var i = 0; i < less.sheets.length; i++) { loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars); } } function initRunningMode() { if (less.env === 'development') { less.watchTimer = setInterval(function () { if (less.watchMode) { fileManager.clearFileCache(); loadStyleSheets(function (e, css, _, sheet, webInfo) { if (e) { errors.add(e, e.href || sheet.href); } else if (css) { browser.createCSS(window.document, css, sheet); } }); } }, options.poll); } } // // Watch mode // less.watch = function () { if (!less.watchMode ) { less.env = 'development'; initRunningMode(); } this.watchMode = true; return true; }; less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; }; // // Synchronously get all <link> tags with the 'rel' attribute set to // "stylesheet/less". // less.registerStylesheetsImmediately = function() { var links = document.getElementsByTagName('link'); less.sheets = []; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && (links[i].type.match(typePattern)))) { less.sheets.push(links[i]); } } }; // // Asynchronously get all <link> tags with the 'rel' attribute set to // "stylesheet/less", returning a Promise. // less.registerStylesheets = function() { return new Promise(function(resolve, reject) { less.registerStylesheetsImmediately(); resolve(); }); }; // // With this function, it's possible to alter variables and re-render // CSS without reloading less-files // less.modifyVars = function(record) { return less.refresh(true, record, false); }; less.refresh = function (reload, modifyVars, clearFileCache) { if ((reload || clearFileCache) && clearFileCache !== false) { fileManager.clearFileCache(); } return new Promise(function (resolve, reject) { var startTime, endTime, totalMilliseconds, remainingSheets; startTime = endTime = new Date(); // Set counter for remaining unprocessed sheets remainingSheets = less.sheets.length; if (remainingSheets === 0) { endTime = new Date(); totalMilliseconds = endTime - startTime; less.logger.info('Less has finished and no sheets were loaded.'); resolve({ startTime: startTime, endTime: endTime, totalMilliseconds: totalMilliseconds, sheets: less.sheets.length }); } else { // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array loadStyleSheets(function (e, css, _, sheet, webInfo) { if (e) { errors.add(e, e.href || sheet.href); reject(e); return; } if (webInfo.local) { less.logger.info('Loading ' + sheet.href + ' from cache.'); } else { less.logger.info('Rendered ' + sheet.href + ' successfully.'); } browser.createCSS(window.document, css, sheet); less.logger.info('CSS for ' + sheet.href + ' generated in ' + (new Date() - endTime) + 'ms'); // Count completed sheet remainingSheets--; // Check if the last remaining sheet was processed and then call the promise if (remainingSheets === 0) { totalMilliseconds = new Date() - startTime; less.logger.info('Less has finished. CSS generated in ' + totalMilliseconds + 'ms'); resolve({ startTime: startTime, endTime: endTime, totalMilliseconds: totalMilliseconds, sheets: less.sheets.length }); } endTime = new Date(); }, reload, modifyVars); } loadStyles(modifyVars); }); }; less.refreshStyles = loadStyles; return less; }; },{"../less":35,"./browser":3,"./cache":4,"./error-reporting":5,"./file-manager":6,"./image-size":7,"./log-listener":9,"./plugin-loader":10,"./utils":11}],9:[function(require,module,exports){ module.exports = function(less, options) { var logLevel_debug = 4, logLevel_info = 3, logLevel_warn = 2, logLevel_error = 1; // The amount of logging in the javascript console. // 3 - Debug, information and errors // 2 - Information and errors // 1 - Errors // 0 - None // Defaults to 2 options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error); if (!options.loggers) { options.loggers = [{ debug: function(msg) { if (options.logLevel >= logLevel_debug) { console.log(msg); } }, info: function(msg) { if (options.logLevel >= logLevel_info) { console.log(msg); } }, warn: function(msg) { if (options.logLevel >= logLevel_warn) { console.warn(msg); } }, error: function(msg) { if (options.logLevel >= logLevel_error) { console.error(msg); } } }]; } for (var i = 0; i < options.loggers.length; i++) { less.logger.addListener(options.loggers[i]); } }; },{}],10:[function(require,module,exports){ // TODO: Add tests for browser @plugin /* global window */ var AbstractPluginLoader = require('../less/environment/abstract-plugin-loader.js'); /** * Browser Plugin Loader */ var PluginLoader = function(less) { this.less = less; // Should we shim this.require for browser? Probably not? }; PluginLoader.prototype = new AbstractPluginLoader(); PluginLoader.prototype.loadPlugin = function(filename, basePath, context, environment, fileManager) { return new Promise(function(fulfill, reject) { fileManager.loadFile(filename, basePath, context, environment) .then(fulfill).catch(reject); }); }; module.exports = PluginLoader; },{"../less/environment/abstract-plugin-loader.js":18}],11:[function(require,module,exports){ module.exports = { extractId: function(href) { return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster .replace(/^\//, '') // Remove root / .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) }, addDataAttr: function(options, tag) { for (var opt in tag.dataset) { if (tag.dataset.hasOwnProperty(opt)) { if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') { options[opt] = tag.dataset[opt]; } else { try { options[opt] = JSON.parse(tag.dataset[opt]); } catch (_) {} } } } } }; },{}],12:[function(require,module,exports){ var contexts = {}; module.exports = contexts; var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) { if (!original) { return; } for (var i = 0; i < propertiesToCopy.length; i++) { if (original.hasOwnProperty(propertiesToCopy[i])) { destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; } } }; /* parse is used whilst parsing */ var parseCopyProperties = [ // options 'paths', // option - unmodified - paths to search for imports on 'relativeUrls', // option - whether to adjust URL's to be relative 'rootpath', // option - rootpath to append to URL's 'strictImports', // option - 'insecure', // option - whether to allow imports from insecure ssl hosts 'dumpLineNumbers', // option - whether to dump line numbers 'compress', // option - whether to compress 'syncImport', // option - whether to import synchronously 'chunkInput', // option - whether to chunk input. more performant but causes parse issues. 'mime', // browser only - mime type for sheet import 'useFileCache', // browser only - whether to use the per file session cache // context 'processImports', // option & context - whether to process imports. if false then imports will not be imported. // Used by the import manager to stop multiple import visitors being created. 'pluginManager' // Used as the plugin manager for the session ]; contexts.Parse = function(options) { copyFromOriginal(options, this, parseCopyProperties); if (typeof this.paths === 'string') { this.paths = [this.paths]; } }; var evalCopyProperties = [ 'paths', // additional include paths 'compress', // whether to compress 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) 'strictMath', // whether math has to be within parenthesis 'strictUnits', // whether units need to evaluate correctly 'sourceMap', // whether to output a source map 'importMultiple', // whether we are currently importing multiple copies 'urlArgs', // whether to add args into url tokens 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false 'pluginManager', // Used as the plugin manager for the session 'importantScope' // used to bubble up !important statements ]; contexts.Eval = function(options, frames) { copyFromOriginal(options, this, evalCopyProperties); if (typeof this.paths === 'string') { this.paths = [this.paths]; } this.frames = frames || []; this.importantScope = this.importantScope || []; }; contexts.Eval.prototype.enterCalc = function () { if (!this.calcStack) { this.calcStack = []; } this.calcStack.push(true); this.inCalc = true; }; contexts.Eval.prototype.exitCalc = function () { this.calcStack.pop(); if (!this.calcStack) { this.inCalc = false; } }; contexts.Eval.prototype.inParenthesis = function () { if (!this.parensStack) { this.parensStack = []; } this.parensStack.push(true); }; contexts.Eval.prototype.outOfParenthesis = function () { this.parensStack.pop(); }; contexts.Eval.prototype.inCalc = false; contexts.Eval.prototype.mathOn = true; contexts.Eval.prototype.isMathOn = function () { if (!this.mathOn) { return false; } return this.strictMath ? (this.parensStack && this.parensStack.length) : true; }; contexts.Eval.prototype.isPathRelative = function (path) { return !/^(?:[a-z-]+:|\/|#)/i.test(path); }; contexts.Eval.prototype.normalizePath = function( path ) { var segments = path.split('/').reverse(), segment; path = []; while (segments.length !== 0 ) { segment = segments.pop(); switch ( segment ) { case '.': break; case '..': if ((path.length === 0) || (path[path.length - 1] === '..')) { path.push( segment ); } else { path.pop(); } break; default: path.push( segment ); break; } } return path.join('/'); }; // todo - do the same for the toCSS ? },{}],13:[function(require,module,exports){ module.exports = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'rebeccapurple':'#663399', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; },{}],14:[function(require,module,exports){ module.exports = { colors: require('./colors'), unitConversions: require('./unit-conversions') }; },{"./colors":13,"./unit-conversions":15}],15:[function(require,module,exports){ module.exports = { length: { 'm': 1, 'cm': 0.01, 'mm': 0.001, 'in': 0.0254, 'px': 0.0254 / 96, 'pt': 0.0254 / 72, 'pc': 0.0254 / 72 * 12 }, duration: { 's': 1, 'ms': 0.001 }, angle: { 'rad': 1 / (2 * Math.PI), 'deg': 1 / 360, 'grad': 1 / 400, 'turn': 1 } }; },{}],16:[function(require,module,exports){ // Export a new default each time module.exports = function() { return { /* Outputs a makefile import dependency list to stdout. */ depends: false, /* Compress using less built-in compression. * This does an okay job but does not utilise all the tricks of * dedicated css compression. */ compress: false, /* Runs the less parser and just reports errors without any output. */ lint: false, /* Sets available include paths. * If the file in an @import rule does not exist at that exact location, * less will look for it at the location(s) passed to this option. * You might use this for instance to specify a path to a library which * you want to be referenced simply and relatively in the less files. */ paths: [], /* color output in the terminal */ color: true, /* The strictImports controls whether the compiler will allow an @import inside of either * @media blocks or (a later addition) other selector blocks. * See: https://github.com/less/less.js/issues/656 */ strictImports: false, /* Allow Imports from Insecure HTTPS Hosts */ insecure: false, /* Allows you to add a path to every generated import and url in your css. * This does not affect less import statements that are processed, just ones * that are left in the output css. */ rootpath: '', /* By default URLs are kept as-is, so if you import a file in a sub-directory * that references an image, exactly the same URL will be output in the css. * This option allows you to re-write URL's in imported files so that the * URL is always relative to the base imported file */ relativeUrls: false, /* Compatibility with IE8. Used for limiting data-uri length */ ieCompat: false, // true until 3.0 /* Without this option on, Less will try and process all math in your css */ strictMath: false, /* Without this option, less attempts to guess at the output unit when it does maths. */ strictUnits: false, /* Effectively the declaration is put at the top of your base Less file, * meaning it can be used but it also can be overridden if this variable * is defined in the file. */ globalVars: null, /* As opposed to the global variable option, this puts the declaration at the * end of your base file, meaning it will override anything defined in your Less file. */ modifyVars: null, /* This option allows you to specify a argument to go on to every URL. */ urlArgs: '' } } },{}],17:[function(require,module,exports){ var abstractFileManager = function() { }; abstractFileManager.prototype.getPath = function (filename) { var j = filename.lastIndexOf('?'); if (j > 0) { filename = filename.slice(0, j); } j = filename.lastIndexOf('/'); if (j < 0) { j = filename.lastIndexOf('\\'); } if (j < 0) { return ''; } return filename.slice(0, j + 1); }; abstractFileManager.prototype.tryAppendExtension = function(path, ext) { return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext; }; abstractFileManager.prototype.tryAppendLessExtension = function(path) { return this.tryAppendExtension(path, '.less'); }; abstractFileManager.prototype.supportsSync = function() { return false; }; abstractFileManager.prototype.alwaysMakePathsAbsolute = function() { return false; }; abstractFileManager.prototype.isPathAbsolute = function(filename) { return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename); }; // TODO: pull out / replace? abstractFileManager.prototype.join = function(basePath, laterPath) { if (!basePath) { return laterPath; } return basePath + laterPath; }; abstractFileManager.prototype.pathDiff = function pathDiff(url, baseUrl) { // diff between two paths to create a relative path var urlParts = this.extractUrlParts(url), baseUrlParts = this.extractUrlParts(baseUrl), i, max, urlDirectories, baseUrlDirectories, diff = ''; if (urlParts.hostPart !== baseUrlParts.hostPart) { return ''; } max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); for (i = 0; i < max; i++) { if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } } baseUrlDirectories = baseUrlParts.directories.slice(i); urlDirectories = urlParts.directories.slice(i); for (i = 0; i < baseUrlDirectories.length - 1; i++) { diff += '../'; } for (i = 0; i < urlDirectories.length - 1; i++) { diff += urlDirectories[i] + '/'; } return diff; }; // helper function, not part of API abstractFileManager.prototype.extractUrlParts = function extractUrlParts(url, baseUrl) { // urlParts[1] = protocol://hostname/ OR / // urlParts[2] = / if path relative to host base // urlParts[3] = directories // urlParts[4] = filename // urlParts[5] = parameters var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, urlParts = url.match(urlPartsRegex), returner = {}, rawDirectories = [], directories = [], i, baseUrlParts; if (!urlParts) { throw new Error('Could not parse sheet href - \'' + url + '\''); } // Stylesheets in IE don't always return the full path if (baseUrl && (!urlParts[1] || urlParts[2])) { baseUrlParts = baseUrl.match(urlPartsRegex); if (!baseUrlParts) { throw new Error('Could not parse page url - \'' + baseUrl + '\''); } urlParts[1] = urlParts[1] || baseUrlParts[1] || ''; if (!urlParts[2]) { urlParts[3] = baseUrlParts[3] + urlParts[3]; } } if (urlParts[3]) { rawDirectories = urlParts[3].replace(/\\/g, '/').split('/'); // collapse '..' and skip '.' for (i = 0; i < rawDirectories.length; i++) { if (rawDirectories[i] === '..') { directories.pop(); } else if (rawDirectories[i] !== '.') { directories.push(rawDirectories[i]); } } } returner.hostPart = urlParts[1]; returner.directories = directories; returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/'); returner.path = (urlParts[1] || '') + directories.join('/'); returner.filename = urlParts[4]; returner.fileUrl = returner.path + (urlParts[4] || ''); returner.url = returner.fileUrl + (urlParts[5] || ''); return returner; }; module.exports = abstractFileManager; },{}],18:[function(require,module,exports){ var functionRegistry = require('../functions/function-registry'), LessError = require('../less-error'); var AbstractPluginLoader = function() { // Implemented by Node.js plugin loader this.require = function() { return null; } }; AbstractPluginLoader.prototype.evalPlugin = function(contents, context, imports, pluginOptions, fileInfo) { var loader, registry, pluginObj, localModule, pluginManager, filename, result; pluginManager = context.pluginManager; if (fileInfo) { if (typeof fileInfo === 'string') { filename = fileInfo; } else { filename = fileInfo.filename; } } var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename; if (filename) { pluginObj = pluginManager.get(filename); if (pluginObj) { result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions); if (result) { return result; } try { if (pluginObj.use) { pluginObj.use.call(this.context, pluginObj); } } catch (e) { e.message = e.message || 'Error during @plugin call'; return new LessError(e, imports, filename); } return pluginObj; } } localModule = { exports: {}, pluginManager: pluginManager, fileInfo: fileInfo }; registry = functionRegistry.create(); var registerPlugin = function(obj) { pluginObj = obj; }; try { loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents); loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo); } catch (e) { return new LessError(e, imports, filename); } if (!pluginObj) { pluginObj = localModule.exports; } pluginObj = this.validatePlugin(pluginObj, filename, shortname); if (pluginObj instanceof LessError) { return pluginObj; } if (pluginObj) { pluginObj.imports = imports; pluginObj.filename = filename; // For < 3.x (or unspecified minVersion) - setOptions() before install() if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) { result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions); if (result) { return result; } } // Run on first load pluginManager.addPlugin(pluginObj, fileInfo.filename, registry); pluginObj.functions = registry.getLocalFunctions(); // Need to call setOptions again because the pluginObj might have functions result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions); if (result) { return result; } // Run every @plugin call try { if (pluginObj.use) { pluginObj.use.call(this.context, pluginObj); } } catch (e) { e.message = e.message || 'Error during @plugin call'; return new LessError(e, imports, filename); } } else { return new LessError({ message: 'Not a valid plugin' }, imports, filename); } return pluginObj; }; AbstractPluginLoader.prototype.trySetOptions = function(plugin, filename, name, options) { if (options && !plugin.setOptions) { return new LessError({ message: 'Options have been provided but the plugin ' + name + ' does not support any options.' }); } try { plugin.setOptions && plugin.setOptions(options); } catch (e) { return new LessError(e); } }; AbstractPluginLoader.prototype.validatePlugin = function(plugin, filename, name) { if (plugin) { // support plugins being a function // so that the plugin can be more usable programmatically if (typeof plugin === 'function') { plugin = new plugin(); } if (plugin.minVersion) { if (this.compareVersion(plugin.minVersion, this.less.version) < 0) { return new LessError({ message: 'Plugin ' + name + ' requires version ' + this.versionToString(plugin.minVersion) }); } } return plugin; } return null; }; AbstractPluginLoader.prototype.compareVersion = function(aVersion, bVersion) { if (typeof aVersion === 'string') { aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/); aVersion.shift(); } for (var i = 0; i < aVersion.length; i++) { if (aVersion[i] !== bVersion[i]) { return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1; } } return 0; }; AbstractPluginLoader.prototype.versionToString = function(version) { var versionString = ''; for (var i = 0; i < version.length; i++) { versionString += (versionString ? '.' : '') + version[i]; } return versionString; }; AbstractPluginLoader.prototype.printUsage = function(plugins) { for (var i = 0; i < plugins.length; i++) { var plugin = plugins[i]; if (plugin.printUsage) { plugin.printUsage(); } } }; module.exports = AbstractPluginLoader; },{"../functions/function-registry":26,"../less-error":36}],19:[function(require,module,exports){ /** * @todo Document why this abstraction exists, and the relationship between * environment, file managers, and plugin manager */ var logger = require('../logger'); var environment = function(externalEnvironment, fileManagers) { this.fileManagers = fileManagers || []; externalEnvironment = externalEnvironment || {}; var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'], requiredFunctions = [], functions = requiredFunctions.concat(optionalFunctions); for (var i = 0; i < functions.length; i++) { var propName = functions[i], environmentFunc = externalEnvironment[propName]; if (environmentFunc) { this[propName] = environmentFunc.bind(externalEnvironment); } else if (i < requiredFunctions.length) { this.warn('missing required function in environment - ' + propName); } } }; environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) { if (!filename) { logger.warn('getFileManager called with no filename.. Please report this issue. continuing.'); } if (currentDirectory == null) { logger.warn('getFileManager called with null directory.. Please report this issue. continuing.'); } var fileManagers = this.fileManagers; if (options.pluginManager) { fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers()); } for (var i = fileManagers.length - 1; i >= 0 ; i--) { var fileManager = fileManagers[i]; if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) { return fileManager; } } return null; }; environment.prototype.addFileManager = function (fileManager) { this.fileManagers.push(fileManager); }; environment.prototype.clearFileManagers = function () { this.fileManagers = []; }; module.exports = environment; },{"../logger":37}],20:[function(require,module,exports){ var functionRegistry = require('./function-registry'), Anonymous = require('../tree/anonymous'), Keyword = require('../tree/keyword'); functionRegistry.addMultiple({ boolean: function(condition) { return condition ? Keyword.True : Keyword.False; }, 'if': function(condition, trueValue, falseValue) { return condition ? trueValue : (falseValue || new Anonymous); } }); },{"../tree/anonymous":48,"../tree/keyword":68,"./function-registry":26}],21:[function(require,module,exports){ var Color = require('../tree/color'), functionRegistry = require('./function-registry'); // Color Blending // ref: http://www.w3.org/TR/compositing-1 function colorBlend(mode, color1, color2) { var ab = color1.alpha, cb, // backdrop as = color2.alpha, cs, // source ar, cr, r = []; // result ar = as + ab * (1 - as); for (var i = 0; i < 3; i++) { cb = color1.rgb[i] / 255; cs = color2.rgb[i] / 255; cr = mode(cb, cs); if (ar) { cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar; } r[i] = cr * 255; } return new Color(r, ar); } var colorBlendModeFunctions = { multiply: function(cb, cs) { return cb * cs; }, screen: function(cb, cs) { return cb + cs - cb * cs; }, overlay: function(cb, cs) { cb *= 2; return (cb <= 1) ? colorBlendModeFunctions.multiply(cb, cs) : colorBlendModeFunctions.screen(cb - 1, cs); }, softlight: function(cb, cs) { var d = 1, e = cb; if (cs > 0.5) { e = 1; d = (cb > 0.25) ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb; } return cb - (1 - 2 * cs) * e * (d - cb); }, hardlight: function(cb, cs) { return colorBlendModeFunctions.overlay(cs, cb); }, difference: function(cb, cs) { return Math.abs(cb - cs); }, exclusion: function(cb, cs) { return cb + cs - 2 * cb * cs; }, // non-w3c functions: average: function(cb, cs) { return (cb + cs) / 2; }, negation: function(cb, cs) { return 1 - Math.abs(cb + cs - 1); } }; for (var f in colorBlendModeFunctions) { if (colorBlendModeFunctions.hasOwnProperty(f)) { colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]); } } functionRegistry.addMultiple(colorBlend); },{"../tree/color":53,"./function-registry":26}],22:[function(require,module,exports){ var Dimension = require('../tree/dimension'), Color = require('../tree/color'), Quoted = require('../tree/quoted'), Anonymous = require('../tree/anonymous'), functionRegistry = require('./function-registry'), colorFunctions; function clamp(val) { return Math.min(1, Math.max(0, val)); } function hsla(color) { return colorFunctions.hsla(color.h, color.s, color.l, color.a); } function number(n) { if (n instanceof Dimension) { return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); } else if (typeof n === 'number') { return n; } else { throw { type: 'Argument', message: 'color functions take numbers as parameters' }; } } function scaled(n, size) { if (n instanceof Dimension && n.unit.is('%')) { return parseFloat(n.value * size / 100); } else { return number(n); } } colorFunctions = { rgb: function (r, g, b) { return colorFunctions.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); a = number(a); return new Color(rgb, a); }, hsl: function (h, s, l) { return colorFunctions.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { var m1, m2; function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } else if (h * 2 < 1) { return m2; } else if (h * 3 < 2) { return m1 + (m2 - m1) * (2 / 3 - h) * 6; } else { return m1; } } h = (number(h) % 360) / 360; s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; m1 = l * 2 - m2; return colorFunctions.rgba(hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255, a); }, hsv: function(h, s, v) { return colorFunctions.hsva(h, s, v, 1.0); }, hsva: function(h, s, v, a) { h = ((number(h) % 360) / 360) * 360; s = number(s); v = number(v); a = number(a); var i, f; i = Math.floor((h / 60) % 6); f = (h / 60) - i; var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)]; var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]]; return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a); }, hue: function (color) { return new Dimension(color.toHSL().h); }, saturation: function (color) { return new Dimension(color.toHSL().s * 100, '%'); }, lightness: function (color) { return new Dimension(color.toHSL().l * 100, '%'); }, hsvhue: function(color) { return new Dimension(color.toHSV().h); }, hsvsaturation: function (color) { return new Dimension(color.toHSV().s * 100, '%'); }, hsvvalue: function (color) { return new Dimension(color.toHSV().v * 100, '%'); }, red: function (color) { return new Dimension(color.rgb[0]); }, green: function (color) { return new Dimension(color.rgb[1]); }, blue: function (color) { return new Dimension(color.rgb[2]); }, alpha: function (color) { return new Dimension(color.toHSL().a); }, luma: function (color) { return new Dimension(color.luma() * color.alpha * 100, '%'); }, luminance: function (color) { var luminance = (0.2126 * color.rgb[0] / 255) + (0.7152 * color.rgb[1] / 255) + (0.0722 * color.rgb[2] / 255); return new Dimension(luminance * color.alpha * 100, '%'); }, saturate: function (color, amount, method) { // filter: saturate(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.s += hsl.s * amount.value / 100; } else { hsl.s += amount.value / 100; } hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount, method) { var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.s -= hsl.s * amount.value / 100; } else { hsl.s -= amount.value / 100; } hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount, method) { var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.l += hsl.l * amount.value / 100; } else { hsl.l += amount.value / 100; } hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount, method) { var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.l -= hsl.l * amount.value / 100; } else { hsl.l -= amount.value / 100; } hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount, method) { var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.a += hsl.a * amount.value / 100; } else { hsl.a += amount.value / 100; } hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount, method) { var hsl = color.toHSL(); if (typeof method !== 'undefined' && method.value === 'relative') { hsl.a -= hsl.a * amount.value / 100; } else { hsl.a -= amount.value / 100; } hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { if (!color1.toHSL || !color2.toHSL) { console.log(color2.type); console.dir(color2); } if (!weight) { weight = new Dimension(50); } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new Color(rgb, alpha); }, greyscale: function (color) { return colorFunctions.desaturate(color, new Dimension(100)); }, contrast: function (color, dark, light, threshold) { // filter: contrast(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } if (typeof light === 'undefined') { light = colorFunctions.rgba(255, 255, 255, 1.0); } if (typeof dark === 'undefined') { dark = colorFunctions.rgba(0, 0, 0, 1.0); } // Figure out which is actually light and dark: if (dark.luma() > light.luma()) { var t = light; light = dark; dark = t; } if (typeof threshold === 'undefined') { threshold = 0.43; } else { threshold = number(threshold); } if (color.luma() < threshold) { return light; } else { return dark; } }, // Changes made in 2.7.0 - Reverted in 3.0.0 // contrast: function (color, color1, color2, threshold) { // // Return which of `color1` and `color2` has the greatest contrast with `color` // // according to the standard WCAG contrast ratio calculation. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef // // The threshold param is no longer used, in line with SASS. // // filter: contrast(3.2); // // should be kept as is, so check for color // if (!color.rgb) { // return null; // } // if (typeof color1 === 'undefined') { // color1 = colorFunctions.rgba(0, 0, 0, 1.0); // } // if (typeof color2 === 'undefined') { // color2 = colorFunctions.rgba(255, 255, 255, 1.0); // } // var contrast1, contrast2; // var luma = color.luma(); // var luma1 = color1.luma(); // var luma2 = color2.luma(); // // Calculate contrast ratios for each color // if (luma > luma1) { // contrast1 = (luma + 0.05) / (luma1 + 0.05); // } else { // contrast1 = (luma1 + 0.05) / (luma + 0.05); // } // if (luma > luma2) { // contrast2 = (luma + 0.05) / (luma2 + 0.05); // } else { // contrast2 = (luma2 + 0.05) / (luma + 0.05); // } // if (contrast1 > contrast2) { // return color1; // } else { // return color2; // } // }, argb: function (color) { return new Anonymous(color.toARGB()); }, color: function(c) { if ((c instanceof Quoted) && (/^#([a-f0-9]{6}|[a-f0-9]{3})$/i.test(c.value))) { return new Color(c.value.slice(1)); } if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) { c.value = undefined; return c; } throw { type: 'Argument', message: 'argument must be a color keyword or 3/6 digit hex e.g. #FFF' }; }, tint: function(color, amount) { return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount); }, shade: function(color, amount) { return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount); } }; functionRegistry.addMultiple(colorFunctions); },{"../tree/anonymous":48,"../tree/color":53,"../tree/dimension":60,"../tree/quoted":78,"./function-registry":26}],23:[function(require,module,exports){ module.exports = function(environment) { var Quoted = require('../tree/quoted'), URL = require('../tree/url'), utils = require('../utils'), functionRegistry = require('./function-registry'), fallback = function(functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); }, logger = require('../logger'); functionRegistry.add('data-uri', function(mimetypeNode, filePathNode) { if (!filePathNode) { filePathNode = mimetypeNode; mimetypeNode = null; } var mimetype = mimetypeNode && mimetypeNode.value; var filePath = filePathNode.value; var currentFileInfo = this.currentFileInfo; var currentDirectory = currentFileInfo.relativeUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath; var fragmentStart = filePath.indexOf('#'); var fragment = ''; if (fragmentStart !== -1) { fragment = filePath.slice(fragmentStart); filePath = filePath.slice(0, fragmentStart); } var context = utils.clone(this.context); context.rawBuffer = true; var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true); if (!fileManager) { return fallback(this, filePathNode); } var useBase64 = false; // detect the mimetype if not given if (!mimetypeNode) { mimetype = environment.mimeLookup(filePath); if (mimetype === 'image/svg+xml') { useBase64 = false; } else { // use base 64 unless it's an ASCII or UTF-8 format var charset = environment.charsetLookup(mimetype); useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; } if (useBase64) { mimetype += ';base64'; } } else { useBase64 = /;base64$/.test(mimetype); } var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment); if (!fileSync.contents) { logger.warn('Skipped data-uri embedding of ' + filePath + ' because file not found'); return fallback(this, filePathNode || mimetypeNode); } var buf = fileSync.contents; if (useBase64 && !environment.encodeBase64) { return fallback(this, filePathNode); } buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf); var uri = 'data:' + mimetype + ',' + buf + fragment; // IE8 cannot handle a data-uri larger than 32,768 characters. If this is exceeded // and the --ieCompat flag is enabled, return a normal url() instead. var DATA_URI_MAX = 32768; if (uri.length >= DATA_URI_MAX) { if (this.context.ieCompat !== false) { logger.warn('Skipped data-uri embedding of ' + filePath + ' because its size (' + uri.length + ' characters) exceeds IE8-safe ' + DATA_URI_MAX + ' characters!'); return fallback(this, filePathNode || mimetypeNode); } } return new URL(new Quoted('"' + uri + '"', uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo); }); }; },{"../logger":37,"../tree/quoted":78,"../tree/url":83,"../utils":87,"./function-registry":26}],24:[function(require,module,exports){ var Keyword = require('../tree/keyword'), functionRegistry = require('./function-registry'); var defaultFunc = { eval: function () { var v = this.value_, e = this.error_; if (e) { throw e; } if (v != null) { return v ? Keyword.True : Keyword.False; } }, value: function (v) { this.value_ = v; }, error: function (e) { this.error_ = e; }, reset: function () { this.value_ = this.error_ = null; } }; functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc)); module.exports = defaultFunc; },{"../tree/keyword":68,"./function-registry":26}],25:[function(require,module,exports){ var Expression = require('../tree/expression'); var functionCaller = function(name, context, index, currentFileInfo) { this.name = name.toLowerCase(); this.index = index; this.context = context; this.currentFileInfo = currentFileInfo; this.func = context.frames[0].functionRegistry.get(this.name); }; functionCaller.prototype.isValid = function() { return Boolean(this.func); }; functionCaller.prototype.call = function(args) { // This code is terrible and should be replaced as per this issue... // https://github.com/less/less.js/issues/2477 if (Array.isArray(args)) { args = args.filter(function (item) { if (item.type === 'Comment') { return false; } return true; }) .map(function(item) { if (item.type === 'Expression') { var subNodes = item.value.filter(function (item) { if (item.type === 'Comment') { return false; } return true; }); if (subNodes.length === 1) { return subNodes[0]; } else { return new Expression(subNodes); } } return item; }); } return this.func.apply(this, args); }; module.exports = functionCaller; },{"../tree/expression":62}],26:[function(require,module,exports){ function makeRegistry( base ) { return { _data: {}, add: function(name, func) { // precautionary case conversion, as later querying of // the registry by function-caller uses lower case as well. name = name.toLowerCase(); if (this._data.hasOwnProperty(name)) { // TODO warn } this._data[name] = func; }, addMultiple: function(functions) { Object.keys(functions).forEach( function(name) { this.add(name, functions[name]); }.bind(this)); }, get: function(name) { return this._data[name] || ( base && base.get( name )); }, getLocalFunctions: function() { return this._data; }, inherit: function() { return makeRegistry( this ); }, create: function(base) { return makeRegistry(base); } }; } module.exports = makeRegistry( null ); },{}],27:[function(require,module,exports){ module.exports = function(environment) { var functions = { functionRegistry: require('./function-registry'), functionCaller: require('./function-caller') }; // register functions require('./boolean'); require('./default'); require('./color'); require('./color-blending'); require('./data-uri')(environment); require('./math'); require('./number'); require('./string'); require('./svg')(environment); require('./types'); return functions; }; },{"./boolean":20,"./color":22,"./color-blending":21,"./data-uri":23,"./default":24,"./function-caller":25,"./function-registry":26,"./math":29,"./number":30,"./string":31,"./svg":32,"./types":33}],28:[function(require,module,exports){ var Dimension = require('../tree/dimension'); var MathHelper = function() { }; MathHelper._math = function (fn, unit, n) { if (!(n instanceof Dimension)) { throw { type: 'Argument', message: 'argument must be a number' }; } if (unit == null) { unit = n.unit; } else { n = n.unify(); } return new Dimension(fn(parseFloat(n.value)), unit); }; module.exports = MathHelper; },{"../tree/dimension":60}],29:[function(require,module,exports){ var functionRegistry = require('./function-registry'), mathHelper = require('./math-helper.js'); var mathFunctions = { // name, unit ceil: null, floor: null, sqrt: null, abs: null, tan: '', sin: '', cos: '', atan: 'rad', asin: 'rad', acos: 'rad' }; for (var f in mathFunctions) { if (mathFunctions.hasOwnProperty(f)) { mathFunctions[f] = mathHelper._math.bind(null, Math[f], mathFunctions[f]); } } mathFunctions.round = function (n, f) { var fraction = typeof f === 'undefined' ? 0 : f.value; return mathHelper._math(function(num) { return num.toFixed(fraction); }, null, n); }; functionRegistry.addMultiple(mathFunctions); },{"./function-registry":26,"./math-helper.js":28}],30:[function(require,module,exports){ var Dimension = require('../tree/dimension'), Anonymous = require('../tree/anonymous'), functionRegistry = require('./function-registry'), mathHelper = require('./math-helper.js'); var minMax = function (isMin, args) { args = Array.prototype.slice.call(args); switch (args.length) { case 0: throw { type: 'Argument', message: 'one or more arguments required' }; } var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, order = [], // elems only contains original argument values. values = {}; // key is the unit.toString() for unified Dimension values, // value is the index into the order array. for (i = 0; i < args.length; i++) { current = args[i]; if (!(current instanceof Dimension)) { if (Array.isArray(args[i].value)) { Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value)); } continue; } currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify(); unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString(); unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic; unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone; j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit]; if (j === undefined) { if (unitStatic !== undefined && unit !== unitStatic) { throw { type: 'Argument', message: 'incompatible types' }; } values[unit] = order.length; order.push(current); continue; } referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify(); if ( isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) { order[j] = current; } } if (order.length == 1) { return order[0]; } args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', '); return new Anonymous((isMin ? 'min' : 'max') + '(' + args + ')'); }; functionRegistry.addMultiple({ min: function () { return minMax(true, arguments); }, max: function () { return minMax(false, arguments); }, convert: function (val, unit) { return val.convertTo(unit.value); }, pi: function () { return new Dimension(Math.PI); }, mod: function(a, b) { return new Dimension(a.value % b.value, a.unit); }, pow: function(x, y) { if (typeof x === 'number' && typeof y === 'number') { x = new Dimension(x); y = new Dimension(y); } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) { throw { type: 'Argument', message: 'arguments must be numbers' }; } return new Dimension(Math.pow(x.value, y.value), x.unit); }, percentage: function (n) { var result = mathHelper._math(function(num) { return num * 100; }, '%', n); return result; } }); },{"../tree/anonymous":48,"../tree/dimension":60,"./function-registry":26,"./math-helper.js":28}],31:[function(require,module,exports){ var Quoted = require('../tree/quoted'), Anonymous = require('../tree/anonymous'), JavaScript = require('../tree/javascript'), functionRegistry = require('./function-registry'); functionRegistry.addMultiple({ e: function (str) { return new Anonymous(str instanceof JavaScript ? str.evaluated : str.value); }, escape: function (str) { return new Anonymous( encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B') .replace(/\(/g, '%28').replace(/\)/g, '%29')); }, replace: function (string, pattern, replacement, flags) { var result = string.value; replacement = (replacement.type === 'Quoted') ? replacement.value : replacement.toCSS(); result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement); return new Quoted(string.quote || '', result, string.escaped); }, '%': function (string /* arg, arg, ... */) { var args = Array.prototype.slice.call(arguments, 1), result = string.value; for (var i = 0; i < args.length; i++) { /* jshint loopfunc:true */ result = result.replace(/%[sda]/i, function(token) { var value = ((args[i].type === 'Quoted') && token.match(/s/i)) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } result = result.replace(/%%/g, '%'); return new Quoted(string.quote || '', result, string.escaped); } }); },{"../tree/anonymous":48,"../tree/javascript":66,"../tree/quoted":78,"./function-registry":26}],32:[function(require,module,exports){ module.exports = function(environment) { var Dimension = require('../tree/dimension'), Color = require('../tree/color'), Expression = require('../tree/expression'), Quoted = require('../tree/quoted'), URL = require('../tree/url'), functionRegistry = require('./function-registry'); functionRegistry.add('svg-gradient', function(direction) { var stops, gradientDirectionSvg, gradientType = 'linear', rectangleDimension = 'x="0" y="0" width="1" height="1"', renderEnv = {compress: false}, returner, directionValue = direction.toCSS(renderEnv), i, color, position, positionValue, alpha; function throwArgumentDescriptor() { throw { type: 'Argument', message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' + ' end_color [end_position] or direction, color list' }; } if (arguments.length == 2) { if (arguments[1].value.length < 2) { throwArgumentDescriptor(); } stops = arguments[1].value; } else if (arguments.length < 3) { throwArgumentDescriptor(); } else { stops = Array.prototype.slice.call(arguments, 1); } switch (directionValue) { case 'to bottom': gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; break; case 'to right': gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; break; case 'to bottom right': gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; break; case 'to top right': gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; break; case 'ellipse': case 'ellipse at center': gradientType = 'radial'; gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; break; default: throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' + ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' }; } returner = '<?xml version="1.0" ?>' + '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; for (i = 0; i < stops.length; i += 1) { if (stops[i] instanceof Expression) { color = stops[i].value[0]; position = stops[i].value[1]; } else { color = stops[i]; position = undefined; } if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) { throwArgumentDescriptor(); } positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%'; alpha = color.alpha; returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>'; } returner += '</' + gradientType + 'Gradient>' + '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>'; returner = encodeURIComponent(returner); returner = 'data:image/svg+xml,' + returner; return new URL(new Quoted('\'' + returner + '\'', returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo); }); }; },{"../tree/color":53,"../tree/dimension":60,"../tree/expression":62,"../tree/quoted":78,"../tree/url":83,"./function-registry":26}],33:[function(require,module,exports){ var Keyword = require('../tree/keyword'), DetachedRuleset = require('../tree/detached-ruleset'), Dimension = require('../tree/dimension'), Color = require('../tree/color'), Quoted = require('../tree/quoted'), Anonymous = require('../tree/anonymous'), URL = require('../tree/url'), Operation = require('../tree/operation'), functionRegistry = require('./function-registry'); var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; }, isunit = function (n, unit) { if (unit === undefined) { throw { type: 'Argument', message: 'missing the required second argument to isunit.' }; } unit = typeof unit.value === 'string' ? unit.value : unit; if (typeof unit !== 'string') { throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' }; } return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False; }, getItemsFromNode = function(node) { // handle non-array values as an array of length 1 // return 'undefined' if index is invalid var items = Array.isArray(node.value) ? node.value : Array(node); return items; }; functionRegistry.addMultiple({ isruleset: function (n) { return isa(n, DetachedRuleset); }, iscolor: function (n) { return isa(n, Color); }, isnumber: function (n) { return isa(n, Dimension); }, isstring: function (n) { return isa(n, Quoted); }, iskeyword: function (n) { return isa(n, Keyword); }, isurl: function (n) { return isa(n, URL); }, ispixel: function (n) { return isunit(n, 'px'); }, ispercentage: function (n) { return isunit(n, '%'); }, isem: function (n) { return isunit(n, 'em'); }, isunit: isunit, unit: function (val, unit) { if (!(val instanceof Dimension)) { throw { type: 'Argument', message: 'the first argument to unit must be a number' + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') }; } if (unit) { if (unit instanceof Keyword) { unit = unit.value; } else { unit = unit.toCSS(); } } else { unit = ''; } return new Dimension(val.value, unit); }, 'get-unit': function (n) { return new Anonymous(n.unit); }, extract: function(values, index) { index = index.value - 1; // (1-based index) return getItemsFromNode(values)[index]; }, length: function(values) { return new Dimension(getItemsFromNode(values).length); }, _SELF: function(n) { return n; } }); },{"../tree/anonymous":48,"../tree/color":53,"../tree/detached-ruleset":59,"../tree/dimension":60,"../tree/keyword":68,"../tree/operation":75,"../tree/quoted":78,"../tree/url":83,"./function-registry":26}],34:[function(require,module,exports){ var contexts = require('./contexts'), Parser = require('./parser/parser'), LessError = require('./less-error'), utils = require('./utils'), PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise, logger = require('./logger'); module.exports = function(environment) { // FileInfo = { // 'relativeUrls' - option - whether to adjust URL's to be relative // 'filename' - full resolved filename of current file // 'rootpath' - path to append to normal URLs for this node // 'currentDirectory' - path to the current file, absolute // 'rootFilename' - filename of the base file // 'entryPath' - absolute path to the entry file // 'reference' - whether the file should not be output and only output parts that are referenced var ImportManager = function(less, context, rootFileInfo) { this.less = less; this.rootFilename = rootFileInfo.filename; this.paths = context.paths || []; // Search paths, when importing this.contents = {}; // map - filename to contents of all the files this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore this.mime = context.mime; this.error = null; this.context = context; // Deprecated? Unused outside of here, could be useful. this.queue = []; // Files which haven't been imported yet this.files = {}; // Holds the imported parse trees. }; /** * Add an import to be imported * @param path - the raw path * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension) * @param currentFileInfo - the current file info (used for instance to work out relative paths) * @param importOptions - import options * @param callback - callback for when it is imported */ ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) { var importManager = this, pluginLoader = this.context.pluginManager.Loader; this.queue.push(path); var fileParsedFunc = function (e, root, fullPath) { importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue var importedEqualsRoot = fullPath === importManager.rootFilename; if (importOptions.optional && e) { callback(null, {rules:[]}, false, null); logger.info('The file ' + fullPath + ' was skipped because it was not found and the import was marked optional.'); } else { // Inline imports aren't cached here. // If we start to cache them, please make sure they won't conflict with non-inline imports of the // same name as they used to do before this comment and the condition below have been added. if (!importManager.files[fullPath] && !importOptions.inline) { importManager.files[fullPath] = { root: root, options: importOptions }; } if (e && !importManager.error) { importManager.error = e; } callback(e, root, importedEqualsRoot, fullPath); } }; var newFileInfo = { relativeUrls: this.context.relativeUrls, entryPath: currentFileInfo.entryPath, rootpath: currentFileInfo.rootpath, rootFilename: currentFileInfo.rootFilename }; var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment); if (!fileManager) { fileParsedFunc({ message: 'Could not find a file-manager for ' + path }); return; } var loadFileCallback = function(loadedFile) { var plugin, resolvedFilename = loadedFile.filename, contents = loadedFile.contents.replace(/^\uFEFF/, ''); // Pass on an updated rootpath if path of imported file is relative and file // is in a (sub|sup) directory // // Examples: // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/', // then rootpath should become 'less/module/nav/' // - If path of imported file is '../mixins.less' and rootpath is 'less/', // then rootpath should become 'less/../' newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename); if (newFileInfo.relativeUrls) { newFileInfo.rootpath = fileManager.join( (importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath)); if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) { newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath); } } newFileInfo.filename = resolvedFilename; var newEnv = new contexts.Parse(importManager.context); newEnv.processImports = false; importManager.contents[resolvedFilename] = contents; if (currentFileInfo.reference || importOptions.reference) { newFileInfo.reference = true; } if (importOptions.isPlugin) { plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo); if (plugin instanceof LessError) { fileParsedFunc(plugin, null, resolvedFilename); } else { fileParsedFunc(null, plugin, resolvedFilename); } } else if (importOptions.inline) { fileParsedFunc(null, contents, resolvedFilename); } else { // import (multiple) parse trees apparently get altered and can't be cached. // TODO: investigate why this is if (importManager.files[resolvedFilename] && !importManager.files[resolvedFilename].options.multiple && !importOptions.multiple) { fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename); } else { new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) { fileParsedFunc(e, root, resolvedFilename); }); } } }; var promise, context = utils.clone(this.context); if (tryAppendExtension) { context.ext = importOptions.isPlugin ? '.js' : '.less'; } if (importOptions.isPlugin) { promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager); } else { promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function(err, loadedFile) { if (err) { fileParsedFunc(err); } else { loadFileCallback(loadedFile); } }); } if (promise) { promise.then(loadFileCallback, fileParsedFunc); } }; return ImportManager; }; },{"./contexts":12,"./less-error":36,"./logger":37,"./parser/parser":42,"./utils":87,"promise":undefined}],35:[function(require,module,exports){ module.exports = function(environment, fileManagers) { var SourceMapOutput, SourceMapBuilder, ParseTree, ImportManager, Environment; var initial = { version: [3, 5, 0], data: require('./data'), tree: require('./tree'), Environment: (Environment = require('./environment/environment')), AbstractFileManager: require('./environment/abstract-file-manager'), AbstractPluginLoader: require('./environment/abstract-plugin-loader'), environment: (environment = new Environment(environment, fileManagers)), visitors: require('./visitors'), Parser: require('./parser/parser'), functions: require('./functions')(environment), contexts: require('./contexts'), SourceMapOutput: (SourceMapOutput = require('./source-map-output')(environment)), SourceMapBuilder: (SourceMapBuilder = require('./source-map-builder')(SourceMapOutput, environment)), ParseTree: (ParseTree = require('./parse-tree')(SourceMapBuilder)), ImportManager: (ImportManager = require('./import-manager')(environment)), render: require('./render')(environment, ParseTree, ImportManager), parse: require('./parse')(environment, ParseTree, ImportManager), LessError: require('./less-error'), transformTree: require('./transform-tree'), utils: require('./utils'), PluginManager: require('./plugin-manager'), logger: require('./logger') }; // Create a public API var ctor = function(t) { return function() { var obj = Object.create(t.prototype); t.apply(obj, Array.prototype.slice.call(arguments, 0)); return obj; }; }; var t, api = Object.create(initial); for (var n in initial.tree) { /* eslint guard-for-in: 0 */ t = initial.tree[n]; if (typeof t === 'function') { api[n.toLowerCase()] = ctor(t); } else { api[n] = Object.create(null); for (var o in t) { /* eslint guard-for-in: 0 */ api[n][o.toLowerCase()] = ctor(t[o]); } } } return api; }; },{"./contexts":12,"./data":14,"./environment/abstract-file-manager":17,"./environment/abstract-plugin-loader":18,"./environment/environment":19,"./functions":27,"./import-manager":34,"./less-error":36,"./logger":37,"./parse":39,"./parse-tree":38,"./parser/parser":42,"./plugin-manager":43,"./render":44,"./source-map-builder":45,"./source-map-output":46,"./transform-tree":47,"./tree":65,"./utils":87,"./visitors":91}],36:[function(require,module,exports){ var utils = require('./utils'); /** * This is a centralized class of any error that could be thrown internally (mostly by the parser). * Besides standard .message it keeps some additional data like a path to the file where the error * occurred along with line and column numbers. * * @class * @extends Error * @type {module.LessError} * * @prop {string} type * @prop {string} filename * @prop {number} index * @prop {number} line * @prop {number} column * @prop {number} callLine * @prop {number} callExtract * @prop {string[]} extract * * @param {Object} e - An error object to wrap around or just a descriptive object * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager? * @param {string} [currentFilename] */ var LessError = module.exports = function LessError(e, fileContentMap, currentFilename) { Error.call(this); var filename = e.filename || currentFilename; this.message = e.message; this.stack = e.stack; if (fileContentMap && filename) { var input = fileContentMap.contents[filename], loc = utils.getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && utils.getLocation(e.call, input).line, lines = input ? input.split('\n') : ''; this.type = e.type || 'Syntax'; this.filename = filename; this.index = e.index; this.line = typeof line === 'number' ? line + 1 : null; this.column = col; if (!this.line && this.stack) { var found = this.stack.match(/(<anonymous>|Function):(\d+):(\d+)/); if (found) { if (found[2]) { this.line = parseInt(found[2]) - 2; } if (found[3]) { this.column = parseInt(found[3]); } } } this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.extract = [ lines[this.line - 2], lines[this.line - 1], lines[this.line] ]; } }; if (typeof Object.create === 'undefined') { var F = function () {}; F.prototype = Error.prototype; LessError.prototype = new F(); } else { LessError.prototype = Object.create(Error.prototype); } LessError.prototype.constructor = LessError; /** * An overridden version of the default Object.prototype.toString * which uses additional information to create a helpful message. * * @param {Object} options * @returns {string} */ LessError.prototype.toString = function(options) { options = options || {}; var message = ''; var extract = this.extract || []; var error = []; var stylize = function (str) { return str; }; if (options.stylize) { var type = typeof options.stylize; if (type !== 'function') { throw Error('options.stylize should be a function, got a ' + type + '!'); } stylize = options.stylize; } if (this.line !== null) { if (typeof extract[0] === 'string') { error.push(stylize((this.line - 1) + ' ' + extract[0], 'grey')); } if (typeof extract[1] === 'string') { var errorTxt = this.line + ' '; if (extract[1]) { errorTxt += extract[1].slice(0, this.column) + stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') + extract[1].slice(this.column + 1), 'red'), 'inverse'); } error.push(errorTxt); } if (typeof extract[2] === 'string') { error.push(stylize((this.line + 1) + ' ' + extract[2], 'grey')); } error = error.join('\n') + stylize('', 'reset') + '\n'; } message += stylize(this.type + 'Error: ' + this.message, 'red'); if (this.filename) { message += stylize(' in ', 'red') + this.filename; } if (this.line) { message += stylize(' on line ' + this.line + ', column ' + (this.column + 1) + ':', 'grey'); } message += '\n' + error; if (this.callLine) { message += stylize('from ', 'red') + (this.filename || '') + '/n'; message += stylize(this.callLine, 'grey') + ' ' + this.callExtract + '/n'; } return message; }; },{"./utils":87}],37:[function(require,module,exports){ module.exports = { error: function(msg) { this._fireEvent('error', msg); }, warn: function(msg) { this._fireEvent('warn', msg); }, info: function(msg) { this._fireEvent('info', msg); }, debug: function(msg) { this._fireEvent('debug', msg); }, addListener: function(listener) { this._listeners.push(listener); }, removeListener: function(listener) { for (var i = 0; i < this._listeners.length; i++) { if (this._listeners[i] === listener) { this._listeners.splice(i, 1); return; } } }, _fireEvent: function(type, msg) { for (var i = 0; i < this._listeners.length; i++) { var logFunction = this._listeners[i][type]; if (logFunction) { logFunction(msg); } } }, _listeners: [] }; },{}],38:[function(require,module,exports){ var LessError = require('./less-error'), transformTree = require('./transform-tree'), logger = require('./logger'); module.exports = function(SourceMapBuilder) { var ParseTree = function(root, imports) { this.root = root; this.imports = imports; }; ParseTree.prototype.toCSS = function(options) { var evaldRoot, result = {}, sourceMapBuilder; try { evaldRoot = transformTree(this.root, options); } catch (e) { throw new LessError(e, this.imports); } try { var compress = Boolean(options.compress); if (compress) { logger.warn('The compress option has been deprecated. We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.'); } var toCSSOptions = { compress: compress, dumpLineNumbers: options.dumpLineNumbers, strictUnits: Boolean(options.strictUnits), numPrecision: 8}; if (options.sourceMap) { sourceMapBuilder = new SourceMapBuilder(options.sourceMap); result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports); } else { result.css = evaldRoot.toCSS(toCSSOptions); } } catch (e) { throw new LessError(e, this.imports); } if (options.pluginManager) { var postProcessors = options.pluginManager.getPostProcessors(); for (var i = 0; i < postProcessors.length; i++) { result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports }); } } if (options.sourceMap) { result.map = sourceMapBuilder.getExternalSourceMap(); } result.imports = []; for (var file in this.imports.files) { if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) { result.imports.push(file); } } return result; }; return ParseTree; }; },{"./less-error":36,"./logger":37,"./transform-tree":47}],39:[function(require,module,exports){ var PromiseConstructor, contexts = require('./contexts'), Parser = require('./parser/parser'), PluginManager = require('./plugin-manager'), LessError = require('./less-error'), utils = require('./utils'); module.exports = function(environment, ParseTree, ImportManager) { var parse = function (input, options, callback) { if (typeof options === 'function') { callback = options; options = utils.defaults(this.options, {}); } else { options = utils.defaults(this.options, options || {}); } if (!callback) { if (!PromiseConstructor) { PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise; } var self = this; return new PromiseConstructor(function (resolve, reject) { parse.call(self, input, options, function(err, output) { if (err) { reject(err); } else { resolve(output); } }); }); } else { var context, rootFileInfo, pluginManager = new PluginManager(this, !options.reUsePluginManager); options.pluginManager = pluginManager; context = new contexts.Parse(options); if (options.rootFileInfo) { rootFileInfo = options.rootFileInfo; } else { var filename = options.filename || 'input'; var entryPath = filename.replace(/[^\/\\]*$/, ''); rootFileInfo = { filename: filename, relativeUrls: context.relativeUrls, rootpath: context.rootpath || '', currentDirectory: entryPath, entryPath: entryPath, rootFilename: filename }; // add in a missing trailing slash if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') { rootFileInfo.rootpath += '/'; } } var imports = new ImportManager(this, context, rootFileInfo); this.importManager = imports; // TODO: allow the plugins to be just a list of paths or names // Do an async plugin queue like lessc if (options.plugins) { options.plugins.forEach(function(plugin) { var evalResult, contents; if (plugin.fileContent) { contents = plugin.fileContent.replace(/^\uFEFF/, ''); evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename); if (evalResult instanceof LessError) { return callback(evalResult); } } else { pluginManager.addPlugin(plugin); } }); } new Parser(context, imports, rootFileInfo) .parse(input, function (e, root) { if (e) { return callback(e); } callback(null, root, imports, options); }, options); } }; return parse; }; },{"./contexts":12,"./less-error":36,"./parser/parser":42,"./plugin-manager":43,"./utils":87,"promise":undefined}],40:[function(require,module,exports){ // Split the input into chunks. module.exports = function (input, fail) { var len = input.length, level = 0, parenLevel = 0, lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, chunks = [], emitFrom = 0, chunkerCurrentIndex, currentChunkStartIndex, cc, cc2, matched; function emitChunk(force) { var len = chunkerCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1)); emitFrom = chunkerCurrentIndex + 1; } for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc = input.charCodeAt(chunkerCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = chunkerCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail('missing opening `(`', chunkerCurrentIndex); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = chunkerCurrentIndex; continue; case 125: // } if (--level < 0) { return fail('missing opening `{`', chunkerCurrentIndex); } if (!level && !parenLevel) { emitChunk(); } continue; case 92: // \ if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; } return fail('unescaped `\\`', chunkerCurrentIndex); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (chunkerCurrentIndex == len - 1) { return fail('unescaped `\\`', chunkerCurrentIndex); } chunkerCurrentIndex++; } } if (matched) { continue; } return fail('unmatched `' + String.fromCharCode(cc) + '`', currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(chunkerCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; } } if (chunkerCurrentIndex == len - 1) { return fail('missing closing `*/`', currentChunkStartIndex); } chunkerCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) { return fail('unmatched `/*`', chunkerCurrentIndex); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail('missing closing `}` or `*/`', lastOpening); } else { return fail('missing closing `}`', lastOpening); } } else if (parenLevel !== 0) { return fail('missing closing `)`', lastOpeningParen); } emitChunk(true); return chunks; }; },{}],41:[function(require,module,exports){ var chunker = require('./chunker'); module.exports = function() { var input, // Less input string j, // current chunk saveStack = [], // holds state for backtracking furthest, // furthest index the parser has gone to furthestPossibleErrorMessage, // if this is furthest we got to, this is the probably cause chunks, // chunkified input current, // current chunk currentPos, // index of current chunk, in `input` parserInput = {}; var CHARCODE_SPACE = 32, CHARCODE_TAB = 9, CHARCODE_LF = 10, CHARCODE_CR = 13, CHARCODE_PLUS = 43, CHARCODE_COMMA = 44, CHARCODE_FORWARD_SLASH = 47, CHARCODE_9 = 57; function skipWhitespace(length) { var oldi = parserInput.i, oldj = j, curr = parserInput.i - currentPos, endIndex = parserInput.i + current.length - curr, mem = (parserInput.i += length), inp = input, c, nextChar, comment; for (; parserInput.i < endIndex; parserInput.i++) { c = inp.charCodeAt(parserInput.i); if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) { nextChar = inp.charAt(parserInput.i + 1); if (nextChar === '/') { comment = {index: parserInput.i, isLineComment: true}; var nextNewLine = inp.indexOf('\n', parserInput.i + 2); if (nextNewLine < 0) { nextNewLine = endIndex; } parserInput.i = nextNewLine; comment.text = inp.substr(comment.index, parserInput.i - comment.index); parserInput.commentStore.push(comment); continue; } else if (nextChar === '*') { var nextStarSlash = inp.indexOf('*/', parserInput.i + 2); if (nextStarSlash >= 0) { comment = { index: parserInput.i, text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i), isLineComment: false }; parserInput.i += comment.text.length - 1; parserInput.commentStore.push(comment); continue; } } break; } if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) { break; } } current = current.slice(length + parserInput.i - mem + curr); currentPos = parserInput.i; if (!current.length) { if (j < chunks.length - 1) { current = chunks[++j]; skipWhitespace(0); // skip space at the beginning of a chunk return true; // things changed } parserInput.finished = true; } return oldi !== parserInput.i || oldj !== j; } parserInput.save = function() { currentPos = parserInput.i; saveStack.push( { current: current, i: parserInput.i, j: j }); }; parserInput.restore = function(possibleErrorMessage) { if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) { furthest = parserInput.i; furthestPossibleErrorMessage = possibleErrorMessage; } var state = saveStack.pop(); current = state.current; currentPos = parserInput.i = state.i; j = state.j; }; parserInput.forget = function() { saveStack.pop(); }; parserInput.isWhitespace = function (offset) { var pos = parserInput.i + (offset || 0), code = input.charCodeAt(pos); return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF); }; // Specialization of $(tok) parserInput.$re = function(tok) { if (parserInput.i > currentPos) { current = current.slice(parserInput.i - currentPos); currentPos = parserInput.i; } var m = tok.exec(current); if (!m) { return null; } skipWhitespace(m[0].length); if (typeof m === 'string') { return m; } return m.length === 1 ? m[0] : m; }; parserInput.$char = function(tok) { if (input.charAt(parserInput.i) !== tok) { return null; } skipWhitespace(1); return tok; }; parserInput.$str = function(tok) { var tokLength = tok.length; // https://jsperf.com/string-startswith/21 for (var i = 0; i < tokLength; i++) { if (input.charAt(parserInput.i + i) !== tok.charAt(i)) { return null; } } skipWhitespace(tokLength); return tok; }; parserInput.$quoted = function(loc) { var pos = loc || parserInput.i, startChar = input.charAt(pos); if (startChar !== '\'' && startChar !== '"') { return; } var length = input.length, currentPosition = pos; for (var i = 1; i + currentPosition < length; i++) { var nextChar = input.charAt(i + currentPosition); switch (nextChar) { case '\\': i++; continue; case '\r': case '\n': break; case startChar: var str = input.substr(currentPosition, i + 1); if (!loc && loc !== 0) { skipWhitespace(i + 1); return str } return [startChar, str]; default: } } return null; }; /** * Permissive parsing. Ignores everything except matching {} [] () and quotes * until matching token (outside of blocks) */ parserInput.$parseUntil = function(tok) { var quote = '', returnVal = null, inComment = false, blockDepth = 0, blockStack = [], parseGroups = [], length = input.length, startPos = parserInput.i, lastPos = parserInput.i, i = parserInput.i, loop = true, testChar; if (typeof tok === 'string') { testChar = function(char) { return char === tok; } } else { testChar = function(char) { return tok.test(char); } } do { var prevChar, nextChar = input.charAt(i); if (blockDepth === 0 && testChar(nextChar)) { returnVal = input.substr(lastPos, i - lastPos); if (returnVal) { parseGroups.push(returnVal); returnVal = parseGroups; } else { returnVal = [' ']; } skipWhitespace(i - startPos); loop = false } else { if (inComment) { if (nextChar === '*' && input.charAt(i + 1) === '/') { i++; blockDepth--; inComment = false; } i++; continue; } switch (nextChar) { case '\\': i++; nextChar = input.charAt(i); parseGroups.push(input.substr(lastPos, i - lastPos + 1)); lastPos = i + 1; break; case '/': if (input.charAt(i + 1) === '*') { i++; inComment = true; blockDepth++; } break; case '\'': case '"': quote = parserInput.$quoted(i); if (quote) { parseGroups.push(input.substr(lastPos, i - lastPos), quote); i += quote[1].length - 1; lastPos = i + 1; } else { skipWhitespace(i - startPos); returnVal = nextChar; loop = false; } break; case '{': blockStack.push('}'); blockDepth++; break; case '(': blockStack.push(')'); blockDepth++; break; case '[': blockStack.push(']'); blockDepth++; break; case '}': case ')': case ']': var expected = blockStack.pop(); if (nextChar === expected) { blockDepth--; } else { // move the parser to the error and return expected skipWhitespace(i - startPos); returnVal = expected; loop = false; } } i++; if (i > length) { loop = false; } } prevChar = nextChar; } while (loop); return returnVal ? returnVal : null; } parserInput.autoCommentAbsorb = true; parserInput.commentStore = []; parserInput.finished = false; // Same as $(), but don't change the state of the parser, // just return the match. parserInput.peek = function(tok) { if (typeof tok === 'string') { // https://jsperf.com/string-startswith/21 for (var i = 0; i < tok.length; i++) { if (input.charAt(parserInput.i + i) !== tok.charAt(i)) { return false; } } return true; } else { return tok.test(current); } }; // Specialization of peek() // TODO remove or change some currentChar calls to peekChar parserInput.peekChar = function(tok) { return input.charAt(parserInput.i) === tok; }; parserInput.currentChar = function() { return input.charAt(parserInput.i); }; parserInput.prevChar = function() { return input.charAt(parserInput.i - 1); }; parserInput.getInput = function() { return input; }; parserInput.peekNotNumeric = function() { var c = input.charCodeAt(parserInput.i); // Is the first char of the dimension 0-9, '.', '+' or '-' return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA; }; parserInput.start = function(str, chunkInput, failFunction) { input = str; parserInput.i = j = currentPos = furthest = 0; // chunking apparently makes things quicker (but my tests indicate // it might actually make things slower in node at least) // and it is a non-perfect parse - it can't recognise // unquoted urls, meaning it can't distinguish comments // meaning comments with quotes or {}() in them get 'counted' // and then lead to parse errors. // In addition if the chunking chunks in the wrong place we might // not be able to parse a parser statement in one go // this is officially deprecated but can be switched on via an option // in the case it causes too much performance issues. if (chunkInput) { chunks = chunker(str, failFunction); } else { chunks = [str]; } current = chunks[0]; skipWhitespace(0); }; parserInput.end = function() { var message, isFinished = parserInput.i >= input.length; if (parserInput.i < furthest) { message = furthestPossibleErrorMessage; parserInput.i = furthest; } return { isFinished: isFinished, furthest: parserInput.i, furthestPossibleErrorMessage: message, furthestReachedEnd: parserInput.i >= input.length - 1, furthestChar: input[parserInput.i] }; }; return parserInput; }; },{"./chunker":40}],42:[function(require,module,exports){ var LessError = require('../less-error'), tree = require('../tree'), visitors = require('../visitors'), getParserInput = require('./parser-input'), utils = require('../utils'), functionRegistry = require('../functions/function-registry'); // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `currentPos` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // var Parser = function Parser(context, imports, fileInfo) { var parsers, parserInput = getParserInput(); function error(msg, type) { throw new LessError( { index: parserInput.i, filename: fileInfo.filename, type: type || 'Syntax', message: msg }, imports ); } function expect(arg, msg, index) { // some older browsers return typeof 'function' for RegExp var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg); if (result) { return result; } error(msg || (typeof arg === 'string' ? 'expected \'' + arg + '\' got \'' + parserInput.currentChar() + '\'' : 'unexpected token')); } // Specialization of expect() function expectChar(arg, msg) { if (parserInput.$char(arg)) { return arg; } error(msg || 'expected \'' + arg + '\' got \'' + parserInput.currentChar() + '\''); } function getDebugInfo(index) { var filename = fileInfo.filename; return { lineNumber: utils.getLocation(index, parserInput.getInput()).line + 1, fileName: filename }; } /** * Used after initial parsing to create nodes on the fly * * @param {String} str - string to parse * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"] * @param {Number} currentIndex - start number to begin indexing * @param {Object} fileInfo - fileInfo to attach to created nodes */ function parseNode(str, parseList, currentIndex, fileInfo, callback) { var result, returnNodes = []; var parser = parserInput; try { parser.start(str, false, function fail(msg, index) { callback({ message: msg, index: index + currentIndex }); }); for (var x = 0, p, i; (p = parseList[x]); x++) { i = parser.i; result = parsers[p](); if (result) { result._index = i + currentIndex; result._fileInfo = fileInfo; returnNodes.push(result); } else { returnNodes.push(null); } } var endInfo = parser.end(); if (endInfo.isFinished) { callback(null, returnNodes); } else { callback(true, null); } } catch (e) { throw new LessError({ index: e.index + currentIndex, message: e.message }, imports, fileInfo.filename); } } // // The Parser // return { parserInput: parserInput, imports: imports, fileInfo: fileInfo, parseNode: parseNode, // // Parse an input string into an abstract syntax tree, // @param str A string containing 'less' markup // @param callback call `callback` when done. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply // parse: function (str, callback, additionalData) { var root, error = null, globalVars, modifyVars, ignored, preText = ''; globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : ''; if (context.pluginManager) { var preProcessors = context.pluginManager.getPreProcessors(); for (var i = 0; i < preProcessors.length; i++) { str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo }); } } if (globalVars || (additionalData && additionalData.banner)) { preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars; ignored = imports.contentsIgnoredChars; ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0; ignored[fileInfo.filename] += preText.length; } str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark str = preText + str.replace(/^\uFEFF/, '') + modifyVars; imports.contents[fileInfo.filename] = str; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { parserInput.start(str, context.chunkInput, function fail(msg, index) { throw new LessError({ index: index, type: 'Parse', message: msg, filename: fileInfo.filename }, imports); }); tree.Node.prototype.parse = this; root = new tree.Ruleset(null, this.parsers.primary()); tree.Node.prototype.rootNode = root; root.root = true; root.firstRoot = true; root.functionRegistry = functionRegistry.inherit(); } catch (e) { return callback(new LessError(e, imports, fileInfo.filename)); } // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occurred. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. var endInfo = parserInput.end(); if (!endInfo.isFinished) { var message = endInfo.furthestPossibleErrorMessage; if (!message) { message = 'Unrecognised input'; if (endInfo.furthestChar === '}') { message += '. Possibly missing opening \'{\''; } else if (endInfo.furthestChar === ')') { message += '. Possibly missing opening \'(\''; } else if (endInfo.furthestReachedEnd) { message += '. Possibly missing something'; } } error = new LessError({ type: 'Parse', message: message, index: endInfo.furthest, filename: fileInfo.filename }, imports); } var finish = function (e) { e = error || e || imports.error; if (e) { if (!(e instanceof LessError)) { e = new LessError(e, imports, fileInfo.filename); } return callback(e); } else { return callback(null, root); } }; if (context.processImports !== false) { new visitors.ImportVisitor(imports, finish) .run(root); } else { return finish(); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Declaration -> Value -> Expression -> Entity // // Here's some Less code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Declaration ("color", Value ([Expression [Color #fff]])) // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$re()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: parsers = { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | declaration)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var mixin = this.mixin, root = [], node; while (true) { while (true) { node = this.comment(); if (!node) { break; } root.push(node); } // always process comments before deciding if finished if (parserInput.finished) { break; } if (parserInput.peek('}')) { break; } node = this.extendRule(); if (node) { root = root.concat(node); continue; } node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule(); if (node) { root.push(node); } else { var foundSemiColon = false; while (parserInput.$char(';')) { foundSemiColon = true; } if (!foundSemiColon) { break; } } } return root; }, // comments are collected by the main parsing mechanism and then assigned to nodes // where the current structure allows it comment: function () { if (parserInput.commentStore.length) { var comment = parserInput.commentStore.shift(); return new(tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo); } }, // // Entities are tokens which can be found inside an Expression // entities: { mixinLookup: function() { return parsers.mixin.call(true, true); }, // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function (forceEscaped) { var str, index = parserInput.i, isEscaped = false; parserInput.save(); if (parserInput.$char('~')) { isEscaped = true; } else if (forceEscaped) { parserInput.restore(); return; } str = parserInput.$quoted(); if (!str) { parserInput.restore(); return; } parserInput.forget(); return new(tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo); }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k = parserInput.$char('%') || parserInput.$re(/^\[?[_A-Za-z-][_A-Za-z0-9-]*\]?/); if (k) { return tree.Color.fromKeyword(k) || new(tree.Keyword)(k); } }, // // A function call // // rgb(255, 0, 255) // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, args, func, index = parserInput.i; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18 if (parserInput.peek(/^url\(/i)) { return; } parserInput.save(); name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/); if (!name) { parserInput.forget(); return; } name = name[1]; func = this.customFuncCall(name); if (func) { args = func.parse(); if (args && func.stop) { parserInput.forget(); return args; } } args = this.arguments(args); if (!parserInput.$char(')')) { parserInput.restore('Could not parse call arguments or missing \')\''); return; } parserInput.forget(); return new(tree.Call)(name, args, index, fileInfo); }, // // Parsing rules for functions with non-standard args, e.g.: // // boolean(not(2 > 1)) // // This is a quick prototype, to be modified/improved when // more custom-parsed funcs come (e.g. `selector(...)`) // customFuncCall: function (name) { /* Ideally the table is to be moved out of here for faster perf., but it's quite tricky since it relies on all these `parsers` and `expect` available only here */ return { alpha: f(parsers.ieAlpha, true), boolean: f(condition), 'if': f(condition) }[name.toLowerCase()]; function f(parse, stop) { return { parse: parse, // parsing function stop: stop // when true - stop after parse() and return its result, // otherwise continue for plain args }; } function condition() { return [expect(parsers.condition, 'expected condition')]; } }, arguments: function (prevArgs) { var argsComma = prevArgs || [], argsSemiColon = [], isSemiColonSeparated, value; parserInput.save(); while (true) { if (prevArgs) { prevArgs = false; } else { value = parsers.detachedRuleset() || this.assignment() || parsers.expression(); if (!value) { break; } if (value.value && value.value.length == 1) { value = value.value[0]; } argsComma.push(value); } if (parserInput.$char(',')) { continue; } if (parserInput.$char(';') || isSemiColonSeparated) { isSemiColonSeparated = true; value = (argsComma.length < 1) ? argsComma[0] : new tree.Value(argsComma); argsSemiColon.push(value); argsComma = []; } } parserInput.forget(); return isSemiColonSeparated ? argsSemiColon : argsComma; }, literal: function () { return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor(); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; parserInput.save(); key = parserInput.$re(/^\w+(?=\s?=)/i); if (!key) { parserInput.restore(); return; } if (!parserInput.$char('=')) { parserInput.restore(); return; } value = parsers.entity(); if (value) { parserInput.forget(); return new(tree.Assignment)(key, value); } else { parserInput.restore(); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value, index = parserInput.i; parserInput.autoCommentAbsorb = false; if (!parserInput.$str('url(')) { parserInput.autoCommentAbsorb = true; return; } value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ''; parserInput.autoCommentAbsorb = true; expectChar(')'); return new(tree.URL)((value.value != null || value instanceof tree.Variable || value instanceof tree.Property) ? value : new(tree.Anonymous)(value, index), index, fileInfo); }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var ch, name, index = parserInput.i; parserInput.save(); if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) { ch = parserInput.currentChar(); if (ch === '(' || ch === '[') { // this may be a VariableCall lookup var result = parsers.variableCall(name); if (!result) { return parserInput.restore(); } else { parserInput.forget(); return result; } } parserInput.forget(); return new(tree.Variable)(name, index, fileInfo); } parserInput.restore(); }, // A variable entity using the protective {} e.g. @{var} variableCurly: function () { var curly, index = parserInput.i; if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) { return new(tree.Variable)('@' + curly[1], index, fileInfo); } }, // // A Property accessor, such as `$color`, in // // background-color: $color // property: function () { var name, index = parserInput.i; if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) { return new(tree.Property)(name, index, fileInfo); } }, // A property entity useing the protective {} e.g. ${prop} propertyCurly: function () { var curly, index = parserInput.i; if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) { return new(tree.Property)('$' + curly[1], index, fileInfo); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { // strip colons, brackets, whitespaces and other characters that should not // definitely be part of color string var colorCandidateString = rgb.input.match(/^#([\w]+).*/); colorCandidateString = colorCandidateString[1]; if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characters error('Invalid HEX color code'); } return new(tree.Color)(rgb[1], undefined, '#' + colorCandidateString); } }, colorKeyword: function () { parserInput.save(); var autoCommentAbsorb = parserInput.autoCommentAbsorb; parserInput.autoCommentAbsorb = false; var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/); parserInput.autoCommentAbsorb = autoCommentAbsorb; if (!k) { parserInput.forget(); return; } parserInput.restore(); var color = tree.Color.fromKeyword(k); if (color) { parserInput.$str(k); return color; } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { if (parserInput.peekNotNumeric()) { return; } var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i); if (value) { return new(tree.Dimension)(value[1], value[2]); } }, // // A unicode descriptor, as is used in unicode-range // // U+0?? or U+00A1-00A9 // unicodeDescriptor: function () { var ud; ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); if (ud) { return new(tree.UnicodeDescriptor)(ud[0]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var js, index = parserInput.i; parserInput.save(); var escape = parserInput.$char('~'); var jsQuote = parserInput.$char('`'); if (!jsQuote) { parserInput.restore(); return; } js = parserInput.$re(/^[^`]*`/); if (js) { parserInput.forget(); return new(tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo); } parserInput.restore('invalid javascript definition'); } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // // Call a variable value to retrieve a detached ruleset // or a value from a detached ruleset's rules. // // @fink(); // @fink; // color: @fink[@color]; // variableCall: function (parsedName) { var lookups, important, i = parserInput.i, inValue = !!parsedName, name = parsedName; parserInput.save(); if (name || (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) { lookups = this.mixin.ruleLookups(); if (!lookups && name[2] !== '()') { parserInput.restore('Missing \'[...]\' lookup in variable call'); return; } if (!inValue) { name = name[1]; } if (lookups && parsers.important()) { important = true; } var call = new tree.VariableCall(name, i, fileInfo); if (!inValue && parsers.end()) { parserInput.forget(); return call; } else { parserInput.forget(); return new tree.NamespaceValue(call, lookups, important, i, fileInfo); } } parserInput.restore(); }, // // extend syntax - used to extend selectors // extend: function(isRule) { var elements, e, index = parserInput.i, option, extendList, extend; if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) { return; } do { option = null; elements = null; while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) { e = this.element(); if (!e) { break; } if (elements) { elements.push(e); } else { elements = [ e ]; } } option = option && option[1]; if (!elements) { error('Missing target selector for :extend().'); } extend = new(tree.Extend)(new(tree.Selector)(elements), option, index, fileInfo); if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } while (parserInput.$char(',')); expect(/^\)/); if (isRule) { expect(/^;/); } return extendList; }, // // extendRule - used in a rule to extend all the parent selectors // extendRule: function() { return this.extend(true); }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // #mixins.square(#fff); // .rounded(4px, black); // .button; // // We can lookup / return a value using the lookup syntax: // // color: #mixin.square(#fff)[@color]; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function (inValue, getLookup) { var s = parserInput.currentChar(), important = false, lookups, index = parserInput.i, elements, args, hasParens; if (s !== '.' && s !== '#') { return; } parserInput.save(); // stop us absorbing part of an invalid selector elements = this.elements(); if (elements) { if (parserInput.$char('(')) { args = this.args(true).args; expectChar(')'); hasParens = true; } if (getLookup !== false) { lookups = this.ruleLookups(); } if (getLookup === true && !lookups) { parserInput.restore(); return; } if (inValue && !lookups && !hasParens) { // This isn't a valid in-value mixin call parserInput.restore(); return; } if (!inValue && parsers.important()) { important = true; } if (inValue || parsers.end()) { parserInput.forget(); var mixin = new(tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important); if (lookups) { return new tree.NamespaceValue(mixin, lookups, important); } else { return mixin; } } } parserInput.restore(); }, /** * Matching elements for mixins * (Start with . or # and can have > ) */ elements: function() { var elements, e, c, elem, elemIndex, re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/; while (true) { elemIndex = parserInput.i; e = parserInput.$re(re); if (!e) { break; } elem = new(tree.Element)(c, e, false, elemIndex, fileInfo); if (elements) { elements.push(elem); } else { elements = [ elem ]; } c = parserInput.$char('>'); } return elements; }, args: function (isCall) { var entities = parsers.entities, returner = { args:null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeparated, expressionContainsNamed, name, nameLoop, value, arg, expand; parserInput.save(); while (true) { if (isCall) { arg = parsers.detachedRuleset() || parsers.expression(); } else { parserInput.commentStore.length = 0; if (parserInput.$str('...')) { returner.variadic = true; if (parserInput.$char(';') && !isSemiColonSeparated) { isSemiColonSeparated = true; } (isSemiColonSeparated ? argsSemiColon : argsComma) .push({ variadic: true }); break; } arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true); } if (!arg) { break; } nameLoop = null; if (arg.throwAwayComments) { arg.throwAwayComments(); } value = arg; var val = null; if (isCall) { // Variable if (arg.value && arg.value.length == 1) { val = arg.value[0]; } } else { val = arg; } if (val && (val instanceof tree.Variable || val instanceof tree.Property)) { if (parserInput.$char(':')) { if (expressions.length > 0) { if (isSemiColonSeparated) { error('Cannot mix ; and , as delimiter types'); } expressionContainsNamed = true; } value = parsers.detachedRuleset() || parsers.expression(); if (!value) { if (isCall) { error('could not understand value for named argument'); } else { parserInput.restore(); returner.args = []; return returner; } } nameLoop = (name = val.name); } else if (parserInput.$str('...')) { if (!isCall) { returner.variadic = true; if (parserInput.$char(';') && !isSemiColonSeparated) { isSemiColonSeparated = true; } (isSemiColonSeparated ? argsSemiColon : argsComma) .push({ name: arg.name, variadic: true }); break; } else { expand = true; } } else if (!isCall) { name = nameLoop = val.name; value = null; } } if (value) { expressions.push(value); } argsComma.push({ name:nameLoop, value:value, expand:expand }); if (parserInput.$char(',')) { continue; } if (parserInput.$char(';') || isSemiColonSeparated) { if (expressionContainsNamed) { error('Cannot mix ; and , as delimiter types'); } isSemiColonSeparated = true; if (expressions.length > 1) { value = new(tree.Value)(expressions); } argsSemiColon.push({ name:name, value:value, expand:expand }); name = null; expressions = []; expressionContainsNamed = false; } } parserInput.forget(); returner.args = isSemiColonSeparated ? argsSemiColon : argsComma; return returner; }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, cond, variadic = false; if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') || parserInput.peek(/^[^{]*\}/)) { return; } parserInput.save(); match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; // .mixincall("@{a}"); // looks a bit like a mixin definition.. // also // .mixincall(@a: {rule: set;}); // so we have to be nice and restore if (!parserInput.$char(')')) { parserInput.restore('Missing closing \')\''); return; } parserInput.commentStore.length = 0; if (parserInput.$str('when')) { // Guard cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { parserInput.forget(); return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { parserInput.restore(); } } else { parserInput.forget(); } }, ruleLookups: function() { var rule, args, lookups = []; if (parserInput.currentChar() !== '[') { return; } while (true) { parserInput.save(); args = null; rule = this.lookupValue(); if (!rule) { parserInput.restore(); break; } lookups.push(rule); parserInput.forget(); } if (lookups.length > 0) { return lookups; } }, lookupValue: function() { parserInput.save(); if (!parserInput.$char('[')) { parserInput.restore(); return; } var name = parserInput.$re(/^(?:@{0,2}|\$)[_a-zA-Z0-9-]+/); if (!parserInput.$char(']')) { parserInput.restore(); return; } if (name) { parserInput.forget(); return name; } parserInput.restore(); } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { var entities = this.entities; return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript(); }, // // A Declaration terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was omitted. // end: function () { return parserInput.$char(';') || parserInput.peek('}'); }, // // IE's alpha function // // alpha(opacity=88) // ieAlpha: function () { var value; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18 if (!parserInput.$re(/^opacity=/i)) { return; } value = parserInput.$re(/^\d+/); if (!value) { value = expect(parsers.entities.variable, 'Could not parse alpha'); value = '@{' + value.name.slice(1) + '}'; } expectChar(')'); return new tree.Quoted('', 'alpha(opacity=' + value + ')'); }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, c, v, index = parserInput.i; c = this.combinator(); e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly(); if (!e) { parserInput.save(); if (parserInput.$char('(')) { if ((v = this.selector(false)) && parserInput.$char(')')) { e = new(tree.Paren)(v); parserInput.forget(); } else { parserInput.restore('Missing closing \')\''); } } else { parserInput.forget(); } } if (e) { return new(tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var c = parserInput.currentChar(); if (c === '/') { parserInput.save(); var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i); if (slashedCombinator) { parserInput.forget(); return new(tree.Combinator)(slashedCombinator); } parserInput.restore(); } if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { parserInput.i++; if (c === '^' && parserInput.currentChar() === '^') { c = '^^'; parserInput.i++; } while (parserInput.isWhitespace()) { parserInput.i++; } return new(tree.Combinator)(c); } else if (parserInput.isWhitespace(-1)) { return new(tree.Combinator)(' '); } else { return new(tree.Combinator)(null); } }, // // A CSS Selector // with less extensions e.g. the ability to extend and guard // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function (isLess) { var index = parserInput.i, elements, extendList, c, e, allExtends, when, condition; isLess = isLess !== false; while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) { if (when) { condition = expect(this.conditions, 'expected condition'); } else if (condition) { error('CSS guard can only be used at the end of selector'); } else if (extendList) { if (allExtends) { allExtends = allExtends.concat(extendList); } else { allExtends = extendList; } } else { if (allExtends) { error('Extend can only be used at the end of selector'); } c = parserInput.currentChar(); if (elements) { elements.push(e); } else { elements = [ e ]; } e = null; } if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break; } } if (elements) { return new(tree.Selector)(elements, allExtends, condition, index, fileInfo); } if (allExtends) { error('Extend must be used to extend a selector, it cannot be used on its own'); } }, selectors: function () { var s, selectors; while (true) { s = this.selector(); if (!s) { break; } if (selectors) { selectors.push(s); } else { selectors = [ s ]; } parserInput.commentStore.length = 0; if (s.condition && selectors.length > 1) { error("Guards are only currently allowed on a single selector."); } if (!parserInput.$char(',')) { break; } if (s.condition) { error("Guards are only currently allowed on a single selector."); } parserInput.commentStore.length = 0; } return selectors; }, attribute: function () { if (!parserInput.$char('[')) { return; } var entities = this.entities, key, val, op; if (!(key = entities.variableCurly())) { key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); } op = parserInput.$re(/^[|~*$^]?=/); if (op) { val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly(); } expectChar(']'); return new(tree.Attribute)(key, op, val); }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) { return content; } }, blockRuleset: function() { var block = this.block(); if (block) { block = new tree.Ruleset(null, block); } return block; }, detachedRuleset: function() { var blockRuleset = this.blockRuleset(); if (blockRuleset) { return new tree.DetachedRuleset(blockRuleset); } }, // // div, .class, body > p {...} // ruleset: function () { var selectors, rules, debugInfo; parserInput.save(); if (context.dumpLineNumbers) { debugInfo = getDebugInfo(parserInput.i); } selectors = this.selectors(); if (selectors && (rules = this.block())) { parserInput.forget(); var ruleset = new(tree.Ruleset)(selectors, rules, context.strictImports); if (context.dumpLineNumbers) { ruleset.debugInfo = debugInfo; } return ruleset; } else { parserInput.restore(); } }, declaration: function () { var name, value, index = parserInput.i, hasDR, c = parserInput.currentChar(), important, merge, isVariable; if (c === '.' || c === '#' || c === '&' || c === ':') { return; } parserInput.save(); name = this.variable() || this.ruleProperty(); if (name) { isVariable = typeof name === 'string'; if (isVariable) { value = this.detachedRuleset(); if (value) { hasDR = true; } } parserInput.commentStore.length = 0; if (!value) { // a name returned by this.ruleProperty() is always an array of the form: // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] // where each item is a tree.Keyword or tree.Variable merge = !isVariable && name.length > 1 && name.pop().value; // Custom property values get permissive parsing if (name[0].value && name[0].value.slice(0, 2) === '--') { value = this.permissiveValue(); } // Try to store values as anonymous // If we need the value later we'll re-parse it in ruleset.parseValue else { value = this.anonymousValue(); } if (value) { parserInput.forget(); // anonymous values absorb the end ';' which is required for them to work return new (tree.Declaration)(name, value, false, merge, index, fileInfo); } if (!value) { value = this.value(); } // As a last resort, try permissiveValue if (!value && isVariable) { value = this.permissiveValue(); } important = this.important(); } if (value && (this.end() || hasDR)) { parserInput.forget(); return new (tree.Declaration)(name, value, important, merge, index, fileInfo); } else { parserInput.restore(); } } else { parserInput.restore(); } }, anonymousValue: function () { var index = parserInput.i; var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/); if (match) { return new(tree.Anonymous)(match[1], index); } }, /** * Used for custom properties, at-rules, and variables (as fallback) * Parses almost anything inside of {} [] () "" blocks * until it reaches outer-most tokens. * * First, it will try to parse comments and entities to reach * the end. This is mostly like the Expression parser except no * math is allowed. */ permissiveValue: function (untilTokens) { var i, e, done, value, tok = untilTokens || ';', index = parserInput.i, result = []; function testCurrentChar() { var char = parserInput.currentChar(); if (typeof tok === 'string') { return char === tok; } else { return tok.test(char); } } if (testCurrentChar()) { return; } value = []; do { e = this.comment(); if (e) { value.push(e); continue; } e = this.entity(); if (e) { value.push(e); } } while (e); done = testCurrentChar(); if (value.length > 0) { value = new(tree.Expression)(value); if (done) { return value; } else { result.push(value); } // Preserve space before $parseUntil as it will not if (parserInput.prevChar() === ' ') { result.push(new tree.Anonymous(' ', index)); } } parserInput.save(); value = parserInput.$parseUntil(tok); if (value) { if (typeof value === 'string') { error('Expected \'' + value + '\'', 'Parse'); } if (value.length === 1 && value[0] === ' ') { parserInput.forget(); return new tree.Anonymous('', index); } var item; for (i = 0; i < value.length; i++) { item = value[i]; if (Array.isArray(item)) { // Treat actual quotes as normal quoted values result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo)); } else { if (i === value.length - 1) { item = item.trim(); } // Treat like quoted values, but replace vars like unquoted expressions var quote = new tree.Quoted('\'', item, true, index, fileInfo); quote.variableRegex = /@([\w-]+)/g; quote.propRegex = /\$([\w-]+)/g; result.push(quote); } } parserInput.forget(); return new tree.Expression(result, true); } parserInput.restore(); }, // // An @import atrule // // @import "lib"; // // Depending on our environment, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // 'import': function () { var path, features, index = parserInput.i; var dir = parserInput.$re(/^@import?\s+/); if (dir) { var options = (dir ? this.importOptions() : null) || {}; if ((path = this.entities.quoted() || this.entities.url())) { features = this.mediaFeatures(); if (!parserInput.$char(';')) { parserInput.i = index; error('missing semi-colon or unrecognised media features on import'); } features = features && new(tree.Value)(features); return new(tree.Import)(path, features, options, index, fileInfo); } else { parserInput.i = index; error('malformed import statement'); } } }, importOptions: function() { var o, options = {}, optionName, value; // list of options, surrounded by parens if (!parserInput.$char('(')) { return null; } do { o = this.importOption(); if (o) { optionName = o; value = true; switch (optionName) { case 'css': optionName = 'less'; value = false; break; case 'once': optionName = 'multiple'; value = false; break; } options[optionName] = value; if (!parserInput.$char(',')) { break; } } } while (o); expectChar(')'); return options; }, importOption: function() { var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/); if (opt) { return opt[1]; } }, mediaFeature: function () { var entities = this.entities, nodes = [], e, p; parserInput.save(); do { e = entities.keyword() || entities.variable() || entities.mixinLookup(); if (e) { nodes.push(e); } else if (parserInput.$char('(')) { p = this.property(); e = this.permissiveValue(')'); if (parserInput.$char(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { error('badly formed media feature definition'); } } else { error('Missing closing \')\'', 'Parse'); } } } while (e); parserInput.forget(); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var entities = this.entities, features = [], e; do { e = this.mediaFeature(); if (e) { features.push(e); if (!parserInput.$char(',')) { break; } } else { e = entities.variable() || entities.mixinLookup(); if (e) { features.push(e); if (!parserInput.$char(',')) { break; } } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules, media, debugInfo, index = parserInput.i; if (context.dumpLineNumbers) { debugInfo = getDebugInfo(index); } parserInput.save(); if (parserInput.$str('@media')) { features = this.mediaFeatures(); rules = this.block(); if (!rules) { error('media definitions require block statements after any features'); } parserInput.forget(); media = new(tree.Media)(rules, features, index, fileInfo); if (context.dumpLineNumbers) { media.debugInfo = debugInfo; } return media; } parserInput.restore(); }, // // A @plugin directive, used to import plugins dynamically. // // @plugin (args) "lib"; // plugin: function () { var path, args, options, index = parserInput.i, dir = parserInput.$re(/^@plugin?\s+/); if (dir) { args = this.pluginArgs(); if (args) { options = { pluginArgs: args, isPlugin: true }; } else { options = { isPlugin: true }; } if ((path = this.entities.quoted() || this.entities.url())) { if (!parserInput.$char(';')) { parserInput.i = index; error('missing semi-colon on @plugin'); } return new(tree.Import)(path, null, options, index, fileInfo); } else { parserInput.i = index; error('malformed @plugin statement'); } } }, pluginArgs: function() { // list of options, surrounded by parens parserInput.save(); if (!parserInput.$char('(')) { parserInput.restore(); return null; } var args = parserInput.$re(/^\s*([^\);]+)\)\s*/); if (args[1]) { parserInput.forget(); return args[1].trim(); } else { parserInput.restore(); return null; } }, // // A CSS AtRule // // @charset "utf-8"; // atrule: function () { var index = parserInput.i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true, isRooted = true; if (parserInput.currentChar() !== '@') { return; } value = this['import']() || this.plugin() || this.media(); if (value) { return value; } parserInput.save(); name = parserInput.$re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = '@' + name.slice(name.indexOf('-', 2) + 1); } switch (nonVendorSpecificName) { case '@charset': hasIdentifier = true; hasBlock = false; break; case '@namespace': hasExpression = true; hasBlock = false; break; case '@keyframes': case '@counter-style': hasIdentifier = true; break; case '@document': case '@supports': hasUnknown = true; isRooted = false; break; default: hasUnknown = true; break; } parserInput.commentStore.length = 0; if (hasIdentifier) { value = this.entity(); if (!value) { error('expected ' + name + ' identifier'); } } else if (hasExpression) { value = this.expression(); if (!value) { error('expected ' + name + ' expression'); } } else if (hasUnknown) { value = this.permissiveValue(/^[{;]/); hasBlock = (parserInput.currentChar() === '{'); if (!value) { if (!hasBlock && parserInput.currentChar() !== ';') { error(name + ' rule is missing block or ending semi-colon'); } } else if (!value.value) { value = null; } } if (hasBlock) { rules = this.blockRuleset(); } if (rules || (!hasBlock && value && parserInput.$char(';'))) { parserInput.forget(); return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted ); } parserInput.restore('at-rule options not recognised'); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = [], index = parserInput.i; do { e = this.expression(); if (e) { expressions.push(e); if (!parserInput.$char(',')) { break; } } } while (e); if (expressions.length > 0) { return new(tree.Value)(expressions, index); } }, important: function () { if (parserInput.currentChar() === '!') { return parserInput.$re(/^! *important/); } }, sub: function () { var a, e; parserInput.save(); if (parserInput.$char('(')) { a = this.addition(); if (a && parserInput.$char(')')) { parserInput.forget(); e = new(tree.Expression)([a]); e.parens = true; return e; } parserInput.restore('Expected \')\''); return; } parserInput.restore(); }, multiplication: function () { var m, a, op, operation, isSpaced; m = this.operand(); if (m) { isSpaced = parserInput.isWhitespace(-1); while (true) { if (parserInput.peek(/^\/[*\/]/)) { break; } parserInput.save(); op = parserInput.$char('/') || parserInput.$char('*'); if (!op) { parserInput.forget(); break; } a = this.operand(); if (!a) { parserInput.restore(); break; } parserInput.forget(); m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = parserInput.isWhitespace(-1); } return operation || m; } }, addition: function () { var m, a, op, operation, isSpaced; m = this.multiplication(); if (m) { isSpaced = parserInput.isWhitespace(-1); while (true) { op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-'))); if (!op) { break; } a = this.multiplication(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = parserInput.isWhitespace(-1); } return operation || m; } }, conditions: function () { var a, b, index = parserInput.i, condition; a = this.condition(); if (a) { while (true) { if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) { break; } b = this.condition(); if (!b) { break; } condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var result, logical, next; function or() { return parserInput.$str('or'); } result = this.conditionAnd(this); if (!result) { return ; } logical = or(); if (logical) { next = this.condition(); if (next) { result = new(tree.Condition)(logical, result, next); } else { return ; } } return result; }, conditionAnd: function () { var result, logical, next; function insideCondition(me) { return me.negatedCondition() || me.parenthesisCondition(); } function and() { return parserInput.$str('and'); } result = insideCondition(this); if (!result) { return ; } logical = and(); if (logical) { next = this.conditionAnd(); if (next) { result = new(tree.Condition)(logical, result, next); } else { return ; } } return result; }, negatedCondition: function () { if (parserInput.$str('not')) { var result = this.parenthesisCondition(); if (result) { result.negate = !result.negate; } return result; } }, parenthesisCondition: function () { function tryConditionFollowedByParenthesis(me) { var body; parserInput.save(); body = me.condition(); if (!body) { parserInput.restore(); return ; } if (!parserInput.$char(')')) { parserInput.restore(); return ; } parserInput.forget(); return body; } var body; parserInput.save(); if (!parserInput.$str('(')) { parserInput.restore(); return ; } body = tryConditionFollowedByParenthesis(this); if (body) { parserInput.forget(); return body; } body = this.atomicCondition(); if (!body) { parserInput.restore(); return ; } if (!parserInput.$char(')')) { parserInput.restore('expected \')\' got \'' + parserInput.currentChar() + '\''); return ; } parserInput.forget(); return body; }, atomicCondition: function () { var entities = this.entities, index = parserInput.i, a, b, c, op; function cond() { return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup(); } cond = cond.bind(this); a = cond(); if (a) { if (parserInput.$char('>')) { if (parserInput.$char('=')) { op = '>='; } else { op = '>'; } } else if (parserInput.$char('<')) { if (parserInput.$char('=')) { op = '<='; } else { op = '<'; } } else if (parserInput.$char('=')) { if (parserInput.$char('>')) { op = '=>'; } else if (parserInput.$char('<')) { op = '=<'; } else { op = '='; } } if (op) { b = cond(); if (b) { c = new(tree.Condition)(op, a, b, index, false); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, false); } return c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var entities = this.entities, negate; if (parserInput.peek(/^-[@\$\(]/)) { negate = parserInput.$char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup(); if (negate) { o.parensInOp = true; o = new(tree.Negative)(o); } return o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var entities = [], e, delim, index = parserInput.i; do { e = this.comment(); if (e) { entities.push(e); continue; } e = this.addition() || this.entity(); if (e) { entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here if (!parserInput.peek(/^\/[\/*]/)) { delim = parserInput.$char('/'); if (delim) { entities.push(new(tree.Anonymous)(delim, index)); } } } } while (e); if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); if (name) { return name[1]; } }, ruleProperty: function () { var name = [], index = [], s, k; parserInput.save(); var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/); if (simpleProperty) { name = [new(tree.Keyword)(simpleProperty[1])]; parserInput.forget(); return name; } function match(re) { var i = parserInput.i, chunk = parserInput.$re(re); if (chunk) { index.push(i); return name.push(chunk[1]); } } match(/^(\*?)/); while (true) { if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) { break; } } if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) { parserInput.forget(); // at last, we have the complete match now. move forward, // convert name particles to tree objects and return: if (name[0] === '') { name.shift(); index.shift(); } for (k = 0; k < name.length; k++) { s = name[k]; name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ? new(tree.Keyword)(s) : (s.charAt(0) === '@' ? new(tree.Variable)('@' + s.slice(2, -1), index[k], fileInfo) : new(tree.Property)('$' + s.slice(2, -1), index[k], fileInfo)); } return name; } parserInput.restore(); } } }; }; Parser.serializeVars = function(vars) { var s = ''; for (var name in vars) { if (Object.hasOwnProperty.call(vars, name)) { var value = vars[name]; s += ((name[0] === '@') ? '' : '@') + name + ': ' + value + ((String(value).slice(-1) === ';') ? '' : ';'); } } return s; }; module.exports = Parser; },{"../functions/function-registry":26,"../less-error":36,"../tree":65,"../utils":87,"../visitors":91,"./parser-input":41}],43:[function(require,module,exports){ /** * Plugin Manager */ var PluginManager = function(less) { this.less = less; this.visitors = []; this.preProcessors = []; this.postProcessors = []; this.installedPlugins = []; this.fileManagers = []; this.iterator = -1; this.pluginCache = {}; this.Loader = new less.PluginLoader(less); }; var pm, PluginManagerFactory = function(less, newFactory) { if (newFactory || !pm) { pm = new PluginManager(less); } return pm; }; /** * Adds all the plugins in the array * @param {Array} plugins */ PluginManager.prototype.addPlugins = function(plugins) { if (plugins) { for (var i = 0; i < plugins.length; i++) { this.addPlugin(plugins[i]); } } }; /** * * @param plugin * @param {String} filename */ PluginManager.prototype.addPlugin = function(plugin, filename, functionRegistry) { this.installedPlugins.push(plugin); if (filename) { this.pluginCache[filename] = plugin; } if (plugin.install) { plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry); } }; /** * * @param filename */ PluginManager.prototype.get = function(filename) { return this.pluginCache[filename]; }; /** * Adds a visitor. The visitor object has options on itself to determine * when it should run. * @param visitor */ PluginManager.prototype.addVisitor = function(visitor) { this.visitors.push(visitor); }; /** * Adds a pre processor object * @param {object} preProcessor * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import */ PluginManager.prototype.addPreProcessor = function(preProcessor, priority) { var indexToInsertAt; for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) { if (this.preProcessors[indexToInsertAt].priority >= priority) { break; } } this.preProcessors.splice(indexToInsertAt, 0, {preProcessor: preProcessor, priority: priority}); }; /** * Adds a post processor object * @param {object} postProcessor * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression */ PluginManager.prototype.addPostProcessor = function(postProcessor, priority) { var indexToInsertAt; for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) { if (this.postProcessors[indexToInsertAt].priority >= priority) { break; } } this.postProcessors.splice(indexToInsertAt, 0, {postProcessor: postProcessor, priority: priority}); }; /** * * @param manager */ PluginManager.prototype.addFileManager = function(manager) { this.fileManagers.push(manager); }; /** * * @returns {Array} * @private */ PluginManager.prototype.getPreProcessors = function() { var preProcessors = []; for (var i = 0; i < this.preProcessors.length; i++) { preProcessors.push(this.preProcessors[i].preProcessor); } return preProcessors; }; /** * * @returns {Array} * @private */ PluginManager.prototype.getPostProcessors = function() { var postProcessors = []; for (var i = 0; i < this.postProcessors.length; i++) { postProcessors.push(this.postProcessors[i].postProcessor); } return postProcessors; }; /** * * @returns {Array} * @private */ PluginManager.prototype.getVisitors = function() { return this.visitors; }; PluginManager.prototype.visitor = function() { var self = this; return { first: function() { self.iterator = -1; return self.visitors[self.iterator]; }, get: function() { self.iterator += 1; return self.visitors[self.iterator]; } }; }; /** * * @returns {Array} * @private */ PluginManager.prototype.getFileManagers = function() { return this.fileManagers; }; // module.exports = PluginManagerFactory; },{}],44:[function(require,module,exports){ var PromiseConstructor, utils = require('./utils'); module.exports = function(environment, ParseTree, ImportManager) { var render = function (input, options, callback) { if (typeof options === 'function') { callback = options; options = utils.defaults(this.options, {}); } else { options = utils.defaults(this.options, options || {}); } if (!callback) { if (!PromiseConstructor) { PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise; } var self = this; return new PromiseConstructor(function (resolve, reject) { render.call(self, input, options, function(err, output) { if (err) { reject(err); } else { resolve(output); } }); }); } else { this.parse(input, options, function(err, root, imports, options) { if (err) { return callback(err); } var result; try { var parseTree = new ParseTree(root, imports); result = parseTree.toCSS(options); } catch (err) { return callback(err); } callback(null, result); }); } }; return render; }; },{"./utils":87,"promise":undefined}],45:[function(require,module,exports){ module.exports = function (SourceMapOutput, environment) { var SourceMapBuilder = function (options) { this.options = options; }; SourceMapBuilder.prototype.toCSS = function(rootNode, options, imports) { var sourceMapOutput = new SourceMapOutput( { contentsIgnoredCharsMap: imports.contentsIgnoredChars, rootNode: rootNode, contentsMap: imports.contents, sourceMapFilename: this.options.sourceMapFilename, sourceMapURL: this.options.sourceMapURL, outputFilename: this.options.sourceMapOutputFilename, sourceMapBasepath: this.options.sourceMapBasepath, sourceMapRootpath: this.options.sourceMapRootpath, outputSourceFiles: this.options.outputSourceFiles, sourceMapGenerator: this.options.sourceMapGenerator, sourceMapFileInline: this.options.sourceMapFileInline }); var css = sourceMapOutput.toCSS(options); this.sourceMap = sourceMapOutput.sourceMap; this.sourceMapURL = sourceMapOutput.sourceMapURL; if (this.options.sourceMapInputFilename) { this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename); } if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) { this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL); } return css + this.getCSSAppendage(); }; SourceMapBuilder.prototype.getCSSAppendage = function() { var sourceMapURL = this.sourceMapURL; if (this.options.sourceMapFileInline) { if (this.sourceMap === undefined) { return ''; } sourceMapURL = 'data:application/json;base64,' + environment.encodeBase64(this.sourceMap); } if (sourceMapURL) { return '/*# sourceMappingURL=' + sourceMapURL + ' */'; } return ''; }; SourceMapBuilder.prototype.getExternalSourceMap = function() { return this.sourceMap; }; SourceMapBuilder.prototype.setExternalSourceMap = function(sourceMap) { this.sourceMap = sourceMap; }; SourceMapBuilder.prototype.isInline = function() { return this.options.sourceMapFileInline; }; SourceMapBuilder.prototype.getSourceMapURL = function() { return this.sourceMapURL; }; SourceMapBuilder.prototype.getOutputFilename = function() { return this.options.sourceMapOutputFilename; }; SourceMapBuilder.prototype.getInputFilename = function() { return this.sourceMapInputFilename; }; return SourceMapBuilder; }; },{}],46:[function(require,module,exports){ module.exports = function (environment) { var SourceMapOutput = function (options) { this._css = []; this._rootNode = options.rootNode; this._contentsMap = options.contentsMap; this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; if (options.sourceMapFilename) { this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/'); } this._outputFilename = options.outputFilename; this.sourceMapURL = options.sourceMapURL; if (options.sourceMapBasepath) { this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); } if (options.sourceMapRootpath) { this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/'); if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') { this._sourceMapRootpath += '/'; } } else { this._sourceMapRootpath = ''; } this._outputSourceFiles = options.outputSourceFiles; this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator(); this._lineNumber = 0; this._column = 0; }; SourceMapOutput.prototype.removeBasepath = function(path) { if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) { path = path.substring(this._sourceMapBasepath.length); if (path.charAt(0) === '\\' || path.charAt(0) === '/') { path = path.substring(1); } } return path; }; SourceMapOutput.prototype.normalizeFilename = function(filename) { filename = filename.replace(/\\/g, '/'); filename = this.removeBasepath(filename); return (this._sourceMapRootpath || '') + filename; }; SourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { // ignore adding empty strings if (!chunk) { return; } var lines, sourceLines, columns, sourceColumns, i; if (fileInfo) { var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file if (this._contentsIgnoredCharsMap[fileInfo.filename]) { // adjust the index index -= this._contentsIgnoredCharsMap[fileInfo.filename]; if (index < 0) { index = 0; } // adjust the source inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); } inputSource = inputSource.substring(0, index); sourceLines = inputSource.split('\n'); sourceColumns = sourceLines[sourceLines.length - 1]; } lines = chunk.split('\n'); columns = lines[lines.length - 1]; if (fileInfo) { if (!mapLines) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, original: { line: sourceLines.length, column: sourceColumns.length}, source: this.normalizeFilename(fileInfo.filename)}); } else { for (i = 0; i < lines.length; i++) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, source: this.normalizeFilename(fileInfo.filename)}); } } } if (lines.length === 1) { this._column += columns.length; } else { this._lineNumber += lines.length - 1; this._column = columns.length; } this._css.push(chunk); }; SourceMapOutput.prototype.isEmpty = function() { return this._css.length === 0; }; SourceMapOutput.prototype.toCSS = function(context) { this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); if (this._outputSourceFiles) { for (var filename in this._contentsMap) { if (this._contentsMap.hasOwnProperty(filename)) { var source = this._contentsMap[filename]; if (this._contentsIgnoredCharsMap[filename]) { source = source.slice(this._contentsIgnoredCharsMap[filename]); } this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); } } } this._rootNode.genCSS(context, this); if (this._css.length > 0) { var sourceMapURL, sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); if (this.sourceMapURL) { sourceMapURL = this.sourceMapURL; } else if (this._sourceMapFilename) { sourceMapURL = this._sourceMapFilename; } this.sourceMapURL = sourceMapURL; this.sourceMap = sourceMapContent; } return this._css.join(''); }; return SourceMapOutput; }; },{}],47:[function(require,module,exports){ var contexts = require('./contexts'), visitor = require('./visitors'), tree = require('./tree'); module.exports = function(root, options) { options = options || {}; var evaldRoot, variables = options.variables, evalEnv = new contexts.Eval(options); // // Allows setting variables with a hash, so: // // `{ color: new tree.Color('#f01') }` will become: // // new tree.Declaration('@color', // new tree.Value([ // new tree.Expression([ // new tree.Color('#f01') // ]) // ]) // ) // if (typeof variables === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (!(value instanceof tree.Value)) { if (!(value instanceof tree.Expression)) { value = new tree.Expression([value]); } value = new tree.Value([value]); } return new tree.Declaration('@' + k, value, false, null, 0); }); evalEnv.frames = [new tree.Ruleset(null, variables)]; } var visitors = [ new visitor.JoinSelectorVisitor(), new visitor.MarkVisibleSelectorsVisitor(true), new visitor.ExtendVisitor(), new visitor.ToCSSVisitor({compress: Boolean(options.compress)}) ], preEvalVisitors = [], v, visitorIterator; /** * first() / get() allows visitors to be added while visiting * * @todo Add scoping for visitors just like functions for @plugin; right now they're global */ if (options.pluginManager) { visitorIterator = options.pluginManager.visitor(); for (var i = 0; i < 2; i++) { visitorIterator.first(); while ((v = visitorIterator.get())) { if (v.isPreEvalVisitor) { if (i === 0 || preEvalVisitors.indexOf(v) === -1) { preEvalVisitors.push(v); v.run(root); } } else { if (i === 0 || visitors.indexOf(v) === -1) { if (v.isPreVisitor) { visitors.unshift(v); } else { visitors.push(v); } } } } } } evaldRoot = root.eval(evalEnv); for (var i = 0; i < visitors.length; i++) { visitors[i].run(evaldRoot); } // Run any remaining visitors added after eval pass if (options.pluginManager) { visitorIterator.first(); while ((v = visitorIterator.get())) { if (visitors.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) { v.run(evaldRoot); } } } return evaldRoot; }; },{"./contexts":12,"./tree":65,"./visitors":91}],48:[function(require,module,exports){ var Node = require('./node'); var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) { this.value = value; this._index = index; this._fileInfo = currentFileInfo; this.mapLines = mapLines; this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike; this.allowRoot = true; this.copyVisibilityInfo(visibilityInfo); }; Anonymous.prototype = new Node(); Anonymous.prototype.type = 'Anonymous'; Anonymous.prototype.eval = function () { return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo()); }; Anonymous.prototype.compare = function (other) { return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined; }; Anonymous.prototype.isRulesetLike = function() { return this.rulesetLike; }; Anonymous.prototype.genCSS = function (context, output) { this.nodeVisible = Boolean(this.value); if (this.nodeVisible) { output.add(this.value, this._fileInfo, this._index, this.mapLines); } }; module.exports = Anonymous; },{"./node":74}],49:[function(require,module,exports){ var Node = require('./node'); var Assignment = function (key, val) { this.key = key; this.value = val; }; Assignment.prototype = new Node(); Assignment.prototype.type = 'Assignment'; Assignment.prototype.accept = function (visitor) { this.value = visitor.visit(this.value); }; Assignment.prototype.eval = function (context) { if (this.value.eval) { return new Assignment(this.key, this.value.eval(context)); } return this; }; Assignment.prototype.genCSS = function (context, output) { output.add(this.key + '='); if (this.value.genCSS) { this.value.genCSS(context, output); } else { output.add(this.value); } }; module.exports = Assignment; },{"./node":74}],50:[function(require,module,exports){ var Node = require('./node'), Selector = require('./selector'), Ruleset = require('./ruleset'), Anonymous = require('./anonymous'); var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) { var i; this.name = name; this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value); if (rules) { if (Array.isArray(rules)) { this.rules = rules; } else { this.rules = [rules]; this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors(); } for (i = 0; i < this.rules.length; i++) { this.rules[i].allowImports = true; } this.setParent(this.rules, this); } this._index = index; this._fileInfo = currentFileInfo; this.debugInfo = debugInfo; this.isRooted = isRooted || false; this.copyVisibilityInfo(visibilityInfo); this.allowRoot = true; }; AtRule.prototype = new Node(); AtRule.prototype.type = 'AtRule'; AtRule.prototype.accept = function (visitor) { var value = this.value, rules = this.rules; if (rules) { this.rules = visitor.visitArray(rules); } if (value) { this.value = visitor.visit(value); } }; AtRule.prototype.isRulesetLike = function() { return this.rules || !this.isCharset(); }; AtRule.prototype.isCharset = function() { return '@charset' === this.name; }; AtRule.prototype.genCSS = function (context, output) { var value = this.value, rules = this.rules; output.add(this.name, this.fileInfo(), this.getIndex()); if (value) { output.add(' '); value.genCSS(context, output); } if (rules) { this.outputRuleset(context, output, rules); } else { output.add(';'); } }; AtRule.prototype.eval = function (context) { var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules; // media stored inside other atrule should not bubble over it // backpup media bubbling information mediaPathBackup = context.mediaPath; mediaBlocksBackup = context.mediaBlocks; // deleted media bubbling information context.mediaPath = []; context.mediaBlocks = []; if (value) { value = value.eval(context); } if (rules) { // assuming that there is only one rule at this point - that is how parser constructs the rule rules = [rules[0].eval(context)]; rules[0].root = true; } // restore media bubbling information context.mediaPath = mediaPathBackup; context.mediaBlocks = mediaBlocksBackup; return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo()); }; AtRule.prototype.variable = function (name) { if (this.rules) { // assuming that there is only one rule at this point - that is how parser constructs the rule return Ruleset.prototype.variable.call(this.rules[0], name); } }; AtRule.prototype.find = function () { if (this.rules) { // assuming that there is only one rule at this point - that is how parser constructs the rule return Ruleset.prototype.find.apply(this.rules[0], arguments); } }; AtRule.prototype.rulesets = function () { if (this.rules) { // assuming that there is only one rule at this point - that is how parser constructs the rule return Ruleset.prototype.rulesets.apply(this.rules[0]); } }; AtRule.prototype.outputRuleset = function (context, output, rules) { var ruleCnt = rules.length, i; context.tabLevel = (context.tabLevel | 0) + 1; // Compressed if (context.compress) { output.add('{'); for (i = 0; i < ruleCnt; i++) { rules[i].genCSS(context, output); } output.add('}'); context.tabLevel--; return; } // Non-compressed var tabSetStr = '\n' + Array(context.tabLevel).join(' '), tabRuleStr = tabSetStr + ' '; if (!ruleCnt) { output.add(' {' + tabSetStr + '}'); } else { output.add(' {' + tabRuleStr); rules[0].genCSS(context, output); for (i = 1; i < ruleCnt; i++) { output.add(tabRuleStr); rules[i].genCSS(context, output); } output.add(tabSetStr + '}'); } context.tabLevel--; }; module.exports = AtRule; },{"./anonymous":48,"./node":74,"./ruleset":79,"./selector":80}],51:[function(require,module,exports){ var Node = require('./node'); var Attribute = function (key, op, value) { this.key = key; this.op = op; this.value = value; }; Attribute.prototype = new Node(); Attribute.prototype.type = 'Attribute'; Attribute.prototype.eval = function (context) { return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value); }; Attribute.prototype.genCSS = function (context, output) { output.add(this.toCSS(context)); }; Attribute.prototype.toCSS = function (context) { var value = this.key.toCSS ? this.key.toCSS(context) : this.key; if (this.op) { value += this.op; value += (this.value.toCSS ? this.value.toCSS(context) : this.value); } return '[' + value + ']'; }; module.exports = Attribute; },{"./node":74}],52:[function(require,module,exports){ var Node = require('./node'), Anonymous = require('./anonymous'), FunctionCaller = require('../functions/function-caller'); // // A function call node. // var Call = function (name, args, index, currentFileInfo) { this.name = name; this.args = args; this.calc = name === 'calc'; this._index = index; this._fileInfo = currentFileInfo; }; Call.prototype = new Node(); Call.prototype.type = 'Call'; Call.prototype.accept = function (visitor) { if (this.args) { this.args = visitor.visitArray(this.args); } }; // // When evaluating a function call, // we either find the function in the functionRegistry, // in which case we call it, passing the evaluated arguments, // if this returns null or we cannot find the function, we // simply print it out as it appeared originally [2]. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // Call.prototype.eval = function (context) { /** * Turn off math for calc(), and switch back on for evaluating nested functions */ var currentMathContext = context.mathOn; context.mathOn = !this.calc; if (this.calc || context.inCalc) { context.enterCalc(); } var args = this.args.map(function (a) { return a.eval(context); }); if (this.calc || context.inCalc) { context.exitCalc(); } context.mathOn = currentMathContext; var result, funcCaller = new FunctionCaller(this.name, context, this.getIndex(), this.fileInfo()); if (funcCaller.isValid()) { try { result = funcCaller.call(args); } catch (e) { throw { type: e.type || 'Runtime', message: 'error evaluating function `' + this.name + '`' + (e.message ? ': ' + e.message : ''), index: this.getIndex(), filename: this.fileInfo().filename, line: e.lineNumber, column: e.columnNumber }; } if (result !== null && result !== undefined) { // Results that that are not nodes are cast as Anonymous nodes // Falsy values or booleans are returned as empty nodes if (!(result instanceof Node)) { if (!result || result === true) { result = new Anonymous(null); } else { result = new Anonymous(result.toString()); } } result._index = this._index; result._fileInfo = this._fileInfo; return result; } } return new Call(this.name, args, this.getIndex(), this.fileInfo()); }; Call.prototype.genCSS = function (context, output) { output.add(this.name + '(', this.fileInfo(), this.getIndex()); for (var i = 0; i < this.args.length; i++) { this.args[i].genCSS(context, output); if (i + 1 < this.args.length) { output.add(', '); } } output.add(')'); }; module.exports = Call; },{"../functions/function-caller":25,"./anonymous":48,"./node":74}],53:[function(require,module,exports){ var Node = require('./node'), colors = require('../data/colors'); // // RGB Colors - #ff0014, #eee // var Color = function (rgb, a, originalForm) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof a === 'number' ? a : 1; if (typeof originalForm !== 'undefined') { this.value = originalForm; } }; Color.prototype = new Node(); Color.prototype.type = 'Color'; function clamp(v, max) { return Math.min(Math.max(v, 0), max); } function toHex(v) { return '#' + v.map(function (c) { c = clamp(Math.round(c), 255); return (c < 16 ? '0' : '') + c.toString(16); }).join(''); } Color.prototype.luma = function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255; r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4); g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4); b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }; Color.prototype.genCSS = function (context, output) { output.add(this.toCSS(context)); }; Color.prototype.toCSS = function (context, doNotCompress) { var compress = context && context.compress && !doNotCompress, color, alpha; // `value` is set if this color was originally // converted from a named color string so we need // to respect this and try to output named color too. if (this.value) { return this.value; } // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. alpha = this.fround(context, this.alpha); if (alpha < 1) { return 'rgba(' + this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1)) .join(',' + (compress ? '' : ' ')) + ')'; } color = this.toRGB(); if (compress) { var splitcolor = color.split(''); // Convert color to short format if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; } } return color; }; // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // Color.prototype.operate = function (context, op, other) { var rgb = new Array(3); var alpha = this.alpha * (1 - other.alpha) + other.alpha; for (var c = 0; c < 3; c++) { rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]); } return new Color(rgb, alpha); }; Color.prototype.toRGB = function () { return toHex(this.rgb); }; Color.prototype.toHSL = function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }; // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript Color.prototype.toHSV = function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; if (max === 0) { s = 0; } else { s = d / max; } if (max === min) { h = 0; } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, v: v, a: a }; }; Color.prototype.toARGB = function () { return toHex([this.alpha * 255].concat(this.rgb)); }; Color.prototype.compare = function (x) { return (x.rgb && x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : undefined; }; Color.fromKeyword = function(keyword) { var c, key = keyword.toLowerCase(); if (colors.hasOwnProperty(key)) { c = new Color(colors[key].slice(1)); } else if (key === 'transparent') { c = new Color([0, 0, 0], 0); } if (c) { c.value = keyword; return c; } }; module.exports = Color; },{"../data/colors":13,"./node":74}],54:[function(require,module,exports){ var Node = require('./node'); var Combinator = function (value) { if (value === ' ') { this.value = ' '; this.emptyOrWhitespace = true; } else { this.value = value ? value.trim() : ''; this.emptyOrWhitespace = this.value === ''; } }; Combinator.prototype = new Node(); Combinator.prototype.type = 'Combinator'; var _noSpaceCombinators = { '': true, ' ': true, '|': true }; Combinator.prototype.genCSS = function (context, output) { var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' '; output.add(spaceOrEmpty + this.value + spaceOrEmpty); }; module.exports = Combinator; },{"./node":74}],55:[function(require,module,exports){ var Node = require('./node'), getDebugInfo = require('./debug-info'); var Comment = function (value, isLineComment, index, currentFileInfo) { this.value = value; this.isLineComment = isLineComment; this._index = index; this._fileInfo = currentFileInfo; this.allowRoot = true; }; Comment.prototype = new Node(); Comment.prototype.type = 'Comment'; Comment.prototype.genCSS = function (context, output) { if (this.debugInfo) { output.add(getDebugInfo(context, this), this.fileInfo(), this.getIndex()); } output.add(this.value); }; Comment.prototype.isSilent = function(context) { var isCompressed = context.compress && this.value[2] !== '!'; return this.isLineComment || isCompressed; }; module.exports = Comment; },{"./debug-info":57,"./node":74}],56:[function(require,module,exports){ var Node = require('./node'); var Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this._index = i; this.negate = negate; }; Condition.prototype = new Node(); Condition.prototype.type = 'Condition'; Condition.prototype.accept = function (visitor) { this.lvalue = visitor.visit(this.lvalue); this.rvalue = visitor.visit(this.rvalue); }; Condition.prototype.eval = function (context) { var result = (function (op, a, b) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: switch (Node.compare(a, b)) { case -1: return op === '<' || op === '=<' || op === '<='; case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; case 1: return op === '>' || op === '>='; default: return false; } } })(this.op, this.lvalue.eval(context), this.rvalue.eval(context)); return this.negate ? !result : result; }; module.exports = Condition; },{"./node":74}],57:[function(require,module,exports){ var debugInfo = function(context, ctx, lineSeparator) { var result = ''; if (context.dumpLineNumbers && !context.compress) { switch (context.dumpLineNumbers) { case 'comments': result = debugInfo.asComment(ctx); break; case 'mediaquery': result = debugInfo.asMediaQuery(ctx); break; case 'all': result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx); break; } } return result; }; debugInfo.asComment = function(ctx) { return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; }; debugInfo.asMediaQuery = function(ctx) { var filenameWithProtocol = ctx.debugInfo.fileName; if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) { filenameWithProtocol = 'file://' + filenameWithProtocol; } return '@media -sass-debug-info{filename{font-family:' + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) { if (a == '\\') { a = '\/'; } return '\\' + a; }) + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; }; module.exports = debugInfo; },{}],58:[function(require,module,exports){ var Node = require('./node'), Value = require('./value'), Keyword = require('./keyword'), Anonymous = require('./anonymous'); var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) { this.name = name; this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]); this.important = important ? ' ' + important.trim() : ''; this.merge = merge; this._index = index; this._fileInfo = currentFileInfo; this.inline = inline || false; this.variable = (variable !== undefined) ? variable : (name.charAt && (name.charAt(0) === '@')); this.allowRoot = true; this.setParent(this.value, this); }; function evalName(context, name) { var value = '', i, n = name.length, output = {add: function (s) {value += s;}}; for (i = 0; i < n; i++) { name[i].eval(context).genCSS(context, output); } return value; } Declaration.prototype = new Node(); Declaration.prototype.type = 'Declaration'; Declaration.prototype.genCSS = function (context, output) { output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex()); try { this.value.genCSS(context, output); } catch (e) { e.index = this._index; e.filename = this._fileInfo.filename; throw e; } output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index); }; Declaration.prototype.eval = function (context) { var strictMathBypass = false, name = this.name, evaldValue, variable = this.variable; if (typeof name !== 'string') { // expand 'primitive' name directly to get // things faster (~10% for benchmark.less): name = (name.length === 1) && (name[0] instanceof Keyword) ? name[0].value : evalName(context, name); variable = false; // never treat expanded interpolation as new variable name } if (name === 'font' && !context.strictMath) { strictMathBypass = true; context.strictMath = true; } try { context.importantScope.push({}); evaldValue = this.value.eval(context); if (!this.variable && evaldValue.type === 'DetachedRuleset') { throw { message: 'Rulesets cannot be evaluated on a property.', index: this.getIndex(), filename: this.fileInfo().filename }; } var important = this.important, importantResult = context.importantScope.pop(); if (!important && importantResult.important) { important = importantResult.important; } return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable); } catch (e) { if (typeof e.index !== 'number') { e.index = this.getIndex(); e.filename = this.fileInfo().filename; } throw e; } finally { if (strictMathBypass) { context.strictMath = false; } } }; Declaration.prototype.makeImportant = function () { return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline); }; module.exports = Declaration; },{"./anonymous":48,"./keyword":68,"./node":74,"./value":84}],59:[function(require,module,exports){ var Node = require('./node'), contexts = require('../contexts'), utils = require('../utils'); var DetachedRuleset = function (ruleset, frames) { this.ruleset = ruleset; this.frames = frames; this.setParent(this.ruleset, this); }; DetachedRuleset.prototype = new Node(); DetachedRuleset.prototype.type = 'DetachedRuleset'; DetachedRuleset.prototype.evalFirst = true; DetachedRuleset.prototype.accept = function (visitor) { this.ruleset = visitor.visit(this.ruleset); }; DetachedRuleset.prototype.eval = function (context) { var frames = this.frames || utils.copyArray(context.frames); return new DetachedRuleset(this.ruleset, frames); }; DetachedRuleset.prototype.callEval = function (context) { return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context); }; module.exports = DetachedRuleset; },{"../contexts":12,"../utils":87,"./node":74}],60:[function(require,module,exports){ var Node = require('./node'), unitConversions = require('../data/unit-conversions'), Unit = require('./unit'), Color = require('./color'); // // A number with a unit // var Dimension = function (value, unit) { this.value = parseFloat(value); if (isNaN(this.value)) { throw new Error('Dimension is not a number.'); } this.unit = (unit && unit instanceof Unit) ? unit : new Unit(unit ? [unit] : undefined); this.setParent(this.unit, this); }; Dimension.prototype = new Node(); Dimension.prototype.type = 'Dimension'; Dimension.prototype.accept = function (visitor) { this.unit = visitor.visit(this.unit); }; Dimension.prototype.eval = function (context) { return this; }; Dimension.prototype.toColor = function () { return new Color([this.value, this.value, this.value]); }; Dimension.prototype.genCSS = function (context, output) { if ((context && context.strictUnits) && !this.unit.isSingular()) { throw new Error('Multiple units in dimension. Correct the units or use the unit function. Bad unit: ' + this.unit.toString()); } var value = this.fround(context, this.value), strValue = String(value); if (value !== 0 && value < 0.000001 && value > -0.000001) { // would be output 1e-6 etc. strValue = value.toFixed(20).replace(/0+$/, ''); } if (context && context.compress) { // Zero values doesn't need a unit if (value === 0 && this.unit.isLength()) { output.add(strValue); return; } // Float values doesn't need a leading zero if (value > 0 && value < 1) { strValue = (strValue).substr(1); } } output.add(strValue); this.unit.genCSS(context, output); }; // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2` will yield `3px`. Dimension.prototype.operate = function (context, op, other) { /* jshint noempty:false */ var value = this._operate(context, op, this.value, other.value), unit = this.unit.clone(); if (op === '+' || op === '-') { if (unit.numerator.length === 0 && unit.denominator.length === 0) { unit = other.unit.clone(); if (this.unit.backupUnit) { unit.backupUnit = this.unit.backupUnit; } } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { // do nothing } else { other = other.convertTo(this.unit.usedUnits()); if (context.strictUnits && other.unit.toString() !== unit.toString()) { throw new Error('Incompatible units. Change the units or use the unit function. Bad units: \'' + unit.toString() + '\' and \'' + other.unit.toString() + '\'.'); } value = this._operate(context, op, this.value, other.value); } } else if (op === '*') { unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); unit.cancel(); } else if (op === '/') { unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); unit.cancel(); } return new Dimension(value, unit); }; Dimension.prototype.compare = function (other) { var a, b; if (!(other instanceof Dimension)) { return undefined; } if (this.unit.isEmpty() || other.unit.isEmpty()) { a = this; b = other; } else { a = this.unify(); b = other.unify(); if (a.unit.compare(b.unit) !== 0) { return undefined; } } return Node.numericCompare(a.value, b.value); }; Dimension.prototype.unify = function () { return this.convertTo({ length: 'px', duration: 's', angle: 'rad' }); }; Dimension.prototype.convertTo = function (conversions) { var value = this.value, unit = this.unit.clone(), i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; if (typeof conversions === 'string') { for (i in unitConversions) { if (unitConversions[i].hasOwnProperty(conversions)) { derivedConversions = {}; derivedConversions[i] = conversions; } } conversions = derivedConversions; } applyUnit = function (atomicUnit, denominator) { /* jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit)) { if (denominator) { value = value / (group[atomicUnit] / group[targetUnit]); } else { value = value * (group[atomicUnit] / group[targetUnit]); } return targetUnit; } return atomicUnit; }; for (groupName in conversions) { if (conversions.hasOwnProperty(groupName)) { targetUnit = conversions[groupName]; group = unitConversions[groupName]; unit.map(applyUnit); } } unit.cancel(); return new Dimension(value, unit); }; module.exports = Dimension; },{"../data/unit-conversions":15,"./color":53,"./node":74,"./unit":82}],61:[function(require,module,exports){ var Node = require('./node'), Paren = require('./paren'), Combinator = require('./combinator'); var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) { this.combinator = combinator instanceof Combinator ? combinator : new Combinator(combinator); if (typeof value === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ''; } this.isVariable = isVariable; this._index = index; this._fileInfo = currentFileInfo; this.copyVisibilityInfo(visibilityInfo); this.setParent(this.combinator, this); }; Element.prototype = new Node(); Element.prototype.type = 'Element'; Element.prototype.accept = function (visitor) { var value = this.value; this.combinator = visitor.visit(this.combinator); if (typeof value === 'object') { this.value = visitor.visit(value); } }; Element.prototype.eval = function (context) { return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo()); }; Element.prototype.clone = function () { return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo()); }; Element.prototype.genCSS = function (context, output) { output.add(this.toCSS(context), this.fileInfo(), this.getIndex()); }; Element.prototype.toCSS = function (context) { context = context || {}; var value = this.value, firstSelector = context.firstSelector; if (value instanceof Paren) { // selector in parens should not be affected by outer selector // flags (breaks only interpolated selectors - see #1973) context.firstSelector = true; } value = value.toCSS ? value.toCSS(context) : value; context.firstSelector = firstSelector; if (value === '' && this.combinator.value.charAt(0) === '&') { return ''; } else { return this.combinator.toCSS(context) + value; } }; module.exports = Element; },{"./combinator":54,"./node":74,"./paren":76}],62:[function(require,module,exports){ var Node = require('./node'), Paren = require('./paren'), Comment = require('./comment'); var Expression = function (value, noSpacing) { this.value = value; this.noSpacing = noSpacing; if (!value) { throw new Error('Expression requires an array parameter'); } }; Expression.prototype = new Node(); Expression.prototype.type = 'Expression'; Expression.prototype.accept = function (visitor) { this.value = visitor.visitArray(this.value); }; Expression.prototype.eval = function (context) { var returnValue, mathOn = context.isMathOn(), inParenthesis = this.parens && !this.parensInOp, doubleParen = false; if (inParenthesis) { context.inParenthesis(); } if (this.value.length > 1) { returnValue = new Expression(this.value.map(function (e) { if (!e.eval) { return e; } return e.eval(context); }), this.noSpacing); } else if (this.value.length === 1) { if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) { doubleParen = true; } returnValue = this.value[0].eval(context); } else { returnValue = this; } if (inParenthesis) { context.outOfParenthesis(); } if (this.parens && this.parensInOp && !mathOn && !doubleParen) { returnValue = new Paren(returnValue); } return returnValue; }; Expression.prototype.genCSS = function (context, output) { for (var i = 0; i < this.value.length; i++) { this.value[i].genCSS(context, output); if (!this.noSpacing && i + 1 < this.value.length) { output.add(' '); } } }; Expression.prototype.throwAwayComments = function () { this.value = this.value.filter(function(v) { return !(v instanceof Comment); }); }; module.exports = Expression; },{"./comment":55,"./node":74,"./paren":76}],63:[function(require,module,exports){ var Node = require('./node'), Selector = require('./selector'); var Extend = function Extend(selector, option, index, currentFileInfo, visibilityInfo) { this.selector = selector; this.option = option; this.object_id = Extend.next_id++; this.parent_ids = [this.object_id]; this._index = index; this._fileInfo = currentFileInfo; this.copyVisibilityInfo(visibilityInfo); this.allowRoot = true; switch (option) { case 'all': this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } this.setParent(this.selector, this); }; Extend.next_id = 0; Extend.prototype = new Node(); Extend.prototype.type = 'Extend'; Extend.prototype.accept = function (visitor) { this.selector = visitor.visit(this.selector); }; Extend.prototype.eval = function (context) { return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo()); }; Extend.prototype.clone = function (context) { return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo()); }; // it concatenates (joins) all selectors in selector array Extend.prototype.findSelfSelectors = function (selectors) { var selfElements = [], i, selectorElements; for (i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [new Selector(selfElements)]; this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo()); }; module.exports = Extend; },{"./node":74,"./selector":80}],64:[function(require,module,exports){ var Node = require('./node'), Media = require('./media'), URL = require('./url'), Quoted = require('./quoted'), Ruleset = require('./ruleset'), Anonymous = require('./anonymous'), utils = require('../utils'), LessError = require('../less-error'); // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) { this.options = options; this._index = index; this._fileInfo = currentFileInfo; this.path = path; this.features = features; this.allowRoot = true; if (this.options.less !== undefined || this.options.inline) { this.css = !this.options.less || this.options.inline; } else { var pathValue = this.getPath(); if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) { this.css = true; } } this.copyVisibilityInfo(visibilityInfo); this.setParent(this.features, this); this.setParent(this.path, this); }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // Import.prototype = new Node(); Import.prototype.type = 'Import'; Import.prototype.accept = function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } this.path = visitor.visit(this.path); if (!this.options.isPlugin && !this.options.inline && this.root) { this.root = visitor.visit(this.root); } }; Import.prototype.genCSS = function (context, output) { if (this.css && this.path._fileInfo.reference === undefined) { output.add('@import ', this._fileInfo, this._index); this.path.genCSS(context, output); if (this.features) { output.add(' '); this.features.genCSS(context, output); } output.add(';'); } }; Import.prototype.getPath = function () { return (this.path instanceof URL) ? this.path.value.value : this.path.value; }; Import.prototype.isVariableImport = function () { var path = this.path; if (path instanceof URL) { path = path.value; } if (path instanceof Quoted) { return path.containsVariables(); } return true; }; Import.prototype.evalForImport = function (context) { var path = this.path; if (path instanceof URL) { path = path.value; } return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo()); }; Import.prototype.evalPath = function (context) { var path = this.path.eval(context); var rootpath = this._fileInfo && this._fileInfo.rootpath; if (!(path instanceof URL)) { if (rootpath) { var pathValue = path.value; // Add the base path if the import is relative if (pathValue && context.isPathRelative(pathValue)) { path.value = rootpath + pathValue; } } path.value = context.normalizePath(path.value); } return path; }; Import.prototype.eval = function (context) { var result = this.doEval(context); if (this.options.reference || this.blocksVisibility()) { if (result.length || result.length === 0) { result.forEach(function (node) { node.addVisibilityBlock(); } ); } else { result.addVisibilityBlock(); } } return result; }; Import.prototype.doEval = function (context) { var ruleset, registry, features = this.features && this.features.eval(context); if (this.options.isPlugin) { if (this.root && this.root.eval) { try { this.root.eval(context); } catch (e) { e.message = 'Plugin error during evaluation'; throw new LessError(e, this.root.imports, this.root.filename); } } registry = context.frames[0] && context.frames[0].functionRegistry; if ( registry && this.root && this.root.functions ) { registry.addMultiple( this.root.functions ); } return []; } if (this.skip) { if (typeof this.skip === 'function') { this.skip = this.skip(); } if (this.skip) { return []; } } if (this.options.inline) { var contents = new Anonymous(this.root, 0, { filename: this.importedFilename, reference: this.path._fileInfo && this.path._fileInfo.reference }, true, true); return this.features ? new Media([contents], this.features.value) : [contents]; } else if (this.css) { var newImport = new Import(this.evalPath(context), features, this.options, this._index); if (!newImport.css && this.error) { throw this.error; } return newImport; } else { ruleset = new Ruleset(null, utils.copyArray(this.root.rules)); ruleset.evalImports(context); return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules; } }; module.exports = Import; },{"../less-error":36,"../utils":87,"./anonymous":48,"./media":69,"./node":74,"./quoted":78,"./ruleset":79,"./url":83}],65:[function(require,module,exports){ var tree = Object.create(null); tree.Node = require('./node'); tree.Color = require('./color'); tree.AtRule = require('./atrule'); tree.DetachedRuleset = require('./detached-ruleset'); tree.Operation = require('./operation'); tree.Dimension = require('./dimension'); tree.Unit = require('./unit'); tree.Keyword = require('./keyword'); tree.Variable = require('./variable'); tree.Property = require('./property'); tree.Ruleset = require('./ruleset'); tree.Element = require('./element'); tree.Attribute = require('./attribute'); tree.Combinator = require('./combinator'); tree.Selector = require('./selector'); tree.Quoted = require('./quoted'); tree.Expression = require('./expression'); tree.Declaration = require('./declaration'); tree.Call = require('./call'); tree.URL = require('./url'); tree.Import = require('./import'); tree.mixin = { Call: require('./mixin-call'), Definition: require('./mixin-definition') }; tree.Comment = require('./comment'); tree.Anonymous = require('./anonymous'); tree.Value = require('./value'); tree.JavaScript = require('./javascript'); tree.Assignment = require('./assignment'); tree.Condition = require('./condition'); tree.Paren = require('./paren'); tree.Media = require('./media'); tree.UnicodeDescriptor = require('./unicode-descriptor'); tree.Negative = require('./negative'); tree.Extend = require('./extend'); tree.VariableCall = require('./variable-call'); tree.NamespaceValue = require('./namespace-value'); module.exports = tree; },{"./anonymous":48,"./assignment":49,"./atrule":50,"./attribute":51,"./call":52,"./color":53,"./combinator":54,"./comment":55,"./condition":56,"./declaration":58,"./detached-ruleset":59,"./dimension":60,"./element":61,"./expression":62,"./extend":63,"./import":64,"./javascript":66,"./keyword":68,"./media":69,"./mixin-call":70,"./mixin-definition":71,"./namespace-value":72,"./negative":73,"./node":74,"./operation":75,"./paren":76,"./property":77,"./quoted":78,"./ruleset":79,"./selector":80,"./unicode-descriptor":81,"./unit":82,"./url":83,"./value":84,"./variable":86,"./variable-call":85}],66:[function(require,module,exports){ var JsEvalNode = require('./js-eval-node'), Dimension = require('./dimension'), Quoted = require('./quoted'), Anonymous = require('./anonymous'); var JavaScript = function (string, escaped, index, currentFileInfo) { this.escaped = escaped; this.expression = string; this._index = index; this._fileInfo = currentFileInfo; }; JavaScript.prototype = new JsEvalNode(); JavaScript.prototype.type = 'JavaScript'; JavaScript.prototype.eval = function(context) { var result = this.evaluateJavaScript(this.expression, context); if (typeof result === 'number') { return new Dimension(result); } else if (typeof result === 'string') { return new Quoted('"' + result + '"', result, this.escaped, this._index); } else if (Array.isArray(result)) { return new Anonymous(result.join(', ')); } else { return new Anonymous(result); } }; module.exports = JavaScript; },{"./anonymous":48,"./dimension":60,"./js-eval-node":67,"./quoted":78}],67:[function(require,module,exports){ var Node = require('./node'), Variable = require('./variable'); var JsEvalNode = function() { }; JsEvalNode.prototype = new Node(); JsEvalNode.prototype.evaluateJavaScript = function (expression, context) { var result, that = this, evalContext = {}; if (!context.javascriptEnabled) { throw { message: 'Inline JavaScript is not enabled. Is it set in your options?', filename: this.fileInfo().filename, index: this.getIndex() }; } expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return that.jsify(new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context)); }); try { expression = new Function('return (' + expression + ')'); } catch (e) { throw { message: 'JavaScript evaluation error: ' + e.message + ' from `' + expression + '`' , filename: this.fileInfo().filename, index: this.getIndex() }; } var variables = context.frames[0].variables(); for (var k in variables) { if (variables.hasOwnProperty(k)) { /* jshint loopfunc:true */ evalContext[k.slice(1)] = { value: variables[k].value, toJS: function () { return this.value.eval(context).toCSS(); } }; } } try { result = expression.call(evalContext); } catch (e) { throw { message: 'JavaScript evaluation error: \'' + e.name + ': ' + e.message.replace(/["]/g, '\'') + '\'' , filename: this.fileInfo().filename, index: this.getIndex() }; } return result; }; JsEvalNode.prototype.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + ']'; } else { return obj.toCSS(); } }; module.exports = JsEvalNode; },{"./node":74,"./variable":86}],68:[function(require,module,exports){ var Node = require('./node'); var Keyword = function (value) { this.value = value; }; Keyword.prototype = new Node(); Keyword.prototype.type = 'Keyword'; Keyword.prototype.genCSS = function (context, output) { if (this.value === '%') { throw { type: 'Syntax', message: 'Invalid % without number' }; } output.add(this.value); }; Keyword.True = new Keyword('true'); Keyword.False = new Keyword('false'); module.exports = Keyword; },{"./node":74}],69:[function(require,module,exports){ var Ruleset = require('./ruleset'), Value = require('./value'), Selector = require('./selector'), Anonymous = require('./anonymous'), Expression = require('./expression'), AtRule = require('./atrule'), utils = require('../utils'); var Media = function (value, features, index, currentFileInfo, visibilityInfo) { this._index = index; this._fileInfo = currentFileInfo; var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors(); this.features = new Value(features); this.rules = [new Ruleset(selectors, value)]; this.rules[0].allowImports = true; this.copyVisibilityInfo(visibilityInfo); this.allowRoot = true; this.setParent(selectors, this); this.setParent(this.features, this); this.setParent(this.rules, this); }; Media.prototype = new AtRule(); Media.prototype.type = 'Media'; Media.prototype.isRulesetLike = function() { return true; }; Media.prototype.accept = function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } if (this.rules) { this.rules = visitor.visitArray(this.rules); } }; Media.prototype.genCSS = function (context, output) { output.add('@media ', this._fileInfo, this._index); this.features.genCSS(context, output); this.outputRuleset(context, output, this.rules); }; Media.prototype.eval = function (context) { if (!context.mediaBlocks) { context.mediaBlocks = []; context.mediaPath = []; } var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo()); if (this.debugInfo) { this.rules[0].debugInfo = this.debugInfo; media.debugInfo = this.debugInfo; } media.features = this.features.eval(context); context.mediaPath.push(media); context.mediaBlocks.push(media); this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit(); context.frames.unshift(this.rules[0]); media.rules = [this.rules[0].eval(context)]; context.frames.shift(); context.mediaPath.pop(); return context.mediaPath.length === 0 ? media.evalTop(context) : media.evalNested(context); }; Media.prototype.evalTop = function (context) { var result = this; // Render all dependent Media blocks. if (context.mediaBlocks.length > 1) { var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors(); result = new Ruleset(selectors, context.mediaBlocks); result.multiMedia = true; result.copyVisibilityInfo(this.visibilityInfo()); this.setParent(result, this); } delete context.mediaBlocks; delete context.mediaPath; return result; }; Media.prototype.evalNested = function (context) { var i, value, path = context.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new Value(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); }); for (i = path.length - 1; i > 0; i--) { path.splice(i, 0, new Anonymous('and')); } return new Expression(path); })); this.setParent(this.features, this); // Fake a tree-node that doesn't output anything. return new Ruleset([], []); }; Media.prototype.permute = function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } }; Media.prototype.bubbleSelectors = function (selectors) { if (!selectors) { return; } this.rules = [new Ruleset(utils.copyArray(selectors), [this.rules[0]])]; this.setParent(this.rules, this); }; module.exports = Media; },{"../utils":87,"./anonymous":48,"./atrule":50,"./expression":62,"./ruleset":79,"./selector":80,"./value":84}],70:[function(require,module,exports){ var Node = require('./node'), Selector = require('./selector'), MixinDefinition = require('./mixin-definition'), defaultFunc = require('../functions/default'); var MixinCall = function (elements, args, index, currentFileInfo, important) { this.selector = new Selector(elements); this.arguments = args || []; this._index = index; this._fileInfo = currentFileInfo; this.important = important; this.allowRoot = true; this.setParent(this.selector, this); }; MixinCall.prototype = new Node(); MixinCall.prototype.type = 'MixinCall'; MixinCall.prototype.accept = function (visitor) { if (this.selector) { this.selector = visitor.visit(this.selector); } if (this.arguments.length) { this.arguments = visitor.visitArray(this.arguments); } }; MixinCall.prototype.eval = function (context) { var mixins, mixin, mixinPath, args = [], arg, argValue, rules = [], match = false, i, m, f, isRecursive, isOneFound, candidates = [], candidate, conditionResult = [], defaultResult, defFalseEitherCase = -1, defNone = 0, defTrue = 1, defFalse = 2, count, originalRuleset, noArgumentsFilter; this.selector = this.selector.eval(context); function calcDefGroup(mixin, mixinPath) { var f, p, namespace; for (f = 0; f < 2; f++) { conditionResult[f] = true; defaultFunc.value(f); for (p = 0; p < mixinPath.length && conditionResult[f]; p++) { namespace = mixinPath[p]; if (namespace.matchCondition) { conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context); } } if (mixin.matchCondition) { conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context); } } if (conditionResult[0] || conditionResult[1]) { if (conditionResult[0] != conditionResult[1]) { return conditionResult[1] ? defTrue : defFalse; } return defNone; } return defFalseEitherCase; } for (i = 0; i < this.arguments.length; i++) { arg = this.arguments[i]; argValue = arg.value.eval(context); if (arg.expand && Array.isArray(argValue.value)) { argValue = argValue.value; for (m = 0; m < argValue.length; m++) { args.push({value: argValue[m]}); } } else { args.push({name: arg.name, value: argValue}); } } noArgumentsFilter = function(rule) {return rule.matchArgs(null, context);}; for (i = 0; i < context.frames.length; i++) { if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) { isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), // and build candidate list with corresponding flags. Then, when we know all possible matches, // we make a final decision. for (m = 0; m < mixins.length; m++) { mixin = mixins[m].rule; mixinPath = mixins[m].path; isRecursive = false; for (f = 0; f < context.frames.length; f++) { if ((!(mixin instanceof MixinDefinition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) { isRecursive = true; break; } } if (isRecursive) { continue; } if (mixin.matchArgs(args, context)) { candidate = {mixin: mixin, group: calcDefGroup(mixin, mixinPath)}; if (candidate.group !== defFalseEitherCase) { candidates.push(candidate); } match = true; } } defaultFunc.reset(); count = [0, 0, 0]; for (m = 0; m < candidates.length; m++) { count[candidates[m].group]++; } if (count[defNone] > 0) { defaultResult = defFalse; } else { defaultResult = defTrue; if ((count[defTrue] + count[defFalse]) > 1) { throw { type: 'Runtime', message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`', index: this.getIndex(), filename: this.fileInfo().filename }; } } for (m = 0; m < candidates.length; m++) { candidate = candidates[m].group; if ((candidate === defNone) || (candidate === defaultResult)) { try { mixin = candidates[m].mixin; if (!(mixin instanceof MixinDefinition)) { originalRuleset = mixin.originalRuleset || mixin; mixin = new MixinDefinition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo()); mixin.originalRuleset = originalRuleset; } var newRules = mixin.evalCall(context, args, this.important).rules; this._setVisibilityToReplacement(newRules); Array.prototype.push.apply(rules, newRules); } catch (e) { throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack }; } } } if (match) { return rules; } } } if (isOneFound) { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.format(args) + '`', index: this.getIndex(), filename: this.fileInfo().filename }; } else { throw { type: 'Name', message: this.selector.toCSS().trim() + ' is undefined', index: this.getIndex(), filename: this.fileInfo().filename }; } }; MixinCall.prototype._setVisibilityToReplacement = function (replacement) { var i, rule; if (this.blocksVisibility()) { for (i = 0; i < replacement.length; i++) { rule = replacement[i]; rule.addVisibilityBlock(); } } }; MixinCall.prototype.format = function (args) { return this.selector.toCSS().trim() + '(' + (args ? args.map(function (a) { var argValue = ''; if (a.name) { argValue += a.name + ':'; } if (a.value.toCSS) { argValue += a.value.toCSS(); } else { argValue += '???'; } return argValue; }).join(', ') : '') + ')'; }; module.exports = MixinCall; },{"../functions/default":24,"./mixin-definition":71,"./node":74,"./selector":80}],71:[function(require,module,exports){ var Selector = require('./selector'), Element = require('./element'), Ruleset = require('./ruleset'), Declaration = require('./declaration'), DetachedRuleset = require('./detached-ruleset'), Expression = require('./expression'), contexts = require('../contexts'), utils = require('../utils'); var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) { this.name = name; this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; var optionalParameters = []; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1; } else { optionalParameters.push(p.name); return count; } }, 0); this.optionalParameters = optionalParameters; this.frames = frames; this.copyVisibilityInfo(visibilityInfo); this.allowRoot = true; }; Definition.prototype = new Ruleset(); Definition.prototype.type = 'MixinDefinition'; Definition.prototype.evalFirst = true; Definition.prototype.accept = function (visitor) { if (this.params && this.params.length) { this.params = visitor.visitArray(this.params); } this.rules = visitor.visitArray(this.rules); if (this.condition) { this.condition = visitor.visit(this.condition); } }; Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) { /* jshint boss:true */ var frame = new Ruleset(null, null), varargs, arg, params = utils.copyArray(this.params), i, j, val, name, isNamedFound, argIndex, argsLength = 0; if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) { frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit(); } mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames)); if (args) { args = utils.copyArray(args); argsLength = args.length; for (i = 0; i < argsLength; i++) { arg = args[i]; if (name = (arg && arg.name)) { isNamedFound = false; for (j = 0; j < params.length; j++) { if (!evaldArguments[j] && name === params[j].name) { evaldArguments[j] = arg.value.eval(context); frame.prependRule(new Declaration(name, arg.value.eval(context))); isNamedFound = true; break; } } if (isNamedFound) { args.splice(i, 1); i--; continue; } else { throw { type: 'Runtime', message: 'Named argument for ' + this.name + ' ' + args[i].name + ' not found' }; } } } } argIndex = 0; for (i = 0; i < params.length; i++) { if (evaldArguments[i]) { continue; } arg = args && args[argIndex]; if (name = params[i].name) { if (params[i].variadic) { varargs = []; for (j = argIndex; j < argsLength; j++) { varargs.push(args[j].value.eval(context)); } frame.prependRule(new Declaration(name, new Expression(varargs).eval(context))); } else { val = arg && arg.value; if (val) { // This was a mixin call, pass in a detached ruleset of it's eval'd rules if (Array.isArray(val)) { val = new DetachedRuleset(new Ruleset('', val)); } else { val = val.eval(context); } } else if (params[i].value) { val = params[i].value.eval(mixinEnv); frame.resetCache(); } else { throw { type: 'Runtime', message: 'wrong number of arguments for ' + this.name + ' (' + argsLength + ' for ' + this.arity + ')' }; } frame.prependRule(new Declaration(name, val)); evaldArguments[i] = val; } } if (params[i].variadic && args) { for (j = argIndex; j < argsLength; j++) { evaldArguments[j] = args[j].value.eval(context); } } argIndex++; } return frame; }; Definition.prototype.makeImportant = function() { var rules = !this.rules ? this.rules : this.rules.map(function (r) { if (r.makeImportant) { return r.makeImportant(true); } else { return r; } }); var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames); return result; }; Definition.prototype.eval = function (context) { return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || utils.copyArray(context.frames)); }; Definition.prototype.evalCall = function (context, args, important) { var _arguments = [], mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames, frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments), rules, ruleset; frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context))); rules = utils.copyArray(this.rules); ruleset = new Ruleset(null, rules); ruleset.originalRuleset = this; ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames))); if (important) { ruleset = ruleset.makeImportant(); } return ruleset; }; Definition.prototype.matchCondition = function (args, context) { if (this.condition && !this.condition.eval( new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])] .concat(this.frames || []) // the parent namespace/mixin frames .concat(context.frames)))) { // the current environment frames return false; } return true; }; Definition.prototype.matchArgs = function (args, context) { var allArgsCnt = (args && args.length) || 0, len, optionalParameters = this.optionalParameters; var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) { if (optionalParameters.indexOf(p.name) < 0) { return count + 1; } else { return count; } }, 0); if (!this.variadic) { if (requiredArgsCnt < this.required) { return false; } if (allArgsCnt > this.params.length) { return false; } } else { if (requiredArgsCnt < (this.required - 1)) { return false; } } // check patterns len = Math.min(requiredArgsCnt, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name && !this.params[i].variadic) { if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) { return false; } } } return true; }; module.exports = Definition; },{"../contexts":12,"../utils":87,"./declaration":58,"./detached-ruleset":59,"./element":61,"./expression":62,"./ruleset":79,"./selector":80}],72:[function(require,module,exports){ var Node = require('./node'), Variable = require('./variable'), Ruleset = require('./ruleset'), Selector = require('./selector'); var NamespaceValue = function (ruleCall, lookups, important, index, fileInfo) { this.value = ruleCall; this.lookups = lookups; this.important = important; this._index = index; this._fileInfo = fileInfo; }; NamespaceValue.prototype = new Node(); NamespaceValue.prototype.type = 'NamespaceValue'; NamespaceValue.prototype.eval = function (context) { var i, j, name, found, rules = this.value.eval(context); for (i = 0; i < this.lookups.length; i++) { name = this.lookups[i]; /** * Eval'd DRs return rulesets. * Eval'd mixins return rules, so let's make a ruleset if we need it. * We need to do this because of late parsing of properties */ if (Array.isArray(rules)) { rules = new Ruleset([new Selector()], rules); } if (name.charAt(0) === '@') { if (name.charAt(1) === '@') { name = '@' + new Variable(name.substr(1)).eval(context).value; } if (rules.variables) { rules = rules.variable(name); } if (!rules) { throw { type: 'Name', message: 'variable ' + name + ' not found', filename: this.fileInfo().filename, index: this.getIndex() }; } } else { if (rules.properties) { rules = rules.property(name.charAt(0) === '$' ? name : '$' + name); } if (!rules) { throw { type: 'Name', message: 'property "' + name + '" not found', filename: this.fileInfo().filename, index: this.getIndex() }; } // Properties are an array of values, since a ruleset can have multiple props. // We pick the last one (the "cascaded" value) rules = rules[rules.length - 1]; } if (rules.value) { rules = rules.eval(context).value; } if (rules.ruleset) { rules = rules.ruleset.eval(context); } } return rules; }; module.exports = NamespaceValue; },{"./node":74,"./ruleset":79,"./selector":80,"./variable":86}],73:[function(require,module,exports){ var Node = require('./node'), Operation = require('./operation'), Dimension = require('./dimension'); var Negative = function (node) { this.value = node; }; Negative.prototype = new Node(); Negative.prototype.type = 'Negative'; Negative.prototype.genCSS = function (context, output) { output.add('-'); this.value.genCSS(context, output); }; Negative.prototype.eval = function (context) { if (context.isMathOn()) { return (new Operation('*', [new Dimension(-1), this.value])).eval(context); } return new Negative(this.value.eval(context)); }; module.exports = Negative; },{"./dimension":60,"./node":74,"./operation":75}],74:[function(require,module,exports){ var Node = function() { this.parent = null; this.visibilityBlocks = undefined; this.nodeVisible = undefined; this.rootNode = null; this.parsed = null; var self = this; Object.defineProperty(this, 'currentFileInfo', { get: function() { return self.fileInfo(); } }); Object.defineProperty(this, 'index', { get: function() { return self.getIndex(); } }); }; Node.prototype.setParent = function(nodes, parent) { function set(node) { if (node && node instanceof Node) { node.parent = parent; } } if (Array.isArray(nodes)) { nodes.forEach(set); } else { set(nodes); } }; Node.prototype.getIndex = function() { return this._index || (this.parent && this.parent.getIndex()) || 0; }; Node.prototype.fileInfo = function() { return this._fileInfo || (this.parent && this.parent.fileInfo()) || {}; }; Node.prototype.isRulesetLike = function() { return false; }; Node.prototype.toCSS = function (context) { var strs = []; this.genCSS(context, { add: function(chunk, fileInfo, index) { strs.push(chunk); }, isEmpty: function () { return strs.length === 0; } }); return strs.join(''); }; Node.prototype.genCSS = function (context, output) { output.add(this.value); }; Node.prototype.accept = function (visitor) { this.value = visitor.visit(this.value); }; Node.prototype.eval = function () { return this; }; Node.prototype._operate = function (context, op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; Node.prototype.fround = function(context, value) { var precision = context && context.numPrecision; // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded: return (precision) ? Number((value + 2e-16).toFixed(precision)) : value; }; Node.compare = function (a, b) { /* returns: -1: a < b 0: a = b 1: a > b and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */ if ((a.compare) && // for "symmetric results" force toCSS-based comparison // of Quoted or Anonymous if either value is one of those !(b.type === 'Quoted' || b.type === 'Anonymous')) { return a.compare(b); } else if (b.compare) { return -b.compare(a); } else if (a.type !== b.type) { return undefined; } a = a.value; b = b.value; if (!Array.isArray(a)) { return a === b ? 0 : undefined; } if (a.length !== b.length) { return undefined; } for (var i = 0; i < a.length; i++) { if (Node.compare(a[i], b[i]) !== 0) { return undefined; } } return 0; }; Node.numericCompare = function (a, b) { return a < b ? -1 : a === b ? 0 : a > b ? 1 : undefined; }; // Returns true if this node represents root of ast imported by reference Node.prototype.blocksVisibility = function () { if (this.visibilityBlocks == null) { this.visibilityBlocks = 0; } return this.visibilityBlocks !== 0; }; Node.prototype.addVisibilityBlock = function () { if (this.visibilityBlocks == null) { this.visibilityBlocks = 0; } this.visibilityBlocks = this.visibilityBlocks + 1; }; Node.prototype.removeVisibilityBlock = function () { if (this.visibilityBlocks == null) { this.visibilityBlocks = 0; } this.visibilityBlocks = this.visibilityBlocks - 1; }; // Turns on node visibility - if called node will be shown in output regardless // of whether it comes from import by reference or not Node.prototype.ensureVisibility = function () { this.nodeVisible = true; }; // Turns off node visibility - if called node will NOT be shown in output regardless // of whether it comes from import by reference or not Node.prototype.ensureInvisibility = function () { this.nodeVisible = false; }; // return values: // false - the node must not be visible // true - the node must be visible // undefined or null - the node has the same visibility as its parent Node.prototype.isVisible = function () { return this.nodeVisible; }; Node.prototype.visibilityInfo = function() { return { visibilityBlocks: this.visibilityBlocks, nodeVisible: this.nodeVisible }; }; Node.prototype.copyVisibilityInfo = function(info) { if (!info) { return; } this.visibilityBlocks = info.visibilityBlocks; this.nodeVisible = info.nodeVisible; }; module.exports = Node; },{}],75:[function(require,module,exports){ var Node = require('./node'), Color = require('./color'), Dimension = require('./dimension'); var Operation = function (op, operands, isSpaced) { this.op = op.trim(); this.operands = operands; this.isSpaced = isSpaced; }; Operation.prototype = new Node(); Operation.prototype.type = 'Operation'; Operation.prototype.accept = function (visitor) { this.operands = visitor.visit(this.operands); }; Operation.prototype.eval = function (context) { var a = this.operands[0].eval(context), b = this.operands[1].eval(context); if (context.isMathOn()) { if (a instanceof Dimension && b instanceof Color) { a = a.toColor(); } if (b instanceof Dimension && a instanceof Color) { b = b.toColor(); } if (!a.operate) { throw { type: 'Operation', message: 'Operation on an invalid type' }; } return a.operate(context, this.op, b); } else { return new Operation(this.op, [a, b], this.isSpaced); } }; Operation.prototype.genCSS = function (context, output) { this.operands[0].genCSS(context, output); if (this.isSpaced) { output.add(' '); } output.add(this.op); if (this.isSpaced) { output.add(' '); } this.operands[1].genCSS(context, output); }; module.exports = Operation; },{"./color":53,"./dimension":60,"./node":74}],76:[function(require,module,exports){ var Node = require('./node'); var Paren = function (node) { this.value = node; }; Paren.prototype = new Node(); Paren.prototype.type = 'Paren'; Paren.prototype.genCSS = function (context, output) { output.add('('); this.value.genCSS(context, output); output.add(')'); }; Paren.prototype.eval = function (context) { return new Paren(this.value.eval(context)); }; module.exports = Paren; },{"./node":74}],77:[function(require,module,exports){ var Node = require('./node'), Declaration = require('./declaration'); var Property = function (name, index, currentFileInfo) { this.name = name; this._index = index; this._fileInfo = currentFileInfo; }; Property.prototype = new Node(); Property.prototype.type = 'Property'; Property.prototype.eval = function (context) { var property, name = this.name; // TODO: shorten this reference var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules; if (this.evaluating) { throw { type: 'Name', message: 'Recursive property reference for ' + name, filename: this.fileInfo().filename, index: this.getIndex() }; } this.evaluating = true; property = this.find(context.frames, function (frame) { var v, vArr = frame.property(name); if (vArr) { for (var i = 0; i < vArr.length; i++) { v = vArr[i]; vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable ); } mergeRules(vArr); v = vArr[vArr.length - 1]; if (v.important) { var importantScope = context.importantScope[context.importantScope.length - 1]; importantScope.important = v.important; } v = v.value.eval(context); return v; } }); if (property) { this.evaluating = false; return property; } else { throw { type: 'Name', message: 'Property \'' + name + '\' is undefined', filename: this.currentFileInfo.filename, index: this.index }; } }; Property.prototype.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { r = fun.call(obj, obj[i]); if (r) { return r; } } return null; }; module.exports = Property; },{"./declaration":58,"./node":74}],78:[function(require,module,exports){ var Node = require('./node'), Variable = require('./variable'), Property = require('./property'); var Quoted = function (str, content, escaped, index, currentFileInfo) { this.escaped = (escaped == null) ? true : escaped; this.value = content || ''; this.quote = str.charAt(0); this._index = index; this._fileInfo = currentFileInfo; this.variableRegex = /@\{([\w-]+)\}/g; this.propRegex = /\$\{([\w-]+)\}/g; }; Quoted.prototype = new Node(); Quoted.prototype.type = 'Quoted'; Quoted.prototype.genCSS = function (context, output) { if (!this.escaped) { output.add(this.quote, this.fileInfo(), this.getIndex()); } output.add(this.value); if (!this.escaped) { output.add(this.quote); } }; Quoted.prototype.containsVariables = function() { return this.value.match(this.variableRegex); }; Quoted.prototype.eval = function (context) { var that = this, value = this.value; var variableReplacement = function (_, name) { var v = new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context, true); return (v instanceof Quoted) ? v.value : v.toCSS(); }; var propertyReplacement = function (_, name) { var v = new Property('$' + name, that.getIndex(), that.fileInfo()).eval(context, true); return (v instanceof Quoted) ? v.value : v.toCSS(); }; function iterativeReplace(value, regexp, replacementFnc) { var evaluatedValue = value; do { value = evaluatedValue; evaluatedValue = value.replace(regexp, replacementFnc); } while (value !== evaluatedValue); return evaluatedValue; } value = iterativeReplace(value, this.variableRegex, variableReplacement); value = iterativeReplace(value, this.propRegex, propertyReplacement); return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo()); }; Quoted.prototype.compare = function (other) { // when comparing quoted strings allow the quote to differ if (other.type === 'Quoted' && !this.escaped && !other.escaped) { return Node.numericCompare(this.value, other.value); } else { return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined; } }; module.exports = Quoted; },{"./node":74,"./property":77,"./variable":86}],79:[function(require,module,exports){ var Node = require('./node'), Declaration = require('./declaration'), Keyword = require('./keyword'), Comment = require('./comment'), Paren = require('./paren'), Selector = require('./selector'), Element = require('./element'), Anonymous = require('./anonymous'), contexts = require('../contexts'), globalFunctionRegistry = require('../functions/function-registry'), defaultFunc = require('../functions/default'), getDebugInfo = require('./debug-info'), utils = require('../utils'); var Ruleset = function (selectors, rules, strictImports, visibilityInfo) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this._variables = null; this._properties = null; this.strictImports = strictImports; this.copyVisibilityInfo(visibilityInfo); this.allowRoot = true; this.setParent(this.selectors, this); this.setParent(this.rules, this); }; Ruleset.prototype = new Node(); Ruleset.prototype.type = 'Ruleset'; Ruleset.prototype.isRuleset = true; Ruleset.prototype.isRulesetLike = function() { return true; }; Ruleset.prototype.accept = function (visitor) { if (this.paths) { this.paths = visitor.visitArray(this.paths, true); } else if (this.selectors) { this.selectors = visitor.visitArray(this.selectors); } if (this.rules && this.rules.length) { this.rules = visitor.visitArray(this.rules); } }; Ruleset.prototype.eval = function (context) { var that = this, selectors, selCnt, selector, i, hasVariable, hasOnePassingSelector = false; if (this.selectors && (selCnt = this.selectors.length)) { selectors = new Array(selCnt); defaultFunc.error({ type: 'Syntax', message: 'it is currently only allowed in parametric mixin guards,' }); for (i = 0; i < selCnt; i++) { selector = this.selectors[i].eval(context); for (var j = 0; j < selector.elements.length; j++) { if (selector.elements[j].isVariable) { hasVariable = true; break; } } selectors[i] = selector; if (selector.evaldCondition) { hasOnePassingSelector = true; } } if (hasVariable) { var toParseSelectors = new Array(selCnt); for (i = 0; i < selCnt; i++) { selector = selectors[i]; toParseSelectors[i] = selector.toCSS(context); } this.parse.parseNode( toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function(err, result) { if (result) { selectors = utils.flattenArray(result); } }); } defaultFunc.reset(); } else { hasOnePassingSelector = true; } var rules = this.rules ? utils.copyArray(this.rules) : null, ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo()), rule, subRule; ruleset.originalRuleset = this; ruleset.root = this.root; ruleset.firstRoot = this.firstRoot; ruleset.allowImports = this.allowImports; if (this.debugInfo) { ruleset.debugInfo = this.debugInfo; } if (!hasOnePassingSelector) { rules.length = 0; } // inherit a function registry from the frames stack when possible; // otherwise from the global registry ruleset.functionRegistry = (function (frames) { var i = 0, n = frames.length, found; for ( ; i !== n ; ++i ) { found = frames[ i ].functionRegistry; if ( found ) { return found; } } return globalFunctionRegistry; }(context.frames)).inherit(); // push the current ruleset to the frames stack var ctxFrames = context.frames; ctxFrames.unshift(ruleset); // currrent selectors var ctxSelectors = context.selectors; if (!ctxSelectors) { context.selectors = ctxSelectors = []; } ctxSelectors.unshift(this.selectors); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { ruleset.evalImports(context); } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. var rsRules = ruleset.rules; for (i = 0; (rule = rsRules[i]); i++) { if (rule.evalFirst) { rsRules[i] = rule.eval(context); } } var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0; // Evaluate mixin calls. for (i = 0; (rule = rsRules[i]); i++) { if (rule.type === 'MixinCall') { /* jshint loopfunc:true */ rules = rule.eval(context).filter(function(r) { if ((r instanceof Declaration) && r.variable) { // do not pollute the scope if the variable is // already there. consider returning false here // but we need a way to "return" variable from mixins return !(ruleset.variable(r.name)); } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); i += rules.length - 1; ruleset.resetCache(); } else if (rule.type === 'VariableCall') { /* jshint loopfunc:true */ rules = rule.eval(context).rules.filter(function(r) { if ((r instanceof Declaration) && r.variable) { // do not pollute the scope at all return false; } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); i += rules.length - 1; ruleset.resetCache(); } } // Evaluate everything else for (i = 0; (rule = rsRules[i]); i++) { if (!rule.evalFirst) { rsRules[i] = rule = rule.eval ? rule.eval(context) : rule; } } // Evaluate everything else for (i = 0; (rule = rsRules[i]); i++) { // for rulesets, check if it is a css guard and can be removed if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) { // check if it can be folded in (e.g. & where) if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) { rsRules.splice(i--, 1); for (var j = 0; (subRule = rule.rules[j]); j++) { if (subRule instanceof Node) { subRule.copyVisibilityInfo(rule.visibilityInfo()); if (!(subRule instanceof Declaration) || !subRule.variable) { rsRules.splice(++i, 0, subRule); } } } } } } // Pop the stack ctxFrames.shift(); ctxSelectors.shift(); if (context.mediaBlocks) { for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) { context.mediaBlocks[i].bubbleSelectors(selectors); } } return ruleset; }; Ruleset.prototype.evalImports = function(context) { var rules = this.rules, i, importRules; if (!rules) { return; } for (i = 0; i < rules.length; i++) { if (rules[i].type === 'Import') { importRules = rules[i].eval(context); if (importRules && (importRules.length || importRules.length === 0)) { rules.splice.apply(rules, [i, 1].concat(importRules)); i += importRules.length - 1; } else { rules.splice(i, 1, importRules); } this.resetCache(); } } }; Ruleset.prototype.makeImportant = function() { var result = new Ruleset(this.selectors, this.rules.map(function (r) { if (r.makeImportant) { return r.makeImportant(); } else { return r; } }), this.strictImports, this.visibilityInfo()); return result; }; Ruleset.prototype.matchArgs = function (args) { return !args || args.length === 0; }; // lets you call a css selector with a guard Ruleset.prototype.matchCondition = function (args, context) { var lastSelector = this.selectors[this.selectors.length - 1]; if (!lastSelector.evaldCondition) { return false; } if (lastSelector.condition && !lastSelector.condition.eval( new contexts.Eval(context, context.frames))) { return false; } return true; }; Ruleset.prototype.resetCache = function () { this._rulesets = null; this._variables = null; this._properties = null; this._lookups = {}; }; Ruleset.prototype.variables = function () { if (!this._variables) { this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { if (r instanceof Declaration && r.variable === true) { hash[r.name] = r; } // when evaluating variables in an import statement, imports have not been eval'd // so we need to go inside import statements. // guard against root being a string (in the case of inlined less) if (r.type === 'Import' && r.root && r.root.variables) { var vars = r.root.variables(); for (var name in vars) { if (vars.hasOwnProperty(name)) { hash[name] = r.root.variable(name); } } } return hash; }, {}); } return this._variables; }; Ruleset.prototype.properties = function () { if (!this._properties) { this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) { if (r instanceof Declaration && r.variable !== true) { var name = (r.name.length === 1) && (r.name[0] instanceof Keyword) ? r.name[0].value : r.name; // Properties don't overwrite as they can merge if (!hash['$' + name]) { hash['$' + name] = [ r ]; } else { hash['$' + name].push(r); } } return hash; }, {}); } return this._properties; }; Ruleset.prototype.variable = function (name) { var decl = this.variables()[name]; if (decl) { return this.parseValue(decl); } }; Ruleset.prototype.property = function (name) { var decl = this.properties()[name]; if (decl) { return this.parseValue(decl); } }; Ruleset.prototype.parseValue = function(toParse) { var self = this; function transformDeclaration(decl) { if (decl.value instanceof Anonymous && !decl.parsed) { if (typeof decl.value.value === 'string') { this.parse.parseNode( decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function(err, result) { if (err) { decl.parsed = true; } if (result) { decl.value = result[0]; decl.important = result[1] || ''; decl.parsed = true; } }); } else { decl.parsed = true; } return decl; } else { return decl; } } if (!Array.isArray(toParse)) { return transformDeclaration.call(self, toParse); } else { var nodes = []; toParse.forEach(function(n) { nodes.push(transformDeclaration.call(self, n)); }); return nodes; } }; Ruleset.prototype.rulesets = function () { if (!this.rules) { return []; } var filtRules = [], rules = this.rules, i, rule; for (i = 0; (rule = rules[i]); i++) { if (rule.isRuleset) { filtRules.push(rule); } } return filtRules; }; Ruleset.prototype.prependRule = function (rule) { var rules = this.rules; if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } this.setParent(rule, this); }; Ruleset.prototype.find = function (selector, self, filter) { self = self || this; var rules = [], match, foundMixins, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > match) { if (!filter || filter(rule)) { foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter); for (var i = 0; i < foundMixins.length; ++i) { foundMixins[i].path.push(rule); } Array.prototype.push.apply(rules, foundMixins); } } else { rules.push({ rule: rule, path: []}); } break; } } } }); this._lookups[key] = rules; return rules; }; Ruleset.prototype.genCSS = function (context, output) { var i, j, charsetRuleNodes = [], ruleNodes = [], debugInfo, // Line number debugging rule, path; context.tabLevel = (context.tabLevel || 0); if (!this.root) { context.tabLevel++; } var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' '), tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' '), sep; var charsetNodeIndex = 0; var importNodeIndex = 0; for (i = 0; (rule = this.rules[i]); i++) { if (rule instanceof Comment) { if (importNodeIndex === i) { importNodeIndex++; } ruleNodes.push(rule); } else if (rule.isCharset && rule.isCharset()) { ruleNodes.splice(charsetNodeIndex, 0, rule); charsetNodeIndex++; importNodeIndex++; } else if (rule.type === 'Import') { ruleNodes.splice(importNodeIndex, 0, rule); importNodeIndex++; } else { ruleNodes.push(rule); } } ruleNodes = charsetRuleNodes.concat(ruleNodes); // If this is the root node, we don't render // a selector, or {}. if (!this.root) { debugInfo = getDebugInfo(context, this, tabSetStr); if (debugInfo) { output.add(debugInfo); output.add(tabSetStr); } var paths = this.paths, pathCnt = paths.length, pathSubCnt; sep = context.compress ? ',' : (',\n' + tabSetStr); for (i = 0; i < pathCnt; i++) { path = paths[i]; if (!(pathSubCnt = path.length)) { continue; } if (i > 0) { output.add(sep); } context.firstSelector = true; path[0].genCSS(context, output); context.firstSelector = false; for (j = 1; j < pathSubCnt; j++) { path[j].genCSS(context, output); } } output.add((context.compress ? '{' : ' {\n') + tabRuleStr); } // Compile rules and rulesets for (i = 0; (rule = ruleNodes[i]); i++) { if (i + 1 === ruleNodes.length) { context.lastRule = true; } var currentLastRule = context.lastRule; if (rule.isRulesetLike(rule)) { context.lastRule = false; } if (rule.genCSS) { rule.genCSS(context, output); } else if (rule.value) { output.add(rule.value.toString()); } context.lastRule = currentLastRule; if (!context.lastRule && rule.isVisible()) { output.add(context.compress ? '' : ('\n' + tabRuleStr)); } else { context.lastRule = false; } } if (!this.root) { output.add((context.compress ? '}' : '\n' + tabSetStr + '}')); context.tabLevel--; } if (!output.isEmpty() && !context.compress && this.firstRoot) { output.add('\n'); } }; Ruleset.prototype.joinSelectors = function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }; Ruleset.prototype.joinSelector = function (paths, context, selector) { function createParenthesis(elementsToPak, originalElement) { var replacementParen, j; if (elementsToPak.length === 0) { replacementParen = new Paren(elementsToPak[0]); } else { var insideParent = new Array(elementsToPak.length); for (j = 0; j < elementsToPak.length; j++) { insideParent[j] = new Element( null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo ); } replacementParen = new Paren(new Selector(insideParent)); } return replacementParen; } function createSelector(containedElement, originalElement) { var element, selector; element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo); selector = new Selector([element]); return selector; } // joins selector path from `beginningPath` with selector path in `addPath` // `replacedElement` contains element that is being replaced by `addPath` // returns concatenated path function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) { var newSelectorPath, lastSelector, newJoinedSelector; // our new selector path newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (beginningPath.length > 0) { newSelectorPath = utils.copyArray(beginningPath); lastSelector = newSelectorPath.pop(); newJoinedSelector = originalSelector.createDerived(utils.copyArray(lastSelector.elements)); } else { newJoinedSelector = originalSelector.createDerived([]); } if (addPath.length > 0) { // /deep/ is a CSS4 selector - (removed, so should deprecate) // that is valid without anything in front of it // so if the & does not have a combinator that is "" or " " then // and there is a combinator on the parent, then grab that. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0]; if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) { combinator = parentEl.combinator; } // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new Element( combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo )); newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1)); } // now add the joined selector - but only if it is not empty if (newJoinedSelector.elements.length !== 0) { newSelectorPath.push(newJoinedSelector); } // put together the parent selectors after the join (e.g. the rest of the parent) if (addPath.length > 1) { var restOfPath = addPath.slice(1); restOfPath = restOfPath.map(function (selector) { return selector.createDerived(selector.elements, []); }); newSelectorPath = newSelectorPath.concat(restOfPath); } return newSelectorPath; } // joins selector path from `beginningPath` with every selector path in `addPaths` array // `replacedElement` contains element that is being replaced by `addPath` // returns array with all concatenated paths function addAllReplacementsIntoPath( beginningPath, addPaths, replacedElement, originalSelector, result) { var j; for (j = 0; j < beginningPath.length; j++) { var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector); result.push(newSelectorPath); } return result; } function mergeElementsOnToSelectors(elements, selectors) { var i, sel; if (elements.length === 0) { return ; } if (selectors.length === 0) { selectors.push([ new Selector(elements) ]); return; } for (i = 0; (sel = selectors[i]); i++) { // if the previous thing in sel is a parent this needs to join on to it if (sel.length > 0) { sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); } else { sel.push(new Selector(elements)); } } } // replace all parent selectors inside `inSelector` by content of `context` array // resulting selectors are returned inside `paths` array // returns true if `inSelector` contained at least one parent selector function replaceParentSelector(paths, context, inSelector) { // The paths are [[Selector]] // The first list is a list of comma separated selectors // The inner list is a list of inheritance separated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector; function findNestedSelector(element) { var maybeSelector; if (!(element.value instanceof Paren)) { return null; } maybeSelector = element.value.value; if (!(maybeSelector instanceof Selector)) { return null; } return maybeSelector; } // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [ [] ]; for (i = 0; (el = inSelector.elements[i]); i++) { // non parent reference elements just get added if (el.value !== '&') { var nestedSelector = findNestedSelector(el); if (nestedSelector != null) { // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); var nestedPaths = [], replaced, replacedNewSelectors = []; replaced = replaceParentSelector(nestedPaths, context, nestedSelector); hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors for (k = 0; k < nestedPaths.length; k++) { var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el); addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors); } newSelectors = replacedNewSelectors; currentElements = []; } else { currentElements.push(el); } } else { hadParentSelector = true; // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { // We need to put the current selectors // then join the last selector's elements on to the parents selectors var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors mergeElementsOnToSelectors(currentElements, newSelectors); for (i = 0; i < newSelectors.length; i++) { length = newSelectors[i].length; if (length > 0) { paths.push(newSelectors[i]); lastSelector = newSelectors[i][length - 1]; newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList); } } return hadParentSelector; } function deriveSelector(visibilityInfo, deriveFrom) { var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition); newSelector.copyVisibilityInfo(visibilityInfo); return newSelector; } // joinSelector code follows var i, newPaths, hadParentSelector; newPaths = []; hadParentSelector = replaceParentSelector(newPaths, context, selector); if (!hadParentSelector) { if (context.length > 0) { newPaths = []; for (i = 0; i < context.length; i++) { var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo())); concatenated.push(selector); newPaths.push(concatenated); } } else { newPaths = [[selector]]; } } for (i = 0; i < newPaths.length; i++) { paths.push(newPaths[i]); } }; module.exports = Ruleset; },{"../contexts":12,"../functions/default":24,"../functions/function-registry":26,"../utils":87,"./anonymous":48,"./comment":55,"./debug-info":57,"./declaration":58,"./element":61,"./keyword":68,"./node":74,"./paren":76,"./selector":80}],80:[function(require,module,exports){ var Node = require('./node'), Element = require('./element'), LessError = require('../less-error'); var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) { this.extendList = extendList; this.condition = condition; this.evaldCondition = !condition; this._index = index; this._fileInfo = currentFileInfo; this.elements = this.getElements(elements); this.mixinElements_ = undefined; this.copyVisibilityInfo(visibilityInfo); this.setParent(this.elements, this); }; Selector.prototype = new Node(); Selector.prototype.type = 'Selector'; Selector.prototype.accept = function (visitor) { if (this.elements) { this.elements = visitor.visitArray(this.elements); } if (this.extendList) { this.extendList = visitor.visitArray(this.extendList); } if (this.condition) { this.condition = visitor.visit(this.condition); } }; Selector.prototype.createDerived = function(elements, extendList, evaldCondition) { elements = this.getElements(elements); var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo()); newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; newSelector.mediaEmpty = this.mediaEmpty; return newSelector; }; Selector.prototype.getElements = function(els) { if (!els) { return [new Element('', '&', false, this._index, this._fileInfo)]; } if (typeof els === 'string') { this.parse.parseNode( els, ['selector'], this._index, this._fileInfo, function(err, result) { if (err) { throw new LessError({ index: err.index, message: err.message }, this.parse.imports, this._fileInfo.filename); } els = result[0].elements; }); } return els; }; Selector.prototype.createEmptySelectors = function() { var el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)]; sels[0].mediaEmpty = true; return sels; }; Selector.prototype.match = function (other) { var elements = this.elements, len = elements.length, olen, i; other = other.mixinElements(); olen = other.length; if (olen === 0 || len < olen) { return 0; } else { for (i = 0; i < olen; i++) { if (elements[i].value !== other[i]) { return 0; } } } return olen; // return number of matched elements }; Selector.prototype.mixinElements = function() { if (this.mixinElements_) { return this.mixinElements_; } var elements = this.elements.map( function(v) { return v.combinator.value + (v.value.value || v.value); }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g); if (elements) { if (elements[0] === '&') { elements.shift(); } } else { elements = []; } return (this.mixinElements_ = elements); }; Selector.prototype.isJustParentSelector = function() { return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); }; Selector.prototype.eval = function (context) { var evaldCondition = this.condition && this.condition.eval(context), elements = this.elements, extendList = this.extendList; elements = elements && elements.map(function (e) { return e.eval(context); }); extendList = extendList && extendList.map(function(extend) { return extend.eval(context); }); return this.createDerived(elements, extendList, evaldCondition); }; Selector.prototype.genCSS = function (context, output) { var i, element; if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') { output.add(' ', this.fileInfo(), this.getIndex()); } for (i = 0; i < this.elements.length; i++) { element = this.elements[i]; element.genCSS(context, output); } }; Selector.prototype.getIsOutput = function() { return this.evaldCondition; }; module.exports = Selector; },{"../less-error":36,"./element":61,"./node":74}],81:[function(require,module,exports){ var Node = require('./node'); var UnicodeDescriptor = function (value) { this.value = value; }; UnicodeDescriptor.prototype = new Node(); UnicodeDescriptor.prototype.type = 'UnicodeDescriptor'; module.exports = UnicodeDescriptor; },{"./node":74}],82:[function(require,module,exports){ var Node = require('./node'), unitConversions = require('../data/unit-conversions'), utils = require('../utils'); var Unit = function (numerator, denominator, backupUnit) { this.numerator = numerator ? utils.copyArray(numerator).sort() : []; this.denominator = denominator ? utils.copyArray(denominator).sort() : []; if (backupUnit) { this.backupUnit = backupUnit; } else if (numerator && numerator.length) { this.backupUnit = numerator[0]; } }; Unit.prototype = new Node(); Unit.prototype.type = 'Unit'; Unit.prototype.clone = function () { return new Unit(utils.copyArray(this.numerator), utils.copyArray(this.denominator), this.backupUnit); }; Unit.prototype.genCSS = function (context, output) { // Dimension checks the unit is singular and throws an error if in strict math mode. var strictUnits = context && context.strictUnits; if (this.numerator.length === 1) { output.add(this.numerator[0]); // the ideal situation } else if (!strictUnits && this.backupUnit) { output.add(this.backupUnit); } else if (!strictUnits && this.denominator.length) { output.add(this.denominator[0]); } }; Unit.prototype.toString = function () { var i, returnStr = this.numerator.join('*'); for (i = 0; i < this.denominator.length; i++) { returnStr += '/' + this.denominator[i]; } return returnStr; }; Unit.prototype.compare = function (other) { return this.is(other.toString()) ? 0 : undefined; }; Unit.prototype.is = function (unitString) { return this.toString().toUpperCase() === unitString.toUpperCase(); }; Unit.prototype.isLength = function () { return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS()); }; Unit.prototype.isEmpty = function () { return this.numerator.length === 0 && this.denominator.length === 0; }; Unit.prototype.isSingular = function() { return this.numerator.length <= 1 && this.denominator.length === 0; }; Unit.prototype.map = function(callback) { var i; for (i = 0; i < this.numerator.length; i++) { this.numerator[i] = callback(this.numerator[i], false); } for (i = 0; i < this.denominator.length; i++) { this.denominator[i] = callback(this.denominator[i], true); } }; Unit.prototype.usedUnits = function() { var group, result = {}, mapUnit, groupName; mapUnit = function (atomicUnit) { /* jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { result[groupName] = atomicUnit; } return atomicUnit; }; for (groupName in unitConversions) { if (unitConversions.hasOwnProperty(groupName)) { group = unitConversions[groupName]; this.map(mapUnit); } } return result; }; Unit.prototype.cancel = function () { var counter = {}, atomicUnit, i; for (i = 0; i < this.numerator.length; i++) { atomicUnit = this.numerator[i]; counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; } for (i = 0; i < this.denominator.length; i++) { atomicUnit = this.denominator[i]; counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; } this.numerator = []; this.denominator = []; for (atomicUnit in counter) { if (counter.hasOwnProperty(atomicUnit)) { var count = counter[atomicUnit]; if (count > 0) { for (i = 0; i < count; i++) { this.numerator.push(atomicUnit); } } else if (count < 0) { for (i = 0; i < -count; i++) { this.denominator.push(atomicUnit); } } } } this.numerator.sort(); this.denominator.sort(); }; module.exports = Unit; },{"../data/unit-conversions":15,"../utils":87,"./node":74}],83:[function(require,module,exports){ var Node = require('./node'); var URL = function (val, index, currentFileInfo, isEvald) { this.value = val; this._index = index; this._fileInfo = currentFileInfo; this.isEvald = isEvald; }; URL.prototype = new Node(); URL.prototype.type = 'Url'; URL.prototype.accept = function (visitor) { this.value = visitor.visit(this.value); }; URL.prototype.genCSS = function (context, output) { output.add('url('); this.value.genCSS(context, output); output.add(')'); }; URL.prototype.eval = function (context) { var val = this.value.eval(context), rootpath; if (!this.isEvald) { // Add the base path if the URL is relative rootpath = this.fileInfo() && this.fileInfo().rootpath; if (rootpath && typeof val.value === 'string' && context.isPathRelative(val.value)) { if (!val.quote) { rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return '\\' + match; }); } val.value = rootpath + val.value; } val.value = context.normalizePath(val.value); // Add url args if enabled if (context.urlArgs) { if (!val.value.match(/^\s*data:/)) { var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; var urlArgs = delimiter + context.urlArgs; if (val.value.indexOf('#') !== -1) { val.value = val.value.replace('#', urlArgs + '#'); } else { val.value += urlArgs; } } } } return new URL(val, this.getIndex(), this.fileInfo(), true); }; module.exports = URL; },{"./node":74}],84:[function(require,module,exports){ var Node = require('./node'); var Value = function (value) { if (!value) { throw new Error('Value requires an array argument'); } if (!Array.isArray(value)) { this.value = [ value ]; } else { this.value = value; } }; Value.prototype = new Node(); Value.prototype.type = 'Value'; Value.prototype.accept = function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }; Value.prototype.eval = function (context) { if (this.value.length === 1) { return this.value[0].eval(context); } else { return new Value(this.value.map(function (v) { return v.eval(context); })); } }; Value.prototype.genCSS = function (context, output) { var i; for (i = 0; i < this.value.length; i++) { this.value[i].genCSS(context, output); if (i + 1 < this.value.length) { output.add((context && context.compress) ? ',' : ', '); } } }; module.exports = Value; },{"./node":74}],85:[function(require,module,exports){ var Node = require('./node'), Variable = require('./variable'), Ruleset = require('./ruleset'), DetachedRuleset = require('./detached-ruleset'), LessError = require('../less-error'); var VariableCall = function (variable, index, currentFileInfo) { this.variable = variable; this._index = index; this._fileInfo = currentFileInfo; this.allowRoot = true; }; VariableCall.prototype = new Node(); VariableCall.prototype.type = 'VariableCall'; VariableCall.prototype.eval = function (context) { var rules, detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context), error = new LessError({message: 'Could not evaluate variable call ' + this.variable}); if (!detachedRuleset.ruleset) { if (Array.isArray(detachedRuleset)) { rules = detachedRuleset; } else if (Array.isArray(detachedRuleset.value)) { rules = detachedRuleset.value; } else { throw error; } detachedRuleset = new DetachedRuleset(new Ruleset('', rules)); } if (detachedRuleset.ruleset) { return detachedRuleset.callEval(context); } throw error; }; module.exports = VariableCall; },{"../less-error":36,"./detached-ruleset":59,"./node":74,"./ruleset":79,"./variable":86}],86:[function(require,module,exports){ var Node = require('./node'), Call = require('./call'); var Variable = function (name, index, currentFileInfo) { this.name = name; this._index = index; this._fileInfo = currentFileInfo; }; Variable.prototype = new Node(); Variable.prototype.type = 'Variable'; Variable.prototype.eval = function (context) { var variable, name = this.name; if (name.indexOf('@@') === 0) { name = '@' + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value; } if (this.evaluating) { throw { type: 'Name', message: 'Recursive variable definition for ' + name, filename: this.fileInfo().filename, index: this.getIndex() }; } this.evaluating = true; variable = this.find(context.frames, function (frame) { var v = frame.variable(name); if (v) { if (v.important) { var importantScope = context.importantScope[context.importantScope.length - 1]; importantScope.important = v.important; } // If in calc, wrap vars in a function call to cascade evaluate args first if (context.inCalc) { return (new Call('_SELF', [v.value])).eval(context); } else { return v.value.eval(context); } } }); if (variable) { this.evaluating = false; return variable; } else { throw { type: 'Name', message: 'variable ' + name + ' is undefined', filename: this.fileInfo().filename, index: this.getIndex() }; } }; Variable.prototype.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { r = fun.call(obj, obj[i]); if (r) { return r; } } return null; }; module.exports = Variable; },{"./call":52,"./node":74}],87:[function(require,module,exports){ /* jshint proto: true */ var utils = { getLocation: function(index, inputStream) { var n = index + 1, line = null, column = -1; while (--n >= 0 && inputStream.charAt(n) !== '\n') { column++; } if (typeof index === 'number') { line = (inputStream.slice(0, index).match(/\n/g) || '').length; } return { line: line, column: column }; }, copyArray: function(arr) { var i, length = arr.length, copy = new Array(length); for (i = 0; i < length; i++) { copy[i] = arr[i]; } return copy; }, clone: function (obj) { var cloned = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { cloned[prop] = obj[prop]; } } return cloned; }, defaults: function(obj1, obj2) { if (!obj2._defaults || obj2._defaults !== obj1) { for (var prop in obj1) { if (obj1.hasOwnProperty(prop)) { if (!obj2.hasOwnProperty(prop)) { obj2[prop] = obj1[prop]; } else if (Array.isArray(obj1[prop]) && Array.isArray(obj2[prop])) { obj1[prop].forEach(function(p) { if (obj2[prop].indexOf(p) === -1) { obj2[prop].push(p); } }); } } } } obj2._defaults = obj1; return obj2; }, merge: function(obj1, obj2) { for (var prop in obj2) { if (obj2.hasOwnProperty(prop)) { obj1[prop] = obj2[prop]; } } return obj1; }, flattenArray: function(arr, result) { result = result || []; for (var i = 0, length = arr.length; i < length; i++) { var value = arr[i]; if (Array.isArray(value)) { utils.flattenArray(value, result); } else { if (value !== undefined) { result.push(value); } } } return result; } }; module.exports = utils; },{}],88:[function(require,module,exports){ var tree = require('../tree'), Visitor = require('./visitor'), logger = require('../logger'), utils = require('../utils'); /* jshint loopfunc:true */ var ExtendFinderVisitor = function() { this._visitor = new Visitor(this); this.contexts = []; this.allExtendsStack = [[]]; }; ExtendFinderVisitor.prototype = { run: function (root) { root = this._visitor.visit(root); root.allExtends = this.allExtendsStack[0]; return root; }, visitDeclaration: function (declNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var i, j, extend, allSelectorsExtendList = [], extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; for (i = 0; i < ruleCnt; i++) { if (rulesetNode.rules[i] instanceof tree.Extend) { allSelectorsExtendList.push(rules[i]); rulesetNode.extendOnEveryPath = true; } } // now find every selector and apply the extends that apply to all extends // and the ones which apply to an individual extend var paths = rulesetNode.paths; for (i = 0; i < paths.length; i++) { var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList; extendList = selExtendList ? utils.copyArray(selExtendList).concat(allSelectorsExtendList) : allSelectorsExtendList; if (extendList) { extendList = extendList.map(function(allSelectorsExtend) { return allSelectorsExtend.clone(); }); } for (j = 0; j < extendList.length; j++) { this.foundExtends = true; extend = extendList[j]; extend.findSelfSelectors(selectorPath); extend.ruleset = rulesetNode; if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } this.allExtendsStack[this.allExtendsStack.length - 1].push(extend); } } this.contexts.push(rulesetNode.selectors); }, visitRulesetOut: function (rulesetNode) { if (!rulesetNode.root) { this.contexts.length = this.contexts.length - 1; } }, visitMedia: function (mediaNode, visitArgs) { mediaNode.allExtends = []; this.allExtendsStack.push(mediaNode.allExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitAtRule: function (atRuleNode, visitArgs) { atRuleNode.allExtends = []; this.allExtendsStack.push(atRuleNode.allExtends); }, visitAtRuleOut: function (atRuleNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; var ProcessExtendsVisitor = function() { this._visitor = new Visitor(this); }; ProcessExtendsVisitor.prototype = { run: function(root) { var extendFinder = new ExtendFinderVisitor(); this.extendIndices = {}; extendFinder.run(root); if (!extendFinder.foundExtends) { return root; } root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); this.allExtendsStack = [root.allExtends]; var newRoot = this._visitor.visit(root); this.checkExtendsForNonMatched(root.allExtends); return newRoot; }, checkExtendsForNonMatched: function(extendList) { var indices = this.extendIndices; extendList.filter(function(extend) { return !extend.hasFoundMatches && extend.parent_ids.length == 1; }).forEach(function(extend) { var selector = '_unknown_'; try { selector = extend.selector.toCSS({}); } catch (_) {} if (!indices[extend.index + ' ' + selector]) { indices[extend.index + ' ' + selector] = true; logger.warn('extend \'' + selector + '\' has no matches'); } }); }, doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { // // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering // and pasting the selector we would do normally, but we are also adding an extend with the same target selector // this means this new extend can then go and alter other extends // // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already // processed if we look at each selector at a time, as is done in visitRuleset var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; iterationCount = iterationCount || 0; // loop through comparing every extend with every target extend. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one // and the second is the target. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the // case when processing media queries for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) { for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) { extend = extendsList[extendIndex]; targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references if ( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ) { continue; } // find a match in the target extends self selector (the bit before :extend) selectorPath = [targetExtend.selfSelectors[0]]; matches = extendVisitor.findMatch(extend, selectorPath); if (matches.length) { extend.hasFoundMatches = true; // we found a match, so for each self selector.. extend.selfSelectors.forEach(function(selfSelector) { var info = targetExtend.visibilityInfo(); // process the extend as usual newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible()); // but now we create a new extend from it newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info); newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector newSelector[newSelector.length - 1].extendList = [newExtend]; // record that we need to add it. extendsToAdd.push(newExtend); newExtend.ruleset = targetExtend.ruleset; // remember its parents for circular references newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple // extends will look at the same selector path, so when extending // we know that any others will be duplicates in terms of what is added to the css if (targetExtend.firstExtendOnThisSelectorPath) { newExtend.firstExtendOnThisSelectorPath = true; targetExtend.ruleset.paths.push(newSelector); } }); } } } if (extendsToAdd.length) { // try to detect circular references to stop a stack overflow. // may no longer be needed. this.extendChainCount++; if (iterationCount > 100) { var selectorOne = '{unable to calculate}'; var selectorTwo = '{unable to calculate}'; try { selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); selectorTwo = extendsToAdd[0].selector.toCSS(); } catch (e) {} throw { message: 'extend circular reference detected. One of the circular extends is currently:' + selectorOne + ':extend(' + selectorTwo + ')'}; } // now process the new extends on the existing rules so that we can handle a extending b extending c extending // d extending e... return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1)); } else { return extendsToAdd; } }, visitDeclaration: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitSelector: function (selectorNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length - 1], selectorsToAdd = [], extendVisitor = this, selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass if (rulesetNode.extendOnEveryPath) { continue; } var extendList = selectorPath[selectorPath.length - 1].extendList; if (extendList && extendList.length) { continue; } matches = this.findMatch(allExtends[extendIndex], selectorPath); if (matches.length) { allExtends[extendIndex].hasFoundMatches = true; allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { var extendedSelectors; extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible()); selectorsToAdd.push(extendedSelectors); }); } } } rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); }, findMatch: function (extend, haystackSelectorPath) { // // look through the haystack selector path to try and find the needle - extend.selector // returns an array of selector matches that can then be replaced // var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, targetCombinator, i, extendVisitor = this, needleElements = extend.selector.elements, potentialMatches = [], potentialMatch, matches = []; // loop through the haystack elements for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); } for (i = 0; i < potentialMatches.length; i++) { potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to // work out what the resulting combinator will be targetCombinator = haystackElement.combinator.value; if (targetCombinator === '' && hackstackElementIndex === 0) { targetCombinator = ' '; } // if we don't match, null our match to indicate failure if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { potentialMatch = null; } else { potentialMatch.matched++; } // if we are still valid and have finished, test whether we have elements after and whether these are allowed if (potentialMatch) { potentialMatch.finished = potentialMatch.matched === needleElements.length; if (potentialMatch.finished && (!extend.allowAfter && (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) { potentialMatch = null; } } // if null we remove, if not, we are still valid, so either push as a valid match or continue if (potentialMatch) { if (potentialMatch.finished) { potentialMatch.length = needleElements.length; potentialMatch.endPathIndex = haystackSelectorIndex; potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again matches.push(potentialMatch); } } else { potentialMatches.splice(i, 1); i--; } } } } return matches; }, isElementValuesEqual: function(elementValue1, elementValue2) { if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') { return elementValue1 === elementValue2; } if (elementValue1 instanceof tree.Attribute) { if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { return false; } if (!elementValue1.value || !elementValue2.value) { if (elementValue1.value || elementValue2.value) { return false; } return true; } elementValue1 = elementValue1.value.value || elementValue1.value; elementValue2 = elementValue2.value.value || elementValue2.value; return elementValue1 === elementValue2; } elementValue1 = elementValue1.value; elementValue2 = elementValue2.value; if (elementValue1 instanceof tree.Selector) { if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { return false; } for (var i = 0; i < elementValue1.elements.length; i++) { if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) { if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) { return false; } } if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) { return false; } } return true; } return false; }, extendSelector:function (matches, selectorPath, replacementSelector, isVisible) { // for a set of matches, replace each match with the replacement selector var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements; for (matchIndex = 0; matchIndex < matches.length; matchIndex++) { match = matches[matchIndex]; selector = selectorPath[match.pathIndex]; firstElement = new tree.Element( match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo() ); if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1] .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } newElements = selector.elements .slice(currentSelectorPathElementIndex, match.index) .concat([firstElement]) .concat(replacementSelector.elements.slice(1)); if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements); } else { path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); path.push(new tree.Selector( newElements )); } currentSelectorPathIndex = match.endPathIndex; currentSelectorPathElementIndex = match.endPathElementIndex; if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } } if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1] .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathIndex++; } path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); path = path.map(function (currentValue) { // we can re-use elements here, because the visibility property matters only for selectors var derived = currentValue.createDerived(currentValue.elements); if (isVisible) { derived.ensureVisibility(); } else { derived.ensureInvisibility(); } return derived; }); return path; }, visitMedia: function (mediaNode, visitArgs) { var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitMediaOut: function (mediaNode) { var lastIndex = this.allExtendsStack.length - 1; this.allExtendsStack.length = lastIndex; }, visitAtRule: function (atRuleNode, visitArgs) { var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitAtRuleOut: function (atRuleNode) { var lastIndex = this.allExtendsStack.length - 1; this.allExtendsStack.length = lastIndex; } }; module.exports = ProcessExtendsVisitor; },{"../logger":37,"../tree":65,"../utils":87,"./visitor":95}],89:[function(require,module,exports){ function ImportSequencer(onSequencerEmpty) { this.imports = []; this.variableImports = []; this._onSequencerEmpty = onSequencerEmpty; this._currentDepth = 0; } ImportSequencer.prototype.addImport = function(callback) { var importSequencer = this, importItem = { callback: callback, args: null, isReady: false }; this.imports.push(importItem); return function() { importItem.args = Array.prototype.slice.call(arguments, 0); importItem.isReady = true; importSequencer.tryRun(); }; }; ImportSequencer.prototype.addVariableImport = function(callback) { this.variableImports.push(callback); }; ImportSequencer.prototype.tryRun = function() { this._currentDepth++; try { while (true) { while (this.imports.length > 0) { var importItem = this.imports[0]; if (!importItem.isReady) { return; } this.imports = this.imports.slice(1); importItem.callback.apply(null, importItem.args); } if (this.variableImports.length === 0) { break; } var variableImport = this.variableImports[0]; this.variableImports = this.variableImports.slice(1); variableImport(); } } finally { this._currentDepth--; } if (this._currentDepth === 0 && this._onSequencerEmpty) { this._onSequencerEmpty(); } }; module.exports = ImportSequencer; },{}],90:[function(require,module,exports){ var contexts = require('../contexts'), Visitor = require('./visitor'), ImportSequencer = require('./import-sequencer'), utils = require('../utils'); var ImportVisitor = function(importer, finish) { this._visitor = new Visitor(this); this._importer = importer; this._finish = finish; this.context = new contexts.Eval(); this.importCount = 0; this.onceFileDetectionMap = {}; this.recursionDetector = {}; this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this)); }; ImportVisitor.prototype = { isReplacing: false, run: function (root) { try { // process the contents this._visitor.visit(root); } catch (e) { this.error = e; } this.isFinished = true; this._sequencer.tryRun(); }, _onSequencerEmpty: function() { if (!this.isFinished) { return; } this._finish(this.error); }, visitImport: function (importNode, visitArgs) { var inlineCSS = importNode.options.inline; if (!importNode.css || inlineCSS) { var context = new contexts.Eval(this.context, utils.copyArray(this.context.frames)); var importParent = context.frames[0]; this.importCount++; if (importNode.isVariableImport()) { this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent)); } else { this.processImportNode(importNode, context, importParent); } } visitArgs.visitDeeper = false; }, processImportNode: function(importNode, context, importParent) { var evaldImportNode, inlineCSS = importNode.options.inline; try { evaldImportNode = importNode.evalForImport(context); } catch (e) { if (!e.filename) { e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename; } // attempt to eval properly and treat as css importNode.css = true; // if that fails, this error will be thrown importNode.error = e; } if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { if (evaldImportNode.options.multiple) { context.importMultiple = true; } // try appending if we haven't determined if it is css or not var tryAppendLessExtension = evaldImportNode.css === undefined; for (var i = 0; i < importParent.rules.length; i++) { if (importParent.rules[i] === importNode) { importParent.rules[i] = evaldImportNode; break; } } var onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported); this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported); } else { this.importCount--; if (this.isFinished) { this._sequencer.tryRun(); } } }, onImported: function (importNode, context, e, root, importedAtRoot, fullPath) { if (e) { if (!e.filename) { e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename; } this.error = e; } var importVisitor = this, inlineCSS = importNode.options.inline, isPlugin = importNode.options.isPlugin, isOptional = importNode.options.optional, duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector; if (!context.importMultiple) { if (duplicateImport) { importNode.skip = true; } else { importNode.skip = function() { if (fullPath in importVisitor.onceFileDetectionMap) { return true; } importVisitor.onceFileDetectionMap[fullPath] = true; return false; }; } } if (!fullPath && isOptional) { importNode.skip = true; } if (root) { importNode.root = root; importNode.importedFilename = fullPath; if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) { importVisitor.recursionDetector[fullPath] = true; var oldContext = this.context; this.context = context; try { this._visitor.visit(root); } catch (e) { this.error = e; } this.context = oldContext; } } importVisitor.importCount--; if (importVisitor.isFinished) { importVisitor._sequencer.tryRun(); } }, visitDeclaration: function (declNode, visitArgs) { if (declNode.value.type === 'DetachedRuleset') { this.context.frames.unshift(declNode); } else { visitArgs.visitDeeper = false; } }, visitDeclarationOut: function(declNode) { if (declNode.value.type === 'DetachedRuleset') { this.context.frames.shift(); } }, visitAtRule: function (atRuleNode, visitArgs) { this.context.frames.unshift(atRuleNode); }, visitAtRuleOut: function (atRuleNode) { this.context.frames.shift(); }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { this.context.frames.unshift(mixinDefinitionNode); }, visitMixinDefinitionOut: function (mixinDefinitionNode) { this.context.frames.shift(); }, visitRuleset: function (rulesetNode, visitArgs) { this.context.frames.unshift(rulesetNode); }, visitRulesetOut: function (rulesetNode) { this.context.frames.shift(); }, visitMedia: function (mediaNode, visitArgs) { this.context.frames.unshift(mediaNode.rules[0]); }, visitMediaOut: function (mediaNode) { this.context.frames.shift(); } }; module.exports = ImportVisitor; },{"../contexts":12,"../utils":87,"./import-sequencer":89,"./visitor":95}],91:[function(require,module,exports){ var visitors = { Visitor: require('./visitor'), ImportVisitor: require('./import-visitor'), MarkVisibleSelectorsVisitor: require('./set-tree-visibility-visitor'), ExtendVisitor: require('./extend-visitor'), JoinSelectorVisitor: require('./join-selector-visitor'), ToCSSVisitor: require('./to-css-visitor') }; module.exports = visitors; },{"./extend-visitor":88,"./import-visitor":90,"./join-selector-visitor":92,"./set-tree-visibility-visitor":93,"./to-css-visitor":94,"./visitor":95}],92:[function(require,module,exports){ var Visitor = require('./visitor'); var JoinSelectorVisitor = function() { this.contexts = [[]]; this._visitor = new Visitor(this); }; JoinSelectorVisitor.prototype = { run: function (root) { return this._visitor.visit(root); }, visitDeclaration: function (declNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { var context = this.contexts[this.contexts.length - 1], paths = [], selectors; this.contexts.push(paths); if (!rulesetNode.root) { selectors = rulesetNode.selectors; if (selectors) { selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); rulesetNode.selectors = selectors.length ? selectors : (selectors = null); if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } } if (!selectors) { rulesetNode.rules = null; } rulesetNode.paths = paths; } }, visitRulesetOut: function (rulesetNode) { this.contexts.length = this.contexts.length - 1; }, visitMedia: function (mediaNode, visitArgs) { var context = this.contexts[this.contexts.length - 1]; mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); }, visitAtRule: function (atRuleNode, visitArgs) { var context = this.contexts[this.contexts.length - 1]; if (atRuleNode.rules && atRuleNode.rules.length) { atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null); } } }; module.exports = JoinSelectorVisitor; },{"./visitor":95}],93:[function(require,module,exports){ var SetTreeVisibilityVisitor = function(visible) { this.visible = visible; }; SetTreeVisibilityVisitor.prototype.run = function(root) { this.visit(root); }; SetTreeVisibilityVisitor.prototype.visitArray = function(nodes) { if (!nodes) { return nodes; } var cnt = nodes.length, i; for (i = 0; i < cnt; i++) { this.visit(nodes[i]); } return nodes; }; SetTreeVisibilityVisitor.prototype.visit = function(node) { if (!node) { return node; } if (node.constructor === Array) { return this.visitArray(node); } if (!node.blocksVisibility || node.blocksVisibility()) { return node; } if (this.visible) { node.ensureVisibility(); } else { node.ensureInvisibility(); } node.accept(this); return node; }; module.exports = SetTreeVisibilityVisitor; },{}],94:[function(require,module,exports){ var tree = require('../tree'), Visitor = require('./visitor'); var CSSVisitorUtils = function(context) { this._visitor = new Visitor(this); this._context = context; }; CSSVisitorUtils.prototype = { containsSilentNonBlockedChild: function(bodyRules) { var rule; if (!bodyRules) { return false; } for (var r = 0; r < bodyRules.length; r++) { rule = bodyRules[r]; if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) { // the atrule contains something that was referenced (likely by extend) // therefore it needs to be shown in output too return true; } } return false; }, keepOnlyVisibleChilds: function(owner) { if (owner && owner.rules) { owner.rules = owner.rules.filter(function(thing) { return thing.isVisible(); }); } }, isEmpty: function(owner) { return (owner && owner.rules) ? (owner.rules.length === 0) : true; }, hasVisibleSelector: function(rulesetNode) { return (rulesetNode && rulesetNode.paths) ? (rulesetNode.paths.length > 0) : false; }, resolveVisibility: function (node, originalRules) { if (!node.blocksVisibility()) { if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) { return ; } return node; } var compiledRulesBody = node.rules[0]; this.keepOnlyVisibleChilds(compiledRulesBody); if (this.isEmpty(compiledRulesBody)) { return ; } node.ensureVisibility(); node.removeVisibilityBlock(); return node; }, isVisibleRuleset: function(rulesetNode) { if (rulesetNode.firstRoot) { return true; } if (this.isEmpty(rulesetNode)) { return false; } if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) { return false; } return true; } }; var ToCSSVisitor = function(context) { this._visitor = new Visitor(this); this._context = context; this.utils = new CSSVisitorUtils(context); }; ToCSSVisitor.prototype = { isReplacing: true, run: function (root) { return this._visitor.visit(root); }, visitDeclaration: function (declNode, visitArgs) { if (declNode.blocksVisibility() || declNode.variable) { return; } return declNode; }, visitMixinDefinition: function (mixinNode, visitArgs) { // mixin definitions do not get eval'd - this means they keep state // so we have to clear that state here so it isn't used if toCSS is called twice mixinNode.frames = []; }, visitExtend: function (extendNode, visitArgs) { }, visitComment: function (commentNode, visitArgs) { if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) { return; } return commentNode; }, visitMedia: function(mediaNode, visitArgs) { var originalRules = mediaNode.rules[0].rules; mediaNode.accept(this._visitor); visitArgs.visitDeeper = false; return this.utils.resolveVisibility(mediaNode, originalRules); }, visitImport: function (importNode, visitArgs) { if (importNode.blocksVisibility()) { return ; } return importNode; }, visitAtRule: function(atRuleNode, visitArgs) { if (atRuleNode.rules && atRuleNode.rules.length) { return this.visitAtRuleWithBody(atRuleNode, visitArgs); } else { return this.visitAtRuleWithoutBody(atRuleNode, visitArgs); } }, visitAnonymous: function(anonymousNode, visitArgs) { if (!anonymousNode.blocksVisibility()) { anonymousNode.accept(this._visitor); return anonymousNode; } }, visitAtRuleWithBody: function(atRuleNode, visitArgs) { // if there is only one nested ruleset and that one has no path, then it is // just fake ruleset function hasFakeRuleset(atRuleNode) { var bodyRules = atRuleNode.rules; return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0); } function getBodyRules(atRuleNode) { var nodeRules = atRuleNode.rules; if (hasFakeRuleset(atRuleNode)) { return nodeRules[0].rules; } return nodeRules; } // it is still true that it is only one ruleset in array // this is last such moment // process childs var originalRules = getBodyRules(atRuleNode); atRuleNode.accept(this._visitor); visitArgs.visitDeeper = false; if (!this.utils.isEmpty(atRuleNode)) { this._mergeRules(atRuleNode.rules[0].rules); } return this.utils.resolveVisibility(atRuleNode, originalRules); }, visitAtRuleWithoutBody: function(atRuleNode, visitArgs) { if (atRuleNode.blocksVisibility()) { return; } if (atRuleNode.name === '@charset') { // Only output the debug info together with subsequent @charset definitions // a comment (or @media statement) before the actual @charset atrule would // be considered illegal css as it has to be on the first line if (this.charset) { if (atRuleNode.debugInfo) { var comment = new tree.Comment('/* ' + atRuleNode.toCSS(this._context).replace(/\n/g, '') + ' */\n'); comment.debugInfo = atRuleNode.debugInfo; return this._visitor.visit(comment); } return; } this.charset = true; } return atRuleNode; }, checkValidNodes: function(rules, isRoot) { if (!rules) { return; } for (var i = 0; i < rules.length; i++) { var ruleNode = rules[i]; if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) { throw { message: 'Properties must be inside selector blocks. They cannot be in the root', index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename}; } if (ruleNode instanceof tree.Call) { throw { message: 'Function \'' + ruleNode.name + '\' is undefined', index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename}; } if (ruleNode.type && !ruleNode.allowRoot) { throw { message: ruleNode.type + ' node returned by a function is not valid here', index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename}; } } }, visitRuleset: function (rulesetNode, visitArgs) { // at this point rulesets are nested into each other var rule, rulesets = []; this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot); if (!rulesetNode.root) { // remove invisible paths this._compileRulesetPaths(rulesetNode); // remove rulesets from this ruleset body and compile them separately var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; for (var i = 0; i < nodeRuleCnt; ) { rule = nodeRules[i]; if (rule && rule.rules) { // visit because we are moving them out from being a child rulesets.push(this._visitor.visit(rule)); nodeRules.splice(i, 1); nodeRuleCnt--; continue; } i++; } // accept the visitor to remove rules and refactor itself // then we can decide nogw whether we want it or not // compile body if (nodeRuleCnt > 0) { rulesetNode.accept(this._visitor); } else { rulesetNode.rules = null; } visitArgs.visitDeeper = false; } else { // if (! rulesetNode.root) { rulesetNode.accept(this._visitor); visitArgs.visitDeeper = false; } if (rulesetNode.rules) { this._mergeRules(rulesetNode.rules); this._removeDuplicateRules(rulesetNode.rules); } // now decide whether we keep the ruleset if (this.utils.isVisibleRuleset(rulesetNode)) { rulesetNode.ensureVisibility(); rulesets.splice(0, 0, rulesetNode); } if (rulesets.length === 1) { return rulesets[0]; } return rulesets; }, _compileRulesetPaths: function(rulesetNode) { if (rulesetNode.paths) { rulesetNode.paths = rulesetNode.paths .filter(function(p) { var i; if (p[0].elements[0].combinator.value === ' ') { p[0].elements[0].combinator = new(tree.Combinator)(''); } for (i = 0; i < p.length; i++) { if (p[i].isVisible() && p[i].getIsOutput()) { return true; } } return false; }); } }, _removeDuplicateRules: function(rules) { if (!rules) { return; } // remove duplicates var ruleCache = {}, ruleList, rule, i; for (i = rules.length - 1; i >= 0 ; i--) { rule = rules[i]; if (rule instanceof tree.Declaration) { if (!ruleCache[rule.name]) { ruleCache[rule.name] = rule; } else { ruleList = ruleCache[rule.name]; if (ruleList instanceof tree.Declaration) { ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)]; } var ruleCSS = rule.toCSS(this._context); if (ruleList.indexOf(ruleCSS) !== -1) { rules.splice(i, 1); } else { ruleList.push(ruleCSS); } } } } }, _mergeRules: function(rules) { if (!rules) { return; } var groups = {}, groupsArr = []; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (rule.merge) { var key = rule.name; groups[key] ? rules.splice(i--, 1) : groupsArr.push(groups[key] = []); groups[key].push(rule); } } groupsArr.forEach(function(group) { if (group.length > 0) { var result = group[0], space = [], comma = [new tree.Expression(space)]; group.forEach(function(rule) { if ((rule.merge === '+') && (space.length > 0)) { comma.push(new tree.Expression(space = [])); } space.push(rule.value); result.important = result.important || rule.important; }); result.value = new tree.Value(comma); } }); } }; module.exports = ToCSSVisitor; },{"../tree":65,"./visitor":95}],95:[function(require,module,exports){ var tree = require('../tree'); var _visitArgs = { visitDeeper: true }, _hasIndexed = false; function _noop(node) { return node; } function indexNodeTypes(parent, ticker) { // add .typeIndex to tree node types for lookup table var key, child; for (key in parent) { /* eslint guard-for-in: 0 */ child = parent[key]; switch (typeof child) { case 'function': // ignore bound functions directly on tree which do not have a prototype // or aren't nodes if (child.prototype && child.prototype.type) { child.prototype.typeIndex = ticker++; } break; case 'object': ticker = indexNodeTypes(child, ticker); break; } } return ticker; } var Visitor = function(implementation) { this._implementation = implementation; this._visitInCache = {}; this._visitOutCache = {}; if (!_hasIndexed) { indexNodeTypes(tree, 1); _hasIndexed = true; } }; Visitor.prototype = { visit: function(node) { if (!node) { return node; } var nodeTypeIndex = node.typeIndex; if (!nodeTypeIndex) { // MixinCall args aren't a node type? if (node.value && node.value.typeIndex) { this.visit(node.value); } return node; } var impl = this._implementation, func = this._visitInCache[nodeTypeIndex], funcOut = this._visitOutCache[nodeTypeIndex], visitArgs = _visitArgs, fnName; visitArgs.visitDeeper = true; if (!func) { fnName = 'visit' + node.type; func = impl[fnName] || _noop; funcOut = impl[fnName + 'Out'] || _noop; this._visitInCache[nodeTypeIndex] = func; this._visitOutCache[nodeTypeIndex] = funcOut; } if (func !== _noop) { var newNode = func.call(impl, node, visitArgs); if (node && impl.isReplacing) { node = newNode; } } if (visitArgs.visitDeeper && node && node.accept) { node.accept(this); } if (funcOut != _noop) { funcOut.call(impl, node); } return node; }, visitArray: function(nodes, nonReplacing) { if (!nodes) { return nodes; } var cnt = nodes.length, i; // Non-replacing if (nonReplacing || !this._implementation.isReplacing) { for (i = 0; i < cnt; i++) { this.visit(nodes[i]); } return nodes; } // Replacing var out = []; for (i = 0; i < cnt; i++) { var evald = this.visit(nodes[i]); if (evald === undefined) { continue; } if (!evald.splice) { out.push(evald); } else if (evald.length) { this.flatten(evald, out); } } return out; }, flatten: function(arr, out) { if (!out) { out = []; } var cnt, i, item, nestedCnt, j, nestedItem; for (i = 0, cnt = arr.length; i < cnt; i++) { item = arr[i]; if (item === undefined) { continue; } if (!item.splice) { out.push(item); continue; } for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { nestedItem = item[j]; if (nestedItem === undefined) { continue; } if (!nestedItem.splice) { out.push(nestedItem); } else if (nestedItem.length) { this.flatten(nestedItem, out); } } } return out; } }; module.exports = Visitor; },{"../tree":65}],96:[function(require,module,exports){ "use strict"; // rawAsap provides everything we need except exception management. var rawAsap = require("./raw"); // RawTasks are recycled to reduce GC churn. var freeTasks = []; // We queue errors to ensure they are thrown in right order (FIFO). // Array-as-queue is good enough here, since we are just dealing with exceptions. var pendingErrors = []; var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); function throwFirstError() { if (pendingErrors.length) { throw pendingErrors.shift(); } } /** * Calls a task as soon as possible after returning, in its own event, with priority * over other events like animation, reflow, and repaint. An error thrown from an * event will not interrupt, nor even substantially slow down the processing of * other events, but will be rather postponed to a lower priority event. * @param {{call}} task A callable object, typically a function that takes no * arguments. */ module.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawAsap(rawTask); } // We wrap tasks with recyclable task objects. A task object implements // `call`, just like a function. function RawTask() { this.task = null; } // The sole purpose of wrapping the task is to catch the exception and recycle // the task object after its single use. RawTask.prototype.call = function () { try { this.task.call(); } catch (error) { if (asap.onerror) { // This hook exists purely for testing purposes. // Its name will be periodically randomized to break any code that // depends on its existence. asap.onerror(error); } else { // In a web browser, exceptions are not fatal. However, to avoid // slowing down the queue of pending tasks, we rethrow the error in a // lower priority turn. pendingErrors.push(error); requestErrorThrow(); } } finally { this.task = null; freeTasks[freeTasks.length] = this; } }; },{"./raw":97}],97:[function(require,module,exports){ (function (global){ "use strict"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including IO, animation, reflow, and redraw // events in browsers. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Equivalent to push, but avoids a function call. queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // `requestFlush` is an implementation-specific method that attempts to kick // off a `flush` event as quickly as possible. `flush` will attempt to exhaust // the event queue before yielding to the browser's own event loop. var requestFlush; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory exhaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } // `requestFlush` is implemented using a strategy based on data collected from // every available SauceLabs Selenium web driver worker at time of writing. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that // have WebKitMutationObserver but not un-prefixed MutationObserver. // Must use `global` or `self` instead of `window` to work in both frames and web // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. /* globals self */ var scope = typeof global !== "undefined" ? global : self; var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; // MutationObservers are desirable because they have high priority and work // reliably everywhere they are implemented. // They are implemented in all modern browsers. // // - Android 4-4.3 // - Chrome 26-34 // - Firefox 14-29 // - Internet Explorer 11 // - iPad Safari 6-7.1 // - iPhone Safari 7-7.1 // - Safari 6-7 if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); // MessageChannels are desirable because they give direct access to the HTML // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera // 11-12, and in web workers in many engines. // Although message channels yield to any queued rendering and IO tasks, they // would be better than imposing the 4ms delay of timers. // However, they do not work reliably in Internet Explorer or Safari. // Internet Explorer 10 is the only browser that has setImmediate but does // not have MutationObservers. // Although setImmediate yields to the browser's renderer, it would be // preferrable to falling back to setTimeout since it does not have // the minimum 4ms penalty. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and // Desktop to a lesser extent) that renders both setImmediate and // MessageChannel useless for the purposes of ASAP. // https://github.com/kriskowal/q/issues/396 // Timers are implemented universally. // We fall back to timers in workers in most engines, and in foreground // contexts in the following browsers. // However, note that even this simple case requires nuances to operate in a // broad spectrum of browsers. // // - Firefox 3-13 // - Internet Explorer 6-9 // - iPad Safari 4.3 // - Lynx 2.8.7 } else { requestFlush = makeRequestCallFromTimer(flush); } // `requestFlush` requests that the high priority event queue be flushed as // soon as possible. // This is useful to prevent an error thrown in a task from stalling the event // queue if the exception handled by Node.js’s // `process.on("uncaughtException")` or by a domain. rawAsap.requestFlush = requestFlush; // To request a high priority event, we induce a mutation observer by toggling // the text of a text node between "1" and "-1". function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; } // The message channel technique was discovered by Malte Ubl and was the // original foundation for this library. // http://www.nonblocking.io/2011/06/windownexttick.html // Safari 6.0.5 (at least) intermittently fails to create message ports on a // page's first load. Thankfully, this version of Safari supports // MutationObservers, so we don't need to fall back in that case. // function makeRequestCallFromMessageChannel(callback) { // var channel = new MessageChannel(); // channel.port1.onmessage = callback; // return function requestCall() { // channel.port2.postMessage(0); // }; // } // For reasons explained above, we are also unable to use `setImmediate` // under any circumstances. // Even if we were, there is another bug in Internet Explorer 10. // It is not sufficient to assign `setImmediate` to `requestFlush` because // `setImmediate` must be called *by name* and therefore must be wrapped in a // closure. // Never forget. // function makeRequestCallFromSetImmediate(callback) { // return function requestCall() { // setImmediate(callback); // }; // } // Safari 6.0 has a problem where timers will get lost while the user is // scrolling. This problem does not impact ASAP because Safari 6.0 supports // mutation observers, so that implementation is used instead. // However, if we ever elect to use timers in Safari, the prevalent work-around // is to add a scroll event listener that calls for a flush. // `setTimeout` does not call the passed callback if the delay is less than // approximately 7 in web workers in Firefox 8 through 18, and sometimes not // even then. function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } // This is for `asap.js` only. // Its name will be periodically randomized to break any code that depends on // its existence. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; // ASAP was originally a nextTick shim included in Q. This was factored out // into this ASAP package. It was later adapted to RSVP which made further // amendments. These decisions, particularly to marginalize MessageChannel and // to capture the MutationObserver implementation in a closure, were integrated // back into ASAP proper. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],98:[function(require,module,exports){ 'use strict'; var asap = require('asap/raw'); function noop() {} // States: // // 0 - pending // 1 - fulfilled with _value // 2 - rejected with _value // 3 - adopted the state of another promise, _value // // once the state is no longer pending (0) it is immutable // All `_` prefixed properties will be reduced to `_{random number}` // at build time to obfuscate them and discourage their use. // We don't use symbols or Object.defineProperty to fully hide them // because the performance isn't good enough. // to avoid using try/catch inside critical functions, we // extract them to here. var LAST_ERROR = null; var IS_ERROR = {}; function getThen(obj) { try { return obj.then; } catch (ex) { LAST_ERROR = ex; return IS_ERROR; } } function tryCallOne(fn, a) { try { return fn(a); } catch (ex) { LAST_ERROR = ex; return IS_ERROR; } } function tryCallTwo(fn, a, b) { try { fn(a, b); } catch (ex) { LAST_ERROR = ex; return IS_ERROR; } } module.exports = Promise; function Promise(fn) { if (typeof this !== 'object') { throw new TypeError('Promises must be constructed via new'); } if (typeof fn !== 'function') { throw new TypeError('Promise constructor\'s argument is not a function'); } this._40 = 0; this._65 = 0; this._55 = null; this._72 = null; if (fn === noop) return; doResolve(fn, this); } Promise._37 = null; Promise._87 = null; Promise._61 = noop; Promise.prototype.then = function(onFulfilled, onRejected) { if (this.constructor !== Promise) { return safeThen(this, onFulfilled, onRejected); } var res = new Promise(noop); handle(this, new Handler(onFulfilled, onRejected, res)); return res; }; function safeThen(self, onFulfilled, onRejected) { return new self.constructor(function (resolve, reject) { var res = new Promise(noop); res.then(resolve, reject); handle(self, new Handler(onFulfilled, onRejected, res)); }); } function handle(self, deferred) { while (self._65 === 3) { self = self._55; } if (Promise._37) { Promise._37(self); } if (self._65 === 0) { if (self._40 === 0) { self._40 = 1; self._72 = deferred; return; } if (self._40 === 1) { self._40 = 2; self._72 = [self._72, deferred]; return; } self._72.push(deferred); return; } handleResolved(self, deferred); } function handleResolved(self, deferred) { asap(function() { var cb = self._65 === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { if (self._65 === 1) { resolve(deferred.promise, self._55); } else { reject(deferred.promise, self._55); } return; } var ret = tryCallOne(cb, self._55); if (ret === IS_ERROR) { reject(deferred.promise, LAST_ERROR); } else { resolve(deferred.promise, ret); } }); } function resolve(self, newValue) { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) { return reject( self, new TypeError('A promise cannot be resolved with itself.') ); } if ( newValue && (typeof newValue === 'object' || typeof newValue === 'function') ) { var then = getThen(newValue); if (then === IS_ERROR) { return reject(self, LAST_ERROR); } if ( then === self.then && newValue instanceof Promise ) { self._65 = 3; self._55 = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(then.bind(newValue), self); return; } } self._65 = 1; self._55 = newValue; finale(self); } function reject(self, newValue) { self._65 = 2; self._55 = newValue; if (Promise._87) { Promise._87(self, newValue); } finale(self); } function finale(self) { if (self._40 === 1) { handle(self, self._72); self._72 = null; } if (self._40 === 2) { for (var i = 0; i < self._72.length; i++) { handle(self, self._72[i]); } self._72 = null; } } function Handler(onFulfilled, onRejected, promise){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, promise) { var done = false; var res = tryCallTwo(fn, function (value) { if (done) return; done = true; resolve(promise, value); }, function (reason) { if (done) return; done = true; reject(promise, reason); }); if (!done && res === IS_ERROR) { done = true; reject(promise, LAST_ERROR); } } },{"asap/raw":97}],99:[function(require,module,exports){ 'use strict'; //This file contains the ES6 extensions to the core Promises/A+ API var Promise = require('./core.js'); module.exports = Promise; /* Static Functions */ var TRUE = valuePromise(true); var FALSE = valuePromise(false); var NULL = valuePromise(null); var UNDEFINED = valuePromise(undefined); var ZERO = valuePromise(0); var EMPTYSTRING = valuePromise(''); function valuePromise(value) { var p = new Promise(Promise._61); p._65 = 1; p._55 = value; return p; } Promise.resolve = function (value) { if (value instanceof Promise) return value; if (value === null) return NULL; if (value === undefined) return UNDEFINED; if (value === true) return TRUE; if (value === false) return FALSE; if (value === 0) return ZERO; if (value === '') return EMPTYSTRING; if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then; if (typeof then === 'function') { return new Promise(then.bind(value)); } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex); }); } } return valuePromise(value); }; Promise.all = function (arr) { var args = Array.prototype.slice.call(arr); return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { if (val && (typeof val === 'object' || typeof val === 'function')) { if (val instanceof Promise && val.then === Promise.prototype.then) { while (val._65 === 3) { val = val._55; } if (val._65 === 1) return res(i, val._55); if (val._65 === 2) reject(val._55); val.then(function (val) { res(i, val); }, reject); return; } else { var then = val.then; if (typeof then === 'function') { var p = new Promise(then.bind(val)); p.then(function (val) { res(i, val); }, reject); return; } } } args[i] = val; if (--remaining === 0) { resolve(args); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); }; Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }); }); }; /* Prototype Methods */ Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; },{"./core.js":98}],100:[function(require,module,exports){ // should work in any browser without browserify if (typeof Promise.prototype.done !== 'function') { Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { setTimeout(function () { throw err }, 0) }) } } },{}],101:[function(require,module,exports){ // not "use strict" so we can declare global "Promise" var asap = require('asap'); if (typeof Promise === 'undefined') { Promise = require('./lib/core.js') require('./lib/es6-extensions.js') } require('./polyfill-done.js'); },{"./lib/core.js":98,"./lib/es6-extensions.js":99,"./polyfill-done.js":100,"asap":96}]},{},[2])(2) });
extend1994/cdnjs
ajax/libs/less.js/3.5.0-beta.6/less.js
JavaScript
mit
435,251
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TransitionIndicator = void 0; /** @internal */ class TransitionIndicator { constructor() { this._element = document.createElement('div'); this._element.classList.add("lm_transition_indicator" /* TransitionIndicator */); document.body.appendChild(this._element); this._toElement = null; this._fromDimensions = null; this._totalAnimationDuration = 200; this._animationStartTime = null; } destroy() { this._element.remove(); } // eslint-disable-next-line @typescript-eslint/no-unused-vars transitionElements(fromElement, toElement) { /** * TODO - This is not quite as cool as expected. Review. */ return; // this._toElement = toElement; // this._animationStartTime = now(); // this._fromDimensions = this._measure(fromElement); // this._fromDimensions.opacity = 0.8; // this._element.show().css(this._fromDimensions); // animFrame(fnBind(this._nextAnimationFrame, this)); } nextAnimationFrame() { // if (this._toElement === null || this._fromDimensions === null || this._animationStartTime === null) { // throw new UnexpectedNullError('TINAFTD97115'); // } else { // const toDimensions = this.measure(this._toElement); // const animationProgress = (now() - this._animationStartTime) / this._totalAnimationDuration; // const currentFrameStyles = {}; // const cssProperty; // if (animationProgress >= 1) { // this._element.style.display = 'none'; // return; // } // toDimensions.opacity = 0; // for (const cssProperty in this._fromDimensions) { // currentFrameStyles[cssProperty] = this._fromDimensions[cssProperty] + // (toDimensions[cssProperty] - this._fromDimensions[cssProperty]) * // animationProgress; // } // this._element.css(currentFrameStyles); // animFrame(fnBind(this._nextAnimationFrame, this)); // } } measure(element) { const rect = element.getBoundingClientRect(); return { left: rect.left, top: rect.top, width: element.offsetWidth, height: element.offsetHeight, }; } } exports.TransitionIndicator = TransitionIndicator; //# sourceMappingURL=transition-indicator.js.map
cdnjs/cdnjs
ajax/libs/golden-layout/2.2.1/cjs/ts/controls/transition-indicator.js
JavaScript
mit
2,585
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PolygonDrawer = void 0; var tslib_1 = require("tslib"); var PolygonDrawerBase_1 = require("./PolygonDrawerBase"); var PolygonDrawer = (function (_super) { tslib_1.__extends(PolygonDrawer, _super); function PolygonDrawer() { return _super !== null && _super.apply(this, arguments) || this; } PolygonDrawer.prototype.getSidesData = function (particle, radius) { var _a, _b; var polygon = particle.shapeData; var sides = (_b = (_a = polygon === null || polygon === void 0 ? void 0 : polygon.sides) !== null && _a !== void 0 ? _a : polygon === null || polygon === void 0 ? void 0 : polygon.nb_sides) !== null && _b !== void 0 ? _b : 5; return { count: { denominator: 1, numerator: sides, }, length: (radius * 2.66) / (sides / 3), }; }; PolygonDrawer.prototype.getCenter = function (particle, radius) { var _a, _b; var polygon = particle.shapeData; var sides = (_b = (_a = polygon === null || polygon === void 0 ? void 0 : polygon.sides) !== null && _a !== void 0 ? _a : polygon === null || polygon === void 0 ? void 0 : polygon.nb_sides) !== null && _b !== void 0 ? _b : 5; return { x: -radius / (sides / 3.5), y: -radius / (2.66 / 3.5), }; }; return PolygonDrawer; }(PolygonDrawerBase_1.PolygonDrawerBase)); exports.PolygonDrawer = PolygonDrawer;
cdnjs/cdnjs
ajax/libs/tsparticles/1.15.0-alpha.8/ShapeDrawers/PolygonDrawer.js
JavaScript
mit
1,541
/* * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * JDK-8069338: Implement sharedScopeCall for optimistic types * * @test * @run */ var c = 0; var n = 1; function f() { return c++ > 10 ? 'f' : 1; } function h() { var x = 0; x += n; x += n; x += n; x += n; x += n; x += n; x += n; x += n; x += n; x += n; x += n; n = 'b'; x += n; x += n; x += n; x += n; x += n; x += n; return x; } function g() { var x = 0; x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); x += f(); return x; } Assert.assertEquals(h(), '11bbbbbb'); Assert.assertEquals(g(), '11ffffff');
md-5/jdk10
test/nashorn/script/basic/JDK-8069338.js
JavaScript
gpl-2.0
1,846
jQuery(function($){$(".siteorigin-premium-teaser").has(".teaser-image").mouseenter(function(){var $$=$(this).find(".teaser-image");if($$.is(":hover"))return;$$.fadeIn(100)}).mouseleave(function(){$(this).find(".teaser-image").clearQueue().fadeOut(100)})});
dconcepcion79/WordPress_TestBuild
wp-content/themes/vantage/extras/premium/js/premium-teaser.min.js
JavaScript
gpl-2.0
256
<script type="text/javascript"><!-- function rowOverEffect(object) { if (object.className == 'moduleRow') object.className = 'moduleRowOver'; } function rowOutEffect(object) { if (object.className == 'moduleRowOver') object.className = 'moduleRow'; } function checkBox(object) { document.account_newsletter.elements[object].checked = !document.account_newsletter.elements[object].checked; } //--></script>
loadedcommerce/Loaded6CE
Loaded_Commerce_CE/includes/javascript/account_newsletters.js
JavaScript
gpl-2.0
414
import _ from "lodash"; import { Meteor } from "meteor/meteor"; /** * Callback hooks to alter the behavior of common operations or trigger other things. * @namespace Hooks.Events */ const Hooks = {}; Hooks.Events = {}; /** * Add a callback function to a hook * @param {String} name - The name of the hook * @param {Function} callback - The callback function * @return {Array} array of the currently defined hooks */ Hooks.Events.add = (name, callback) => { // if callback array doesn't exist yet, initialize it if (typeof Hooks.Events[name] === "undefined") { Hooks.Events[name] = []; } return Hooks.Events[name].push(callback); }; /** * Remove a callback from a hook * @param {String} name - The name of the hook * @param {String} callbackName - The name of the function to remove * @return {Array} array of remaining callbacks */ Hooks.Events.remove = (name, callbackName) => { Hooks.Events[name] = _.reject(Hooks.Events[name], (callback) => { return callback.name === callbackName; }); return Hooks.Events; }; /** * Successively run all of a hook's callbacks on an item * @param {String} name - The name of the hook * @param {Object} item - The object, modifier, etc. on which to run the callbacks * @param {Object} [constant] - An optional constant that will be passed along to each callback * @return {Object} Returns the item after it has been through all callbacks for this hook */ Hooks.Events.run = (name, item, constant) => { const callbacks = Hooks.Events[name]; // if the hook exists, and contains callbacks to run if (typeof callbacks !== "undefined" && !!callbacks.length) { return callbacks.reduce((result, callback) => { return callback(result, constant); }, item); } return item; }; /** * Successively run all of a hook's callbacks on an item, in async mode (only works on server) * @param {String} name - The name of the hook * @param {Object} item - The object, modifier, etc. on which to run the callbacks * @param {Object} [constant] - An optional constant that will be passed along to each callback * @return {Object} Returns the item after it has been through all callbacks for this hook */ Hooks.Events.runAsync = (name, item, constant) => { const callbacks = Hooks.Events[name]; if (Meteor.isServer && typeof callbacks !== "undefined" && !!callbacks.length) { // use defer to avoid holding up client Meteor.defer(() => { // run all async server callbacks successively on object callbacks.forEach((callback) => { callback(item, constant); }); }); } return item; }; export default Hooks;
spestushko/reaction
server/api/hooks.js
JavaScript
gpl-3.0
2,641
$(function(){var url=location.pathname;url=url.substring($('body').data('locale-root'),url.length);url=url.replace(/\/*$/,'');$.ajax({url:$('body').data('site-root')+'_tracking',type:'POST',data:{url:url,type:'page'},timeout:300});$('a.resource-url-analytics').click(function(e){var url=$(e.target).closest('a').attr('href');$.ajax({url:$('body').data('site-root')+'_tracking',data:{url:url,type:'resource'},type:'POST',complete:function(){location.href=url;},timeout:30});e.preventDefault();});});
nucleo-digital/ckan-theme-cmbd
public/base/javascript/tracking.min.js
JavaScript
gpl-3.0
498
import { clickable, fillable } from 'ember-cli-page-object'; import fields from '../form-field'; export default { ...fields, ttlValue: fillable('[data-test-ttl-value]'), ttlUnit: fillable('[data-test-ttl-value]'), save: clickable('[data-test-save-config]'), };
joelthompson/vault
ui/tests/pages/components/auth-config-form/options.js
JavaScript
mpl-2.0
270
/** * Advanced OpenWorkflow, Automating SugarCRM. * @package Advanced OpenWorkflow for SugarCRM * @copyright SalesAgility Ltd http://www.salesagility.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE * along with this program; if not, see http://www.gnu.org/licenses * or write to the Free Software Foundation,Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA * * @author SalesAgility <info@salesagility.com> */ var cr_fields = new Array(); var cr_relationships = new Array(); var cr_module = new Array(); var crln = new Array(); var crreln = new Array(); function show_crModuleFields(ln){ clear_crLines(ln); cr_module[ln] = document.getElementById('aow_actions_param_record_type'+ln).value; if(cr_module[ln] != ''){ var callback = { success: function(result) { cr_fields[ln] = result.responseText; //add_crLine(ln); document.getElementById('addcrline'+ln).style.display = ''; //document.getElementById('aow_action_div'+ln).innerHTML ="<select tabindex='116' name='service_vat[]' id='service_vat'>" + cr_fields[ln] + "</select>"; } } var callback2 = { success: function(result) { cr_relationships[ln] = result.responseText; //add_crLine(ln); document.getElementById('addcrrelline'+ln).style.display = ''; //document.getElementById('aow_action_div'+ln).innerHTML ="<select tabindex='116' name='service_vat[]' id='service_vat'>" + cr_fields[ln] + "</select>"; } } YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getModuleFields&aow_module="+cr_module[ln],callback); YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getModuleRelationships&aow_module="+cr_module[ln],callback2); } } function show_crModuleField(ln, cln, value, type_value){ if (typeof value === 'undefined') { value = ''; } if (typeof type_value === 'undefined') { type_value = ''; } flow_module = document.getElementById('flow_module').value; var aow_field = document.getElementById('aow_actions_param'+ln+'_field'+cln).value; if(aow_field != ''){ var callback = { success: function(result) { document.getElementById('crLine'+ln+'_fieldType'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); document.getElementById('crLine'+ln+'_fieldType'+cln).onchange = function(){show_crModuleFieldType(ln, cln);}; }, failure: function(result) { document.getElementById('crLine'+ln+'_fieldType'+cln).innerHTML = ''; } } var callback2 = { success: function(result) { document.getElementById('crLine'+ln+'_field'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); }, failure: function(result) { document.getElementById('crLine'+ln+'_field'+cln).innerHTML = ''; } } var aow_field_name = "aow_actions_param["+ln+"][value]["+cln+"]"; var aow_field_type_name = "aow_actions_param["+ln+"][value_type]["+cln+"]"; YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getActionFieldTypeOptions&aow_module="+cr_module[ln]+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_type_name+"&aow_value="+type_value,callback); YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getModuleFieldTypeSet&aow_module="+cr_module[ln]+"&alt_module="+flow_module+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_name+"&aow_value="+value+"&aow_type="+type_value,callback2); } else { document.getElementById('crLine'+ln+'_fieldType'+cln).innerHTML = ''; document.getElementById('crLine'+ln+'_field'+cln).innerHTML = ''; } } function show_crModuleFieldType(ln, cln, value){ if (typeof value === 'undefined') { value = ''; } var callback = { success: function(result) { document.getElementById('crLine'+ln+'_field'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); }, failure: function(result) { document.getElementById('crLine'+ln+'_field'+cln).innerHTML = ''; } } flow_module = document.getElementById('flow_module').value; var aow_field = document.getElementById('aow_actions_param'+ln+'_field'+cln).value; var type_value = document.getElementById("aow_actions_param["+ln+"][value_type]["+cln+"]").value; var aow_field_name = "aow_actions_param["+ln+"][value]["+cln+"]"; YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getModuleFieldTypeSet&aow_module="+cr_module[ln]+"&alt_module="+flow_module+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_name+"&aow_value="+value+"&aow_type="+type_value,callback); } function load_crline(ln, field, value, value_type){ document.getElementById('addcrline'+ln).style.display = ''; document.getElementById('addcrrelline'+ln).style.display = ''; cln = add_crLine(ln); document.getElementById("aow_actions_param"+ln+"_field"+cln).value = field; show_crModuleField(ln, cln, value, value_type); } function show_crRelField(ln, cln, value, type_value){ if (typeof value === 'undefined') { value = ''; } if (typeof type_value === 'undefined') { type_value = ''; } flow_module = document.getElementById('flow_module').value; var aow_field = document.getElementById('aow_actions_param'+ln+'_rel'+cln).value; if(aow_field != ''){ var callback = { success: function(result) { document.getElementById('crRelLine'+ln+'_fieldType'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); document.getElementById('crRelLine'+ln+'_fieldType'+cln).onchange = function(){show_crRelFieldType(ln, cln);}; }, failure: function(result) { document.getElementById('crRelLine'+ln+'_fieldType'+cln).innerHTML = ''; } } var callback2 = { success: function(result) { document.getElementById('crRelLine'+ln+'_field'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); }, failure: function(result) { document.getElementById('crRelLine'+ln+'_field'+cln).innerHTML = ''; } } var aow_field_name = "aow_actions_param["+ln+"][rel_value]["+cln+"]"; var aow_field_type_name = "aow_actions_param["+ln+"][rel_value_type]["+cln+"]"; YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getActionFieldTypeOptions&aow_module="+cr_module[ln]+"&alt_module="+flow_module+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_type_name+"&aow_value="+type_value,callback); YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getRelFieldTypeSet&aow_module="+cr_module[ln]+"&alt_module="+flow_module+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_name+"&aow_value="+value+"&aow_type="+type_value,callback2); } else { document.getElementById('crRelLine'+ln+'_fieldType'+cln).innerHTML = ''; document.getElementById('crRelLine'+ln+'_field'+cln).innerHTML = ''; } } function show_crRelFieldType(ln, cln, value){ if (typeof value === 'undefined') { value = ''; } var callback = { success: function(result) { document.getElementById('crRelLine'+ln+'_field'+cln).innerHTML = result.responseText; SUGAR.util.evalScript(result.responseText); enableQS(false); }, failure: function(result) { document.getElementById('crRelLine'+ln+'_field'+cln).innerHTML = ''; } } flow_module = document.getElementById('flow_module').value; var aow_field = document.getElementById('aow_actions_param'+ln+'_rel'+cln).value; var type_value = document.getElementById("aow_actions_param["+ln+"][rel_value_type]["+cln+"]").value; var aow_field_name = "aow_actions_param["+ln+"][rel_value]["+cln+"]"; YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOW_WorkFlow&action=getModuleFieldTypeSet&aow_module="+cr_module[ln]+"&alt_module="+flow_module+"&aow_fieldname="+aow_field+"&aow_newfieldname="+aow_field_name+"&aow_value="+value+"&aow_type="+type_value,callback); } function load_crrelline(ln, field, value, value_type){ document.getElementById('addcrline'+ln).style.display = ''; document.getElementById('addcrrelline'+ln).style.display = ''; cln = add_crRelLine(ln); document.getElementById("aow_actions_param"+ln+"_rel"+cln).value = field; show_crRelField(ln, cln, value, value_type); } function add_crLine(ln){ if(crln[ln] == null){crln[ln] = 0} /*if (document.getElementById(tableid + '_head') != null) { document.getElementById(tableid + '_head').style.display = ""; }*/ tablebody = document.createElement("tbody"); tablebody.id = 'crLine'+ln+'_body' + crln[ln]; document.getElementById('crLine'+ln+'_table').appendChild(tablebody); var x = tablebody.insertRow(-1); x.id = 'crLine'+ln+'_line' + crln[ln]; var a = x.insertCell(0); a.innerHTML = "<button type='button' id='crLine"+ln+"_delete" + crln[ln]+"' class='button' value='Remove Line' tabindex='116' onclick='clear_crLine(" + ln + ",this);'><img src='themes/default/images/id-ff-remove-nobg.png' alt='Remove Line'></button>"; var b = x.insertCell(1); b.innerHTML = "<select tabindex='116' name='aow_actions_param["+ln+"][field]["+crln[ln]+"]' id='aow_actions_param"+ln+"_field"+crln[ln]+"' onchange='show_crModuleField(" + ln + "," + crln[ln] + ");'>" + cr_fields[ln] + "</select>"; var c = x.insertCell(2); c.id = 'crLine'+ln+'_fieldType' + crln[ln]; var d = x.insertCell(3); d.id = 'crLine'+ln+'_field' + crln[ln]; crln[ln]++; return crln[ln] -1; } function clear_crLine(ln, cln){ document.getElementById('crLine'+ln+'_table').deleteRow(cln.parentNode.parentNode.rowIndex); } function add_crRelLine(ln){ if(crreln[ln] == null){crreln[ln] = 0} /*if (document.getElementById(tableid + '_head') != null) { document.getElementById(tableid + '_head').style.display = ""; }*/ tablebody = document.createElement("tbody"); tablebody.id = 'crRelLine'+ln+'_body' + crreln[ln]; document.getElementById('crRelLine'+ln+'_table').appendChild(tablebody); var x = tablebody.insertRow(-1); x.id = 'crRelLine'+ln+'_line' + crreln[ln]; var a = x.insertCell(0); a.innerHTML = "<button type='button' id='crRelLine"+ln+"_delete" + crreln[ln]+"' class='button' value='Remove Line' tabindex='116' onclick='clear_crRelLine(" + ln + ",this);'><img src='themes/default/images/id-ff-remove-nobg.png' alt='Remove Line'></button>"; var b = x.insertCell(1); b.innerHTML = "<select tabindex='116' name='aow_actions_param["+ln+"][rel]["+crreln[ln]+"]' id='aow_actions_param"+ln+"_rel"+crreln[ln]+"' onchange='show_crRelField(" + ln + "," + crreln[ln] + ");'>" + cr_relationships[ln] + "</select>"; var c = x.insertCell(2); c.id = 'crRelLine'+ln+'_fieldType' + crreln[ln]; var d = x.insertCell(3); d.id = 'crRelLine'+ln+'_field' + crreln[ln]; crreln[ln]++; return crreln[ln] -1; } function clear_crRelLine(ln, cln){ document.getElementById('crRelLine'+ln+'_table').deleteRow(cln.parentNode.parentNode.rowIndex); } function clear_crLines(ln){ var cr_rows = document.getElementById('crLine'+ln+'_table').getElementsByTagName('tr'); var cr_row_length = cr_rows.length; var i; for (i=0; i < cr_row_length; i++) { document.getElementById('crLine'+ln+'_table').deleteRow(cr_rows[i]); } var cr_rel_rows = document.getElementById('crRelLine'+ln+'_table').getElementsByTagName('tr'); var cr_rel_row_length = cr_rel_rows.length; var i; for (i=0; i < cr_rel_row_length; i++) { document.getElementById('crRelLine'+ln+'_table').deleteRow(cr_rel_rows [i]); } document.getElementById('addcrline'+ln).style.display = 'none'; document.getElementById('addcrrelline'+ln).style.display = 'none'; } function hideElem(id){ if(document.getElementById(id)){ document.getElementById(id).style.display = "none"; document.getElementById(id).value = ""; } } function showElem(id){ if(document.getElementById(id)){ document.getElementById(id).style.display = ""; } } function assign_field_change(field){ hideElem(field + '[1]'); hideElem(field + '[2]'); if(document.getElementById(field + '[0]').value == 'role'){ showElem(field + '[2]'); } else if(document.getElementById(field + '[0]').value == 'security_group'){ showElem(field + '[1]'); showElem(field + '[2]'); } } function date_field_change(field){ if(document.getElementById(field + '[1]').value == 'now'){ hideElem(field + '[2]'); hideElem(field + '[3]'); } else { showElem(field + '[2]'); showElem(field + '[3]'); } }
ben-github/SuiteCRM
modules/AOW_Actions/actions/actionCreateRecord.js
JavaScript
agpl-3.0
14,151
putCshData(gsProjPath,gaCsh,gaWindow,gaRmtProj);
SuperMap/iClient-Android-Example
help/html/mergedProjects/forAndroidJavaDoc/whcshdata.js
JavaScript
apache-2.0
53
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const INVALID_PROPS = [ 'EPSILON', 'MAX_SAFE_INTEGER', 'MIN_SAFE_INTEGER', 'isFinite', 'isInteger', 'isNaN', 'isSafeInteger', 'parseFloat', 'parseInt', ]; /** * @param {string} property * @return {boolean} */ function isInvalidProperty(property) { return INVALID_PROPS.indexOf(property) != -1; } module.exports = function (context) { return { MemberExpression: function (node) { if ( node.object.name == 'Number' && isInvalidProperty(node.property.name) ) { context.report({ node, message: 'no ES2015 "Number" methods and properties allowed to be ' + 'used.', }); } }, }; };
prateekbh/amphtml
build-system/eslint-rules/no-es2015-number-props.js
JavaScript
apache-2.0
1,349
'use strict'; var $ = require('../internals/export'); var IS_PURE = require('../internals/is-pure'); var getBuiltIn = require('../internals/get-built-in'); var anObject = require('../internals/an-object'); var aFunction = require('../internals/a-function'); var bind = require('../internals/bind-context'); var speciesConstructor = require('../internals/species-constructor'); var getMapIterator = require('../internals/get-map-iterator'); var iterate = require('../internals/iterate'); // `Map.prototype.mapKeys` method // https://github.com/tc39/proposal-collection-methods $({ target: 'Map', proto: true, real: true, forced: IS_PURE }, { mapKeys: function mapKeys(callbackfn /* , thisArg */) { var map = anObject(this); var iterator = getMapIterator(map); var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var newMap = new (speciesConstructor(map, getBuiltIn('Map')))(); var setter = aFunction(newMap.set); iterate(iterator, function (key, value) { setter.call(newMap, boundFunction(value, key, map), value); }, undefined, true, true); return newMap; } });
ChromeDevTools/devtools-node-modules
third_party/node_modules/core-js/modules/esnext.map.map-keys.js
JavaScript
apache-2.0
1,143
// Copyright (C) 2014 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 14.5.3 description: > computed property generator method names can be called "constructor" ---*/ class C4 { *['constructor']() {} }
sebastienros/jint
Jint.Tests.Test262/test/language/computed-property-names/class/method/constructor-can-be-generator.js
JavaScript
bsd-2-clause
289
/** * 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 EventPluginRegistry * @flow */ 'use strict'; import type { DispatchConfig, ReactSyntheticEvent, } from 'ReactSyntheticEventType'; import type { AnyNativeEvent, PluginName, PluginModule, } from 'PluginModuleType'; type NamesToPlugins = {[key: PluginName]: PluginModule<AnyNativeEvent>}; type EventPluginOrder = null | Array<PluginName>; var invariant = require('invariant'); /** * Injectable ordering of event plugins. */ var eventPluginOrder: EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins: NamesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering(): void { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName, ); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } invariant( pluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName, ); EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { invariant( publishEventForPlugin( publishedEvents[eventName], pluginModule, eventName, ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName, ); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin( dispatchConfig: DispatchConfig, pluginModule: PluginModule<AnyNativeEvent>, eventName: string, ): boolean { invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName, ); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, pluginModule, eventName, ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, pluginModule, eventName, ); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName( registrationName: string, pluginModule: PluginModule<AnyNativeEvent>, eventName: string, ): void { invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName, ); EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if (__DEV__) { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: __DEV__ ? {} : (null: any), // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function( injectedEventPluginOrder: EventPluginOrder, ): void { invariant( !eventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.', ); // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function( injectedNamesToPlugins: NamesToPlugins ): void { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName, ); namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function( event: ReactSyntheticEvent, ): null | PluginModule<AnyNativeEvent> { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var {phasedRegistrationNames} = dispatchConfig; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[ phasedRegistrationNames[phase] ]; if (pluginModule) { return pluginModule; } } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function(): void { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (__DEV__) { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } }, }; module.exports = EventPluginRegistry;
staltz/react
src/renderers/shared/stack/event/EventPluginRegistry.js
JavaScript
bsd-3-clause
9,997
var mdeps = require('../'); var test = require('tape'); var JSONStream = require('JSONStream'); var packer = require('browser-pack'); var concat = require('concat-stream'); test('global transforms', function (t) { t.plan(1); var p = mdeps(__dirname + '/files/tr_global/main.js', { transform: [ 'tr-c', 'tr-d' ], globalTransform: [ __dirname + '/files/tr_global/node_modules/tr-e', __dirname + '/files/tr_global/node_modules/tr-f' ], transformKey: [ 'browserify', 'transform' ] }); var pack = packer(); p.pipe(JSONStream.stringify()).pipe(pack).pipe(concat(function (src) { Function(['console'], src)({ log: function (msg) { t.equal(msg, 111111); } }); })); });
frangucc/gamify
www/sandbox/pals/node_modules/cordova/node_modules/cordova-lib/node_modules/cordova-js/node_modules/browserify/node_modules/module-deps/test/tr_global.js
JavaScript
mit
808
define(['aeris/util'], function(_) { /** * Logical operators for use in constructing * queries included in Aeris API requests. * * @class aeris.api.Operator * @static */ var Operators = { AND: 'AND', OR: 'OR' }; return _.expose(Operators, 'aeris.api.Operator'); });
MikeLockz/exit-now-mobile
www/lib/aerisjs/src/api/operator.js
JavaScript
mit
302
define( //begin v1.x content { "HKD_displayName": "Dólar de Hong Kong", "CNY_displayName": "Yuan chinês", "JPY_displayName": "Iene japonês", "JPY_symbol": "JP¥", "USD_displayName": "Dólar americano", "CAD_symbol": "CA$", "GBP_displayName": "Libra esterlina", "CHF_displayName": "Franco suíço", "CNY_symbol": "CN¥", "EUR_displayName": "Euro", "GBP_symbol": "£", "CAD_displayName": "Dólar canadense", "USD_symbol": "US$", "EUR_symbol": "€", "AUD_displayName": "Dólar australiano", "CHF_symbol": "CHF", "HKD_symbol": "HK$", "AUD_symbol": "AU$" } //end v1.x content );
cdnjs/cdnjs
ajax/libs/dojo/1.17.1/cldr/nls/pt/currency.js
JavaScript
mit
595
addModule('RESMenu', function(module, moduleID) { module.moduleName = 'RES Menu'; module.category = 'Core'; module.description = 'The <span class="gearIcon"></span> dropdown menu to manage RES settings and quick options'; module.alwaysEnabled = true; module.hidden = true; module.beforeLoad = function() { renderConsoleLink(); }; module.go = function() { addConsoleLink(); }; module.afterLoad = function() { addLegacyStyling(); }; var menuItems = $(); function renderConsoleLink() { var RESPrefsLink = $('<span id="openRESPrefs"><span id="RESSettingsButton" title="RES Settings" class="gearIcon"></span>') .mouseenter(module.showPrefsDropdown.bind(module)); module.RESPrefsLink = RESPrefsLink[0]; } function addConsoleLink() { module.userMenu = document.querySelector('#header-bottom-right'); $(module.userMenu).find('ul').after(module.RESPrefsLink).after('<span class="separator">|</span>'); } module.showPrefsDropdown = function() { modules['hover'].dropdownList(moduleID, modules['hover'].HIDDEN_FROM_SETTINGS) .options({ openDelay: 200, fadeDelay: 200, fadeSpeed: 0.2 }) .populateWith(populateDropdown) .target(module.RESPrefsLink.querySelector('#RESSettingsButton')) // workaround subreddit stylings where the container ends up super tall .begin(); }; module.hidePrefsDropdown = function() { modules['hover'].dropdownList(moduleID).close(true); }; function populateDropdown(def, base, context) { def.resolve(menuItems); } module.addMenuItem = function (ele, onClick, prepend) { var menuItem = $(ele); if (!menuItem.is('li')) { menuItem = $('<li />').append(ele); } menuItem[0].addEventListener('click', onClick); if (prepend) { menuItems = menuItem.add(menuItems); } else { menuItems = menuItems.add(menuItem); } }; function getMenuButton() { return $(module.RESPrefsLink).find('.gearIcon'); } module.setNewNotification = function(callback, isImportant) { var gearIcon = getMenuButton(); gearIcon.addClass('newNotification'); module.onClickMenuButton(callback, isImportant); if (isImportant) { gearIcon.addClass('important'); } }; var onClickMenuButton; module.onClickMenuButton = function(callback, isImportant) { var menuButton = getMenuButton(); if (!onClickMenuButton || (isImportant && !onClickMenuButton.isImportant)) { onClickMenuButton = $.Callbacks(); onClickMenuButton.add(module.hidePrefsDropdown.bind(module)); if (isImportant) { onClickMenuButton.isImportant = isImportant; } } if (isImportant || !onClickMenuButton.isImportant) { onClickMenuButton.add(callback); } menuButton.on('click', onClickMenuButton.fire); }; function addLegacyStyling() { var gearIcon = module.RESPrefsLink.querySelector('.gearIcon'), backgroundImage = window.getComputedStyle(gearIcon).backgroundImage; if (modules['styleTweaks'].isSubredditStyleEnabled() && backgroundImage && backgroundImage !== 'none') { document.body.classList.add('res-gearIcon-legacy'); } } });
Goctionni/Reddit-Enhancement-Suite
lib/modules/menu.js
JavaScript
gpl-3.0
3,043
var validLangs = ["bg","ca","ca@valencia","cs","da","de","el","en","en-GB","es","es-ES","fi","fr","fr-CA","fy","hu","id","it","ja","ko-KR","lt","nb","nl","nn","pl","pt-BR","pt-PT","ru","sv","tr","uk","vi","zh-CN","zh-TW"]
plouj/syncthing
gui/default/assets/lang/valid-langs.js
JavaScript
mpl-2.0
222
//>>built define("dojox/lang/functional/array",["dojo/_base/kernel","dojo/_base/lang","dojo/_base/array","./lambda"],function(k,h,n,g){var l={};h.mixin(g,{filter:function(a,d,c){"string"==typeof a&&(a=a.split(""));c=c||k.global;d=g.lambda(d);var b=[],f,e,m;if(h.isArray(a)){e=0;for(m=a.length;e<m;++e)f=a[e],d.call(c,f,e,a)&&b.push(f)}else if("function"==typeof a.hasNext&&"function"==typeof a.next)for(e=0;a.hasNext();)f=a.next(),d.call(c,f,e++,a)&&b.push(f);else for(e in a)e in l||(f=a[e],d.call(c,f,e,a)&&b.push(f)); return b},forEach:function(a,d,c){"string"==typeof a&&(a=a.split(""));c=c||k.global;d=g.lambda(d);var b,f;if(h.isArray(a)){b=0;for(f=a.length;b<f;d.call(c,a[b],b,a),++b);}else if("function"==typeof a.hasNext&&"function"==typeof a.next)for(b=0;a.hasNext();d.call(c,a.next(),b++,a));else for(b in a)b in l||d.call(c,a[b],b,a);return c},map:function(a,d,c){"string"==typeof a&&(a=a.split(""));c=c||k.global;d=g.lambda(d);var b,f,e;if(h.isArray(a)){b=Array(f=a.length);for(e=0;e<f;b[e]=d.call(c,a[e],e,a), ++e);}else if("function"==typeof a.hasNext&&"function"==typeof a.next){b=[];for(e=0;a.hasNext();b.push(d.call(c,a.next(),e++,a)));}else for(e in b=[],a)e in l||b.push(d.call(c,a[e],e,a));return b},every:function(a,d,c){"string"==typeof a&&(a=a.split(""));c=c||k.global;d=g.lambda(d);var b,f;if(h.isArray(a)){b=0;for(f=a.length;b<f;++b)if(!d.call(c,a[b],b,a))return!1}else if("function"==typeof a.hasNext&&"function"==typeof a.next)for(b=0;a.hasNext();){if(!d.call(c,a.next(),b++,a))return!1}else for(b in a)if(!(b in l)&&!d.call(c,a[b],b,a))return!1;return!0},some:function(a,d,c){"string"==typeof a&&(a=a.split(""));c=c||k.global;d=g.lambda(d);var b,f;if(h.isArray(a)){b=0;for(f=a.length;b<f;++b)if(d.call(c,a[b],b,a))return!0}else if("function"==typeof a.hasNext&&"function"==typeof a.next)for(b=0;a.hasNext();){if(d.call(c,a.next(),b++,a))return!0}else for(b in a)if(!(b in l)&&d.call(c,a[b],b,a))return!0;return!1}});return g});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/lang/functional/array.js
JavaScript
apache-2.0
1,955
/* eslint-env jest */ /** * @fileoverview Enforce all aria-* properties are valid. * @author Ethan Cohen */ // ----------------------------------------------------------------------------- // Requirements // ----------------------------------------------------------------------------- import { aria } from 'aria-query'; import { RuleTester } from 'eslint'; import parserOptionsMapper from '../../__util__/parserOptionsMapper'; import rule from '../../../src/rules/aria-props'; import getSuggestion from '../../../src/util/getSuggestion'; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ruleTester = new RuleTester(); const ariaAttributes = [...aria.keys()]; const errorMessage = (name) => { const suggestions = getSuggestion(name, ariaAttributes); const message = `${name}: This attribute is an invalid ARIA attribute.`; if (suggestions.length > 0) { return { type: 'JSXAttribute', message: `${message} Did you mean to use ${suggestions}?`, }; } return { type: 'JSXAttribute', message, }; }; // Create basic test cases using all valid role types. const basicValidityTests = ariaAttributes.map(prop => ({ code: `<div ${prop.toLowerCase()}="foobar" />`, })); ruleTester.run('aria-props', rule, { valid: [ // Variables should pass, as we are only testing literals. { code: '<div />' }, { code: '<div></div>' }, { code: '<div aria="wee"></div>' }, // Needs aria-* { code: '<div abcARIAdef="true"></div>' }, { code: '<div fooaria-foobar="true"></div>' }, { code: '<div fooaria-hidden="true"></div>' }, { code: '<Bar baz />' }, { code: '<input type="text" aria-errormessage="foobar" />' }, ].concat(basicValidityTests).map(parserOptionsMapper), invalid: [ { code: '<div aria-="foobar" />', errors: [errorMessage('aria-')] }, { code: '<div aria-labeledby="foobar" />', errors: [errorMessage('aria-labeledby')], }, { code: '<div aria-skldjfaria-klajsd="foobar" />', errors: [errorMessage('aria-skldjfaria-klajsd')], }, ].map(parserOptionsMapper), });
BigBoss424/portfolio
v8/development/node_modules/eslint-plugin-jsx-a11y/__tests__/src/rules/aria-props-test.js
JavaScript
apache-2.0
2,215
var element = document.getElementById("pagination"); var comp = new u.pagination({ el: element,showState:false }); comp.update({ totalPages: 100, pageSize: 20, currentPage: 1, totalCount: 200 }); comp.on('pageChange', function(pageIndex) { console.log('新的页号为' + pageIndex); }); comp.on('sizeChange', function(arg) { console.log('每页显示条数为' + arg[0]); });
iuap-design/neoui
snippets/plugin/jspagination/demo/1-base/widget.js
JavaScript
bsd-2-clause
402
var base = require('./webpack.base.config'); var config = base('production'); // production overrides go here module.exports = config;
chrxr/wagtail
webpack.prd.config.js
JavaScript
bsd-3-clause
139
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {addWebUIListener} from 'chrome://resources/js/cr.m.js'; import {$} from 'chrome://resources/js/util.m.js'; import {createElementFromText} from './utils.js'; const nextTaskLogSeq = 1; /** * Handles per-task log event. * @param {!{ * duration: number, * task_description: string, * result_description: string, * details: !Array, * }} taskLog */ function onTaskLogRecorded(taskLog) { const details = document.createElement('td'); details.classList.add('task-log-details'); const label = document.createElement('label'); details.appendChild(label); const collapseCheck = document.createElement('input'); collapseCheck.setAttribute('type', 'checkbox'); collapseCheck.classList.add('task-log-collapse-check'); label.appendChild(collapseCheck); const ul = document.createElement('ul'); for (let i = 0; i < taskLog.details.length; ++i) { ul.appendChild(createElementFromText('li', taskLog.details[i])); } label.appendChild(ul); const tr = document.createElement('tr'); tr.appendChild(createElementFromText( 'td', taskLog.duration.toString(), {'class': 'task-log-duration'})); tr.appendChild(createElementFromText( 'td', taskLog.task_description, {'class': 'task-log-description'})); tr.appendChild(createElementFromText( 'td', taskLog.result_description, {'class': 'task-log-result'})); tr.appendChild(details); $('task-log-entries').appendChild(tr); } /** * Get initial sync service values and set listeners to get updated values. */ function main() { addWebUIListener('task-log-recorded', onTaskLogRecorded); chrome.send('observeTaskLog'); } document.addEventListener('DOMContentLoaded', main);
ric2b/Vivaldi-browser
chromium/chrome/browser/resources/sync_file_system_internals/task_log.js
JavaScript
bsd-3-clause
1,852
/** * Copyright 2012 Google, Inc. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** * @fileoverview Chrome extension content script. * Injected onto all pages at all times. Checks for the existence of a special * cookie ({@see WTF_ENABLED_COOKIE}) to know whether to actually add the * scripts to the page. * * @author benvanik@google.com (Ben Vanik) */ (function() { // console.log utility that doesn't explode when it's not present. var log = window.console ? window.console.log.bind(window.console) : function() {}; /** * Injects the extension, if needed. * This is called on startup in the content-script context. */ function main() { var topWindow = window.top; var isTop = window.top === window; // Check the top window for options. var options = null; try { var optionsEl = topWindow.document.querySelector('x-wtf-options'); if (optionsEl) { // Options exist in the DOM, use those. options = JSON.parse(optionsEl.text); } } catch (e) { // Failed, likely because of cross-domain iframe issues. } // Grab options - if not found, not injected. if (!options) { options = fetchOptions(topWindow); } if (!options) { return; } // Add options to the document for other frames/etc to find. if (!optionsEl) { try { optionsEl = document.createElement('x-wtf-options'); optionsEl.text = JSON.stringify(options); topWindow.document.documentElement.appendChild(optionsEl); } catch (e) { // Failed, likely because of cross-domain iframe issues. } } if (options['__instrumented__']) { // Instrumentation mode. if (isTop) { // Create a blob that is both the falafel and process scripts. // This is used to create the worker. var xhr = new XMLHttpRequest(); xhr.open('GET', chrome.extension.getURL('third_party/falafel.js'), false); xhr.send(); var falafelSource = xhr.responseText; xhr = new XMLHttpRequest(); xhr.open('GET', chrome.extension.getURL('wtf-process.js'), false); xhr.send(); var processSource = xhr.responseText; var blob = new Blob([ falafelSource, processSource ], { type: 'application/javascript' }); var blobUrl = URL.createObjectURL(blob); options['wtf.instrumentation.blob'] = blobUrl; injectScriptFile(chrome.extension.getURL('third_party/falafel.js')); injectScriptFile(chrome.extension.getURL('wtf-process.js')); injectScriptFile(chrome.extension.getURL('wtf-call-tracing.js')); } injectScriptFunction(function(options) { // If we are nested in an iframe, protect against cross-origin errors. try { window.top.wtfi.prepare(options, window); } catch (e) { } }, [ options ]); } else { // Normal tracing mode. // Inject the tracing framework script and the prepare function. if (isTop) { var traceScriptUrl = chrome.extension.getURL('wtf_trace_web_js_compiled.js'); injectScriptFunction(function(traceScriptUrl) { window.WTF_TRACE_SCRIPT_URL = traceScriptUrl; }, [traceScriptUrl]); injectScriptFile(traceScriptUrl); } injectScriptFunction(function(options) { // If we are nested in an iframe, protect against cross-origin errors. try { window.top.wtf.trace.prepare(options, window); } catch (e) { } }, [ options ]); if (isTop) { // Inject addons, if required. var addons = injectAddons(options['wtf.addons'] || []); // Inject preparation code to start tracing with the desired options. injectScriptFunction(startTracing, [ addons ]); } } if (isTop) { setupCommunications(); } }; /** * Fetches the options from the extension background page. * This will only return a value if the options were injected in a cookie, and * if no options are returned it means the injection is not active. * @return {!Object} Options object. */ function fetchOptions() { /** * Name of the cookie that contains the options for the injection. * The data is just a blob GUID that is used to construct a URL to the blob * exposed by the extension. * @const * @type {string} */ var WTF_OPTIONS_COOKIE = 'wtf'; /** * Cookie used for instrumentation options. * @const * @type {string} */ var WTF_INSTRUMENTATION_COOKIE = 'wtfi'; // Check for the injection cookie. var optionsUuid = null; var instrumentationOptions = null; var cookies = document.cookie.split('; '); for (var n = 0; n < cookies.length; n++) { if (cookies[n].lastIndexOf(WTF_OPTIONS_COOKIE + '=') == 0) { optionsUuid = cookies[n].substr(cookies[n].indexOf('=') + 1); } if (cookies[n].lastIndexOf(WTF_INSTRUMENTATION_COOKIE + '=') == 0) { instrumentationOptions = cookies[n].substr(cookies[n].indexOf('=') + 1); } } if (!optionsUuid && !instrumentationOptions) { return null; } // If we have an instrumentation cookie we use that and go into // instrumentation mode. if (instrumentationOptions) { instrumentationOptions = JSON.parse(instrumentationOptions); instrumentationOptions['__instrumented__'] = true; return instrumentationOptions; } // Fetch the options from the extension. // This is complicated by a regression in Chrome that prevents the blob trick // from working in certain versions. We try that first (as it's the best) and // if it fails we fallback to a nasty HTTP header trick. // https://code.google.com/p/chromium/issues/detail?id=295829 // blob:chrome-extension%3A//[extension id]/[options uuid] var blobUrl = 'blob:' + chrome.extension.getURL(optionsUuid).replace(':', '%3A'); var headerUrl = 'http://tracing-framework.appspot.com/tab-options/' + optionsUuid; try { var xhr = new XMLHttpRequest(); xhr.open('GET', blobUrl, false); xhr.send(null); if (xhr.status != 200) { log('Failed to load WTF injection options:', blobUrl, xhr.status, xhr.statusText); return null; } return JSON.parse(xhr.responseText); } catch(e) { log('Failed to parse WTF injection options (falling back to headers)... ' + 'See https://code.google.com/p/chromium/issues/detail?id=295829'); // Try the headers. try { var xhr = new XMLHttpRequest(); xhr.open('GET', headerUrl, false); xhr.send(null); var optionsData = xhr.getResponseHeader('X-WTF-Options'); if (!optionsData) { log('Failed to load WTF injection options from header:' + headerUrl); log('Using defaults for settings :('); return { 'wtf.injector': true, 'wtf.injector.failed': true, 'wtf.trace.session.bufferSize': 6 * 1024 * 1024, 'wtf.trace.session.maximumMemoryUsage': 512 * 1024 * 1024, 'wtf.trace.provider.chromeDebug.present': true, 'wtf.trace.provider.chromeDebug.tracing': false }; } return JSON.parse(optionsData); } catch(e) { log('Really failed to fetch WTF injection options, aborting', e); // Try again! window.setTimeout(function() { window.location.reload(); }, 100); return null; } } return null; }; /** * Injects the given addons into the page. * @param {!Array.<string>} manifestUrls Addon manifest JSON URLs. * @return {!Object.<!Object>} Addon manifests, mapped by manifest URL. */ function injectAddons(manifestUrls) { var addons = {}; for (var n = 0; n < manifestUrls.length; n++) { // Fetch Manifest JSON. var url = manifestUrls[n]; var json = getUrl(url); if (!json) { log('Unable to fetch manifest JSON: ' + url); continue; } json = JSON.parse(json); addons[url] = json; // If it has a tracing node, inject scripts. var tracingInfo = json['tracing']; if (tracingInfo && tracingInfo['scripts']) { var tracingScripts = tracingInfo['scripts']; for (var m = 0; m < tracingScripts.length; m++) { var scriptUrl = resolveUrl(url, tracingScripts[m]); if (!injectScriptFile(scriptUrl)) { log('Error loading addon ' + url + ':'); log('Tracing script file not found: ' + scriptUrl); } } } } return addons; }; /** * In-page trace preparation function. * This is directly inserted into the page and should run immediately after * the library has been loaded. * * This function is stringified and passed to the page, so expect no closure * variables and all arguments must be serializable. * * @param {!Object.<!Object>} addons A map of URL to addon JSON. */ function startTracing(addons) { // NOTE: this code is injected by string and cannot access any closure // variables! // Register addons. for (var url in addons) { var name = addons[url]['name']; if (window.console) { console.log('WTF Addon Installed: ' + name + ' (' + url + ')'); } wtf.addon.registerAddon(url, addons[url]); } // Show HUD. wtf.hud.prepare(); // Start recording. wtf.trace.start(); }; /** * Converts a list of Uint8Arrays to regular arrays. * @param {!Array.<!Uint8Array>} sources Source arrays. * @return {!Array.<!Array.<number>>} Target arrays. */ function convertUint8ArraysToArrays(sources) { var targets = []; for (var n = 0; n < sources.length; n++) { var source = sources[n]; var target = new Array(source.length); for (var i = 0; i < source.length; i++) { target[i] = source[i]; } targets.push(target); } return targets; }; /** * Sets up two-way communications with the page. * This enables proxying to the background page. */ function setupCommunications() { // Initiate a connection to the background page that we can use as a // channel for settings saving/etc. var port = chrome.extension.connect({ name: 'injector' }); // Listen for data from the extension. port.onMessage.addListener(function(data, port) { // We try to keep the data opaque so we don't waste any time here. sendMessage(data); }); // Setup a communication channel with the page via events. var localId = String(Number(Date.now())); window.addEventListener('message', function(e) { // The message here is from the wtf.ipc.MessageChannel, and has some header // data in it. // Note that because we are also sending messages it's possible to get // our own messages back, so filter that by localId. var packet = e.data; if (!packet || !packet['wtf_ipc_connect_token'] || packet['wtf_ipc_sender_token'] == localId) { return; } var data = packet['data']; e.stopPropagation(); // NOTE: Chrome ports do not support transferrables! Need to convert! // Pass through the messages. // We trust the Chrome security model and just send the data along. port.postMessage(data); }, false); function sendMessage(data) { var packet = { 'wtf_ipc_connect_token': true, 'wtf_ipc_sender_token': localId, 'data': data }; window.postMessage(packet, '*'); }; }; /** * Synchronously fetch the given URL. * If the URL is a reference to an extension resource it must be in the * web_accessible_resources manifest group. * @param {string} url URL to fetch. * @return {string|null} URL contents. */ function getUrl(url) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.send(''); if (xhr.status != 200) { return null; } return xhr.responseText; }; /** * Hackily resolves a URL relative to a base. * @param {string} base Base URL. * @param {string} url Relative or absolute URL. * @return {string} Resolved URL. */ function resolveUrl(base, url) { var value = ''; if (url.indexOf('://') != -1) { // Likely absolute... value = url; } else { // Combine by smashing together and letting the browser figure it out. if (url.length && url[0] == '/') { // URL is absolute, so strip base to just host. var i = url.indexOf('://') + 3; i = url.indexOf('/', i); if (i != -1) { value = base + url; } else { value = base.substr(0, i) + url; } } else { // URL is relative, so combine with base. if (base[base.length] == '/') { value = base + '/' + url; } else { value = base + '/../' + url; } } } return value; }; /** * Injects a <script> tag into the document as early as possible. * The hope is that the injected contents run before any of the user code. * @param {!Element} script <script> element. */ function injectScriptTag(script) { // Get some kind of target to put the script in. // Only valid documents get body/head, so this is a nice way to ignore bad // ones. Try to insert as early as possible. var targetElement = document.documentElement || document.head || document.body; if (targetElement) { if (targetElement.firstElementChild) { targetElement.insertBefore(script, targetElement.firstElementChild); } else { targetElement.appendChild(script); } script.parentNode.removeChild(script); } }; /** * Injects a function into the page. * @param {!Function} fn Function to inject. * @param {Array=} opt_args Arguments array. All must be string serializable. */ function injectScriptFunction(fn, opt_args) { // Format args as strings that can go in the source. var args = opt_args || []; for (var n = 0; n < args.length; n++) { if (args[n] === undefined) { args[n] = 'undefined'; } else if (args[n] === null) { args[n] = 'null'; } else if (typeof args[n] == 'string') { // TODO(benvanik): escape args[n] = '"' + args[n] + '"'; } else if (typeof args[n] == 'object') { args[n] = JSON.stringify(args[n]); } } args = args.join(','); // TODO(benvanik): escape fn source var source = [ '(' + String(fn) + ')(' + args + ');', '// Web Tracing Framework injected function: ' + fn.name, '//# sourceURL=x://wtf-injector/' + fn.name ].join('\n'); // Create script tag. var script = document.createElement('script'); script.appendChild(document.createTextNode(source)); // Add to page. injectScriptTag(script); }; /** * Injects a script file into the page. * If the URL is to a chrome:// path it must be in the web_accessible_resources * manifest group. * @param {string} url Script URL. * @return {boolean} Whether the source file was found. */ function injectScriptFile(url) { // Synchronous read of the source. var rawText = getUrl(url); if (!rawText) { return false; } var filename = url; var lastSlash = url.lastIndexOf('/'); if (lastSlash != -1) { filename = url.substr(lastSlash + 1); } var source = [ '(function() {' + rawText + '})();', '// Web Tracing Framework injected file: ' + url, '//# sourceURL=x://wtf-injector/' + filename ].join('\n'); // Setup script tag with the raw source. var script = document.createElement('script'); script.type = 'text/javascript'; script.text = source; // Add to page. injectScriptTag(script); return true; }; main(); })();
google/tracing-framework
extensions/wtf-injector-chrome/wtf-injector.js
JavaScript
bsd-3-clause
15,362
// @flow // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design import { types as tt } from "./types"; import { lineBreak } from "../util/whitespace"; export class TokContext { constructor( token: string, isExpr?: boolean, preserveSpace?: boolean, override?: Function, // Takes a Tokenizer as a this-parameter, and returns void. ) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; } token: string; isExpr: boolean; preserveSpace: boolean; override: ?Function; } export const types: { [key: string]: TokContext, } = { braceStatement: new TokContext("{", false), braceExpression: new TokContext("{", true), templateQuasi: new TokContext("${", true), parenStatement: new TokContext("(", false), parenExpression: new TokContext("(", true), template: new TokContext("`", true, true, p => p.readTmplToken()), functionExpression: new TokContext("function", true), }; // Token-specific context update code tt.parenR.updateContext = tt.braceR.updateContext = function() { if (this.state.context.length === 1) { this.state.exprAllowed = true; return; } const out = this.state.context.pop(); if ( out === types.braceStatement && this.curContext() === types.functionExpression ) { this.state.context.pop(); this.state.exprAllowed = false; } else if (out === types.templateQuasi) { this.state.exprAllowed = true; } else { this.state.exprAllowed = !out.isExpr; } }; tt.name.updateContext = function(prevType) { if (this.state.value === "of" && this.curContext() === types.parenStatement) { this.state.exprAllowed = !prevType.beforeExpr; return; } this.state.exprAllowed = false; if (prevType === tt._let || prevType === tt._const || prevType === tt._var) { if (lineBreak.test(this.input.slice(this.state.end))) { this.state.exprAllowed = true; } } if (this.state.isIterator) { this.state.isIterator = false; } }; tt.braceL.updateContext = function(prevType) { this.state.context.push( this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression, ); this.state.exprAllowed = true; }; tt.dollarBraceL.updateContext = function() { this.state.context.push(types.templateQuasi); this.state.exprAllowed = true; }; tt.parenL.updateContext = function(prevType) { const statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while; this.state.context.push( statementParens ? types.parenStatement : types.parenExpression, ); this.state.exprAllowed = true; }; tt.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; tt._function.updateContext = function(prevType) { if (this.state.exprAllowed && !this.braceIsBlock(prevType)) { this.state.context.push(types.functionExpression); } this.state.exprAllowed = false; }; tt.backQuote.updateContext = function() { if (this.curContext() === types.template) { this.state.context.pop(); } else { this.state.context.push(types.template); } this.state.exprAllowed = false; };
samwgoldman/babel
packages/babylon/src/tokenizer/context.js
JavaScript
mit
3,313
define(function (require) { var zrUtil = require('zrender/core/util'); var numberUtil = require('./number'); var textContain = require('zrender/contain/text'); var formatUtil = {}; /** * 每三位默认加,格式化 * @type {string|number} x */ formatUtil.addCommas = function (x) { if (isNaN(x)) { return '-'; } x = (x + '').split('.'); return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,') + (x.length > 1 ? ('.' + x[1]) : ''); }; /** * @param {string} str * @return {string} str */ formatUtil.toCamelCase = function (str) { return str.toLowerCase().replace(/-(.)/g, function(match, group1) { return group1.toUpperCase(); }); }; /** * Normalize css liked array configuration * e.g. * 3 => [3, 3, 3, 3] * [4, 2] => [4, 2, 4, 2] * [4, 3, 2] => [4, 3, 2, 3] * @param {number|Array.<number>} val */ formatUtil.normalizeCssArray = function (val) { var len = val.length; if (typeof (val) === 'number') { return [val, val, val, val]; } else if (len === 2) { // vertical | horizontal return [val[0], val[1], val[0], val[1]]; } else if (len === 3) { // top | horizontal | bottom return [val[0], val[1], val[2], val[1]]; } return val; }; formatUtil.encodeHTML = function (source) { return String(source) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); }; var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; var wrapVar = function (varName, seriesIdx) { return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}'; }; /** * Template formatter * @param {string} tpl * @param {Array.<Object>|Object} paramsList * @return {string} */ formatUtil.formatTpl = function (tpl, paramsList) { if (!zrUtil.isArray(paramsList)) { paramsList = [paramsList]; } var seriesLen = paramsList.length; if (!seriesLen) { return ''; } var $vars = paramsList[0].$vars || []; for (var i = 0; i < $vars.length; i++) { var alias = TPL_VAR_ALIAS[i]; tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0)); } for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) { for (var k = 0; k < $vars.length; k++) { tpl = tpl.replace( wrapVar(TPL_VAR_ALIAS[k], seriesIdx), paramsList[seriesIdx][$vars[k]] ); } } return tpl; }; /** * @param {string} str * @return {string} * @inner */ var s2d = function (str) { return str < 10 ? ('0' + str) : str; }; /** * ISO Date format * @param {string} tpl * @param {number} value * @inner */ formatUtil.formatTime = function (tpl, value) { if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year' ) { tpl = 'MM-dd\nyyyy'; } var date = numberUtil.parseDate(value); var y = date.getFullYear(); var M = date.getMonth() + 1; var d = date.getDate(); var h = date.getHours(); var m = date.getMinutes(); var s = date.getSeconds(); tpl = tpl.replace('MM', s2d(M)) .toLowerCase() .replace('yyyy', y) .replace('yy', y % 100) .replace('dd', s2d(d)) .replace('d', d) .replace('hh', s2d(h)) .replace('h', h) .replace('mm', s2d(m)) .replace('m', m) .replace('ss', s2d(s)) .replace('s', s); return tpl; }; /** * Capital first * @param {string} str * @return {string} */ formatUtil.capitalFirst = function (str) { return str ? str.charAt(0).toUpperCase() + str.substr(1) : str; }; formatUtil.truncateText = textContain.truncateText; return formatUtil; });
yhtml5/YHTML5-Work
work-summary/20170115-Annual-Summary/app/bower_components/echarts/src/util/format.js
JavaScript
mit
4,398
export const shared = Object.create(null);
Hansoft/meteor
tools/tests/apps/dynamic-import/imports/prefetch-child.js
JavaScript
mit
43
(function ($) { "use strict"; // autoResize option will turn off resizable and draggable. Drupal.settings.dialog = $.extend({autoResize: true, maxHeight: '95%'}, Drupal.settings.dialog); /** * Resets the current options for positioning. * * This is used as a window resize and scroll callback to reposition the * jQuery UI dialog. Although not a built-in jQuery UI option, this can * be disabled by setting autoResize: false in the options array when creating * a new Drupal.dialog(). */ function resetSize(event) { var positionOptions = ['width', 'height', 'minWidth', 'minHeight', 'maxHeight', 'maxWidth', 'position']; var adjustedOptions = {}; var windowHeight = $(window).height(); var option, optionValue, adjustedValue; for (var n = 0; n < positionOptions.length; n++) { option = positionOptions[n]; optionValue = event.data.settings[option]; if (optionValue) { // jQuery UI does not support percentages on heights, convert to pixels. if (typeof optionValue === 'string' && /%$/.test(optionValue) && /height/i.test(option)) { // Take offsets in account. windowHeight -= Drupal.displace.offsets.top + Drupal.displace.offsets.bottom; adjustedValue = parseInt(0.01 * parseInt(optionValue, 10) * windowHeight, 10); // Don't force the dialog to be bigger vertically than needed. if (option === 'height' && event.data.$element.parent().outerHeight() < adjustedValue) { adjustedValue = 'auto'; } adjustedOptions[option] = adjustedValue; } } } // Offset the dialog center to be at the center of Drupal.displace.offsets. adjustedOptions = resetPosition(adjustedOptions); event.data.$element .dialog('option', adjustedOptions) .trigger('dialogContentResize'); } /** * Position the dialog's center at the center of displace.offsets boundaries. */ function resetPosition(options) { var offsets = Drupal.displace.offsets; var left = offsets.left - offsets.right; var top = offsets.top - offsets.bottom; var leftString = (left > 0 ? '+' : '-') + Math.abs(Math.round(left / 2)) + 'px'; var topString = (top > 0 ? '+' : '-') + Math.abs(Math.round(top / 2)) + 'px'; options.position = { my: 'center' + (left !== 0 ? leftString : '') + ' center' + (top !== 0 ? topString : ''), of: window }; return options; } $(window).on({ 'dialog:aftercreate': function (event, dialog, $element, settings) { var autoResize = Drupal.debounce(resetSize, 20); var eventData = {settings: settings, $element: $element}; if (settings.autoResize === true || settings.autoResize === 'true') { $element .dialog('option', {resizable: false, draggable: false}) .dialog('widget').css('position', 'fixed'); $(window) .on('resize.dialogResize scroll.dialogResize', eventData, autoResize) .trigger('resize.dialogResize'); $(document).on('drupalViewportOffsetChange', eventData, autoResize); } }, 'dialog:beforeclose': function (event, dialog, $element) { $(window).off('.dialogResize'); } }); })(jQuery);
mhamed/wordtosay
sites/all/modules/contrib/dialog/js/dialog/dialog.position.js
JavaScript
gpl-2.0
3,252
/*global avadaredux_change, wp, avadaredux*/ (function( $ ) { "use strict"; avadaredux.field_objects = avadaredux.field_objects || {}; avadaredux.field_objects.slides = avadaredux.field_objects.slides || {}; $( document ).ready( function() { //avadaredux.field_objects.slides.init(); } ); avadaredux.field_objects.slides.init = function( selector ) { if ( !selector ) { selector = $( document ).find( ".avadaredux-group-tab:visible" ).find( '.avadaredux-container-slides:visible' ); } $( selector ).each( function() { var el = $( this ); avadaredux.field_objects.media.init(el); var parent = el; if ( !el.hasClass( 'avadaredux-field-container' ) ) { parent = el.parents( '.avadaredux-field-container:first' ); } if ( parent.is( ":hidden" ) ) { // Skip hidden fields return; } if ( parent.hasClass( 'avadaredux-container-slides' ) ) { parent.addClass( 'avadaredux-field-init' ); } if ( parent.hasClass( 'avadaredux-field-init' ) ) { parent.removeClass( 'avadaredux-field-init' ); } else { return; } el.find( '.avadaredux-slides-remove' ).live( 'click', function() { avadaredux_change( $( this ) ); $( this ).parent().siblings().find( 'input[type="text"]' ).val( '' ); $( this ).parent().siblings().find( 'textarea' ).val( '' ); $( this ).parent().siblings().find( 'input[type="hidden"]' ).val( '' ); var slideCount = $( this ).parents( '.avadaredux-container-slides:first' ).find( '.avadaredux-slides-accordion-group' ).length; if ( slideCount > 1 ) { $( this ).parents( '.avadaredux-slides-accordion-group:first' ).slideUp( 'medium', function() { $( this ).remove(); } ); } else { var content_new_title = $( this ).parent( '.avadaredux-slides-accordion' ).data( 'new-content-title' ); $( this ).parents( '.avadaredux-slides-accordion-group:first' ).find( '.remove-image' ).click(); $( this ).parents( '.avadaredux-container-slides:first' ).find( '.avadaredux-slides-accordion-group:last' ).find( '.avadaredux-slides-header' ).text( content_new_title ); } } ); //el.find( '.avadaredux-slides-add' ).click( el.find( '.avadaredux-slides-add' ).off('click').click( function() { var newSlide = $( this ).prev().find( '.avadaredux-slides-accordion-group:last' ).clone( true ); var slideCount = $( newSlide ).find( '.slide-title' ).attr( "name" ).match( /[0-9]+(?!.*[0-9])/ ); var slideCount1 = slideCount * 1 + 1; $( newSlide ).find( 'input[type="text"], input[type="hidden"], textarea' ).each( function() { $( this ).attr( "name", jQuery( this ).attr( "name" ).replace( /[0-9]+(?!.*[0-9])/, slideCount1 ) ).attr( "id", $( this ).attr( "id" ).replace( /[0-9]+(?!.*[0-9])/, slideCount1 ) ); $( this ).val( '' ); if ( $( this ).hasClass( 'slide-sort' ) ) { $( this ).val( slideCount1 ); } } ); var content_new_title = $( this ).prev().data( 'new-content-title' ); $( newSlide ).find( '.screenshot' ).removeAttr( 'style' ); $( newSlide ).find( '.screenshot' ).addClass( 'hide' ); $( newSlide ).find( '.screenshot a' ).attr( 'href', '' ); $( newSlide ).find( '.remove-image' ).addClass( 'hide' ); $( newSlide ).find( '.avadaredux-slides-image' ).attr( 'src', '' ).removeAttr( 'id' ); $( newSlide ).find( 'h3' ).text( '' ).append( '<span class="avadaredux-slides-header">' + content_new_title + '</span><span class="ui-accordion-header-icon ui-icon ui-icon-plus"></span>' ); $( this ).prev().append( newSlide ); } ); el.find( '.slide-title' ).keyup( function( event ) { var newTitle = event.target.value; $( this ).parents().eq( 3 ).find( '.avadaredux-slides-header' ).text( newTitle ); } ); el.find( ".avadaredux-slides-accordion" ) .accordion( { header: "> div > fieldset > h3", collapsible: true, active: false, heightStyle: "content", icons: { "header": "ui-icon-plus", "activeHeader": "ui-icon-minus" } } ) .sortable( { axis: "y", handle: "h3", connectWith: ".avadaredux-slides-accordion", start: function( e, ui ) { ui.placeholder.height( ui.item.height() ); ui.placeholder.width( ui.item.width() ); }, placeholder: "ui-state-highlight", stop: function( event, ui ) { // IE doesn't register the blur when sorting // so trigger focusout handlers to remove .ui-state-focus ui.item.children( "h3" ).triggerHandler( "focusout" ); var inputs = $( 'input.slide-sort' ); inputs.each( function( idx ) { $( this ).val( idx ); } ); } } ); } ); }; })( jQuery );
aotash/chemdry
wp-content/themes/chemdry/includes/avadaredux/avadaredux-framework/AvadaReduxCore/inc/fields/slides/field_slides.js
JavaScript
gpl-2.0
6,882
( function( mw, $ ) { "use strict"; mw.PluginManager.add( 'watermark', mw.KBaseComponent.extend({ defaultConfig: { "parent": "videoHolder", "order": "3", "cssClass": "bottomLeft", "img": null, "href": null, "padding": null, "hideTimeout": 0 }, isSafeEnviornment: function(){ return this.getConfig('img') || this.getConfig('watermarkPath'); }, setup: function(){ var _this = this; // support legacy position config: if( this.getConfig('watermarkPosition') ){ this.setConfig('cssClass', this.getConfig('watermarkPosition')); } // support legacy path config: if( this.getConfig('watermarkPath') ){ this.setConfig('img', this.getConfig('watermarkPath')); } this.bind('AdSupport_StartAdPlayback', function(){ _this.getComponent().hide(); }); this.bind('AdSupport_EndAdPlayback', function(){ _this.getComponent().show(); }); if( this.getConfig('hideTimeout') != 0 ){ this.bind('onChangeMediaDone playerReady', function(){ _this.getComponent().show(); _this.timeoutWatermark(); }); } }, watermarkLoaded: function(){ this.getPlayer().triggerHelper("waterMarkLoaded", [this.getComponent().get(0)]); }, getComponent: function(){ var _this = this; if(!this.$el){ var img = $('<img />') .one("load", function(){ _this.watermarkLoaded(); }) .attr({ 'src': this.getConfig('img') }); this.$el = $('<div />') .addClass ( this.getCssClass() ) .append( $('<a />').attr({ 'href' : this.getConfig('href'), 'target' : '_blank' }) .click( function(){ _this.getPlayer().sendNotification( 'watermarkClick' ); return true; }) .append(img) ); if( this.getConfig('padding') ){ this.$el.css('padding', this.getConfig('padding') ); } } return this.$el; }, timeoutWatermark: function(){ var _this = this; this.bind('firstPlay', function() { setTimeout(function () { _this.$el.fadeOut("slow"); }, _this.getConfig('hideTimeout') * 1000) }); } })); })( window.mw, jQuery );
FlixMaster/mwEmbed
modules/KalturaSupport/resources/uiConfComponents/watermarkPlugin.js
JavaScript
agpl-3.0
2,158
import { Component, Input } from '@angular/core'; export var NgbDatepickerDayView = (function () { function NgbDatepickerDayView() { } NgbDatepickerDayView.prototype.isMuted = function () { return !this.selected && (this.date.month !== this.currentMonth || this.disabled); }; NgbDatepickerDayView.decorators = [ { type: Component, args: [{ selector: '[ngbDatepickerDayView]', styles: ["\n :host { \n text-align: center;\n padding: 0.185rem 0.25rem; \n border-radius: 0.25rem;\n }\n "], host: { '[class.bg-primary]': 'selected', '[class.text-white]': 'selected', '[class.text-muted]': 'isMuted()', '[class.btn-secondary]': '!disabled' }, template: "{{ date.day }}" },] }, ]; /** @nocollapse */ NgbDatepickerDayView.ctorParameters = []; NgbDatepickerDayView.propDecorators = { 'currentMonth': [{ type: Input },], 'date': [{ type: Input },], 'disabled': [{ type: Input },], 'selected': [{ type: Input },], }; return NgbDatepickerDayView; }()); //# sourceMappingURL=datepicker-day-view.js.map
CAH-FlyChen/Evolution.Framework
src/Evolution.Web.Html/wwwroot/lib/@ng-bootstrap/ng-bootstrap/datepicker/datepicker-day-view.js
JavaScript
apache-2.0
1,312
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/data/api/Identity",["../../_base/declare","./Read"],function(b,c){return b("dojo.data.api.Identity",c,{getFeatures:function(){return{"dojo.data.api.Read":!0,"dojo.data.api.Identity":!0}},getIdentity:function(a){throw Error("Unimplemented API: dojo.data.api.Identity.getIdentity");},getIdentityAttributes:function(a){throw Error("Unimplemented API: dojo.data.api.Identity.getIdentityAttributes");},fetchItemByIdentity:function(a){if(!this.isItemLoaded(a.item))throw Error("Unimplemented API: dojo.data.api.Identity.fetchItemByIdentity"); }})});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojo/data/api/Identity.js
JavaScript
apache-2.0
762
Package.describe({ name: 'mizzao:timesync', summary: 'NTP-style time synchronization between server and client', version: '0.3.4', git: 'https://github.com/mizzao/meteor-timesync.git' }); Package.onUse(function (api) { api.use([ 'check', 'tracker', 'http', ], 'client'); api.use([ 'webapp', ], 'server'); api.use([ 'ecmascript', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); Package.onTest(function (api) { api.use([ 'ecmascript', 'tinytest', 'test-helpers' ]); api.use(['tracker'], 'client'); api.use('mizzao:timesync'); api.addFiles('tests/client.js', 'client'); });
Sing-Li/Rocket.Chat
packages/meteor-timesync/package.js
JavaScript
mit
666
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. 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-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ // @tag dom,core /** */ Ext.define('Ext.dom.Element_fx', { override: 'Ext.dom.Element' }, function() { var Element = Ext.dom.Element, VISIBILITY = "visibility", DISPLAY = "display", NONE = "none", HIDDEN = 'hidden', VISIBLE = 'visible', OFFSETS = "offsets", ASCLASS = "asclass", NOSIZE = 'nosize', ORIGINALDISPLAY = 'originalDisplay', VISMODE = 'visibilityMode', ISVISIBLE = 'isVisible', OFFSETCLASS = Ext.baseCSSPrefix + 'hide-offsets', getDisplay = function(el) { var data = (el.$cache || el.getCache()).data, display = data[ORIGINALDISPLAY]; if (display === undefined) { data[ORIGINALDISPLAY] = display = ''; } return display; }, getVisMode = function(el){ var data = (el.$cache || el.getCache()).data, visMode = data[VISMODE]; if (visMode === undefined) { data[VISMODE] = visMode = Element.VISIBILITY; } return visMode; }; Element.override({ /** * The element's default display mode. */ originalDisplay : "", visibilityMode : 1, /** * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property. * @param {Boolean} visible Whether the element is visible * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object * @return {Ext.dom.Element} this */ setVisible : function(visible, animate) { var me = this, dom = me.dom, visMode = getVisMode(me); // hideMode string override if (typeof animate == 'string') { switch (animate) { case DISPLAY: visMode = Element.DISPLAY; break; case VISIBILITY: visMode = Element.VISIBILITY; break; case OFFSETS: visMode = Element.OFFSETS; break; case NOSIZE: case ASCLASS: visMode = Element.ASCLASS; break; } me.setVisibilityMode(visMode); animate = false; } if (!animate || !me.anim) { if (visMode == Element.DISPLAY) { return me.setDisplayed(visible); } else if (visMode == Element.OFFSETS) { me[visible?'removeCls':'addCls'](OFFSETCLASS); } else if (visMode == Element.VISIBILITY) { me.fixDisplay(); // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting dom.style.visibility = visible ? '' : HIDDEN; } else if (visMode == Element.ASCLASS) { me[visible?'removeCls':'addCls'](me.visibilityCls || Element.visibilityCls); } } else { // closure for composites if (visible) { me.setOpacity(0.01); me.setVisible(true); } if (!Ext.isObject(animate)) { animate = { duration: 350, easing: 'ease-in' }; } me.animate(Ext.applyIf({ callback: function() { if (!visible) { // Grab the dom again, since the reference may have changed if we use fly Ext.fly(dom, '_internal').setVisible(false).setOpacity(1); } }, to: { opacity: (visible) ? 1 : 0 } }, animate)); } (me.$cache || me.getCache()).data[ISVISIBLE] = visible; return me; }, /** * @private * Determine if the Element has a relevant height and width available based * upon current logical visibility state */ hasMetrics : function(){ var visMode = getVisMode(this); return this.isVisible() || (visMode == Element.OFFSETS) || (visMode == Element.VISIBILITY); }, /** * Toggles the element's visibility or display, depending on visibility mode. * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object * @return {Ext.dom.Element} this */ toggle : function(animate){ var me = this; me.setVisible(!me.isVisible(), me.anim(animate)); return me; }, /** * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true. * @param {Boolean/String} value Boolean value to display the element using its default display, or a string to set the display directly. * @return {Ext.dom.Element} this */ setDisplayed : function(value) { if(typeof value == "boolean"){ value = value ? getDisplay(this) : NONE; } this.setStyle(DISPLAY, value); return this; }, // private fixDisplay : function(){ var me = this; if (me.isStyle(DISPLAY, NONE)) { me.setStyle(VISIBILITY, HIDDEN); me.setStyle(DISPLAY, getDisplay(me)); // first try reverting to default if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block me.setStyle(DISPLAY, "block"); } } }, /** * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object * @return {Ext.dom.Element} this */ hide : function(animate){ // hideMode override if (typeof animate == 'string'){ this.setVisible(false, animate); return this; } this.setVisible(false, this.anim(animate)); return this; }, /** * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object * @return {Ext.dom.Element} this */ show : function(animate){ // hideMode override if (typeof animate == 'string'){ this.setVisible(true, animate); return this; } this.setVisible(true, this.anim(animate)); return this; } }); });
ryancanulla/findMe
web/ext/src/dom/Element_fx.js
JavaScript
mit
7,489
frappe.ui.form.GridRowForm = Class.extend({ init: function(opts) { $.extend(this, opts); this.wrapper = $('<div class="form-in-grid"></div>') .appendTo(this.row.wrapper); }, render: function() { var me = this; this.make_form(); this.form_area.empty(); this.layout = new frappe.ui.form.Layout({ fields: this.row.docfields, body: this.form_area, no_submit_on_enter: true, frm: this.row.frm, }); this.layout.make(); this.fields = this.layout.fields; this.fields_dict = this.layout.fields_dict; this.layout.refresh(this.row.doc); // copy get_query to fields for(var fieldname in (this.row.grid.fieldinfo || {})) { var fi = this.row.grid.fieldinfo[fieldname]; $.extend(me.fields_dict[fieldname], fi); } this.toggle_add_delete_button_display(this.wrapper); this.row.grid.open_grid_row = this; this.set_focus(); }, make_form: function() { if(!this.form_area) { $(frappe.render_template("grid_form", {grid:this})).appendTo(this.wrapper); this.form_area = this.wrapper.find(".form-area"); this.row.set_row_index(); this.set_form_events(); } }, set_form_events: function() { var me = this; this.wrapper.find(".grid-delete-row") .on('click', function() { me.row.remove(); return false; }); this.wrapper.find(".grid-insert-row") .on('click', function() { me.row.insert(true); return false; }); this.wrapper.find(".grid-insert-row-below") .on('click', function() { me.row.insert(true, true); return false; }); this.wrapper.find(".grid-append-row") .on('click', function() { me.row.toggle_view(false); me.row.grid.add_new_row(me.row.doc.idx+1, null, true); return false; }); this.wrapper.find(".grid-form-heading, .grid-footer-toolbar").on("click", function() { me.row.toggle_view(); return false; }); }, toggle_add_delete_button_display: function($parent) { $parent.find(".grid-header-toolbar .btn, .grid-footer-toolbar .btn") .toggle(this.row.grid.is_editable()); }, refresh_field: function(fieldname) { if(this.fields_dict[fieldname]) { this.fields_dict[fieldname].refresh(); this.layout && this.layout.refresh_dependency(); } }, set_focus: function() { // wait for animation and then focus on the first row var me = this; setTimeout(function() { if(me.row.frm && me.row.frm.doc.docstatus===0 || !me.row.frm) { var first = me.form_area.find("input:first"); if(first.length && !in_list(["Date", "Datetime", "Time"], first.attr("data-fieldtype"))) { try { first.get(0).focus(); } catch(e) { // } } } }, 500); }, });
StrellaGroup/frappe
frappe/public/js/frappe/form/grid_row_form.js
JavaScript
mit
2,632
var irc = require('../lib/irc.js'); var should = require('should'); var _ = require('underscore'); describe("irc.parseMessage", function() { var checks = { ':irc.dollyfish.net.nz 372 nodebot :The message of the day was last changed: 2012-6-16 23:57': { prefix: "irc.dollyfish.net.nz", server: "irc.dollyfish.net.nz", command: "rpl_motd", rawCommand: "372", commandType: "reply", args: [ "nodebot", "The message of the day was last changed: 2012-6-16 23:57" ] }, ':Ned!~martyn@irc.dollyfish.net.nz PRIVMSG #test :Hello nodebot!': { prefix: "Ned!~martyn@irc.dollyfish.net.nz", nick: "Ned", user: "~martyn", host: "irc.dollyfish.net.nz", command: "PRIVMSG", rawCommand: "PRIVMSG", commandType: "normal", args: [ "#test", "Hello nodebot!" ] }, ':Ned!~martyn@irc.dollyfish.net.nz PRIVMSG #test ::-)': { prefix: "Ned!~martyn@irc.dollyfish.net.nz", nick: "Ned", user: "~martyn", host: "irc.dollyfish.net.nz", command: "PRIVMSG", rawCommand: "PRIVMSG", commandType: "normal", args: [ "#test", ":-)" ] }, ':Ned!~martyn@irc.dollyfish.net.nz PRIVMSG #test ::': { prefix: "Ned!~martyn@irc.dollyfish.net.nz", nick: "Ned", user: "~martyn", host: "irc.dollyfish.net.nz", command: "PRIVMSG", rawCommand: "PRIVMSG", commandType: "normal", args: [ "#test", ":" ] }, ":Ned!~martyn@irc.dollyfish.net.nz PRIVMSG #test ::^:^:": { prefix: "Ned!~martyn@irc.dollyfish.net.nz", nick: "Ned", user: "~martyn", host: "irc.dollyfish.net.nz", command: "PRIVMSG", rawCommand: "PRIVMSG", commandType: "normal", args: [ "#test", ":^:^:" ] }, ":some.irc.net 324 webuser #channel +Cnj 5:10": { prefix: "some.irc.net", server: "some.irc.net", command: "rpl_channelmodeis", rawCommand: "324", commandType: "reply", args: [ "webuser", "#channel", "+Cnj", "5:10" ] }, ":nick!user@host QUIT :Ping timeout: 252 seconds": { prefix: "nick!user@host", nick: "nick", user: "user", host: "host", command: "QUIT", rawCommand: "QUIT", commandType: "normal", args: [ "Ping timeout: 252 seconds" ] }, ":nick!user@host PRIVMSG #channel :so : colons: :are :: not a problem ::::": { prefix: "nick!user@host", nick: "nick", user: "user", host: "host", command: "PRIVMSG", rawCommand: "PRIVMSG", commandType: "normal", args: [ "#channel", "so : colons: :are :: not a problem ::::" ] } }; _.each(checks, function(result, line) { it('parse ' + line, function() { JSON.stringify(result).should.equal(JSON.stringify(irc.parseMessage(line))); }); }); });
clarkeadg/piratesails
node_modules/sails-irc/node_modules/irc/test/parse-line.js
JavaScript
mit
3,289
ace.define("ace/ext/themelist",["require","exports","module","ace/lib/fixoldbrowsers"], function(acequire, exports, module) { "use strict"; acequire("ace/lib/fixoldbrowsers"); var themeData = [ ["Chrome" ], ["Clouds" ], ["Crimson Editor" ], ["Dawn" ], ["Dreamweaver" ], ["Eclipse" ], ["GitHub" ], ["Solarized Light"], ["TextMate" ], ["Tomorrow" ], ["XCode" ], ["Kuroir"], ["KatzenMilch"], ["Ambiance" ,"ambiance" , "dark"], ["Chaos" ,"chaos" , "dark"], ["Clouds Midnight" ,"clouds_midnight" , "dark"], ["Cobalt" ,"cobalt" , "dark"], ["idle Fingers" ,"idle_fingers" , "dark"], ["krTheme" ,"kr_theme" , "dark"], ["Merbivore" ,"merbivore" , "dark"], ["Merbivore Soft" ,"merbivore_soft" , "dark"], ["Mono Industrial" ,"mono_industrial" , "dark"], ["Monokai" ,"monokai" , "dark"], ["Pastel on dark" ,"pastel_on_dark" , "dark"], ["Solarized Dark" ,"solarized_dark" , "dark"], ["Terminal" ,"terminal" , "dark"], ["Tomorrow Night" ,"tomorrow_night" , "dark"], ["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"], ["Tomorrow Night Bright","tomorrow_night_bright" , "dark"], ["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"], ["Twilight" ,"twilight" , "dark"], ["Vibrant Ink" ,"vibrant_ink" , "dark"] ]; exports.themesByName = {}; exports.themes = themeData.map(function(data) { var name = data[1] || data[0].replace(/ /g, "_").toLowerCase(); var theme = { caption: data[0], theme: "ace/theme/" + name, isDark: data[2] == "dark", name: name }; exports.themesByName[name] = theme; return theme; }); }); (function() { ace.acequire(["ace/ext/themelist"], function() {}); })();
phupn1510/ELK
kibana/kibana/node_modules/brace/ext/themelist.js
JavaScript
mit
2,271
(function(){var e=function(e){var t=this,n=function(){function r(e){var t="100%",n="0px",r={top:n,bottom:t,left:n,right:t};return r[e]||e}var t="background-position",n=e.camelCase;e.each(["x","y"],function(i,s){var o=n(t+"-"+s);e.cssHooks[o]={get:function(n){var s=e.css(n,t).split(/\s+/,2);return r(s[i])},set:function(n,s){var o=e.css(n,t).split(/\s+/,2);o[i]=r(s),e.style(n,t,o.join(" "))}},e.fx.step[o]=function(t){e.style(t.elem,t.prop,t.now)}})};n(),t.resolveWith(n)};dispatch("backgroundPosition").containing(e).to("Foundry/2.1 Modules")})();
cjaypierson/lpm
media/foundry/2.1/scripts/backgroundPosition.js
JavaScript
gpl-2.0
549
(function ($) { Drupal.behaviors.openlayers_spinjs = { attach: function (context, settings) { for (var map_id in settings.spinjs) { var target = document.getElementById('map-container-' + map_id); var spinner = new Spinner(settings.spinjs[map_id]).spin(target); setTimeout(function() { $(spinner.el).fadeOut('slow', function() { spinner.stop(); }); }, 1000); } } } }(jQuery));
KenAdamson/rwb-site
sites/all/modules/openlayers/modules/openlayers_library/src/Plugin/Component/SpinJS/js/spin.js
JavaScript
gpl-2.0
465
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'showblocks', 'ko', { toolbar: '블록 보기' } );
gmuro/dolibarr
htdocs/includes/ckeditor/ckeditor/_source/plugins/showblocks/lang/ko.js
JavaScript
gpl-3.0
222
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, less */ /** * ExtensionUtils defines utility methods for implementing extensions. */ define(function (require, exports, module) { "use strict"; /** * Appends a <style> tag to the document's head. * * @param {!string} css CSS code to use as the tag's content * @return {!HTMLStyleElement} The generated HTML node **/ function addEmbeddedStyleSheet(css) { return $("<style>").text(css).appendTo("head")[0]; } /** * Appends a <link> tag to the document's head. * * @param {!string} url URL to a style sheet * @param {$.Deferred=} deferred Optionally check for load and error events * @return {!HTMLLinkElement} The generated HTML node **/ function addLinkedStyleSheet(url, deferred) { var attributes = { type: "text/css", rel: "stylesheet", href: url }; var $link = $("<link/>").attr(attributes); if (deferred) { $link.on('load', deferred.resolve).on('error', deferred.reject); } $link.appendTo("head"); return $link[0]; } /** * Parses LESS code and returns a promise that resolves with plain CSS code. * * Pass the {@link url} argument to resolve relative URLs contained in the code. * Make sure URLs in the code are wrapped in quotes, like so: * background-image: url("image.png"); * * @param {!string} code LESS code to parse * @param {?string} url URL to the file containing the code * @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed */ function parseLessCode(code, url) { var result = new $.Deferred(), options; if (url) { var dir = url.slice(0, url.lastIndexOf("/") + 1), file = url.slice(dir.length); options = { filename: file, paths: [dir], rootpath: dir }; } var parser = new less.Parser(options); parser.parse(code, function onParse(err, tree) { if (err) { result.reject(err); } else { result.resolve(tree.toCSS()); } }); return result.promise(); } /** * Returns a path to an extension module. * * @param {!module} module Module provided by RequireJS * @param {?string} path Relative path from the extension folder to a file * @return {!string} The path to the module's folder **/ function getModulePath(module, path) { var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1); if (path) { modulePath += path; } return modulePath; } /** * Returns a URL to an extension module. * * @param {!module} module Module provided by RequireJS * @param {?string} path Relative path from the extension folder to a file * @return {!string} The URL to the module's folder **/ function getModuleUrl(module, path) { var url = encodeURI(getModulePath(module, path)); // On Windows, $.get() fails if the url is a full pathname. To work around this, // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname, // but *doesn't* work if it is prepended with "file://". Go figure. // However, the prefix "file://localhost" does work. if (brackets.platform === "win" && url.indexOf(":") !== -1) { url = "file:///" + url; } return url; } /** * Performs a GET request using a path relative to an extension module. * * The resulting URL can be retrieved in the resolve callback by accessing * * @param {!module} module Module provided by RequireJS * @param {!string} path Relative path from the extension folder to a file * @return {!$.Promise} A promise object that is resolved with the contents of the requested file **/ function loadFile(module, path) { var url = getModuleUrl(module, path), promise = $.get(url); return promise; } /** * Loads a style sheet (CSS or LESS) relative to the extension module. * * @param {!module} module Module provided by RequireJS * @param {!string} path Relative path from the extension folder to a CSS or LESS file * @return {!$.Promise} A promise object that is resolved with an HTML node if the file can be loaded. */ function loadStyleSheet(module, path) { var result = new $.Deferred(); loadFile(module, path) .done(function (content) { var url = this.url; if (url.slice(-5) === ".less") { parseLessCode(content, url) .done(function (css) { result.resolve(addEmbeddedStyleSheet(css)); }) .fail(result.reject); } else { var deferred = new $.Deferred(), link = addLinkedStyleSheet(url, deferred); deferred .done(function () { result.resolve(link); }) .fail(result.reject); } }) .fail(result.reject); return result.promise(); } exports.addEmbeddedStyleSheet = addEmbeddedStyleSheet; exports.addLinkedStyleSheet = addLinkedStyleSheet; exports.parseLessCode = parseLessCode; exports.getModulePath = getModulePath; exports.getModuleUrl = getModuleUrl; exports.loadFile = loadFile; exports.loadStyleSheet = loadStyleSheet; });
MatiasNAmendola/gnome-web
usr/lib/brackets/src/utils/ExtensionUtils.js
JavaScript
gpl-3.0
7,333
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview TraceEventImporter imports TraceEvent-formatted data * into the provided timeline model. */ base.require('timeline_model'); base.require('timeline_color_scheme'); base.exportTo('tracing', function() { function TraceEventImporter(model, eventData) { this.importPriority = 1; this.model_ = model; if (typeof(eventData) === 'string' || eventData instanceof String) { // If the event data begins with a [, then we know it should end with a ]. // The reason we check for this is because some tracing implementations // cannot guarantee that a ']' gets written to the trace file. So, we are // forgiving and if this is obviously the case, we fix it up before // throwing the string at JSON.parse. if (eventData[0] == '[') { n = eventData.length; if (eventData[n - 1] == '\n') { eventData = eventData.substring(0, n - 1); n--; if (eventData[n - 1] == '\r') { eventData = eventData.substring(0, n - 1); n--; } } if (eventData[n - 1] == ',') eventData = eventData.substring(0, n - 1); if (eventData[n - 1] != ']') eventData = eventData + ']'; } this.events_ = JSON.parse(eventData); } else { this.events_ = eventData; } // Some trace_event implementations put the actual trace events // inside a container. E.g { ... , traceEvents: [ ] } // If we see that, just pull out the trace events. if (this.events_.traceEvents) { this.events_ = this.events_.traceEvents; for (fieldName in this.events_) { if (fieldName == 'traceEvents') continue; this.model_.metadata.push({name: fieldName, value: this.events_[fieldName]}); } } // Async events need to be processed durign finalizeEvents this.allAsyncEvents_ = []; } /** * @return {boolean} Whether obj is a TraceEvent array. */ TraceEventImporter.canImport = function(eventData) { // May be encoded JSON. But we dont want to parse it fully yet. // Use a simple heuristic: // - eventData that starts with [ are probably trace_event // - eventData that starts with { are probably trace_event // May be encoded JSON. Treat files that start with { as importable by us. if (typeof(eventData) === 'string' || eventData instanceof String) { return eventData[0] == '{' || eventData[0] == '['; } // Might just be an array of events if (eventData instanceof Array && eventData.length && eventData[0].ph) return true; // Might be an object with a traceEvents field in it. if (eventData.traceEvents) return eventData.traceEvents instanceof Array && eventData.traceEvents[0].ph; return false; }; TraceEventImporter.prototype = { __proto__: Object.prototype, /** * Helper to process an 'async finish' event, which will close an open slice * on a TimelineAsyncSliceGroup object. */ processAsyncEvent: function(index, event) { var thread = this.model_.getOrCreateProcess(event.pid). getOrCreateThread(event.tid); this.allAsyncEvents_.push({ event: event, thread: thread}); }, /** * Helper that creates and adds samples to a TimelineCounter object based on * 'C' phase events. */ processCounterEvent: function(event) { var ctr_name; if (event.id !== undefined) ctr_name = event.name + '[' + event.id + ']'; else ctr_name = event.name; var ctr = this.model_.getOrCreateProcess(event.pid) .getOrCreateCounter(event.cat, ctr_name); // Initialize the counter's series fields if needed. if (ctr.numSeries == 0) { for (var seriesName in event.args) { ctr.seriesNames.push(seriesName); ctr.seriesColors.push( tracing.getStringColorId(ctr.name + '.' + seriesName)); } if (ctr.numSeries == 0) { this.model_.importErrors.push('Expected counter ' + event.name + ' to have at least one argument to use as a value.'); // Drop the counter. delete ctr.parent.counters[ctr.name]; return; } } // Add the sample values. ctr.timestamps.push(event.ts / 1000); for (var i = 0; i < ctr.numSeries; i++) { var seriesName = ctr.seriesNames[i]; if (event.args[seriesName] === undefined) { ctr.samples.push(0); continue; } ctr.samples.push(event.args[seriesName]); } }, /** * Walks through the events_ list and outputs the structures discovered to * model_. */ importEvents: function() { // Walk through events var events = this.events_; // Some events cannot be handled until we have done a first pass over the // data set. So, accumulate them into a temporary data structure. var second_pass_events = []; for (var eI = 0; eI < events.length; eI++) { var event = events[eI]; if (event.ph == 'B') { var thread = this.model_.getOrCreateProcess(event.pid) .getOrCreateThread(event.tid); if (!thread.isTimestampValidForBeginOrEnd(event.ts / 1000)) { this.model_.importErrors.push( 'Timestamps are moving backward.'); continue; } thread.beginSlice(event.cat, event.name, event.ts / 1000, event.args); } else if (event.ph == 'E') { var thread = this.model_.getOrCreateProcess(event.pid) .getOrCreateThread(event.tid); if (!thread.isTimestampValidForBeginOrEnd(event.ts / 1000)) { this.model_.importErrors.push( 'Timestamps are moving backward.'); continue; } if (!thread.openSliceCount) { this.model_.importErrors.push( 'E phase event without a matching B phase event.'); continue; } var slice = thread.endSlice(event.ts / 1000); for (var arg in event.args) { if (slice.args[arg] !== undefined) { this.model_.importErrors.push( 'Both the B and E phases of ' + slice.name + 'provided values for argument ' + arg + '. ' + 'The value of the E phase event will be used.'); } slice.args[arg] = event.args[arg]; } } else if (event.ph == 'S') { this.processAsyncEvent(eI, event); } else if (event.ph == 'F') { this.processAsyncEvent(eI, event); } else if (event.ph == 'T') { this.processAsyncEvent(eI, event); } else if (event.ph == 'I') { // Treat an Instant event as a duration 0 slice. // TimelineSliceTrack's redraw() knows how to handle this. var thread = this.model_.getOrCreateProcess(event.pid) .getOrCreateThread(event.tid); thread.beginSlice(event.cat, event.name, event.ts / 1000, event.args); thread.endSlice(event.ts / 1000); } else if (event.ph == 'C') { this.processCounterEvent(event); } else if (event.ph == 'M') { if (event.name == 'thread_name') { var thread = this.model_.getOrCreateProcess(event.pid) .getOrCreateThread(event.tid); thread.name = event.args.name; } else { this.model_.importErrors.push( 'Unrecognized metadata name: ' + event.name); } } else if (event.ph == 's') { // NB: toss until there's proper support } else if (event.ph == 't') { // NB: toss until there's proper support } else if (event.ph == 'f') { // NB: toss until there's proper support } else { this.model_.importErrors.push( 'Unrecognized event phase: ' + event.ph + '(' + event.name + ')'); } } }, /** * Called by the TimelineModel after all other importers have imported their * events. */ finalizeImport: function() { this.createAsyncSlices_(); }, createAsyncSlices_: function() { if (this.allAsyncEvents_.length == 0) return; this.allAsyncEvents_.sort(function(x, y) { return x.event.ts - y.event.ts; }); var asyncEventStatesByNameThenID = {}; var allAsyncEvents = this.allAsyncEvents_; for (var i = 0; i < allAsyncEvents.length; i++) { var asyncEventState = allAsyncEvents[i]; var event = asyncEventState.event; var name = event.name; if (name === undefined) { this.model_.importErrors.push( 'Async events (ph: S, T or F) require an name parameter.'); continue; } var id = event.id; if (id === undefined) { this.model_.importErrors.push( 'Async events (ph: S, T or F) require an id parameter.'); continue; } // TODO(simonjam): Add a synchronous tick on the appropriate thread. if (event.ph == 'S') { if (asyncEventStatesByNameThenID[name] === undefined) asyncEventStatesByNameThenID[name] = {}; if (asyncEventStatesByNameThenID[name][id]) { this.model_.importErrors.push( 'At ' + event.ts + ', a slice of the same id ' + id + ' was alrady open.'); continue; } asyncEventStatesByNameThenID[name][id] = []; asyncEventStatesByNameThenID[name][id].push(asyncEventState); } else { if (asyncEventStatesByNameThenID[name] === undefined) { this.model_.importErrors.push( 'At ' + event.ts + ', no slice named ' + name + ' was open.'); continue; } if (asyncEventStatesByNameThenID[name][id] === undefined) { this.model_.importErrors.push( 'At ' + event.ts + ', no slice named ' + name + ' with id=' + id + ' was open.'); continue; } var events = asyncEventStatesByNameThenID[name][id]; events.push(asyncEventState); if (event.ph == 'F') { // Create a slice from start to end. var slice = new tracing.TimelineAsyncSlice( events[0].event.cat, name, tracing.getStringColorId(name), events[0].event.ts / 1000); slice.duration = (event.ts / 1000) - (events[0].event.ts / 1000); slice.startThread = events[0].thread; slice.endThread = asyncEventState.thread; slice.id = id; slice.args = events[0].event.args; slice.subSlices = []; // Create subSlices for each step. for (var j = 1; j < events.length; ++j) { var subName = name; if (events[j - 1].event.ph == 'T') subName = name + ':' + events[j - 1].event.args.step; var subSlice = new tracing.TimelineAsyncSlice( events[0].event.cat, subName, tracing.getStringColorId(name + j), events[j - 1].event.ts / 1000); subSlice.duration = (events[j].event.ts / 1000) - (events[j - 1].event.ts / 1000); subSlice.startThread = events[j - 1].thread; subSlice.endThread = events[j].thread; subSlice.id = id; subSlice.args = events[j - 1].event.args; slice.subSlices.push(subSlice); } // The args for the finish event go in the last subSlice. var lastSlice = slice.subSlices[slice.subSlices.length - 1]; for (var arg in event.args) lastSlice.args[arg] = event.args[arg]; // Add |slice| to the start-thread's asyncSlices. slice.startThread.asyncSlices.push(slice); delete asyncEventStatesByNameThenID[name][id]; } } } } }; tracing.TimelineModel.registerImporter(TraceEventImporter); return { TraceEventImporter: TraceEventImporter }; });
ThangBK2009/android-source-browsing.platform--external--chromium-trace
trace-viewer/src/trace_event_importer.js
JavaScript
bsd-3-clause
12,543
var through = require('through2'); var derequire = require('./'); module.exports = function apply(b, opts) { var buffers = []; if (!Array.isArray(opts)) { opts = undefined; } b.pipeline.get('pack').push(through(function(chunk, enc, next) { buffers.push(chunk); next(); }, function(next) { this.push(derequire(Buffer.concat(buffers), opts)); next(); })); b.once('reset', function() { apply(b, opts); }); };
LeoLombardi/tos-laimas-compass
tos-laimas-compass-win32-x64/resources/app/node_modules/derequire/plugin.js
JavaScript
mit
451
require([ 'core/dispatcher' ], function(Dispatcher) { var global = this; /** * Store-testing facilities for jasmine suites. * * Exposed facilities: * * 1. Global onChange and onError spies * * Since it's very common you'll want to pass "onChange" and "onError" * callbacks to test store activity, you get these as jasmine spies for free * in every spec. * * They're also exposed to the global context, so you can just reference them * as "onChange" and "onError". * * 2. Helper method: "this.sendAction()" * * Signature: * this.sendAction(action, payload[, customOnChange, customOnError]) * * Returns: * The promise returned by the Dispatcher. * * Send an action request through the dispatcher with the given payload. * * If you don't pass in custom onChange and onError handlers, the global ones * will be used. * * describe('statistics:generateReport', function() { * this.storeSuite(myStore); * * it('should work', function() { * this.sendAction('statistics:generateReport', 'student_analysis'); * expect(onChange).toHaveBeenCalled(); * }); * }); * * 3. Auto-reset of store state, if you pass it in * * 4. Suite implicitly becomes a PromiseSuite (see jasmine_rsvp) so you can do * `this.flush()` to flush the promise queue. * * @param {Store} [store=undefined] * The store you're testing. If you pass this in, you will get an * auto afterEach() block that resets the Store's state by calling * store.__reset__(). */ jasmine.Suite.prototype.storeSuite = function(store) { this.promiseSuite = true; this.beforeEach(function() { var onChange = global.onChange = jasmine.createSpy('onChange'); var onError = global.onError = jasmine.createSpy('onError'); this.sendAction = function(action, payload, _onChange, _onError) { var svc = Dispatcher.dispatch(action, payload); _onChange = _onChange || onChange; _onError = _onError || onError; svc.promise.then(_onChange, _onError); this.flush(); return svc.promise; }; }); this.afterEach(function() { if (store) { store.__reset__(); } }); }; });
dgynn/canvas-lms
client_apps/canvas_quizzes/apps/statistics/test/helpers/store_suite.js
JavaScript
agpl-3.0
2,326
//! moment.js locale configuration //! locale : Gujarati [gu] //! author : Kaushik Thanki : https://github.com/Kaushik1987 import moment from '../moment'; var symbolMap = { '1': '૧', '2': '૨', '3': '૩', '4': '૪', '5': '૫', '6': '૬', '7': '૭', '8': '૮', '9': '૯', '0': '૦', }, numberMap = { '૧': '1', '૨': '2', '૩': '3', '૪': '4', '૫': '5', '૬': '6', '૭': '7', '૮': '8', '૯': '9', '૦': '0', }; export default moment.defineLocale('gu', { months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split( '_' ), monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split( '_' ), monthsParseExact: true, weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split( '_' ), weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'), weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'), longDateFormat: { LT: 'A h:mm વાગ્યે', LTS: 'A h:mm:ss વાગ્યે', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm વાગ્યે', LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે', }, calendar: { sameDay: '[આજ] LT', nextDay: '[કાલે] LT', nextWeek: 'dddd, LT', lastDay: '[ગઇકાલે] LT', lastWeek: '[પાછલા] dddd, LT', sameElse: 'L', }, relativeTime: { future: '%s મા', past: '%s પહેલા', s: 'અમુક પળો', ss: '%d સેકંડ', m: 'એક મિનિટ', mm: '%d મિનિટ', h: 'એક કલાક', hh: '%d કલાક', d: 'એક દિવસ', dd: '%d દિવસ', M: 'એક મહિનો', MM: '%d મહિનો', y: 'એક વર્ષ', yy: '%d વર્ષ', }, preparse: function (string) { return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Gujarati notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati. meridiemParse: /રાત|બપોર|સવાર|સાંજ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'રાત') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'સવાર') { return hour; } else if (meridiem === 'બપોર') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'સાંજ') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'રાત'; } else if (hour < 10) { return 'સવાર'; } else if (hour < 17) { return 'બપોર'; } else if (hour < 20) { return 'સાંજ'; } else { return 'રાત'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6, // The week that contains Jan 6th is the first week of the year. }, });
edwinspire/open-ams
node_modules/moment/src/locale/gu.js
JavaScript
lgpl-3.0
4,136
define([ 'underscore', './interval' ], function (_, Interval) { 'use strict'; var ts = {}; // map compatable parseInt function base10Int(val) { return parseInt(val, 10); } // trim the ms off of a time, but return it with empty ms. function getDatesTime(date) { return Math.floor(date.getTime() / 1000)*1000; } /** * Certain graphs require 0 entries to be specified for them to render * properly (like the line graph). So with this we will caluclate all of * the expected time measurements, and fill the missing ones in with 0 * @param {object} opts An object specifying some/all of the options * * OPTIONS: * @opt {string} interval The interval notion describing the expected spacing between * each data point. * @opt {date} start_date (optional) The start point for the time series, setting this and the * end_date will ensure that the series streches to resemble the entire * expected result * @opt {date} end_date (optional) The end point for the time series, see start_date * @opt {string} fill_style Either "minimal", or "all" describing the strategy used to zero-fill * the series. */ ts.ZeroFilled = function (opts) { opts = _.defaults(opts, { interval: '10m', start_date: null, end_date: null, fill_style: 'minimal' }); // the expected differenece between readings. this.interval = new Interval(opts.interval); //this.interval = 1 // will keep all values here, keyed by their time this._data = {}; this.start_value = opts.start_date && base10Int(opts.start_date); this.end_value = opts.end_date && base10Int(opts.end_date); this.opts = opts; }; /** * Add a row * @param {int} time The time for the value, in * @param {any} value The value at this time */ ts.ZeroFilled.prototype.addValue = function (time, value) { if (time instanceof Date) { time = getDatesTime(time); } else { time = base10Int(time); } if (!isNaN(time)) { this._data[time] = (_.isUndefined(value) ? 0 : value); } this._cached_times = null; }; /** * Get an array of the times that have been explicitly set in the series * @param {array} include (optional) list of timestamps to include in the response * @return {array} An array of integer times. */ ts.ZeroFilled.prototype.getOrderedTimes = function (include) { var times = _.map(_.keys(this._data), base10Int); if (_.isArray(include)) { times = times.concat(include); } return _.uniq(times.sort(function (a, b) { // decending numeric sort return a - b; }), true); }; /** * return the rows in the format: * [ [time, value], [time, value], ... ] * * Heavy lifting is done by _get(Min|All)FlotPairs() * @param {array} required_times An array of timestamps that must be in the resulting pairs * @return {array} */ ts.ZeroFilled.prototype.getFlotPairs = function (required_times) { var times = this.getOrderedTimes(required_times), strategy, pairs; if(this.opts.fill_style === 'all') { strategy = this._getAllFlotPairs; } else { strategy = this._getMinFlotPairs; } pairs = _.reduce( times, // what strategy, // how [], // where this // context ); // if the first or last pair is inside either the start or end time, // add those times to the series with null values so the graph will stretch to contain them. if (this.start_value && (pairs.length === 0 || pairs[0][0] > this.start_value)) { pairs.unshift([this.start_value, null]); } if (this.end_value && (pairs.length === 0 || pairs[pairs.length - 1][0] < this.end_value)) { pairs.push([this.end_value, null]); } return pairs; }; /** * ** called as a reduce stragegy in getFlotPairs() ** * Fill zero's on either side of the current time, unless there is already a measurement there or * we are looking at an edge. * @return {array} An array of points to plot with flot */ ts.ZeroFilled.prototype._getMinFlotPairs = function (result, time, i, times) { var next, expected_next, prev, expected_prev; // check for previous measurement if (i > 0) { prev = times[i - 1]; expected_prev = this.interval.before(time); if (prev < expected_prev) { result.push([expected_prev, 0]); } } // add the current time result.push([ time, this._data[time] || 0 ]); // check for next measurement if (times.length > i) { next = times[i + 1]; expected_next = this.interval.after(time); if (next > expected_next) { result.push([expected_next, 0]); } } return result; }; /** * ** called as a reduce stragegy in getFlotPairs() ** * Fill zero's to the right of each time, until the next measurement is reached or we are at the * last measurement * @return {array} An array of points to plot with flot */ ts.ZeroFilled.prototype._getAllFlotPairs = function (result, time, i, times) { var next, expected_next; result.push([ times[i], this._data[times[i]] || 0 ]); next = times[i + 1]; expected_next = this.interval.after(time); for(; times.length > i && next > expected_next; expected_next = this.interval.after(expected_next)) { result.push([expected_next, 0]); } return result; }; return ts; });
LucidWorks/solr-for-datascience
static/app/panels/rangeFacet/timeSeries.js
JavaScript
apache-2.0
5,619
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax "use strict"; function f(v) { %DeoptimizeFunction(test); return 153; } function test() { var o = {}; var q = "q"; o.__defineSetter__(q, f); assertEquals(1, o[q] = 1); } %PrepareFunctionForOptimization(test); test(); test(); %OptimizeFunctionOnNextCall(test); test();
weolar/miniblink49
v8_7_5/test/mjsunit/compiler/deopt-accessors6.js
JavaScript
apache-2.0
484
// Copyright 2012 the V8 project authors. 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // 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 // OWNER 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. // Flags: --allow-natives-syntax --use-osr function test() { // Loop to force OSR. var j = 0; for (var i = 0; i < 80000; i++) { j++; } function SarShr(val) { return val >> (-2 >>> 0); } var K3 = 0x80000000; %PrepareFunctionForOptimization(SarShr); assertEquals(-2, SarShr(K3 | 0)); assertEquals(-2, SarShr(K3 | 0)); %OptimizeFunctionOnNextCall(SarShr); assertEquals(-2, SarShr(K3 | 0)); } test(); //test();
weolar/miniblink49
v8_7_5/test/mjsunit/compiler/osr-sar.js
JavaScript
apache-2.0
2,041