<commit_before>require("underscore");
var utils = require("../common/utils");
var loading = require("./loading");
var Iframe = require("./iframe");
var tenantList = {};
var DEFAULT_CONFIG;

// get parameters from easemob.js
var baseConfig = getScriptConfig();
var _config = {};
var iframe;
var bind;

window.easemobim = window.easemobim || {};
window.easemobim.config = window.easemobim.config || {};
window.easemobim.version = "__WEBIM_PLUGIN_VERSION__";

if(
	/MSIE 7\.0/.test(navigator.userAgent)
	&& !window.localStorage
	&& !document.querySelector
){
	easemobim.bind = function(){
		alert("您使用的IE浏览器版本过低，请使用IE8以上版本的IE浏览器或Chrome浏览器"); // eslint-disable-line no-alert
	};
	throw new Error("unsupported browser.");
}

require("../../plugin-scss/easemob.scss");

DEFAULT_CONFIG = {
	tenantId: "",
	to: "",
	agentName: "",
	appKey: "",
	domain: "",
	path: "",
	ticket: true,
	staticPath: "",
	buttonText: __("common.contact_agent"),
	dialogWidth: "360px",
	dialogHeight: "550px",
	dragenable: true,
	minimum: true,
	soundReminder: true,
	titleSlide: true,
	dialogPosition: { x: "10px", y: "10px" },
	user: {
		username: "",
		password: "",
		token: ""
	},
	fromUrl: window.location.href,
	referer: document.referrer
};
console.log(window.location.href)

// init _config & concat config and global easemobim.config
function reset(config){
	var hide;
	var resources;
	var sat;
	// growing io user id
	// 由于存在 cookie 跨域问题，所以从配置传过去
	var configData = _.extend({}, DEFAULT_CONFIG, { grUserId: utils.get("gr_user_id") });
	config = config || {};
	configData = _.extend({}, configData, easemobim.config, config);

	hide = utils.convertFalse(configData.hide) !== "" ? configData.hide : baseConfig.json.hide;
	resources = utils.convertFalse(_config.resources) !== "" ? configData.resources : baseConfig.json.resources;
	sat = utils.convertFalse(configData.satisfaction) !== "" ? configData.satisfaction : baseConfig.json.sat;

	configData = _.extend({}, configData, {
		tenantId: configData.tenantId || baseConfig.json.tenantId,
		configId: configData.configId || baseConfig.json.configId,
		hide: utils.convertFalse(hide),
		resources: utils.convertFalse(resources),
		satisfaction: utils.convertFalse(sat),
		domain: configData.domain || baseConfig.domain,
		path: configData.path || (baseConfig.domain + "__WEBIM_SLASH_KEY_PATH__/webim"),
		staticPath: configData.staticPath || (baseConfig.domain + "__WEBIM_SLASH_KEY_PATH__/webim/static"),
		guestId: utils.getStore("guestId") // 这个是别人种的cookie
	});
	// demo 页面点击联系客服带着 tenantId, 就删除 config 中的 configId, 否则 configId 存在就会用 configId 去渲染页面
	if(config.tenantId){
		configData.configId = "";
	}
	setConfig(configData);
}

function setConfig(configExt){
	_config = _.extend({}, _config, configExt);
}

// get config from current script
function getScriptConfig(){
	var src;
	var obj = {};
	var scripts = document.scripts;
	var s, l, i, len;

	for(s = 0, l = scripts.length; s < l; s++){
		if(~scripts[s].src.indexOf("easemob.js")){
			// src 会被强制加上域名
			src = scripts[s].src;
			break;
		}
	}

	if(!src){
		return { json: obj, domain: "" };
	}

	var tmp;
	var idx = src.indexOf("?");
	var sIdx = ~src.indexOf("//") ? src.indexOf("//") : 0;
	var domain = src.slice(0, src.indexOf("/", sIdx + 2));
	var arr = src.slice(idx + 1).split("&");

	for(i = 0, len = arr.length; i < len; i++){
		tmp = arr[i].split("=");
		obj[tmp[0]] = tmp.length > 1 ? decodeURIComponent(tmp[1]) : "";
	}
	return { json: obj, domain: domain };
}

/*
 * @param: {String} 技能组名称，选填
 * 兼容旧版接口，建议使用easemobim.bind方法
 */
window.easemobIM = function(group){
	easemobim.bind({ emgroup: group });
};
window.easemobIMS = function(tenantId, group){
	easemobim.bind({ tenantId: tenantId, emgroup: group });
};

/*
 * @param: {Object} config
 */

bind = function(config, autoLoad){
	var cacheKeyName;
	var i;
	reset(config);
	// 自动加载的
	// 后续把此 if else 消除掉
	if(autoLoad){
		if(
			(!_config.hide || _config.autoConnect || _config.eventCollector)
			&& (_config.tenantId || _config.configId)
			// CLOUD-15297 【dev47.35】网页插件：手机端不弹出自动邀请弹窗
			// && !utils.isMobile
		){
			cacheKeyName = _config.configId || (_config.tenantId + (_config.emgroup || ""));
			if(!_config.user.username){
				// 从cookie里取用户名
				// keyName = [to + ] tenantId [ + emgroup]
				_config.isUsernameFromCookie = true;
				_config.user = {
					username: utils.get(
						_config.configId || ((_config.to || "") + _config.tenantId + (_config.emgroup || ""))
					)
				};
			}
			iframe = tenantList[cacheKeyName] || new Iframe(_config);
			tenantList[cacheKeyName] = iframe;
			iframe.set(_config, iframe.close);
			// 访客上报用后失效
			easemobim.config.eventCollector = false;
		}
	}
	// 用户点击的
	else{
		// 防止空参数调用异常
		config = config || {};
		config.emgroup = config.emgroup || easemobim.config.emgroup || "";

		cacheKeyName = config.configId || (config.tenantId + config.emgroup);

		for(i in tenantList){
			if(Object.prototype.hasOwnProperty.call(tenantList, i)){
				// if(tenantList[i].show){
				// 	return false
				// }
				tenantList[i].close();
			}
		}

		iframe = tenantList[cacheKeyName];

		if(iframe){
			iframe.open();
		}
		else{
			utils.isMobile && loading.show();
			if(!_config.user.username){
				// 从cookie里取用户名
				// keyName = [to + ] tenantId [ + emgroup]
				config.isUsernameFromCookie = true;
				config.user = {
					username: utils.get(
						_config.configId || ((_config.to || "") + _config.tenantId + (_config.emgroup || ""))
					)
				};
			}
			setConfig(config);

			if(!_config.tenantId && !_config.configId){
				console.error("No tenantId is specified.");
				return;
			}

			iframe = new Iframe(_config);
			tenantList[cacheKeyName] = iframe;

			iframe.set(_config, iframe.open);
		}
	}

};

// open api1: send custom extend message
easemobim.sendExt = function(ext){
	if(iframe){
		iframe.send({
			ext: ext
		});
	}
	else{
		console.error("The chat window is not initialized.");
	}
};

// open api2: send text message
/*
 * @param: {object} 消息体
 * {
 *		data: "text msg",
 *		ext: {}
 * }
 */

easemobim.sendText = function(msg){
	if(iframe){
		iframe.sendText(msg);
	}
	else{
		console.error("The chat window is not initialized.");
	}
};

easemobim.minimize = function(){
	if(iframe){
		iframe.close();
	}
};
easemobim.restore = function(){
	if(iframe){
		iframe.open();
	}
};

// user click
window.easemobim.bind = function(config){
	bind(config, false);
};

// auto load
bind({}, true);

// support cmd & amd
if(typeof module === "object" && typeof module.exports === "object"){
	module.exports = easemobim;
}
else if(typeof define === "function" && define.amd){
	define("easemob-kefu-webim-plugin", [], function(){
		return easemobim;
	});
}
<commit_msg>店匠：着陆页获取 iframe 的 iframe 的父级url<commit_after>require("underscore");
var utils = require("../common/utils");
var loading = require("./loading");
var Iframe = require("./iframe");
var tenantList = {};
var DEFAULT_CONFIG;

// get parameters from easemob.js
var baseConfig = getScriptConfig();
var _config = {};
var iframe;
var bind;

window.easemobim = window.easemobim || {};
window.easemobim.config = window.easemobim.config || {};
window.easemobim.version = "__WEBIM_PLUGIN_VERSION__";

if(
	/MSIE 7\.0/.test(navigator.userAgent)
	&& !window.localStorage
	&& !document.querySelector
){
	easemobim.bind = function(){
		alert("您使用的IE浏览器版本过低，请使用IE8以上版本的IE浏览器或Chrome浏览器"); // eslint-disable-line no-alert
	};
	throw new Error("unsupported browser.");
}

require("../../plugin-scss/easemob.scss");

DEFAULT_CONFIG = {
	tenantId: "",
	to: "",
	agentName: "",
	appKey: "",
	domain: "",
	path: "",
	ticket: true,
	staticPath: "",
	buttonText: __("common.contact_agent"),
	dialogWidth: "360px",
	dialogHeight: "550px",
	dragenable: true,
	minimum: true,
	soundReminder: true,
	titleSlide: true,
	dialogPosition: { x: "10px", y: "10px" },
	user: {
		username: "",
		password: "",
		token: ""
	},
	fromUrl: window.location.href,
	referer: document.referrer
};
if(DEFAULT_CONFIG.fromUrl == "about:blank"){
	DEFAULT_CONFIG.fromUrl = window.frameElement.baseURI
}

// init _config & concat config and global easemobim.config
function reset(config){
	var hide;
	var resources;
	var sat;
	// growing io user id
	// 由于存在 cookie 跨域问题，所以从配置传过去
	var configData = _.extend({}, DEFAULT_CONFIG, { grUserId: utils.get("gr_user_id") });
	config = config || {};
	configData = _.extend({}, configData, easemobim.config, config);

	hide = utils.convertFalse(configData.hide) !== "" ? configData.hide : baseConfig.json.hide;
	resources = utils.convertFalse(_config.resources) !== "" ? configData.resources : baseConfig.json.resources;
	sat = utils.convertFalse(configData.satisfaction) !== "" ? configData.satisfaction : baseConfig.json.sat;

	configData = _.extend({}, configData, {
		tenantId: configData.tenantId || baseConfig.json.tenantId,
		configId: configData.configId || baseConfig.json.configId,
		hide: utils.convertFalse(hide),
		resources: utils.convertFalse(resources),
		satisfaction: utils.convertFalse(sat),
		domain: configData.domain || baseConfig.domain,
		path: configData.path || (baseConfig.domain + "__WEBIM_SLASH_KEY_PATH__/webim"),
		staticPath: configData.staticPath || (baseConfig.domain + "__WEBIM_SLASH_KEY_PATH__/webim/static"),
		guestId: utils.getStore("guestId") // 这个是别人种的cookie
	});
	// demo 页面点击联系客服带着 tenantId, 就删除 config 中的 configId, 否则 configId 存在就会用 configId 去渲染页面
	if(config.tenantId){
		configData.configId = "";
	}
	setConfig(configData);
}

function setConfig(configExt){
	_config = _.extend({}, _config, configExt);
}

// get config from current script
function getScriptConfig(){
	var src;
	var obj = {};
	var scripts = document.scripts;
	var s, l, i, len;

	for(s = 0, l = scripts.length; s < l; s++){
		if(~scripts[s].src.indexOf("easemob.js")){
			// src 会被强制加上域名
			src = scripts[s].src;
			break;
		}
	}

	if(!src){
		return { json: obj, domain: "" };
	}

	var tmp;
	var idx = src.indexOf("?");
	var sIdx = ~src.indexOf("//") ? src.indexOf("//") : 0;
	var domain = src.slice(0, src.indexOf("/", sIdx + 2));
	var arr = src.slice(idx + 1).split("&");

	for(i = 0, len = arr.length; i < len; i++){
		tmp = arr[i].split("=");
		obj[tmp[0]] = tmp.length > 1 ? decodeURIComponent(tmp[1]) : "";
	}
	return { json: obj, domain: domain };
}

/*
 * @param: {String} 技能组名称，选填
 * 兼容旧版接口，建议使用easemobim.bind方法
 */
window.easemobIM = function(group){
	easemobim.bind({ emgroup: group });
};
window.easemobIMS = function(tenantId, group){
	easemobim.bind({ tenantId: tenantId, emgroup: group });
};

/*
 * @param: {Object} config
 */

bind = function(config, autoLoad){
	var cacheKeyName;
	var i;
	reset(config);
	// 自动加载的
	// 后续把此 if else 消除掉
	if(autoLoad){
		if(
			(!_config.hide || _config.autoConnect || _config.eventCollector)
			&& (_config.tenantId || _config.configId)
			// CLOUD-15297 【dev47.35】网页插件：手机端不弹出自动邀请弹窗
			// && !utils.isMobile
		){
			cacheKeyName = _config.configId || (_config.tenantId + (_config.emgroup || ""));
			if(!_config.user.username){
				// 从cookie里取用户名
				// keyName = [to + ] tenantId [ + emgroup]
				_config.isUsernameFromCookie = true;
				_config.user = {
					username: utils.get(
						_config.configId || ((_config.to || "") + _config.tenantId + (_config.emgroup || ""))
					)
				};
			}
			iframe = tenantList[cacheKeyName] || new Iframe(_config);
			tenantList[cacheKeyName] = iframe;
			iframe.set(_config, iframe.close);
			// 访客上报用后失效
			easemobim.config.eventCollector = false;
		}
	}
	// 用户点击的
	else{
		// 防止空参数调用异常
		config = config || {};
		config.emgroup = config.emgroup || easemobim.config.emgroup || "";

		cacheKeyName = config.configId || (config.tenantId + config.emgroup);

		for(i in tenantList){
			if(Object.prototype.hasOwnProperty.call(tenantList, i)){
				// if(tenantList[i].show){
				// 	return false
				// }
				tenantList[i].close();
			}
		}

		iframe = tenantList[cacheKeyName];

		if(iframe){
			iframe.open();
		}
		else{
			utils.isMobile && loading.show();
			if(!_config.user.username){
				// 从cookie里取用户名
				// keyName = [to + ] tenantId [ + emgroup]
				config.isUsernameFromCookie = true;
				config.user = {
					username: utils.get(
						_config.configId || ((_config.to || "") + _config.tenantId + (_config.emgroup || ""))
					)
				};
			}
			setConfig(config);

			if(!_config.tenantId && !_config.configId){
				console.error("No tenantId is specified.");
				return;
			}

			iframe = new Iframe(_config);
			tenantList[cacheKeyName] = iframe;

			iframe.set(_config, iframe.open);
		}
	}

};

// open api1: send custom extend message
easemobim.sendExt = function(ext){
	if(iframe){
		iframe.send({
			ext: ext
		});
	}
	else{
		console.error("The chat window is not initialized.");
	}
};

// open api2: send text message
/*
 * @param: {object} 消息体
 * {
 *		data: "text msg",
 *		ext: {}
 * }
 */

easemobim.sendText = function(msg){
	if(iframe){
		iframe.sendText(msg);
	}
	else{
		console.error("The chat window is not initialized.");
	}
};

easemobim.minimize = function(){
	if(iframe){
		iframe.close();
	}
};
easemobim.restore = function(){
	if(iframe){
		iframe.open();
	}
};

// user click
window.easemobim.bind = function(config){
	bind(config, false);
};

// auto load
bind({}, true);

// support cmd & amd
if(typeof module === "object" && typeof module.exports === "object"){
	module.exports = easemobim;
}
else if(typeof define === "function" && define.amd){
	define("easemob-kefu-webim-plugin", [], function(){
		return easemobim;
	});
}
<|endoftext|>


<commit_before>angular.module('ram.touchspin', [])

.directive('ramTouchSpin', ['$timeout', '$interval', '$document', '$locale', function ($timeout, $interval, $document, $locale) {
    'use strict';

    var keyCodes = {
        left: 37,
        right: 39,
        up: 38,
        down: 40
    };

    var setScopeValues = function (scope, attrs) {
        if(attrs.min !== undefined){
            scope.min = parseFloat(Number(attrs.min));
        }else{
            scope.min = undefined;
        }
        if(attrs.max !== undefined){
            scope.max = parseFloat(Number(attrs.max));
        }else{
            scope.max = undefined;
        }
        scope.step = attrs.step || 1;
        scope.prefix = attrs.prefix || undefined;
        scope.postfix = attrs.postfix || undefined;
        scope.decimals = attrs.decimals || 0;
        scope.stepInterval = attrs.stepInterval || 100;
        scope.stepIntervalDelay = attrs.stepIntervalDelay || 500;
        scope.emptyStringNull = attrs.nullable || false;
        scope.initval = attrs.initval || (scope.emptyStringNull ? null : 0);
		//TODO: hanlde initial value
        //scope.model = scope.model !== undefined ? scope.model : scope.initval;
        var localeDecimalSeparator;
        if($locale.NUMBER_FORMATS.DECIMAL_SEP === undefined){
            //Be prepared for the case that variable name changes, this is not a public api
            localeDecimalSeparator = '.';
        }
        else{
            localeDecimalSeparator = $locale.NUMBER_FORMATS.DECIMAL_SEP;
        }
        scope.decimalSep = attrs.decimalSep || localeDecimalSeparator;
        if (attrs.withKey === "false") {
            scope.withKey = false;
        } else {
            scope.withKey = true;
        }
        if (attrs.vertical === "false") {
            scope.verticalButtons = false;
        } else {
            scope.verticalButtons = true;
        }
        if (scope.decimalSep === ".") {
            scope.regex = /^-?(?:\d+|\d*\.(\d+)?)$/i;
        } else if (scope.decimalSep === ",") {
            scope.regex = /^-?(?:\d+|\d*\,(\d+)?)$/i;
        } else {
            //any decimal separator
            scope.regex = new RegExp("^-?(?:\\d+|\\d*" + scope.decimalSep + "(\\d+)?)$");
        }
    };

    var toFloat = function (value, scope) {
        if(value === "" && scope.emptyStringNull){
            return null;
        }
        if (scope.decimalSep !== "." && (typeof value === "string" || value instanceof String)) {
            value = value.replace(scope.decimalSep, ".");
        }
        value = parseFloat(Number(value));
        return value;
    }

    var toString = function (value, decimalSep) {
        if(value === null || value === undefined){
            return "";
        }
        if( typeof value === 'number'){
            value = value.toString();
        }
        value = value.replace('.', decimalSep);
        return value;
    }

    return {
        restrict: 'EA',
        scope: true,
		require: 'ngModel',
        replace: true,
        link: function (scope, element, attrs, ngModelCtrl) {
            var timeout, timer, clickStart;
            scope.focused = false;

            setScopeValues(scope, attrs);

			//Move the name attribute
			var divElem = angular.element(element);
			divElem.removeAttr('name');
			angular.element(divElem[0].querySelector('input')).attr('name', name);

			var orignalRender = ngModelCtrl.$render;

			ngModelCtrl.$render = function () {
				scope.val = toString( ngModelCtrl.$modelValue, scope.decimalSep);
			};

			var updateNgModelValue = function(val){
				ngModelCtrl.$setViewValue(val);
				orignalRender();
			}

            scope.updateValue = function () {
                if (scope.val !== undefined) {
					//check regex first
					if(scope.regex.test(scope.val)){
						ngModelCtrl.$setValidity('invalid', true);
					}else{
						ngModelCtrl.$setValidity('invalid', false);
						return;
					}

                    var value = toFloat(scope.val, scope);
                    var adjustVal = false
                    if (scope.max != undefined && value > scope.max){
                         value = scope.max;
                         adjustVal = true;
                    }
                    else if (scope.min != undefined && value < scope.min) {
                        value = scope.min;
                        adjustVal = true;
                    }
                    if(adjustVal){
                        scope.val = toString(value,  scope.decimalSep);
                    }
					updateNgModelValue(value);
                }
            }

            scope.increment = function () {
                var value = parseFloat(parseFloat(Number(ngModelCtrl.$modelValue)) + parseFloat(scope.step)).toFixed(scope.decimals);
                if (scope.max != undefined && value > scope.max) return;
				updateNgModelValue( toFloat(value, scope));
				ngModelCtrl.$render();
            };

            scope.decrement = function () {
                var value = parseFloat(parseFloat(Number(ngModelCtrl.$modelValue)) - parseFloat(scope.step)).toFixed(scope.decimals);
                if (scope.min != undefined && value < scope.min) {
                    value = parseFloat(scope.min).toFixed(scope.decimals);
					updateNgModelValue( toFloat(value, scope));
                    return;
                }
                updateNgModelValue( toFloat(value, scope));
				ngModelCtrl.$render();
            };

           scope.startSpinUp = function () {
				scope.increment();

				clickStart = Date.now();

				timeout = $timeout(function() {
					timer = $interval(function() {
						scope.increment();
					}, scope.stepInterval);
				}, scope.stepIntervalDelay);
			};

			scope.startSpinDown = function () {
				scope.decrement();

				clickStart = Date.now();

				timeout = $timeout(function() {
					timer = $interval(function() {
						scope.decrement();
					}, scope.stepInterval);
				}, scope.stepIntervalDelay);
			};

			scope.stopSpin = function () {
                $timeout.cancel(timeout);
                $interval.cancel(timer);
			};

            scope.focus = function () {
                scope.focused = true;
            }

            scope.blur = function () {
                scope.focused = false;
            }

            var $body = $document.find('body');
            $body.bind('keydown', function (event) {
                if (!scope.withKey || !scope.focused) {
                    return;
                }
                event = event || window.event;
                var which = event.which;
                if (which === keyCodes.up) {
                    scope.increment();
                    event.preventDefault();
                    scope.$apply();
                } else if (which === keyCodes.down) {
                    scope.decrement();
                    event.preventDefault();
                    scope.$apply();
                }
            });
        },

        template:
		'
' +
		'  ' +
		'    <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()"></button>' +
		'  ' +
		'  ' +
		'  <input type="text" ng-model="val" class="form-control" ng-change="updateValue()" ng-blur="blur()" ng-focus="focus()">' +
		'  ' +
        '  ' +
		'    <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()"></button>' +
		'  ' +
        '  ' +
        '      <button class="btn btn-default bootstrap-touchspin-up" type="button" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()"></button>' +
        '      <button class="btn btn-default bootstrap-touchspin-down" type="button"ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()"></button>' +
        '  ' +
		'
'

    };

}]);<commit_msg>Working on validation. Everything should work by now.<commit_after>angular.module('ram.touchspin', [])

.directive('ramTouchSpin', ['$timeout', '$interval', '$document', '$locale', function ($timeout, $interval, $document, $locale) {
    'use strict';

    var keyCodes = {
        left: 37,
        right: 39,
        up: 38,
        down: 40
    };

    var setScopeValues = function (scope, attrs) {
        if(attrs.min !== undefined){
            scope.min = parseFloat(Number(attrs.min));
        }else{
            scope.min = undefined;
        }
        if(attrs.max !== undefined){
            scope.max = parseFloat(Number(attrs.max));
        }else{
            scope.max = undefined;
        }
        scope.step = attrs.step || 1;
        scope.prefix = attrs.prefix || undefined;
        scope.postfix = attrs.postfix || undefined;
        scope.decimals = attrs.decimals || 0;
        scope.stepInterval = attrs.stepInterval || 100;
        scope.stepIntervalDelay = attrs.stepIntervalDelay || 500;
        scope.emptyStringNull = attrs.nullable || false;
        scope.initval = attrs.initval || (scope.emptyStringNull ? null : 0);
		//TODO: hanlde initial value
        //scope.model = scope.model !== undefined ? scope.model : scope.initval;
        var localeDecimalSeparator;
        if($locale.NUMBER_FORMATS.DECIMAL_SEP === undefined){
            //Be prepared for the case that variable name changes, this is not a public api
            localeDecimalSeparator = '.';
        }
        else{
            localeDecimalSeparator = $locale.NUMBER_FORMATS.DECIMAL_SEP;
        }
        scope.decimalSep = attrs.decimalSep || localeDecimalSeparator;
        if (attrs.withKey === "false") {
            scope.withKey = false;
        } else {
            scope.withKey = true;
        }
        if (attrs.vertical === "false") {
            scope.verticalButtons = false;
        } else {
            scope.verticalButtons = true;
        }
        if (scope.decimalSep === ".") {
            scope.regex = /^-?(?:\d+|\d*\.(\d+)?)$/i;
        } else if (scope.decimalSep === ",") {
            scope.regex = /^-?(?:\d+|\d*\,(\d+)?)$/i;
        } else {
            //any decimal separator
            scope.regex = new RegExp("^-?(?:\\d+|\\d*" + scope.decimalSep + "(\\d+)?)$");
        }
    };

    var toFloat = function (value, scope) {
        if(value === "" && scope.emptyStringNull){
            return null;
        }
        if (scope.decimalSep !== "." && (typeof value === "string" || value instanceof String)) {
            value = value.replace(scope.decimalSep, ".");
        }
        value = parseFloat(Number(value));
        return value;
    }

    var toString = function (value, decimalSep) {
        if(value === null || value === undefined){
            return "";
        }
        if( typeof value === 'number'){
            value = value.toString();
        }
        value = value.replace('.', decimalSep);
        return value;
    }

    return {
        restrict: 'EA',
        scope: true,
		require: 'ngModel',
        replace: true,
        link: function (scope, element, attrs, ngModelCtrl) {
            var timeout, timer, clickStart;
            scope.focused = false;

            setScopeValues(scope, attrs);

			//Move the name attribute
			var divElem = angular.element(element);
			divElem.removeAttr('name');
			angular.element(divElem[0].querySelector('input')).attr('name', name);

			var orignalRender = ngModelCtrl.$render;

			ngModelCtrl.$render = function () {
				scope.val = toString( ngModelCtrl.$modelValue, scope.decimalSep);
			};

			var updateNgModelValue = function(val){
				ngModelCtrl.$setViewValue(val);
				orignalRender();
			}

            scope.updateValue = function () {
                if (scope.val !== undefined) {
					//check regex first
					if(scope.val === "" || scope.regex.test(scope.val)){
						ngModelCtrl.$setValidity('invalid', true);
					}else{
						ngModelCtrl.$setValidity('invalid', false);
						orignalRender();
						return;
					}
					//parse and update
                    var value = toFloat(scope.val, scope);
                    var adjustVal = false
                    if (scope.max != undefined && value > scope.max){
                         value = scope.max;
                         adjustVal = true;
                    }
                    else if (scope.min != undefined && value < scope.min) {
                        value = scope.min;
                        adjustVal = true;
                    }
                    if(adjustVal){
                        scope.val = toString(value,  scope.decimalSep);
                    }
					updateNgModelValue(value);
                }
            }

            scope.increment = function () {
                var value = parseFloat(parseFloat(Number(ngModelCtrl.$modelValue)) + parseFloat(scope.step)).toFixed(scope.decimals);
                if (scope.max != undefined && value > scope.max) return;
				updateNgModelValue( toFloat(value, scope));
				ngModelCtrl.$render();
            };

            scope.decrement = function () {
                var value = parseFloat(parseFloat(Number(ngModelCtrl.$modelValue)) - parseFloat(scope.step)).toFixed(scope.decimals);
                if (scope.min != undefined && value < scope.min) {
                    value = parseFloat(scope.min).toFixed(scope.decimals);
					updateNgModelValue( toFloat(value, scope));
                    return;
                }
                updateNgModelValue( toFloat(value, scope));
				ngModelCtrl.$render();
            };

           scope.startSpinUp = function () {
				scope.increment();

				clickStart = Date.now();

				timeout = $timeout(function() {
					timer = $interval(function() {
						scope.increment();
					}, scope.stepInterval);
				}, scope.stepIntervalDelay);
			};

			scope.startSpinDown = function () {
				scope.decrement();

				clickStart = Date.now();

				timeout = $timeout(function() {
					timer = $interval(function() {
						scope.decrement();
					}, scope.stepInterval);
				}, scope.stepIntervalDelay);
			};

			scope.stopSpin = function () {
                $timeout.cancel(timeout);
                $interval.cancel(timer);
			};

            scope.focus = function () {
                scope.focused = true;
            }

            scope.blur = function () {
                scope.focused = false;
            }

            var $body = $document.find('body');
            $body.bind('keydown', function (event) {
                if (!scope.withKey || !scope.focused) {
                    return;
                }
                event = event || window.event;
                var which = event.which;
                if (which === keyCodes.up) {
                    scope.increment();
                    event.preventDefault();
                    scope.$apply();
                } else if (which === keyCodes.down) {
                    scope.decrement();
                    event.preventDefault();
                    scope.$apply();
                }
            });
        },

        template:
		'
' +
		'  ' +
		'    <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()"></button>' +
		'  ' +
		'  ' +
		'  <input type="text" ng-model="val" class="form-control" ng-change="updateValue()" ng-blur="blur()" ng-focus="focus()">' +
		'  ' +
        '  ' +
		'    <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()"></button>' +
		'  ' +
        '  ' +
        '      <button class="btn btn-default bootstrap-touchspin-up" type="button" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()"></button>' +
        '      <button class="btn btn-default bootstrap-touchspin-down" type="button"ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()"></button>' +
        '  ' +
		'
'

    };

}]);<|endoftext|>


<commit_before>/*global require, localStorage, screen*/
var gui = require('nw.gui'); // Load native UI library

(function () {
    "use strict";
    var win = gui.Window.get(), // Get the current window
        windowKey = "window",
        windowConf = {
            width : screen.availWidth / 2,
            height : screen.availHeight,
            x : screen.availWidth / 2,
            y : 0
        },
        confStr = localStorage.getItem(windowKey);

    if (confStr) {
        windowConf = JSON.parse(confStr);
    }

    if (windowConf.width > screen.availWidth ||
        windowConf.height > screen.availHeight ||
        windowConf.x > screen.availWidth ||
        windowConf.y > screen.availHeight) {

        windowConf = {
            width : screen.availWidth / 2,
            height : screen.availHeight,
            x : screen.availWidth / 2,
            y : 0
        };
    }

    win.width = windowConf.width;
    win.height = windowConf.height;
    win.x = windowConf.x;
    win.y = windowConf.y;

    localStorage.setItem(windowKey, JSON.stringify(windowConf));

    win.on('close', function () {
        localStorage.setItem(windowKey, JSON.stringify({
            width : win.width,
            height : win.height,
            x : win.x,
            y : win.y
        }));

        this.hide();
    });
}());

var minimizeWindow = function () {
    "use strict";
    var win = gui.Window.get(),
        windowKey = "window";

    localStorage.setItem(windowKey, JSON.stringify({
        width : win.width,
        height : win.height,
        x : win.x,
        y : win.y
    }));

    win.minimize();
};

var closeWindow = function () {
    "use strict";
    var win = gui.Window.get(),
        windowKey = "window";

    localStorage.setItem(windowKey, JSON.stringify({
        width : win.width,
        height : win.height,
        x : win.x,
        y : win.y
    }));

    win.hide();
};

var openExternalUrl = function (url) {
    "use strict";
    gui.Shell.openExternal(url);
};<commit_msg>Added command line argument --tray<commit_after>/*global require, localStorage, screen*/
var gui = require('nw.gui'); // Load native UI library

(function () {
    "use strict";
    var win = gui.Window.get(), // Get the current window
        windowKey = "window",
        windowConf = {
            width : screen.availWidth / 2,
            height : screen.availHeight,
            x : screen.availWidth / 2,
            y : 0
        },
        confStr = localStorage.getItem(windowKey),
		startInTray = false;

    if (confStr) {
        windowConf = JSON.parse(confStr);
    }

    if (windowConf.width > screen.availWidth ||
        windowConf.height > screen.availHeight ||
        windowConf.x > screen.availWidth ||
        windowConf.y > screen.availHeight) {

        windowConf = {
            width : screen.availWidth / 2,
            height : screen.availHeight,
            x : screen.availWidth / 2,
            y : 0
        };
    }

    win.width = windowConf.width;
    win.height = windowConf.height;
    win.x = windowConf.x;
    win.y = windowConf.y;

    localStorage.setItem(windowKey, JSON.stringify(windowConf));

	for (var i = 0; i < gui.App.argv.length; i++){
		if (gui.App.argv[i] == '--tray'){
			startInTray = true;
		}
	}

	if (!startInTray) {
		win.show();
	}

    win.on('close', function () {
        localStorage.setItem(windowKey, JSON.stringify({
            width : win.width,
            height : win.height,
            x : win.x,
            y : win.y
        }));

        this.hide();
    });
}());

var minimizeWindow = function () {
    "use strict";
    var win = gui.Window.get(),
        windowKey = "window";

    localStorage.setItem(windowKey, JSON.stringify({
        width : win.width,
        height : win.height,
        x : win.x,
        y : win.y
    }));

    win.minimize();
};

var closeWindow = function () {
    "use strict";
    var win = gui.Window.get(),
        windowKey = "window";

    localStorage.setItem(windowKey, JSON.stringify({
        width : win.width,
        height : win.height,
        x : win.x,
        y : win.y
    }));

    win.hide();
};

var openExternalUrl = function (url) {
    "use strict";
    gui.Shell.openExternal(url);
};<|endoftext|>


<commit_before>import * as coerce from './coerce.js';
import * as constants from '../constants';
import { crouton_thrift } from '../platform_abstraction_layer'; // eslint-disable-line camelcase

export default class SpanImp {

    // ---------------------------------------------------------------------- //
    // OpenTracing Implementation
    // ---------------------------------------------------------------------- //

    tracer() {
        return this._tracer;
    }

    context() {
        return this._context;
    }

    setOperationName(name) {
        this._operation = `${name}`;
    }

    addTags(keyValuePairs) {
        for (let key in keyValuePairs) {
            // NB: Older versions of IE don't support `String.prototype.startsWith()`
            if (key.substr(0, constants.JOIN_ID_PREFIX.length) === constants.JOIN_ID_PREFIX) {
                this.setJoinID(key, keyValuePairs[key]);
            } else {
                this._tags[key] = keyValuePairs[key];
            }
        }
    }

    /**
     * The set of OpenTracing fields is:
     * - 'event'
     * - 'timestamp'
     * - 'payload'
     */
    // Log record specified by fields
    log(fields) {
        const argumentType = typeof fields;
        if (argumentType !== 'string') {
            this._tracer._error('Span.log() expects an object as its argument');
            return;
        }

        let rec = this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_STRING_TO_LEVEL[fields.level] || constants.LOG_INFO);

        //
        // OpenTracing attributes
        //
        if (fields.event !== undefined) {
            rec.name(fields.event);
        }
        if (fields.timestamp !== undefined) {
            // The incoming 'timestamp' field is in milliseconds. The internal
            // timestamp is in microseconds.
            rec.timestamp(fields.timestamp * 1000);
        }
        if (fields.payload !== undefined) {
            rec.payload(fields.payload);
        }

        //
        // LightStep-specific attributes
        //
        if (fields.message !== undefined) {
            rec.message(fields.message);
        }
        if (fields.timestamp_micros !== undefined) {
            rec.timestamp(fields.timestamp_micros);
        }
        rec.end();
    }

    finish(finishTime) {
        return this.end(finishTime);
    }

    // ---------------------------------------------------------------------- //
    // Private methods
    // ---------------------------------------------------------------------- //

    constructor(tracer, spanContext) {
        console.assert(typeof tracer === 'object', 'Invalid runtime');  // eslint-disable-line no-console

        this._tracer = tracer;
        this._context = spanContext;
        this._ended  = false;

        this._operation   = '';
        this._tags        = {};
        this._joinIDs     = {};
        this._beginMicros = tracer._platform.nowMicros();
        this._endMicros   = 0;
        this._errorFlag   = false;
    }

    // ---------------------------------------------------------------------- //
    // LightStep Extensions
    // ---------------------------------------------------------------------- //

    getOperationName() {
        return this._operation;
    }

    // Getter only. The GUID is immutable once set internally.
    guid() {
        return this._context._guid;
    }

    traceGUID() {
        return this._context._traceGUID;
    }

    parentGUID() {
        return this._tags.parent_span_guid;
    }

    setParentGUID(guid) {
        this._tags.parent_span_guid = coerce.toString(guid);
        return this;
    }

    beginMicros() {
        return this._beginMicros;
    }

    setBeginMicros(micros) {
        this._beginMicros = micros;
        return this;
    }

    endMicros() {
        return this._endMicros;
    }

    setEndMicros(micros) {
        this._endMicros = micros;
        return this;
    }

    /**
     * Returns a URL to the trace containing this span.
     *
     * Unlike most methods, it *is* safe to call this method after `finish()`.
     *
     * @return {string} the absolute URL for the span
     */
    generateTraceURL() {
        let micros;
        if (this._beginMicros > 0 && this._endMicros > 0) {
            micros = Math.floor((this._beginMicros + this._endMicros) / 2);
        } else {
            micros = this._tracer._platform.nowMicros();
        }

        let urlPrefix = constants.LIGHTSTEP_APP_URL_PREFIX;
        let accessToken = encodeURIComponent(this._tracer.options().access_token);
        let guid = encodeURIComponent(this.guid());
        return `${urlPrefix}/${accessToken}/trace?span_guid=${guid}&at_micros=${micros}`;
    }

    getTags() {
        return this._tags;
    }

    setJoinID(key, value) {
        this._tags[key] = value;
        this._joinIDs[key] = true;
        return this;
    }

    /**
     * Finishes the span.
     *
     * @param  {Number} finishTime
     *         	Optional Unix timestamp in milliseconds setting an explicit
     *         	finish time for the span.
     */
    end(finishTime) {
        // Ensure a single span is not recorded multiple times
        if (this._ended) {
            return;
        }
        this._ended = true;

        if (finishTime !== undefined) {
            this._endMicros = finishTime * 1000;
        }

        // Do not set endMicros if it has already been set. This accounts for
        // the case of a span that has had it's times set manually (i.e. allows
        // for retroactively created spans that might not be possible to create
        // in real-time).
        if (this._endMicros === 0) {
            this._endMicros = this._tracer._platform.nowMicros();
        }
        this._tracer._addSpanRecord(this._toThrift());
    }

    // Info log record with an optional payload
    info(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_INFO)
            .message(msg)
            .payload(payload)
            .end();
    }

    warn(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_WARN)
            .message(msg)
            .payload(payload)
            .end();
    }

    error(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_ERROR)
            .message(msg)
            .payload(payload)
            .end();
    }

    // Special case to format exception information a little bit more nicely
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
    exception(msg, exception) {
        if (exception.message === undefined || exception.stack === undefined) {
            return this.error(msg, exception);
        }

        let stack = exception.stack.split('\n');
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_ERROR)
            .message(msg)
            .payload({
                name        : exception.name,
                message     : exception.message,
                filename    : exception.filename,
                line_number : exception.lineNumber,
                stack       : stack,
            })
            .end();
    }

    fatal(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_FATAL)
            .message(msg)
            .payload(payload)
            .end();
    }

    _toThrift() {
        // TODO: the backend understands join IDs and attributes.  The outer API
        // understands trace context attributes and tags.  The mapping is a
        // little confusing at the moment...

        let joinIDs = [];
        let attributes = [];
        for (let key in this._tags) {
            if (key in this._joinIDs) {
                this._addTagAsJoinID(joinIDs, key);
            } else {
                attributes.push(new crouton_thrift.KeyValue({
                    Key   : coerce.toString(key),
                    Value : coerce.toString(this._tags[key]),
                }));
            }
        }

        let record = new crouton_thrift.SpanRecord({
            span_guid       : this.guid(),
            trace_guid      : this.traceGUID(),
            runtime_guid    : this._tracer.guid(),
            span_name       : this._operation,
            join_ids        : joinIDs,
            oldest_micros   : this._beginMicros,
            youngest_micros : this._endMicros,
            attributes      : attributes,
            error_flag      : this._errorFlag,
        });
        return record;
    }

    // Helper to reduce duplicated code
    _addTagAsJoinID(joinIDs, key) {
        let value = this._tags[key];
        if (value === undefined) {
            return;
        }
        joinIDs.push(new crouton_thrift.TraceJoinId({
            TraceKey : coerce.toString(key),
            Value    : coerce.toString(value),
        }));
    }
}
<commit_msg>Fix mistake in last PR<commit_after>import * as coerce from './coerce.js';
import * as constants from '../constants';
import { crouton_thrift } from '../platform_abstraction_layer'; // eslint-disable-line camelcase

export default class SpanImp {

    // ---------------------------------------------------------------------- //
    // OpenTracing Implementation
    // ---------------------------------------------------------------------- //

    tracer() {
        return this._tracer;
    }

    context() {
        return this._context;
    }

    setOperationName(name) {
        this._operation = `${name}`;
    }

    addTags(keyValuePairs) {
        for (let key in keyValuePairs) {
            // NB: Older versions of IE don't support `String.prototype.startsWith()`
            if (key.substr(0, constants.JOIN_ID_PREFIX.length) === constants.JOIN_ID_PREFIX) {
                this.setJoinID(key, keyValuePairs[key]);
            } else {
                this._tags[key] = keyValuePairs[key];
            }
        }
    }

    /**
     * The set of OpenTracing fields is:
     * - 'event'
     * - 'timestamp'
     * - 'payload'
     */
    // Log record specified by fields
    log(fields) {
        const argumentType = typeof fields;
        if (argumentType !== 'object') {
            this._tracer._error('Span.log() expects an object as its argument');
            return;
        }

        let rec = this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_STRING_TO_LEVEL[fields.level] || constants.LOG_INFO);

        //
        // OpenTracing attributes
        //
        if (fields.event !== undefined) {
            rec.name(fields.event);
        }
        if (fields.timestamp !== undefined) {
            // The incoming 'timestamp' field is in milliseconds. The internal
            // timestamp is in microseconds.
            rec.timestamp(fields.timestamp * 1000);
        }
        if (fields.payload !== undefined) {
            rec.payload(fields.payload);
        }

        //
        // LightStep-specific attributes
        //
        if (fields.message !== undefined) {
            rec.message(fields.message);
        }
        if (fields.timestamp_micros !== undefined) {
            rec.timestamp(fields.timestamp_micros);
        }
        rec.end();
    }

    finish(finishTime) {
        return this.end(finishTime);
    }

    // ---------------------------------------------------------------------- //
    // Private methods
    // ---------------------------------------------------------------------- //

    constructor(tracer, spanContext) {
        console.assert(typeof tracer === 'object', 'Invalid runtime');  // eslint-disable-line no-console

        this._tracer = tracer;
        this._context = spanContext;
        this._ended  = false;

        this._operation   = '';
        this._tags        = {};
        this._joinIDs     = {};
        this._beginMicros = tracer._platform.nowMicros();
        this._endMicros   = 0;
        this._errorFlag   = false;
    }

    // ---------------------------------------------------------------------- //
    // LightStep Extensions
    // ---------------------------------------------------------------------- //

    getOperationName() {
        return this._operation;
    }

    // Getter only. The GUID is immutable once set internally.
    guid() {
        return this._context._guid;
    }

    traceGUID() {
        return this._context._traceGUID;
    }

    parentGUID() {
        return this._tags.parent_span_guid;
    }

    setParentGUID(guid) {
        this._tags.parent_span_guid = coerce.toString(guid);
        return this;
    }

    beginMicros() {
        return this._beginMicros;
    }

    setBeginMicros(micros) {
        this._beginMicros = micros;
        return this;
    }

    endMicros() {
        return this._endMicros;
    }

    setEndMicros(micros) {
        this._endMicros = micros;
        return this;
    }

    /**
     * Returns a URL to the trace containing this span.
     *
     * Unlike most methods, it *is* safe to call this method after `finish()`.
     *
     * @return {string} the absolute URL for the span
     */
    generateTraceURL() {
        let micros;
        if (this._beginMicros > 0 && this._endMicros > 0) {
            micros = Math.floor((this._beginMicros + this._endMicros) / 2);
        } else {
            micros = this._tracer._platform.nowMicros();
        }

        let urlPrefix = constants.LIGHTSTEP_APP_URL_PREFIX;
        let accessToken = encodeURIComponent(this._tracer.options().access_token);
        let guid = encodeURIComponent(this.guid());
        return `${urlPrefix}/${accessToken}/trace?span_guid=${guid}&at_micros=${micros}`;
    }

    getTags() {
        return this._tags;
    }

    setJoinID(key, value) {
        this._tags[key] = value;
        this._joinIDs[key] = true;
        return this;
    }

    /**
     * Finishes the span.
     *
     * @param  {Number} finishTime
     *         	Optional Unix timestamp in milliseconds setting an explicit
     *         	finish time for the span.
     */
    end(finishTime) {
        // Ensure a single span is not recorded multiple times
        if (this._ended) {
            return;
        }
        this._ended = true;

        if (finishTime !== undefined) {
            this._endMicros = finishTime * 1000;
        }

        // Do not set endMicros if it has already been set. This accounts for
        // the case of a span that has had it's times set manually (i.e. allows
        // for retroactively created spans that might not be possible to create
        // in real-time).
        if (this._endMicros === 0) {
            this._endMicros = this._tracer._platform.nowMicros();
        }
        this._tracer._addSpanRecord(this._toThrift());
    }

    // Info log record with an optional payload
    info(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_INFO)
            .message(msg)
            .payload(payload)
            .end();
    }

    warn(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_WARN)
            .message(msg)
            .payload(payload)
            .end();
    }

    error(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_ERROR)
            .message(msg)
            .payload(payload)
            .end();
    }

    // Special case to format exception information a little bit more nicely
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
    exception(msg, exception) {
        if (exception.message === undefined || exception.stack === undefined) {
            return this.error(msg, exception);
        }

        let stack = exception.stack.split('\n');
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_ERROR)
            .message(msg)
            .payload({
                name        : exception.name,
                message     : exception.message,
                filename    : exception.filename,
                line_number : exception.lineNumber,
                stack       : stack,
            })
            .end();
    }

    fatal(msg, payload) {
        this._tracer.log()
            .span(this.guid())
            .level(constants.LOG_FATAL)
            .message(msg)
            .payload(payload)
            .end();
    }

    _toThrift() {
        // TODO: the backend understands join IDs and attributes.  The outer API
        // understands trace context attributes and tags.  The mapping is a
        // little confusing at the moment...

        let joinIDs = [];
        let attributes = [];
        for (let key in this._tags) {
            if (key in this._joinIDs) {
                this._addTagAsJoinID(joinIDs, key);
            } else {
                attributes.push(new crouton_thrift.KeyValue({
                    Key   : coerce.toString(key),
                    Value : coerce.toString(this._tags[key]),
                }));
            }
        }

        let record = new crouton_thrift.SpanRecord({
            span_guid       : this.guid(),
            trace_guid      : this.traceGUID(),
            runtime_guid    : this._tracer.guid(),
            span_name       : this._operation,
            join_ids        : joinIDs,
            oldest_micros   : this._beginMicros,
            youngest_micros : this._endMicros,
            attributes      : attributes,
            error_flag      : this._errorFlag,
        });
        return record;
    }

    // Helper to reduce duplicated code
    _addTagAsJoinID(joinIDs, key) {
        let value = this._tags[key];
        if (value === undefined) {
            return;
        }
        joinIDs.push(new crouton_thrift.TraceJoinId({
            TraceKey : coerce.toString(key),
            Value    : coerce.toString(value),
        }));
    }
}
<|endoftext|>


<commit_before>/*
Language: Swift
Author: Chris Eidhof <chris@eidhof.nl>
*/

function(hljs) {
  var SWIFT_KEYWORDS =
    'class deinit enum extension func import init let protocol static ' +
    'struct subscript typealias var break case continue default do ' +
    'else fallthrough if in for return switch where while as dynamicType ' +
    'is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ ' +
    '__LINE__ associativity didSet get infix inout left mutating none ' +
    'nonmutating operator override postfix precedence prefix right set '+
    'unowned unowned safe unsafe weak willSet';
  var TYPE = {
    className: 'type',
    begin: '\\b[A-Z][\\w\']*',
    relevance: 0
  };
  var BLOCK_COMMENT = {
    className: 'comment',
    begin: '/\\*', end: '\\*/',
    contains: [hljs.PHRASAL_WORDS_MODE, 'self']
  };
  var SUBST = {
    className: 'subst',
    begin: /\\\(/, end: '\\)',
    keywords: SWIFT_KEYWORDS,
    contains: [] // assigned later
  };
  var QUOTE_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    contains: [SUBST, hljs.BACKSLASH_ESCAPE]
  });
  SUBST.contains = [hljs.C_NUMBER_MODE, hljs.TITLE_MODE, QUOTE_STRING_MODE];

  return {
    keywords: {
      keyword: SWIFT_KEYWORDS,
      literal:
        'true false nil'
    },
    contains: [
      QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      BLOCK_COMMENT,
      TYPE,
      hljs.C_NUMBER_MODE,
      {
        className: 'func',
        beginKeywords: 'func', end: /(\{)|(\->)/, excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
          {
            className: 'generics',
            begin: /\</, end: /\>/,
            illegal: /\>/
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: [
              hljs.C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ],
            illegal: /["'\(]/
          }
        ],
        illegal: /\[|%/
      },
    ]
  };
}
<commit_msg>Remove TITLE from interpolated strings<commit_after>/*
Language: Swift
Author: Chris Eidhof <chris@eidhof.nl>
*/

function(hljs) {
  var SWIFT_KEYWORDS =
    'class deinit enum extension func import init let protocol static ' +
    'struct subscript typealias var break case continue default do ' +
    'else fallthrough if in for return switch where while as dynamicType ' +
    'is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ ' +
    '__LINE__ associativity didSet get infix inout left mutating none ' +
    'nonmutating operator override postfix precedence prefix right set '+
    'unowned unowned safe unsafe weak willSet';
  var TYPE = {
    className: 'type',
    begin: '\\b[A-Z][\\w\']*',
    relevance: 0
  };
  var BLOCK_COMMENT = {
    className: 'comment',
    begin: '/\\*', end: '\\*/',
    contains: [hljs.PHRASAL_WORDS_MODE, 'self']
  };
  var SUBST = {
    className: 'subst',
    begin: /\\\(/, end: '\\)',
    keywords: SWIFT_KEYWORDS,
    contains: [] // assigned later
  };
  var QUOTE_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    contains: [SUBST, hljs.BACKSLASH_ESCAPE]
  });
  SUBST.contains = [hljs.C_NUMBER_MODE, QUOTE_STRING_MODE];

  return {
    keywords: {
      keyword: SWIFT_KEYWORDS,
      literal:
        'true false nil'
    },
    contains: [
      QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      BLOCK_COMMENT,
      TYPE,
      hljs.C_NUMBER_MODE,
      {
        className: 'func',
        beginKeywords: 'func', end: /(\{)|(\->)/, excludeEnd: true,
        contains: [
          hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
          {
            className: 'generics',
            begin: /\</, end: /\>/,
            illegal: /\>/
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: [
              hljs.C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE
            ],
            illegal: /["'\(]/
          }
        ],
        illegal: /\[|%/
      },
    ]
  };
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 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.
 *
 */

define(function (require, exports) {
    "use strict";

    var _ = require("lodash");

    var PlayObject = require("../playobject"),
        referenceBy = require("./reference").wrapper("layer"),
        referenceOf = require("./reference").refersTo,
        inUnits = require("./unit"),
        color = require("./color"),
        assert = require("../util").assert;

    /**
     * Generically build a PlayObject for a layerEffect
     * The layerEffectValue parameter should be a fully constructed object that can be supplied to the "to.value"
     * property of the descriptor.
     *
     * @private
     * @param {ActionDescriptor} ref layer(s) reference
     * @param {string} layerEffectType type of layerEffect (example: dropShadow)
     * @param {object} layerEffectValue object that can be supplied for "to.value" in the descriptor
     *
     * @return {PlayObject}
     */
    var _layerEffectDescriptor = function (ref, layerEffectType, layerEffectValue) {
        var val = {};

        //TODO future: validate the layerEffectType against a list.  Only supporting drop shadow for now
        val[layerEffectType] = {
            obj: layerEffectType,
            value: layerEffectValue
        };

        return new PlayObject(
            "set",
            {
                "null": {
                    "ref": [
                        {
                            "property": "layerEffects",
                            "ref": "property"
                        },
                        ref
                    ]
                },
                "to": {
                    "obj": "layerEffects",
                    "value": val
                }
            }
        );
    };

    /**
     * Update drop shadow layer effect properties for the given layer(s)
     *
     * The expected format of the properties object is like:
     * {enabled: true, color: {r: 255, g: 0, b: 0}, blur: 20}
     * Distance/positions values in pixels
     * Angles in degrees
     * Opacity percentage [0,100]
     *
     * @param {ActionDescriptor} ref - Reference of layer(s) to update
     * @param {object} properties intermediate object format using photoshop names, but without units
     *
     * @return {PlayObject}
     */
    var setDropShadow = function (ref, properties) {
        assert(referenceOf(ref) === "layer", "setDropShadow is passed a non-layer reference");

        var layerEffectPsProperties = {
            enabled: properties.enabled === undefined ? true : properties.enabled,
            useGlobalAngle: properties.useGlobalAngle === undefined ? true : properties.useGlobalAngle
        };

        if (_.isObject(properties.color)) {
            layerEffectPsProperties.color = color.colorObject(properties.color);
        }
        if (_.isNumber(properties.opacity)) {
            layerEffectPsProperties.opacity = inUnits.percent(properties.opacity);
        }
        if (_.isNumber(properties.chokeMatte)) {
            layerEffectPsProperties.chokeMatte = inUnits.pixels(properties.chokeMatte);
        }
        if (_.isNumber(properties.blur)) {
            layerEffectPsProperties.blur = inUnits.pixels(properties.blur);
        }
        if (_.isNumber(properties.localLightingAngle)) {
            layerEffectPsProperties.localLightingAngle = inUnits.degrees(properties.localLightingAngle);
        }
        if (_.isNumber(properties.distance)) {
            layerEffectPsProperties.distance = inUnits.pixels(properties.distance);
        }

        return _layerEffectDescriptor(ref, "dropShadow", layerEffectPsProperties);
    };

    exports.referenceBy = referenceBy;

    exports.setDropShadow = setDropShadow;
});
<commit_msg>Update adaptor to accept calls to multiple Layer Effects<commit_after>/*
 * Copyright (c) 2014 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.
 *
 */

define(function (require, exports) {
    "use strict";

    var _ = require("lodash");

    var PlayObject = require("../playobject"),
        referenceBy = require("./reference").wrapper("layer"),
        referenceOf = require("./reference").refersTo,
        inUnits = require("./unit"),
        color = require("./color"),
        assert = require("../util").assert;

    /**
     * Generically build a PlayObject for a layerEffect
     * The layerEffectValue parameter should be a fully constructed object that can be supplied to the "to.value"
     * property of the descriptor.
     *
     * @private
     * @param {ActionDescriptor} ref layer(s) reference
     * @param {string} layerEffectType type of layerEffect (example: dropShadow)
     * @param {object} layerEffectValue object that can be supplied for "to.value" in the descriptor
     * @param {boolean} multi value that allows function to return the Multi Layer Effect friendly descriptor
     *
     * @return {PlayObject}
     */
    var _layerEffectDescriptor = function (ref, layerEffectType, layerEffectValue, multi) {
        var val = {};

        if (multi) {
            val[layerEffectType] = layerEffectValue;
        } else {
            val[layerEffectType] = {
                obj: layerEffectType,
                value: layerEffectValue
            };
        }

        return new PlayObject(
            "set",
            {
                "null": {
                    "ref": [
                        {
                            "property": "layerEffects",
                            "ref": "property"
                        },
                        ref
                    ]
                },
                "to": {
                    "obj": "layerEffects",
                    "value": val
                }
            }
        );
    };

    /**
     * Parse DropShadow JS properties and assign units to make them acceptable to PS
     *
     * The expected format of the properties object is like:
     * {enabled: true, color: {r: 255, g: 0, b: 0}, blur: 20}
     * Distance/positions values in pixels
     * Angles in degrees
     * Opacity percentage [0,100]
     *
     * @private
     * @param {object} properties intermediate object format using Photoshop names, but without units
     *
     * @return {object} PS friendly Properties
     */
    var _dropShadowProperties = function (properties) {
        var layerEffectPsProperties = {
            enabled: properties.enabled === undefined ? true : properties.enabled,
            useGlobalAngle: properties.useGlobalAngle === undefined ? true : properties.useGlobalAngle
        };

        if (_.isObject(properties.color)) {
            layerEffectPsProperties.color = color.colorObject(properties.color);
        }
        if (_.isNumber(properties.opacity)) {
            layerEffectPsProperties.opacity = inUnits.percent(properties.opacity);
        }
        if (_.isNumber(properties.chokeMatte)) {
            layerEffectPsProperties.chokeMatte = inUnits.pixels(properties.chokeMatte);
        }
        if (_.isNumber(properties.blur)) {
            layerEffectPsProperties.blur = inUnits.pixels(properties.blur);
        }
        if (_.isNumber(properties.localLightingAngle)) {
            layerEffectPsProperties.localLightingAngle = inUnits.degrees(properties.localLightingAngle);
        }
        if (_.isNumber(properties.distance)) {
            layerEffectPsProperties.distance = inUnits.pixels(properties.distance);
        }
        return layerEffectPsProperties;
    };
    /**
     * Update drop shadow layer effect properties for the given layer(s)
     *
     *
     * @param {ActionDescriptor} ref - Reference of layer(s) to update
     * @param {object} properties intermediate object format using Photoshop names, but without units
     *
     * @return {PlayObject}
     */
    var setDropShadow = function (ref, properties) {
        assert(referenceOf(ref) === "layer", "setDropShadow is passed a non-layer reference");

        return _layerEffectDescriptor(ref, "dropShadow", _dropShadowProperties(properties));
    };

    /**
     * Return drop shadow descriptor for the given properties
     *
     * The expected format of the properties object is like:
     * {enabled: true, color: {r: 255, g: 0, b: 0}, blur: 20}
     * Distance/positions values in pixels
     * Angles in degrees
     * Opacity percentage [0,100]
     *
     * @param {object} properties intermediate object format using Photoshop names, but without units
     *
     * @return {Descriptor}
     */

    var  dropShadowDescriptor = function (properties) {
        return {
            "obj": "dropShadow",
            "value": _dropShadowProperties(properties)
        };
    };

    /**
     * Update multiple drop shadow layer effect properties for the given layer(s)
     *
     * @param {ActionDescriptor} ref - Reference of layer(s) to update
     * @param {Array} propertyArray Array of DropShadow properties
     *
     * @return {PlayObject}
     */
    var setDropShadows = function (ref, propertyArray) {
        assert(referenceOf(ref) === "layer", "setDropShadow is passed a non-layer reference");

        var descriptorArray = propertyArray.reduce(function (array, properties) {
            array.push(dropShadowDescriptor(properties));
            return array;
        }, []);

        return _layerEffectDescriptor(ref, "dropShadowMulti", descriptorArray, true);
    };

    exports.referenceBy = referenceBy;

    exports.dropShadowDescriptor = dropShadowDescriptor;
    exports.setDropShadow = setDropShadow;
    exports.setDropShadows = setDropShadows;
});
<|endoftext|>


<commit_before>var global_context = ActiveSupport.getGlobalContext();
var ie = !!(global_context.attachEvent && !global_context.opera);

ActiveSupport.DOM = {
    ieAttributeTranslations: {
        'class': 'className',
        'checked': 'defaultChecked',
        'usemap': 'useMap',
        'for': 'htmlFor',
        'readonly': 'readOnly',
        'colspan': 'colSpan',
        'bgcolor': 'bgColor',
        'cellspacing': 'cellSpacing',
        'cellpadding': 'cellPadding'
    },
    keyCodes: {
        KEY_BACKSPACE: 8,
        KEY_TAB:       9,
        KEY_RETURN:   13,
        KEY_ESC:      27,
        KEY_LEFT:     37,
        KEY_UP:       38,
        KEY_RIGHT:    39,
        KEY_DOWN:     40,
        KEY_DELETE:   46,
        KEY_HOME:     36,
        KEY_END:      35,
        KEY_PAGEUP:   33,
        KEY_PAGEDOWN: 34,
        KEY_INSERT:   45
    },
    cache: {},
    create: function create(tag_name,attributes)
    {
        attributes = attributes || {};
        tag_name = tag_name.toLowerCase();
        var element;
        if(ie && (attributes.name || (tag_name == 'input' && attributes.type)))
        {
            //ie needs these attributes to be written in the string passed to createElement
            tag = '<' + tag_name;
            if(attributes.name)
            {
                tag += ' name="' + attributes.name + '"';
            }
            if(tag_name == 'input' && attributes.type)
            {
                tag += ' type="' + attributes.type + '"';
            }
            tag += '>';
            delete attributes.name;
            delete attributes.type;
            element = ActiveSupport.DOM.extend(global_context.document.createElement(tag));
        }
        else
        {
            if(!ActiveSupport.DOM.cache[tag_name])
            {
                ActiveSupport.DOM.cache[tag_name] = ActiveSupport.DOM.extend(global_context.document.createElement(tag_name));
            }
            element = ActiveSupport.DOM.cache[tag_name].cloneNode(false);
        }
        ActiveSupport.DOM.writeAttribute(element,attributes);
        return element;
    },
    extend: function extend(element)
    {
        return element;
    },
    clear: function clear(element)
    {
        while(element.firstChild)
        {
            element.removeChild(element.firstChild);
        }
        return element;
    },
    hide: function hide(element)
    {
        element.style.display = 'none';
        return element;
    },
    show: function show(element)
    {
        element.style.display = '';
        return element;
    },
    remove: function remove(element)
    {
        element.parentNode.removeChild(element);
        return element;
    },
    insert: function insert(element,content,position)
    {
        if(content && typeof(content.getElement) == 'function')
        {
            content = content.getElement();
        }
        if(!content || !content.nodeType || content.nodeType !== 1)
        {
            content = global_context.document.createTextNode(String(content));
        }
        if(!position)
        {
            position = 'bottom';
        }
        switch(position)
        {
            case 'top': element.insertBefore(content,element.firstChild); break;
            case 'bottom': element.appendChild(content); break;
            case 'before': element.parentNode.insertBefore(content,element); break;
            case 'after': element.parentNode.insertBefore(content,element.nextSibling); break;
        }
        return element;
    },
    update: function update(element,content,position)
    {
        ActiveSupport.DOM.clear(element);
        ActiveSupport.DOM.insert(element,content,position);
    },
    collect: function collect(target_element,elements,callback,context)
    {
        if(callback)
        {
            var arguments_array = ActiveSupport.arrayFrom(arguments);
            var arguments_for_bind = arguments_array.slice(3);
            if(arguments_for_bind.length > 0)
            {
                arguments_for_bind.unshift(callback);
                callback = ActiveSupport.bind.apply(ActiveSupport,arguments_for_bind);
            }
            var collected_elements = [];
            for(var i = 0; i < elements.length; ++i)
            {
                collected_elements.push(callback(elements[i]));
            }
            elements = collected_elements;
        }
        for(var i = 0; i < elements.length; ++i)
        {
            target_element.appendChild(elements[i]);
        }
        return elements;
    },
    writeAttribute: function writeAttribute(element,name,value)
    {
        var transitions = {
            className: 'class',
            htmlFor:   'for'
        };
        var attributes = {};
        if(typeof name === 'object')
        {
            attributes = name;
        }
        else
        {
            attributes[name] = typeof(value) === 'undefined' ? true : value;
        }
        for(var attribute_name in attributes)
        {
            name = transitions[attribute_name] || attribute_name;
            value = attributes[attribute_name];
            if(value === false || value === null)
            {
                element.removeAttribute(name);
            }
            else if(value === true)
            {
                element.setAttribute(name,name);
            }
            else
            {
                if(!ie)
                {
                    element.setAttribute(name,value);
                }
                else
                {
                    if(name == 'style')
                    {
                        element.style.cssText = value;
                    }
                    else
                    {
                        element.setAttribute(ActiveSupport.DOM.ieAttributeTranslations[name] || name,value);
                    }
                }
            }
        }
        return element;
    },
    hasClassName: function hasClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        var element_class_name = element.className;
        return (element_class_name.length > 0 && (element_class_name == class_name || new RegExp("(^|\\s)" + class_name + "(\\s|$)").test(element_class_name)));
    },
    addClassName: function addClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        if(!ActiveSupport.DOM.hasClassName(element,class_name))
        {
            element.className += (element.className ? ' ' : '') + class_name;
        }
        return element;
    },
    removeClassName: function removeClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        element.className = element.className.replace(new RegExp("(^|\\s+)" + class_name + "(\\s+|$)"),' ').replace(/^\s+/, '').replace(/\s+$/, '');
        return element;
    },
    documentReadyObservers: [],
    observe: function observe(element,event_name,callback,context)
    {
        //bind context to context and curried arguments if applicable
        if(arguments.length > 3)
        {
            var arguments_array = ActiveSupport.arrayFrom(arguments);
            var arguments_for_bind = arguments_array.slice(3);
            if(arguments_for_bind.length > 0)
            {
                arguments_for_bind.unshift(callback);
                callback = ActiveSupport.bind.apply(ActiveSupport,arguments_for_bind);
            }
        }

        //dom:ready support
        if(element == ActiveSupport.getGlobalContext().document && event_name == 'ready')
        {
            if(ActiveSupport.DOM.documentReadyObservers == null)
            {
                //ActiveSupport.DOM.documentReadyObservers will be null if the document is ready
                //if so, trigger the observer now
                callback();
            }
            else
            {
                ActiveSupport.DOM.documentReadyObservers.push(callback);
            }
            return;
        }

        //create callback wrapper
        var callback_wrapper = function callback_wrapper(event){
            if(!event)
            {
                event = window.event;
            }
            return callback(
                event,
                //event.srcElement ? (event.srcElement.nodeType == 3 ? event.srcElement.parentNode : event.srcElement) : null,
                function stop_callback(){
                    event.cancelBubble = true;
                    event.returnValue = false;
                    if(event.preventDefault)
                    {
                        event.preventDefault();
                    }
                    if(event.stopPropagation)
                    {
                        event.stopPropagation();
                    }
                },function remove_event_listener(){
                    if(element.removeEventListener)
                    {
                        element.removeEventListener(event_name,callback_wrapper,false);
                    }
                    else
                    {
                        element.detachEvent("on" + event_name,callback_wrapper);
                    }
                }
            );
        };

        //attach event listener
        if(element.addEventListener)
        {
            element.addEventListener(event_name,callback_wrapper,false);
        }
        else
        {
            element.attachEvent('on' + event_name,callback_wrapper);
        }

        return callback_wrapper;
    }
};

/*
Ported from Prototype.js usage:

    ActiveSupport.DOM.observe(document,'ready',function(){

    });
*/
(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */

  var timer;
  var loaded = false;

  function fire_content_loaded_event()
  {
      if(loaded)
      {
          return;
      }
      if(timer)
      {
          window.clearTimeout(timer);
      }
      loaded = true;
      if(ActiveSupport.DOM.documentReadyObservers.length > 0)
      {
          for(var i = 0; i < ActiveSupport.DOM.documentReadyObservers.length; ++i)
          {
              ActiveSupport.DOM.documentReadyObservers[i]();
          }
          ActiveSupport.DOM.documentReadyObservers = null;
      }
  };

  function check_ready_state(event,stop,stop_observing)
  {
      if(document.readyState === 'complete')
      {
          stop_observing();
          fire_content_loaded_event();
      }
  };

  function poll_do_scroll()
  {
      try
      {
          document.documentElement.doScroll('left');
      }
      catch(e)
      {
          timer = window.setTimeout(poll_do_scroll);
          return;
      }
      fire_content_loaded_event();
  };

  if(document.addEventListener)
  {
      document.addEventListener('DOMContentLoaded',fire_content_loaded_event,false);
  }
  else
  {
      ActiveSupport.DOM.observe(document,'readystatechange',check_ready_state);
      if(window == top)
      {
          timer = window.setTimeout(poll_do_scroll);
      }
  }

  ActiveSupport.DOM.observe(window,'load',fire_content_loaded_event);
})();

//Ajax Library integration
(function(){
    //Prototype
    if(global_context.Prototype && global_context.Prototype.Browser && global_context.Prototype.Browser.IE && global_context.Element && global_context.Element.extend)
    {
        ActiveSupport.DOM.extend = function extendForPrototype(element){
          return Element.extend(element);
        };
    };
    //MooTools
    if(global_context.MooTools && global_context.Browser && global_context.Browser.Engine.trident && global_context.document.id)
    {
        ActiveSupport.DOM.extend = function extendForMooTools(element){
            return global_context.document.id(element);
        };
    }
})();<commit_msg>added array support to DOM.insert<commit_after>var global_context = ActiveSupport.getGlobalContext();
var ie = !!(global_context.attachEvent && !global_context.opera);

ActiveSupport.DOM = {
    ieAttributeTranslations: {
        'class': 'className',
        'checked': 'defaultChecked',
        'usemap': 'useMap',
        'for': 'htmlFor',
        'readonly': 'readOnly',
        'colspan': 'colSpan',
        'bgcolor': 'bgColor',
        'cellspacing': 'cellSpacing',
        'cellpadding': 'cellPadding'
    },
    keyCodes: {
        KEY_BACKSPACE: 8,
        KEY_TAB:       9,
        KEY_RETURN:   13,
        KEY_ESC:      27,
        KEY_LEFT:     37,
        KEY_UP:       38,
        KEY_RIGHT:    39,
        KEY_DOWN:     40,
        KEY_DELETE:   46,
        KEY_HOME:     36,
        KEY_END:      35,
        KEY_PAGEUP:   33,
        KEY_PAGEDOWN: 34,
        KEY_INSERT:   45
    },
    cache: {},
    create: function create(tag_name,attributes)
    {
        attributes = attributes || {};
        tag_name = tag_name.toLowerCase();
        var element;
        if(ie && (attributes.name || (tag_name == 'input' && attributes.type)))
        {
            //ie needs these attributes to be written in the string passed to createElement
            tag = '<' + tag_name;
            if(attributes.name)
            {
                tag += ' name="' + attributes.name + '"';
            }
            if(tag_name == 'input' && attributes.type)
            {
                tag += ' type="' + attributes.type + '"';
            }
            tag += '>';
            delete attributes.name;
            delete attributes.type;
            element = ActiveSupport.DOM.extend(global_context.document.createElement(tag));
        }
        else
        {
            if(!ActiveSupport.DOM.cache[tag_name])
            {
                ActiveSupport.DOM.cache[tag_name] = ActiveSupport.DOM.extend(global_context.document.createElement(tag_name));
            }
            element = ActiveSupport.DOM.cache[tag_name].cloneNode(false);
        }
        ActiveSupport.DOM.writeAttribute(element,attributes);
        return element;
    },
    extend: function extend(element)
    {
        return element;
    },
    clear: function clear(element)
    {
        while(element.firstChild)
        {
            element.removeChild(element.firstChild);
        }
        return element;
    },
    hide: function hide(element)
    {
        element.style.display = 'none';
        return element;
    },
    show: function show(element)
    {
        element.style.display = '';
        return element;
    },
    remove: function remove(element)
    {
        element.parentNode.removeChild(element);
        return element;
    },
    insert: function insert(element,content,position)
    {
        if(content && typeof(content.getElement) == 'function')
        {
            content = content.getElement();
        }
        if(ActiveSupport.isArray(content))
        {
            for(var i = 0; i < content.length; ++i)
            {
                ActiveSupport.DOM.insert(element,content[i],position);
            }
        }
        else
        {
            if(!content || !content.nodeType || content.nodeType !== 1)
            {
                content = global_context.document.createTextNode(String(content));
            }
            if(!position)
            {
                position = 'bottom';
            }
            switch(position)
            {
                case 'top': element.insertBefore(content,element.firstChild); break;
                case 'bottom': element.appendChild(content); break;
                case 'before': element.parentNode.insertBefore(content,element); break;
                case 'after': element.parentNode.insertBefore(content,element.nextSibling); break;
            }
        }
        return element;
    },
    update: function update(element,content,position)
    {
        ActiveSupport.DOM.clear(element);
        ActiveSupport.DOM.insert(element,content,position);
    },
    collect: function collect(target_element,elements,callback,context)
    {
        if(callback)
        {
            var arguments_array = ActiveSupport.arrayFrom(arguments);
            var arguments_for_bind = arguments_array.slice(3);
            if(arguments_for_bind.length > 0)
            {
                arguments_for_bind.unshift(callback);
                callback = ActiveSupport.bind.apply(ActiveSupport,arguments_for_bind);
            }
            var collected_elements = [];
            for(var i = 0; i < elements.length; ++i)
            {
                collected_elements.push(callback(elements[i]));
            }
            elements = collected_elements;
        }
        for(var i = 0; i < elements.length; ++i)
        {
            target_element.appendChild(elements[i]);
        }
        return elements;
    },
    writeAttribute: function writeAttribute(element,name,value)
    {
        var transitions = {
            className: 'class',
            htmlFor:   'for'
        };
        var attributes = {};
        if(typeof name === 'object')
        {
            attributes = name;
        }
        else
        {
            attributes[name] = typeof(value) === 'undefined' ? true : value;
        }
        for(var attribute_name in attributes)
        {
            name = transitions[attribute_name] || attribute_name;
            value = attributes[attribute_name];
            if(value === false || value === null)
            {
                element.removeAttribute(name);
            }
            else if(value === true)
            {
                element.setAttribute(name,name);
            }
            else
            {
                if(!ie)
                {
                    element.setAttribute(name,value);
                }
                else
                {
                    if(name == 'style')
                    {
                        element.style.cssText = value;
                    }
                    else
                    {
                        element.setAttribute(ActiveSupport.DOM.ieAttributeTranslations[name] || name,value);
                    }
                }
            }
        }
        return element;
    },
    hasClassName: function hasClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        var element_class_name = element.className;
        return (element_class_name.length > 0 && (element_class_name == class_name || new RegExp("(^|\\s)" + class_name + "(\\s|$)").test(element_class_name)));
    },
    addClassName: function addClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        if(!ActiveSupport.DOM.hasClassName(element,class_name))
        {
            element.className += (element.className ? ' ' : '') + class_name;
        }
        return element;
    },
    removeClassName: function removeClassName(element,class_name)
    {
        if(!element)
        {
            return false;
        }
        element.className = element.className.replace(new RegExp("(^|\\s+)" + class_name + "(\\s+|$)"),' ').replace(/^\s+/, '').replace(/\s+$/, '');
        return element;
    },
    documentReadyObservers: [],
    observe: function observe(element,event_name,callback,context)
    {
        //bind context to context and curried arguments if applicable
        if(arguments.length > 3)
        {
            var arguments_array = ActiveSupport.arrayFrom(arguments);
            var arguments_for_bind = arguments_array.slice(3);
            if(arguments_for_bind.length > 0)
            {
                arguments_for_bind.unshift(callback);
                callback = ActiveSupport.bind.apply(ActiveSupport,arguments_for_bind);
            }
        }

        //dom:ready support
        if(element == ActiveSupport.getGlobalContext().document && event_name == 'ready')
        {
            if(ActiveSupport.DOM.documentReadyObservers == null)
            {
                //ActiveSupport.DOM.documentReadyObservers will be null if the document is ready
                //if so, trigger the observer now
                callback();
            }
            else
            {
                ActiveSupport.DOM.documentReadyObservers.push(callback);
            }
            return;
        }

        //create callback wrapper
        var callback_wrapper = function callback_wrapper(event){
            if(!event)
            {
                event = window.event;
            }
            return callback(
                event,
                //event.srcElement ? (event.srcElement.nodeType == 3 ? event.srcElement.parentNode : event.srcElement) : null,
                function stop_callback(){
                    event.cancelBubble = true;
                    event.returnValue = false;
                    if(event.preventDefault)
                    {
                        event.preventDefault();
                    }
                    if(event.stopPropagation)
                    {
                        event.stopPropagation();
                    }
                },function remove_event_listener(){
                    if(element.removeEventListener)
                    {
                        element.removeEventListener(event_name,callback_wrapper,false);
                    }
                    else
                    {
                        element.detachEvent("on" + event_name,callback_wrapper);
                    }
                }
            );
        };

        //attach event listener
        if(element.addEventListener)
        {
            element.addEventListener(event_name,callback_wrapper,false);
        }
        else
        {
            element.attachEvent('on' + event_name,callback_wrapper);
        }

        return callback_wrapper;
    }
};

/*
Ported from Prototype.js usage:

    ActiveSupport.DOM.observe(document,'ready',function(){

    });
*/
(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */

  var timer;
  var loaded = false;

  function fire_content_loaded_event()
  {
      if(loaded)
      {
          return;
      }
      if(timer)
      {
          window.clearTimeout(timer);
      }
      loaded = true;
      if(ActiveSupport.DOM.documentReadyObservers.length > 0)
      {
          for(var i = 0; i < ActiveSupport.DOM.documentReadyObservers.length; ++i)
          {
              ActiveSupport.DOM.documentReadyObservers[i]();
          }
          ActiveSupport.DOM.documentReadyObservers = null;
      }
  };

  function check_ready_state(event,stop,stop_observing)
  {
      if(document.readyState === 'complete')
      {
          stop_observing();
          fire_content_loaded_event();
      }
  };

  function poll_do_scroll()
  {
      try
      {
          document.documentElement.doScroll('left');
      }
      catch(e)
      {
          timer = window.setTimeout(poll_do_scroll);
          return;
      }
      fire_content_loaded_event();
  };

  if(document.addEventListener)
  {
      document.addEventListener('DOMContentLoaded',fire_content_loaded_event,false);
  }
  else
  {
      ActiveSupport.DOM.observe(document,'readystatechange',check_ready_state);
      if(window == top)
      {
          timer = window.setTimeout(poll_do_scroll);
      }
  }

  ActiveSupport.DOM.observe(window,'load',fire_content_loaded_event);
})();

//Ajax Library integration
(function(){
    //Prototype
    if(global_context.Prototype && global_context.Prototype.Browser && global_context.Prototype.Browser.IE && global_context.Element && global_context.Element.extend)
    {
        ActiveSupport.DOM.extend = function extendForPrototype(element){
          return Element.extend(element);
        };
    };
    //MooTools
    if(global_context.MooTools && global_context.Browser && global_context.Browser.Engine.trident && global_context.document.id)
    {
        ActiveSupport.DOM.extend = function extendForMooTools(element){
            return global_context.document.id(element);
        };
    }
})();<|endoftext|>


<commit_before>var Layout = {
    create: function create(structure,methods)
    {
        var view_class = ActiveView.create(structure,methods)
        ActiveSupport.extend(view_class.prototype,Layout.InstanceMethods);
        return view_class;
    }
};

Layout.InstanceMethods = {
    setTarget: function setTarget(target)
    {
        this._target = target;
        return target;
    },
    getTarget: function getTarget()
    {
        return this._target;
    }
};

ActiveView.Layout = Layout;<commit_msg>refactored ActiveView layouts<commit_after>ActiveSupport.extend(InstanceMethods,{
    setTarget: function setTarget(target)
    {
        this._target = target;
        return target;
    },
    getTarget: function getTarget()
    {
        return this._target;
    }
});

ActiveView.yieldGenerator = function yieldGenerator()
{
    return function yield(element)
    {
        element = element || ActiveView.defaultStructure();
        this.setTarget(element);
    };
};<|endoftext|>