code
stringlengths
2
1.05M
(class (Surface width height) (set! this.canv (document.createElement "canvas")) (set! this.graph (this.canv.getContext "2d")) (when (and width height) (this.setSize width height)) (method (setSize width height) (set! this.width width) (set! this.height height) (set! this.canv.width width) (set! this.canv.style.width (+ width "px")) (set! this.canv.height height) (set! this.canv.style.height (+ height "px")))) (define front (new Surface)) (define back (new Surface)) (document.body.appendChild front.canv) (define g front.graph) (define WIDTH 0) (define HEIGHT 0) (define MID_WIDTH 0) (define MID_HEIGHT 0) (define (setWindowSize) (set! WIDTH (- window.innerWidth 5)) (set! HEIGHT (- window.innerHeight 5)) (set! MID_WIDTH (* 0.5 WIDTH)) (set! MID_HEIGHT (* 0.5 HEIGHT)) (send front setSize WIDTH HEIGHT) undefined) (setWindowSize) (on window:resize setWindowSize) (class (Pattern lineHeight fg text bg) (set! this.lineHeight lineHeight) (set! this.fg fg) (set! this.bg bg) (set! this.text text)) (define (pattern-group lineHeight fg texts...) (texts.map (lambda (text) (new Pattern lineHeight fg text)))) (class (Shape width height patterns) (define surf (new Surface width height)) (when (not (instanceof patterns Array)) (set! patterns [patterns])) (patterns.forEach (lambda (pattern) (when pattern.bg (set! surf.graph.fillStyle pattern.bg) (surf.graph.fillRect 0 0 width height)) (define font (+ pattern.lineHeight "px monospace")) (set! surf.graph.font font) (set! surf.graph.fillStyle pattern.fg) (set! parts (pattern.text.split "\n")) (parts.forEach (lambda (p i) (define y (* pattern.lineHeight (+ 1 i))) (surf.graph.fillText p 0 y))))) (set! this.img surf.canv) (set! this.midX (* -0.5 width)) (set! this.midY (* -0.5 height)) (set! this.width width) (set! this.height height) (method (draw) // (set! g.strokeStyle "#ff00ff") // (g.strokeRect this.midX this.midY this.width this.height) (g.drawImage this.img this.midX this.midY) undefined)) (class (Animation width height duration patternGroup runOnce) (set! this.width width) (set! this.height height) (set! this.shapes (patternGroup.map (lambda (pattern) (new Shape width height pattern)))) (set! this.loop (not runOnce)) (set! this.duration duration) (set! this.frequency (/ 1 duration)) (set! this.current 0) (method (update dt) (set! this.current (+ this.current dt)) (when (and this.loop (> this.current this.duration)) (set! this.current (- this.current this.duration))) undefined) (method (draw) (define i (Math.floor (* this.current this.shapes.length this.frequency))) (if this.loop (set! i (% i this.shapes.length)) (set! i (Math.min i (- this.shapes.length 1)))) (this.shapes[i].draw) undefined)) (class (BoardObject x y animation) (set! this.loc (new Vector x y)) (set! this.spd (new Vector 0 0)) (set! this.animation animation) (method (update dt) (this.animation.update dt) (set! this.loc (this.loc.add (this.spd.mul dt)))) (method (draw) (g.save) (g.translate this.loc.x this.loc.y) (define angle (Math.atan2 this.spd.y this.spd.x)) (when (< this.spd.x 0) (g.scale -1 1) (set! angle (- Math.PI angle))) (g.rotate angle) (this.animation.draw) (g.restore)))
var _ = require( "lodash" ), commonJSHintOptions = require( "../../jshint-options.json" ); module.exports = { nonlib: { options: commonJSHintOptions, files: { src: [] .concat( require( "../../js-example-and-test-files" ) ) .concat( require( "../../js-build-files" ) ) } }, lib: { options: _.extend( {}, commonJSHintOptions, { predef: [ "-console" ] } ), files: { src: require( "../../js-lib-files" ) } } };
import { Component } from '@angular/core'; import { Race } from './race'; import { RaceService } from './race.service'; @Component({ selector: 'my-races', templateUrl: 'app/races.component.html', styleUrls:['app/races.component.css'] }) export class RacesComponent { heading = "Ultra Racing Schedule" cash = 10000; races: Race[]; constructor(private raceService: RaceService) { } ngOnInit() { this.raceService.getRaces().subscribe(races => this.races = races); } totalCost() { let sum = 0; for (let race of this.races) { if (race.isRacing) sum += race.entryFee; } return sum; } cashLeft() { return this.cash - this.totalCost(); } enterRace(race) { if (this.cashLeft() > race.entryFee) { race.isRacing = true; } else { alert("You don't have enough cash"); } } cancelRace(race) { race.isRacing = false; } constructor(private raceService: RaceService) { } }
/* * * HomePage reducer * */ import { fromJS, List, Map } from 'immutable'; import { CANCEL_CHANGES, DELETE_DATA, DELETE_DATA_SUCCEEDED, FETCH_DATA, FETCH_DATA_SUCCEEDED, ON_CHANGE, RESET_PROPS, SET_DATA_TO_EDIT, SET_FORM, SET_FORM_ERRORS, SUBMIT_SUCCEEDED, UNSET_DATA_TO_EDIT, } from './constants'; const initialState = fromJS({ data: fromJS({}), dataToDelete: Map({}), dataToEdit: '', deleteEndPoint: '', didCheckErrors: false, formErrors: List([]), initialData: Map({}), isLoading: true, modifiedData: Map({}), showButtons: false, didDeleteData: false, endPoint: 'roles', }); function homePageReducer(state = initialState, action) { switch (action.type) { case CANCEL_CHANGES: return state .set('formErrors', List([])) .update('modifiedData', () => state.get('initialData')); case DELETE_DATA: return state .set('dataToDelete', Map(action.dataToDelete)) .set('deleteEndPoint', action.deleteEndPoint); case DELETE_DATA_SUCCEEDED: return state .updateIn(['data', state.get('endPoint')], list => list.splice(action.indexDataToDelete, 1)) .set('deleteEndPoint', '') .set('dataToDelete', Map({})) .update('didDeleteData', (v) => !v); case FETCH_DATA: return state .update('endPoint', () => action.endPoint) .update('isLoading', () => true); case FETCH_DATA_SUCCEEDED: return state .updateIn(['data', state.get('endPoint')], () => List(action.data)) .updateIn(['initialData', state.get('endPoint')], () => action.modifiedData) .update('isLoading', () => false) .updateIn(['modifiedData', state.get('endPoint')], () => action.modifiedData); case ON_CHANGE: return state .updateIn(action.keys, () => action.value); case RESET_PROPS: return initialState .update('data', () => state.get('data')) .update('initialData', () => state.get('initialData')) .update('modifiedData', () => state.get('modifiedData')) .update('endPoint', () => 'roles'); case SET_DATA_TO_EDIT: return state.update('dataToEdit', () => action.dataToEdit); case SET_FORM: return state .set('formErrors', List([])) .updateIn(['initialData', state.get('endPoint')], () => action.form) .updateIn(['modifiedData', state.get('endPoint')], () => action.form); case SET_FORM_ERRORS: return state .update('didCheckErrors', (v) => v = !v) .set('formErrors', List(action.formErrors)); case SUBMIT_SUCCEEDED: return state .set('formErrors', List([])) .update('dataToEdit', () => '') .update('initialData', () => state.get('modifiedData')); case UNSET_DATA_TO_EDIT: return state .set('formErrors', List([])) .update('dataToEdit', () => '') .update('modifiedData', () => state.get('initialData')); default: return state; } } export default homePageReducer;
/** * @author Arthur Purnama (arthur@purnama.de) */ oldModule.controller('oldModule.UserController', ['$scope', '$constant', 'UserService', 'ErrorService', '$location', function ($scope, $constant, userService, errorService, $location) { if ($location.path() === '/'+$constant.module.old.path+'/user/application') { $scope.templateUrl = $constant.module.old.templates+'user.application.list.tpl.html'; } else if ($location.path() === '/'+$constant.module.old.path+'/user') { userService.findAll(function (response) { $scope.users = response.data; $scope.templateUrl = $constant.module.old.templates+'user.tpl.html'; }, function (response) { $scope.templateUrl = errorService.manageError(response.status); }); } }]);
(function() { 'use strict'; angular .module('app', ['ngMaterial', 'ui.router', 'uiGmapgoogle-maps', 'firebase', 'color.picker', 'app.services', 'textAngular', 'app.home', 'app.freeTrialForm', 'app.admin', 'mdPickers']) .config(function($mdThemingProvider, $mdIconProvider, $stateProvider, $urlRouterProvider, uiGmapGoogleMapApiProvider) { $mdIconProvider .defaultIconSet("./assets/svg/avatars.svg", 128) .icon("menu" , "./assets/svg/menu.svg" , 24) .icon("share" , "./assets/svg/share.svg" , 24) .icon("google_plus", "./assets/svg/google_plus.svg" , 512) .icon("hangouts" , "./assets/svg/hangouts.svg" , 512) .icon("twitter" , "./assets/svg/twitter.svg" , 512) .icon("phone" , "./assets/svg/phone.svg" , 512); $mdThemingProvider.theme('default') .primaryPalette('blue') .accentPalette('pink') .backgroundPalette('grey'); $urlRouterProvider.otherwise("/"); uiGmapGoogleMapApiProvider.configure({ key: 'AIzaSyCjY6ww8ne3L5JBOpjvyWF4uDEwVBMbSsM', v: '3.23', //defaults to latest 3.X anyhow libraries: 'geometry,drawing' }); }) .run(function($rootScope, $state) { $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { if (error === "AUTH_REQUIRED") { $state.go("home"); } if (error === "USER_LOGGED_IN") { console.log(error); $state.go('admin.menu'); } }); }); })();
/* Rabbits, by Notion. 0.0.5a Rabbits it's a JS based (As you already may know) routes manager, that's it :3 CC-BY, Notion */ var params = []; var route = function (r){ this.route = r; this.params_indices = []; this.params_types = []; this.has_params = false; for (var i = 0; i < this.route.length; i++) { // Get the parameter position and the variable name if( this.route[i].match(/\:(\w+)/) != null){ this.params_indices.push([0, ""]); this.params_indices[this.params_indices.length - 1][0] = i; this.params_indices[this.params_indices.length - 1][1] = this.route[i].match(/\:(\w+)/)[0]; this.has_params = true; } }; }; var rabbitsModule = function (r) { this.routes = r; this.regex_routes = []; this.routes_obj = []; this.padding = 3; // Distance where rabbits it's going to start to read. this.error_code = null; this.rabbits_elements = []; this.project_name = "rabbits"; this.procedure = []; this.execution_list = []; this.DEFAULT_LANG = "ES"; // Default configuration for locales usage this.error_codes = [ {code: 404, action: function(){alert("This is not the page you're looking for... ");} } ]; this.prerender = function (){ // This guy here is in charge to do the thing var _paths = []; for (var i = 0; i < this.routes.length; i++) { _paths.push(this.routes[i].path); this.routes_obj.push( new route(this.routes[i].path.split("/")) ); }; // Pass the route to the route obj for it's future use //console.log(this.routes_obj); for (var i = 0; i < _paths.length; i++) { _paths[i] = _paths[i].replace(/\//g, "\\/" ); _paths[i] = "/" + _paths[i] + "/"; _paths[i] = _paths[i].replace(/\:(\w+)/g, "([a-zA-Z0-9]{0,})" ); // the bunny should look for letters and numbers } for (var i = 0; i < _paths.length; i++) { this.regex_routes.push(_paths[i]); // Add the partial path to the paths that we'll use to match routes } // console.log(this.regex_routes); // Uncomment for debugging } this.match = function(){ var has_match = false; this.prerender(); // prerender the routes var _path = window.location.pathname.split("/"); var path = ""; for(var i = this.padding; i < _path.length; i++){ path += "/" + _path[i]; } // console.log(path); //uncomment for debugging for (var i = 0; i < this.routes.length; i++) { // Go through the routes var compiled = "'" + path + "'.match(" + this.regex_routes[i] + ")"; // Build the match //console.log(compiled); if( eval(compiled) != null ){ // The route matched? if (i != 0 || path == "/") { has_match = true; }; if( !this.routes_obj[i].has_params ){ // Is there any parameter? if ( typeof(this.routes[i].callback) == "string" ){ // Is it an string or a function var f = this.routes[i].callback + "()"; eval(f); //Ejecute string }else{ //Then it's a lambda this.routes[i].callback(); //Ejecute function or lambda } }else{ var local = []; for (var j = 0; j < this.routes_obj[i].params_indices.length; j++) { //console.log(this.routes_obj[i].params_indices[j][1]); window.params[ this.routes_obj[i].params_indices[j][1] ] = window.location.pathname.split("/")[this.routes_obj[i].params_indices[j][0] + (this.padding - 1)]; local.push(window.location.pathname.split("/")[this.routes_obj[i].params_indices[j][0] + (this.padding - 1)] ); }; this.routes[i].callback(local); } } }; if (!has_match) { this.error_code = 404; //As any page was found we set the error code as 404 }; if(this.error_code != null) this.error_catcher(); return this.error_code; }; this.error_catcher = function(){ for (var i = 0; i < this.error_codes.length; i++) { if(this.error_codes[i].code == this.error_code){ if ( typeof(this.error_codes[i].action) == "string" ){ // Is it an string or a function var f = this.error_codes[i].action + "()"; eval(f); //Ejecute string }else{ //Then it's a lambda this.error_codes[i].action(); //Ejecute function or lambda } } }; }; this.set_error_codes = function(errors){ //We overwrite the default error codes. for (var i = 0; i < this.error_codes.length; i++) { var done = false; for (var j = 0; j < errors.length; j++) { if(this.error_codes[i].code == errors[j].code){ done = true; this.error_codes[i].action = errors[j].action; } if (!done) { this.error_codes.push(errors[j]); }; } } } /* This little function is used to redirect things when you're using rabbits */ this.push = function(title, url, callback){ history.pushState(null, title, "/" + this.project_name + "/r"+url); callback(); } this.get_elements_by_attr = function(attribute, context){ //The original version of this functions it's in http://stackoverflow.com/questions/9496427/can-i-get-elements-by-attribute-selector-when-queryselectorall-is-not-available var nodeList = (context || document).getElementsByTagName('*'); var nodeArray = []; var i = 0; var j = 0; var node = null; var attr = null; while(node = nodeList[i++]){ j = 0; while(attr = node.attributes[j++]){ var tmp = attr.name; // Use a tmp variable to save the value of the attribute because it's an object if (eval("'" + tmp + "'.match(" + attribute + ")")) // check regex nodeArray.push(node); } } return nodeArray; } this.function_tail = function( elements ){ var attr = null; var self = null; var j = 0; for (var i = 0; i < elements.length; i++) { j = 0; self = elements[i]; while(attr = elements[i].attributes[j++]){ var tmp = attr.name; // Use a tmp variable to save the value of the attribute because it's an object if (eval("'" + tmp + "'.match(/(rabbit|rbt)-*/g)")) { // check regex tmp = tmp.substr(tmp.indexOf("-") + 1, tmp.length - 1); // Here we get the function name and so on //console.log( typeof attr.value, attr.value ); this.rabbits_elements.push(self); //console.log(tmp); this.procedure.push(tmp); this.execution_list.push("this.r_" + tmp + "(" + (this.rabbits_elements.length - 1) + ",'" + attr.value + "')"); // We execute the function with it's value as a parameter } } }; this.execute(); } this.execute = function(){ for (var i = 0; i < this.execution_list.length; i++) { this.execution_list[i] = this.execution_list[i].replace(/\'/g, "\'"); eval(this.execution_list[i]); }; } this.init = function(callback){ this.function_tail( this.get_elements_by_attr("/(rabbit|rbt)-*/g") ); // Get elements with rbt or rabbit attr if (typeof callback != "undefined") callback(); } this.r_times = function(index, json){ // Repeats a DOM element n times var element = this.rabbits_elements[index]; var content = element.innerHTML; var output = ""; var _times = parseInt(json); console.log(content); content = content.replace(/\n/g, ""); for (var i = 0; i < _times; i++) { var _tmp = content.replace(/\{\$index\}/g, i); output += _tmp; }; element.innerHTML = output; }; this.r_class = function(index, json){ // You use this as rbt-class="(condition) true : false" :) var condition = ""; var end = /\?/g; var start = /\¿/g; end.test(json); start.test(json); var condition = json.substring(start.lastIndex, end.lastIndex - 1); var _class = json.substring(end.lastIndex + 1, json.length); var elemente = this.rabbits_elements[index]; console.log(condition, eval(condition)); if ( eval(condition) ) { _class = _class.split(":")[0].replace(/\:/g, ""); this.rabbits_elements[index].className = _class; }else{ if ( _class.indexOf(":") != -1 ) { _class = _class.split(":")[1].replace(/\:/g, ""); this.rabbits_elements[index].className = _class; }; }; } this.raise = function(ex){ for (var i = 0; i < this.error_codes.length; i++) { if( this.error_codes[i].code == ex ){ this.error_codes[i].action(); break; }; }; } this.r_content = function(index, json){ var xmlhttp; var path = ""; var element = this.rabbits_elements[index]; var self = this; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } if (json.indexOf(".") != -1) { // if a file extension is specified path = json; }else{ path = "_" + json + ".html"; }; console.log(path); xmlhttp.open("GET", path, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { switch(xmlhttp.status){ case 200: element.innerHTML = xmlhttp.responseText; break; case 400: self.raise(1.400); break; case 404: self.raise(1.404); break; case 500: self.raise(1.500); break; } } } xmlhttp.send(); } this.get_lang = function(){ var name = "lang="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return this.DEFAULT_LANG; }; this.setCookie = function(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } this.set_lang = function(lang, r){ this.setCookie("lang", lang, 365); if (typeof r != "undefined") { if (r) { location.reload(); }; }; } this.r_locale = function(index, json){ var lang = this.get_lang(); var txt = ""; if (lang != "" && lang != this.DEFAULT_LANG){ //console.log(this.rabbits_elements[index].innerHTML, json); eval("txt = " + lang + "." + json); if (typeof txt != "undefined") { //console.log(this.rabbits_elements[index], this.rabbits_elements[index].value); if (typeof this.rabbits_elements[index].value == "undefined"){ this.rabbits_elements[index].innerHTML = txt; }else{ this.rabbits_elements[index].value = txt; } }; }; } this.r_repeat = function(index, json){ var json = eval(json); var template = this.rabbits_elements[index].innerHTML; template = template.replace(/\t/g, ""); var element = this.rabbits_elements[index]; element.innerHTML = ""; for (var i = 0; i < json.length; i++) { var tmp = template; tmp = tmp.replace(/\n/g, ""); var end = /\]/g; var start = /\[/g; var times = tmp.match(end).length; for(var index = 0; index < times; index++){ end = /\]/g; start = /\[/g; //console.log(tmp); end.test(tmp); var j = end.lastIndex; start.test(tmp); var k = start.lastIndex; //console.log(tmp[j-1], tmp[k-1], index); var found = false; var part = tmp.substring(k-1, j); part = part.replace(/\s/g, ""); //console.log(part, "in -> ", index, "i -> ", i); var part_ = part.substring(1, part.indexOf(".")); var _part = part.substring(part.indexOf(".") + 1, part.length); _part = _part.replace(/\]/g, ""); //console.log(eval("/\\[" + part_ + "\\." + _part + "\\]/g"), eval("json["+i+"]." + _part), "->", i); //console.log("-> ", eval("json["+i+"]." + _part)); tmp = tmp.replace(/\{\$index\}/g, "" + i); tmp = tmp.replace(eval("/\\[" + part_ + "\\." + _part + "\\]/g"), eval("json["+i+"]." + _part)); //console.log(tmp) } element.innerHTML += tmp; } } } /* This little function is used to redirect things when you're using rabbits */ var push = function(title, url, callback) { history.pushState(null, title, "/" + this.project_name + "/r" + url); callback(); }
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part2 = { init: function() { var vs = "uvxyz"; var maxDepth = 5; var minDepth = 4; var exp; var numCorrect = 0; var exps = [ ]; var isCorrect; var options = [ 0, 1, 2, 3, 4]; // David: all of these helper functions (except isNew) are // duplicated in RP14part1.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function findMatchingParen(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s) { var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".") { p1++; } // do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); } function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function function isNew(arr) { var exp = arr[arr.length-1]; for(var i=0; i<arr.length-1; i++) { if (arr[i] === exp) { return false; } } return true; } while (exps.length < 4) { if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp exps.push( L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")) ); isCorrect = true; } else { exps.push( getSyntaxError(minDepth,maxDepth,vs) ); isCorrect = question.answer === "True"; } if (isNew(exps)) { numCorrect += isCorrect ? 1 : 0; } else { exps.pop(); } } this.expressions = exps.join("<br />"); this.answer = String(numCorrect); options.splice(numCorrect,1); //console.log(numCorrect); this.option1 = options[0]; this.option2 = options[1]; this.option3 = options[2]; this.option4 = options[3]; } //init };// RP14part2 window.RP14part2 = window.RP14part2 || RP14part2; }());
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the PagingGetMultiplePagesOptions class. * @constructor * Additional parameters for the Paging_getMultiplePages operation. * @member {number} [maxresults] Sets the maximum number of items to return in * the response. * * @member {number} [timeout] Sets the maximum time that the server can spend * processing the request, in seconds. The default is 30 seconds. Default * value: 30 . * */ function PagingGetMultiplePagesOptions() { } /** * Defines the metadata of PagingGetMultiplePagesOptions * * @returns {object} metadata of PagingGetMultiplePagesOptions * */ PagingGetMultiplePagesOptions.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'PagingGetMultiplePagesOptions', modelProperties: { maxresults: { required: false, type: { name: 'Number' } }, timeout: { required: false, defaultValue: 30, type: { name: 'Number' } } } } }; }; module.exports = PagingGetMultiplePagesOptions;
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([ "./kendo.draganddrop" ], f); })(function(){ (function($, undefined) { var kendo = window.kendo, Widget = kendo.ui.Widget, START = "start", BEFORE_MOVE = "beforeMove", MOVE = "move", END = "end", CHANGE = "change", CANCEL = "cancel", ACTION_SORT = "sort", ACTION_REMOVE = "remove", ACTION_RECEIVE = "receive", DEFAULT_FILTER = ">*", MISSING_INDEX = -1; function containsOrEqualTo(parent, child) { try { return $.contains(parent, child) || parent == child; } catch (e) { return false; } } function defaultHint(element) { return element.clone(); } function defaultPlaceholder(element) { return element.clone().removeAttr("id").css("visibility", "hidden"); } var Sortable = Widget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(that, element, options); if(!that.options.placeholder) { that.options.placeholder = defaultPlaceholder; } if(!that.options.hint) { that.options.hint = defaultHint; } that._draggable = that._createDraggable(); }, events: [ START, BEFORE_MOVE, MOVE, END, CHANGE, CANCEL ], options: { name: "Sortable", hint: null, placeholder: null, filter: DEFAULT_FILTER, holdToDrag: false, disabled: null, container: null, connectWith: null, handler: null, cursorOffset: null, axis: null, ignore: null, cursor: "auto" }, destroy: function() { this._draggable.destroy(); Widget.fn.destroy.call(this); }, _createDraggable: function() { var that = this, element = that.element, options = that.options; return new kendo.ui.Draggable(element, { filter: options.filter, hint: kendo.isFunction(options.hint) ? options.hint : $(options.hint), holdToDrag: options.holdToDrag, container: options.container ? $(options.container) : null, cursorOffset: options.cursorOffset, axis: options.axis, ignore: options.ignore, dragstart: $.proxy(that._dragstart, that), dragcancel: $.proxy(that._dragcancel, that), drag: $.proxy(that._drag, that), dragend: $.proxy(that._dragend, that) }); }, _dragstart: function(e) { var draggedElement = this.draggedElement = e.currentTarget, target = e.target || kendo.elementUnderCursor(e), disabled = this.options.disabled, handler = this.options.handler, _placeholder = this.options.placeholder, placeholder = this.placeholder = kendo.isFunction(_placeholder) ? $(_placeholder.call(this, draggedElement)) : $(_placeholder); if(disabled && draggedElement.is(disabled)) { e.preventDefault(); } else if(handler && !$(target).is(handler)) { e.preventDefault(); } else { if(this.trigger(START, { item: draggedElement, draggableEvent: e })) { e.preventDefault(); } else { draggedElement.css("display", "none"); draggedElement.before(placeholder); this._setCursor(); } } }, _dragcancel: function(e) { this._cancel(); this.trigger(CANCEL, { item: this.draggedElement }); this._resetCursor(); }, _drag: function(e) { var draggedElement = this.draggedElement, target = this._findTarget(e), targetCenter, cursorOffset = { left: e.x.location, top: e.y.location }, offsetDelta, axisDelta = { x: e.x.delta, y: e.y.delta }, direction, sibling, getSibling, axis = this.options.axis, eventData = { item: draggedElement, list: this, draggableEvent: e }; if(axis === "x" || axis === "y") { this._movementByAxis(axis, cursorOffset, axisDelta[axis], eventData); return; } if(target) { targetCenter = this._getElementCenter(target.element); offsetDelta = { left: Math.round(cursorOffset.left - targetCenter.left), top: Math.round(cursorOffset.top - targetCenter.top) }; $.extend(eventData, { target: target.element }); if(target.appendToBottom) { this._movePlaceholder(target, null, eventData); return; } if(target.appendAfterHidden) { this._movePlaceholder(target, "next", eventData); } if(this._isFloating(target.element)) { //horizontal if(axisDelta.x < 0 && offsetDelta.left < 0) { direction = "prev"; } else if(axisDelta.x > 0 && offsetDelta.left > 0) { direction = "next"; } } else { //vertical if(axisDelta.y < 0 && offsetDelta.top < 0) { direction = "prev"; } else if(axisDelta.y > 0 && offsetDelta.top > 0) { direction = "next"; } } if(direction) { getSibling = (direction === "prev") ? jQuery.fn.prev : jQuery.fn.next; sibling = getSibling.call(target.element); //find the prev/next visible sibling while(sibling.length && !sibling.is(":visible")) { sibling = getSibling.call(sibling); } if(sibling[0] != this.placeholder[0]) { this._movePlaceholder(target, direction, eventData); } } } }, _dragend: function(e) { var placeholder = this.placeholder, draggedElement = this.draggedElement, draggedIndex = this.indexOf(draggedElement), placeholderIndex = this.indexOf(placeholder), connectWith = this.options.connectWith, connectedList, isDefaultPrevented, eventData, connectedListEventData; this._resetCursor(); eventData = { action: ACTION_SORT, item: draggedElement, oldIndex: draggedIndex, newIndex: placeholderIndex, draggableEvent: e }; if(placeholderIndex >= 0) { isDefaultPrevented = this.trigger(END, eventData); } else { connectedList = placeholder.parents(connectWith).getKendoSortable(); eventData.action = ACTION_REMOVE; connectedListEventData = $.extend({}, eventData, { action: ACTION_RECEIVE, oldIndex: MISSING_INDEX, newIndex: connectedList.indexOf(placeholder) }); isDefaultPrevented = !(!this.trigger(END, eventData) && !connectedList.trigger(END, connectedListEventData)); } if(isDefaultPrevented || placeholderIndex === draggedIndex) { this._cancel(); return; } placeholder.replaceWith(draggedElement); draggedElement.show(); this._draggable.dropped = true; eventData = { action: this.indexOf(draggedElement) != MISSING_INDEX ? ACTION_SORT : ACTION_REMOVE, item: draggedElement, oldIndex: draggedIndex, newIndex: this.indexOf(draggedElement), draggableEvent: e }; this.trigger(CHANGE, eventData); if(connectedList) { connectedListEventData = $.extend({}, eventData, { action: ACTION_RECEIVE, oldIndex: MISSING_INDEX, newIndex: connectedList.indexOf(draggedElement) }); connectedList.trigger(CHANGE, connectedListEventData); } }, _findTarget: function(e) { var element = this._findElementUnderCursor(e), items, connectWith = this.options.connectWith, node; if($.contains(this.element[0], element)) { //the element is part of the sortable container items = this.items(); node = items.filter(element)[0] || items.has(element)[0]; return node ? { element: $(node), sortable: this } : null; } else if (this.element[0] == element && this._isEmpty()) { return { element: this.element, sortable: this, appendToBottom: true }; } else if (this.element[0] == element && this._isLastHidden()) { node = this.items().eq(0); return { element: node , sortable: this, appendAfterHidden: true }; } else if (connectWith) { //connected lists are present return this._searchConnectedTargets(element, e); } }, _findElementUnderCursor: function(e) { var elementUnderCursor = kendo.elementUnderCursor(e), draggable = e.sender, disabled = this.options.disabled, filter = this.options.filter, items = this.items(); if(containsOrEqualTo(draggable.hint[0], elementUnderCursor)) { draggable.hint.hide(); elementUnderCursor = kendo.elementUnderCursor(e); // IE8 does not return the element in iframe from first attempt if (!elementUnderCursor) { elementUnderCursor = kendo.elementUnderCursor(e); } draggable.hint.show(); } return elementUnderCursor; }, _searchConnectedTargets: function(element, e) { var connected = $(this.options.connectWith), sortableInstance, items, node; for (var i = 0; i < connected.length; i++) { sortableInstance = connected.eq(i).getKendoSortable(); if($.contains(connected[i], element)) { if(sortableInstance) { items = sortableInstance.items(); node = items.filter(element)[0] || items.has(element)[0]; if(node) { sortableInstance.placeholder = this.placeholder; return { element: $(node), sortable: sortableInstance }; } else { return null; } } } else if(connected[i] == element) { if(sortableInstance && sortableInstance._isEmpty()) { return { element: connected.eq(i), sortable: sortableInstance, appendToBottom: true }; } else if (this._isCursorAfterLast(sortableInstance, e)) { node = sortableInstance.items().last(); return { element: node, sortable: sortableInstance }; } } } }, _isCursorAfterLast: function(sortable, e) { var lastItem = sortable.items().last(), cursorOffset = { left: e.x.location, top: e.y.location }, lastItemOffset, delta; lastItemOffset = kendo.getOffset(lastItem); lastItemOffset.top += lastItem.outerHeight(); lastItemOffset.left += lastItem.outerWidth(); if(this._isFloating(lastItem)) { //horizontal delta = lastItemOffset.left - cursorOffset.left; } else { //vertical delta = lastItemOffset.top - cursorOffset.top; } return delta < 0 ? true : false; }, _movementByAxis: function(axis, cursorOffset, delta, eventData) { var cursorPosition = (axis === "x") ? cursorOffset.left : cursorOffset.top, target = (delta < 0) ? this.placeholder.prev() : this.placeholder.next(), targetCenter; if (target.length && !target.is(":visible")) { target = (delta <0) ? target.prev() : target.next(); } $.extend(eventData, { target: target }); targetCenter = this._getElementCenter(target); if (targetCenter) { targetCenter = (axis === "x") ? targetCenter.left : targetCenter.top; } if (target.length && delta < 0 && cursorPosition - targetCenter < 0) { //prev this._movePlaceholder({ element: target, sortable: this }, "prev", eventData); } else if (target.length && delta > 0 && cursorPosition - targetCenter > 0) { //next this._movePlaceholder({ element: target, sortable: this }, "next", eventData); } }, _movePlaceholder: function(target, direction, eventData) { var placeholder = this.placeholder; if (!target.sortable.trigger(BEFORE_MOVE, eventData)) { if (!direction) { target.element.append(placeholder); } else if (direction === "prev") { target.element.before(placeholder); } else if (direction === "next") { target.element.after(placeholder); } target.sortable.trigger(MOVE, eventData); } }, _setCursor: function() { var cursor = this.options.cursor, body; if(cursor && cursor !== "auto") { body = $(document.body); this._originalCursorType = body.css("cursor"); body.css({ "cursor": cursor }); if(!this._cursorStylesheet) { this._cursorStylesheet = $("<style>* { cursor: " + cursor + " !important; }</style>"); } this._cursorStylesheet.appendTo(body); } }, _resetCursor: function() { if(this._originalCursorType) { $(document.body).css("cursor", this._originalCursorType); this._originalCursorType = null; this._cursorStylesheet.remove(); } }, _getElementCenter: function(element) { var center = element.length ? kendo.getOffset(element) : null; if(center) { center.top += element.outerHeight() / 2; center.left += element.outerWidth() / 2; } return center; }, _isFloating: function(item) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); }, _cancel: function() { this.draggedElement.show(); this.placeholder.remove(); }, _items: function() { var filter = this.options.filter, items; if(filter) { items = this.element.find(filter); } else { items = this.element.children(); } return items; }, indexOf: function(element) { var items = this._items(), placeholder = this.placeholder, draggedElement = this.draggedElement; if(placeholder && element[0] == placeholder[0]) { return items.not(draggedElement).index(element); } else { return items.not(placeholder).index(element); } }, items: function() { var placeholder = this.placeholder, items = this._items(); if(placeholder) { items = items.not(placeholder); } return items; }, _isEmpty: function() { return !this.items().length; }, _isLastHidden: function() { return this.items().length === 1 && this.items().is(":hidden"); } }); kendo.ui.plugin(Sortable); })(window.kendo.jQuery); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import React, { Component, PropTypes } from 'react'; import { Field } from 'redux-form'; import blockLoading from 'assets/blockLoading.gif'; import styles from 'modules/common/styles'; import { required } from './validations'; class RichTextField extends Component { static propTypes = { input: PropTypes.object.isRequired, meta: PropTypes.object.isRequired, label: PropTypes.string, } constructor(props) { super(props); this.state = { Editor: null }; } componentDidMount() { this.mounted = true; this.loadEditor(); } componentWillUnmount() { this.mounted = false; this.setState({ Editor: null }); } loadEditor = () => { System.import('modules/common/editor').then((module) => { if (this.mounted && !this.state.Editor) { this.setState({ Editor: module.default }); } }); } renderEditor = () => { // todo place holder using textLabel const { input: { value, onChange } } = this.props; // eslint-disable-line const { Editor } = this.state; if (Editor) { return <Editor onChange={onChange} content={value} />; } return <div><img src={blockLoading} role="presentation" /></div>; } render() { const { meta: { error }, label } = this.props; return ( <div className={styles.w100}> <div className={error ? styles.colorError : null}> {label} </div> {this.renderEditor()} { error && <div><small className={styles.colorError}>{error}</small></div>} </div> ); } } export default ({ ...props }) => <Field name="desc" validate={[required]} component={RichTextField} props={{ ...props }} />;
Cursor = function() { this.x = 0; this.y = 0; this.color = WHITE; return this; } Cursor.prototype.move = function(event) { this.x = event.offsetX; this.y = event.offsetY; }; Cursor.prototype.hoverOn = function() { this.color = CURSOR_HOVER; }; Cursor.prototype.hoverOff = function() { this.color = WHITE; }; Cursor.prototype.render = function(context) { context.fillStyle = this.color; var x = this.x; var y = this.y; context.beginPath(); context.moveTo(x, y); context.lineTo(x += 13, y += 13); context.lineTo(x -= 8, y); context.lineTo(this.x, this.y + 19); context.closePath(); context.fill(); context.strokeStyle = BLACK; context.lineWidth = 2; context.stroke(); context.strokeStyle = CURSOR_OUTLINE; context.lineWidth = 1; context.stroke(); };
import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import config from './webpack.config.js'; const serverOptions = { publicPath: config.output.publicPath, contentBase: 'src', hot: true, stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false }, historyApiFallback: true }; const compiler = webpack(config); const webpackDevServer = new WebpackDevServer(compiler, serverOptions); webpackDevServer.listen(config._hotPort, function listen(err) { if (err) { throw err; } console.log('webpack dev server listening on %s', config._hotPort); });
// All the subviews of a TodosAppView will always have // the same model as the TodosAppView has. // maria.ElementView.subclass(checkit, 'TodosAppView', { properties: { getContainerEl: function() { return this.find('.content'); // child views will be appended to this element }, initialize: function() { this.appendChild(new checkit.TodosInputView()); this.appendChild(new checkit.TodosToolbarView()); this.appendChild(new checkit.TodosListView()); this.appendChild(new checkit.TodosStatsView()); }, insertBefore: function(newChild, oldChild) { newChild.setModel(this.getModel()); maria.ElementView.prototype.insertBefore.call(this, newChild, oldChild); }, setModel: function(model) { if (model !== this.getModel()) { maria.ElementView.prototype.setModel.call(this, model); var childViews = this.childNodes; for (var i = 0, ilen = childViews.length; i < ilen; i++) { childViews[i].setModel(model); } } } } });
import {createStore} from 'redux'; import reducer from './reducer'; export default function makeStore() { return createStore(reducer); }
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; const _excluded = ["disableUnderline", "fullWidth", "inputComponent", "multiline", "type", "hiddenLabel"]; import * as React from 'react'; import { refType } from '@material-ui/utils'; import PropTypes from 'prop-types'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import InputBase from '../InputBase'; import styled, { rootShouldForwardProp } from '../styles/styled'; import useThemeProps from '../styles/useThemeProps'; import filledInputClasses, { getFilledInputUtilityClass } from './filledInputClasses'; import { rootOverridesResolver as inputBaseRootOverridesResolver, inputOverridesResolver as inputBaseInputOverridesResolver, InputBaseRoot, InputBaseComponent as InputBaseInput } from '../InputBase/InputBase'; import { jsx as _jsx } from "react/jsx-runtime"; const useUtilityClasses = styleProps => { const { classes, disableUnderline } = styleProps; const slots = { root: ['root', !disableUnderline && 'underline'], input: ['input'] }; const composedClasses = composeClasses(slots, getFilledInputUtilityClass, classes); return _extends({}, classes, composedClasses); }; const FilledInputRoot = styled(InputBaseRoot, { shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes', name: 'MuiFilledInput', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; return [...inputBaseRootOverridesResolver(props, styles), !styleProps.disableUnderline && styles.underline]; } })(({ theme, styleProps }) => { const light = theme.palette.mode === 'light'; const bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)'; const backgroundColor = light ? 'rgba(0, 0, 0, 0.06)' : 'rgba(255, 255, 255, 0.09)'; return _extends({ /* Styles applied to the root element. */ position: 'relative', backgroundColor, borderTopLeftRadius: theme.shape.borderRadius, borderTopRightRadius: theme.shape.borderRadius, transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), '&:hover': { backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.13)', // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor } }, [`&.${filledInputClasses.focused}`]: { backgroundColor }, [`&.${filledInputClasses.disabled}`]: { backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)' } }, !styleProps.disableUnderline && { '&:after': { borderBottom: `2px solid ${theme.palette[styleProps.color].main}`, left: 0, bottom: 0, // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), pointerEvents: 'none' // Transparent to the hover style. }, [`&.${filledInputClasses.focused}:after`]: { transform: 'scaleX(1)' }, [`&.${filledInputClasses.error}:after`]: { borderBottomColor: theme.palette.error.main, transform: 'scaleX(1)' // error is always underlined in red }, '&:before': { borderBottom: `1px solid ${bottomLineColor}`, left: 0, bottom: 0, // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242 content: '"\\00a0"', position: 'absolute', right: 0, transition: theme.transitions.create('border-bottom-color', { duration: theme.transitions.duration.shorter }), pointerEvents: 'none' // Transparent to the hover style. }, [`&:hover:not(.${filledInputClasses.disabled}):before`]: { borderBottom: `1px solid ${theme.palette.text.primary}` }, [`&.${filledInputClasses.disabled}:before`]: { borderBottomStyle: 'dotted' } }, styleProps.startAdornment && { paddingLeft: 12 }, styleProps.endAdornment && { paddingRight: 12 }, styleProps.multiline && _extends({ padding: '25px 12px 8px' }, styleProps.size === 'small' && { paddingTop: 21, paddingBottom: 4 }, styleProps.hiddenLabel && { paddingTop: 16, paddingBottom: 17 })); }); const FilledInputInput = styled(InputBaseInput, { name: 'MuiFilledInput', slot: 'Input', overridesResolver: inputBaseInputOverridesResolver })(({ theme, styleProps }) => _extends({ paddingTop: 25, paddingRight: 12, paddingBottom: 8, paddingLeft: 12, '&:-webkit-autofill': { WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset', WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff', caretColor: theme.palette.mode === 'light' ? null : '#fff', borderTopLeftRadius: 'inherit', borderTopRightRadius: 'inherit' } }, styleProps.size === 'small' && { paddingTop: 21, paddingBottom: 4 }, styleProps.hiddenLabel && { paddingTop: 16, paddingBottom: 17 }, styleProps.multiline && { paddingTop: 0, paddingBottom: 0, paddingLeft: 0, paddingRight: 0 }, styleProps.startAdornment && { paddingLeft: 0 }, styleProps.endAdornment && { paddingRight: 0 }, styleProps.hiddenLabel && styleProps.size === 'small' && { paddingTop: 8, paddingBottom: 9 })); const FilledInput = /*#__PURE__*/React.forwardRef(function FilledInput(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiFilledInput' }); const { fullWidth = false, inputComponent = 'input', multiline = false, type = 'text' } = props, other = _objectWithoutPropertiesLoose(props, _excluded); const styleProps = _extends({}, props, { fullWidth, inputComponent, multiline, type }); const classes = useUtilityClasses(props); return /*#__PURE__*/_jsx(InputBase, _extends({ components: { Root: FilledInputRoot, Input: FilledInputInput }, componentsProps: { root: { styleProps }, input: { styleProps } }, fullWidth: fullWidth, inputComponent: inputComponent, multiline: multiline, ref: ref, type: type }, other, { classes: classes })); }); process.env.NODE_ENV !== "production" ? FilledInput.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element is focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component. */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]), /** * The default value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the component is disabled. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the `input` will indicate an error. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ error: PropTypes.bool, /** * If `true`, the `input` will take up the full width of its container. * @default false */ fullWidth: PropTypes.bool, /** * If `true`, the label is hidden. * This is used to increase density for a `FilledInput`. * Be sure to add `aria-label` to the `input` element. * @default false */ hiddenLabel: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the `input` element. * Either a string to use a HTML element or a component. * @default 'input' */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. * @default {} */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. * The prop defaults to the value (`'none'`) inherited from the parent FormControl component. */ margin: PropTypes.oneOf(['dense', 'none']), /** * Maximum number of rows to display when multiline option is set to true. */ maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Minimum number of rows to display when multiline option is set to true. */ minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * If `true`, a `textarea` element is rendered. * @default false */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the `input` before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element is required. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). * @default 'text' */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; FilledInput.muiName = 'Input'; export default FilledInput;
BASE.require([ "jQuery" ], function () { BASE.namespace("components.ui.inputs"); var Future = BASE.async.Future; components.ui.inputs.UIFileInputBehavior = function (elem) { var self = this; var $elem = $(elem); var $fileInput = $('<input type="file">'); $elem.data('fileInput', self); var getFileFromUri = function (uri) { return new Future(function (setValue, setError) { var readerFunction = window.resolveLocalFileSystemURL; if (typeof readerFunction !== "function") { readerFunction = window.resolveLocalFileSystemURI; } readerFunction(uri, function (fileEntry) { fileEntry.file(function (file) { setValue(file); }, function (error) { setError(error); }); }, setError); }).then().ifError(function (error) { console.log(error); }); } $fileInput.css({ position: 'absolute', width: '100%', height: '100%', opacity: 0, overflow: 'hidden', border: 0, top: 0, left: 0 }); $elem.append($fileInput); $fileInput.on('change', function (event) { event.stopPropagation(); // IE fires clears the value of the input when you click "Browse", triggering a change if ($fileInput.val() !== "") { $elem.trigger({ type: 'change', value: $fileInput.val().split('\\').pop(), file: $fileInput[0].files[0] }); } }); $fileInput.on('cordovaChange', function (event) { var uri = event.value; getFileFromUri(uri).then(function(file){ $elem.trigger({ type: 'change', value: file.name, file: file, }); }); }); $fileInput.on('click', function (event) { this.value = null; if (typeof cordova !== 'undefined' && typeof imagePicker !== 'undefined') { event.preventDefault(); window.imagePicker.getPictures( function (results) { $fileInput.trigger({ type: 'cordovaChange', value: results[0] }); }, function (error) { console.log('Error: ' + error); }, { maximumImagesCount: 1, } ); } }); self.getFileInput = function () { return $fileInput[0]; }; self.setFileInputName = function (name) { $fileInput.attr('name', name); }; self.triggerClick = function () { $fileInput.trigger('click'); } }; });
import wretch from 'wretch'; const api = wretch() .url(process.env.API_URL || 'http://localhost:3002/api') .auth(`Bearer ${localStorage.getItem('authToken')}`); /* * Exported methods shouldn't be used directly from a component; use * one of the actual API libs instead. */ export function get(app, path, data = undefined, config = {}) { let request = api.url(`/${app}/${path}`); if (data) { request = request.query(data); } return request.get().res(parseResponse); } export function post(app, path, data = null, config = {}) { return api .url(`/${app}/${path}`) .post(data) .badRequest(parseValidationError) .res(parseResponse); } export function put(app, path, data = null, config = {}) { return api .url(`/${app}/${path}`) .put(data) .badRequest(parseValidationError) .res(parseResponse); } export function delete_(app, path, data = null, config = {}) { return api .url(`/${app}/${path}`) .delete(data) .res(parseResponse); } export class ValidationError extends Error { constructor(message, validationErrors) { super(message); // 'Error' breaks prototype chain here Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain this.validationErrors = validationErrors; this.statusCode = 400; } } const isJSONResponse = response => /application\/json/.test(response.headers.get('content-type')); const parseResponse = response => { if (!response.ok) { throw new Error(response.status + ' ' + response.statusText); } if (isJSONResponse(response)) { return response.json(); } return response.text(); }; const parseValidationError = async ({ response, text }) => { if (isJSONResponse(response)) { const json = JSON.parse(text); throw new ValidationError(json.error, json.message); } throw new Error(error.text); };
const loadData = require('../loadData') jest.mock('fs-extra') jest.mock('../../utils/get-closest-config', () => require('../../../mocks/get-closest-config')) describe('load Plugins', () => { it('should save property into context', async () => { const result = await loadData({ data: '', site: {}, otherKey: true, src: '/path/to/', }) expect(result.otherKey).toBeTruthy() }) it('throws if context is not passed as an object', async () => { try { await loadData() } catch (error) { expect(error.message).toBe('should pass a object to load.') } }) it('throws if context.src is not passed as a string', async () => { try { await loadData({ site: {}, }) } catch (error) { expect(error.message).toBe('context.src must be a string.') } }) it('throws if context.site is not passed as a object', async () => { try { await loadData({ src: '/path/to', }) } catch (error) { expect(error.message).toBe('context.site must be passed as a object.') } }) })
/** * hasClass method * check if element has class * @param {string} cls - class name to check for * @return {boolean} */ hasClass: function(cls) { return this.length ? this[0].classList.contains(cls) : false; },
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu" ], "MONTH": [ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember" ], "SHORTDAY": [ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des" ], "fullDate": "EEEE, dd MMMM yyyy", "longDate": "d MMMM yyyy", "medium": "d MMM yyyy HH:mm:ss", "mediumDate": "d MMM yyyy", "mediumTime": "HH:mm:ss", "short": "dd/MM/yy HH:mm", "shortDate": "dd/MM/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Rp", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "id", "pluralCat": function (n) { return PLURAL_CATEGORY.OTHER;} }); }]);
import 'ember'; import Ember from 'ember-metal/core'; import isEnabled from 'ember-metal/features'; import EmberHandlebars from 'ember-htmlbars/compat'; import HandlebarsCompatibleHelper from 'ember-htmlbars/compat/helper'; import Helper from 'ember-htmlbars/helper'; import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils'; import viewKeyword from 'ember-htmlbars/keywords/view'; var compile, helpers, makeBoundHelper; compile = EmberHandlebars.compile; helpers = EmberHandlebars.helpers; makeBoundHelper = EmberHandlebars.makeBoundHelper; var makeViewHelper = EmberHandlebars.makeViewHelper; var App, registry, container, originalViewKeyword; function reverseHelper(value) { return arguments.length > 1 ? value.split('').reverse().join('') : '--'; } QUnit.module('Application Lifecycle - Helper Registration', { setup() { originalViewKeyword = registerKeyword('view', viewKeyword); }, teardown() { Ember.run(function() { if (App) { App.destroy(); } App = null; Ember.TEMPLATES = {}; }); resetKeyword('view', originalViewKeyword); } }); var boot = function(callback) { Ember.run(function() { App = Ember.Application.create({ name: 'App', rootElement: '#qunit-fixture' }); App.deferReadiness(); App.Router = Ember.Router.extend({ location: 'none' }); registry = App.registry; container = App.__container__; if (callback) { callback(); } }); var router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); Ember.run(function() { router.handleURL('/'); }); }; QUnit.test('Unbound dashed helpers registered on the container can be late-invoked', function() { Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{x-borf}} {{x-borf \'YES\'}}</div>'); let helper = new HandlebarsCompatibleHelper(function(val) { return arguments.length > 1 ? val : 'BORF'; }); boot(() => { registry.register('helper:x-borf', helper); }); equal(Ember.$('#wrapper').text(), 'BORF YES', 'The helper was invoked from the container'); ok(!helpers['x-borf'], 'Container-registered helper doesn\'t wind up on global helpers hash'); }); // need to make `makeBoundHelper` for HTMLBars QUnit.test('Bound helpers registered on the container can be late-invoked', function() { Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{x-reverse}} {{x-reverse foo}}</div>'); boot(function() { registry.register('controller:application', Ember.Controller.extend({ foo: 'alex' })); registry.register('helper:x-reverse', makeBoundHelper(reverseHelper)); }); equal(Ember.$('#wrapper').text(), '-- xela', 'The bound helper was invoked from the container'); ok(!helpers['x-reverse'], 'Container-registered helper doesn\'t wind up on global helpers hash'); }); QUnit.test('Bound `makeViewHelper` helpers registered on the container can be used', function() { Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{x-foo}} {{x-foo name=foo}}</div>'); boot(function() { registry.register('controller:application', Ember.Controller.extend({ foo: 'alex' })); registry.register('helper:x-foo', makeViewHelper(Ember.Component.extend({ layout: compile('woot!!{{attrs.name}}') }))); }); equal(Ember.$('#wrapper').text(), 'woot!! woot!!alex', 'The helper was invoked from the container'); }); if (isEnabled('ember-htmlbars-dashless-helpers')) { QUnit.test('Undashed helpers registered on the container can be invoked', function() { Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{omg}}|{{yorp \'boo\'}}|{{yorp \'ya\'}}</div>'); expectDeprecation(function() { boot(function() { registry.register('helper:omg', function([value]) { return 'OMG'; }); registry.register('helper:yorp', makeBoundHelper(function(value) { return value; })); }, /Please use Ember.Helper.build to wrap helper functions./); }); equal(Ember.$('#wrapper').text(), 'OMG|boo|ya', 'The helper was invoked from the container'); }); } else { QUnit.test('Undashed helpers registered on the container can not (presently) be invoked', function() { // Note: the reason we're not allowing undashed helpers is to avoid // a possible perf hit in hot code paths, i.e. _triageMustache. // We only presently perform container lookups if prop.indexOf('-') >= 0 Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{omg}}|{{omg \'GRRR\'}}|{{yorp}}|{{yorp \'ahh\'}}</div>'); expectAssertion(function() { boot(function() { registry.register('helper:omg', function() { return 'OMG'; }); registry.register('helper:yorp', makeBoundHelper(function() { return 'YORP'; })); }); }, /A helper named 'omg' could not be found/); }); } QUnit.test('Helpers can receive injections', function() { Ember.TEMPLATES.application = compile('<div id=\'wrapper\'>{{full-name}}</div>'); var serviceCalled = false; boot(function() { registry.register('service:name-builder', Ember.Service.extend({ build() { serviceCalled = true; } })); registry.register('helper:full-name', Helper.extend({ nameBuilder: Ember.inject.service('name-builder'), compute() { this.get('nameBuilder').build(); } })); }); ok(serviceCalled, 'service was injected, method called'); });
import { computed } from '@ember/object'; import Oauth2 from 'torii/providers/oauth2-code'; import { configurable } from 'torii/configuration'; /** * This class implements authentication against AzureAD * using the OAuth2 authorization flow in a popup window. * @class */ var AzureAdOauth2 = Oauth2.extend({ name: 'azure-ad-oauth2', baseUrl: computed(function() { return 'https://login.windows.net/' + this.get('tennantId') + '/oauth2/authorize'; }), tennantId: configurable('tennantId', 'common'), // additional url params that this provider requires requiredUrlParams: ['api-version', 'client_id'], optionalUrlParams: ['scope', 'nonce', 'response_mode'], responseMode: configurable('responseMode', null), responseParams: computed(function () { return [ this.get('responseType'), 'state' ]; }), apiVersion: '1.0', responseType: configurable('responseType', 'code'), redirectUri: configurable('redirectUri', function azureRedirectUri(){ // A hack that allows redirectUri to be configurable // but default to the superclass return this._super(); }) }); export default AzureAdOauth2;
require('../spec_helper'); import {itPropagatesAttributes} from '../support/shared_examples'; import {mergeProps} from '../../../src/pivotal-ui-react/helpers/helpers'; describe('lists', function() { const UnorderedList = require('../../../src/pivotal-ui-react/lists/lists').UnorderedList; const OrderedList = require('../../../src/pivotal-ui-react/lists/lists').OrderedList; const ListItem = require('../../../src/pivotal-ui-react/lists/lists').ListItem; const BreadcrumbList = require('../../../src/pivotal-ui-react/lists/lists').BreadcrumbList; const StepList = require('../../../src/pivotal-ui-react/lists/lists').StepList; const GroupList = require('../../../src/pivotal-ui-react/lists/lists').GroupList; const GroupListInverse = require('../../../src/pivotal-ui-react/lists/lists').GroupListInverse; const InlineList = require('../../../src/pivotal-ui-react/lists/lists').InlineList; function itRenders(Element, identifier, props = {}) { const testProps = { className: 'test-class', id: 'test-id', style: { opacity: '0.75' } }; beforeEach(function() { React.render( <Element {...mergeProps(props, testProps)}> <ListItem>A</ListItem> <ListItem>B</ListItem> </Element>, root); }); afterEach(function() { React.unmountComponentAtNode(root); }); itPropagatesAttributes(identifier, testProps); it('renders', function() { expect('#root li').toHaveLength(2); }); } describe('UnorderedList', function() { itRenders(UnorderedList, '#root ul'); it('adds list-unordered class', function() { expect('#root ul').toHaveClass('list-unordered'); }); }); describe('OrderedList', function() { itRenders(OrderedList, '#root ol'); }); describe('Checked List', function(){ itRenders(UnorderedList, '#root ul', {'checked': true}); it('adds list-checked class', function() { expect('#root ul').toHaveClass('list-checked'); }); }); describe('Unstyled List', function(){ itRenders(UnorderedList, '#root ul', {'unstyled': true}); it('adds the list-unstyled class', function() { expect('#root ul').toHaveClass('list-unstyled'); }); }); describe('BreadcrumbList', function(){ itRenders(BreadcrumbList, '#root ul'); it('adds the list-breadcrumb class', function() { expect('#root ul').toHaveClass('list-breadcrumb'); }); }); describe('StepList', function(){ itRenders(StepList, '#root ol'); it('adds the list-steps class', function(){ expect('#root ol').toHaveClass('list-steps'); }); }); describe('GroupList', function(){ itRenders(GroupList, '#root ul'); it('adds the list-group class', function(){ expect('#root ul').toHaveClass('list-group'); expect('#root ul li:first').toHaveClass('list-group-item'); }); }); describe('GroupListInverse', function(){ itRenders(GroupListInverse, '#root ul'); it('adds the list-group-inverse class', function(){ expect('#root ul').toHaveClass('list-group-inverse'); expect('#root ul li:first').toHaveClass('list-group-item'); }); }); describe('InlineList without divider', function(){ itRenders(InlineList, '#root ul'); it('adds list-inline classes', function(){ expect('#root ul').toHaveClass('list-inline'); expect('#root ul').not.toHaveClass('list-inline-divider'); }); }); describe('List which is inline with divider', function(){ itRenders(InlineList, '#root ul', {'divider': true}); it('adds list-inline-divider classes', function(){ expect('#root ul').toHaveClass('list-inline-divider'); }); }); describe('List spacing', function(){ ['n', 's', 'm', 'l', 'xl'].forEach(function(size){ describe('vertical spacing', function() { itRenders(UnorderedList, '#root ul', {'spacing': size}); it('adds a' + size + 'vertical spacing class', function(){ expect('#root ul').toHaveClass('lv' + size); }); }); describe('horizontal spacing', function() { itRenders(InlineList, '#root ul', {'spacing': size}); it('adds a' + size + 'horizontal spacing class', function(){ expect('#root ul').toHaveClass('lh' + size); }); }); }); }); describe('ListItem', () => { const testItemProps = { className: 'test-item-class', id: 'test-item-id', style: { opacity: '0.5' } }; beforeEach(function() { React.render( <ul> <ListItem {...testItemProps}>A</ListItem> </ul>, root ); }); itPropagatesAttributes('#root li:first', testItemProps); }); });
var path = require('path'); var webpack = require('webpack'); var AUTOPREFIXER_LOADER = 'autoprefixer-loader?{browsers:[' + '"Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", ' + '"Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6"]}'; module.exports = { devtool: 'source-map', entry: { subschema: './src/index.jsx' }, devServer: { contentBase: path.join(__dirname, ".build"), info: true, // --no-info option hot: true, inline: true, port: 8084 }, output: { path: path.join(__dirname, "dist"), filename: 'subschema.js', libraryTarget: 'umd', library: 'Subschema' }, externals: [{ 'react/addons': 'react', react: true }], stats: { colors: true, reasons: true }, module: { loaders: [ { test: /\.js(x)?$/, excludes: /node_modules/, //do this to prevent babel fromt tanslating everything. includes: [ '~/node_modules/react', '~/node_modules/react-router', '~/node_modules/react-bootstrap', '~/node_modules/subschema-builder' ], loaders: ['babel-loader?stage=0'] }, {test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000'}, {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/font-woff"}, {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=application/octet-stream"}, {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file"}, // {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&minetype=image/svg+xml"}, // Optionally extract less files // or any other compile-to-css language { test: /\.css$/, loader: 'style-loader!css-loader!' + AUTOPREFIXER_LOADER }, { test: /\.less$/, loader: 'style!css!less-loader' } ] }, /* resolve: { alias: { 'subschema': __dirname } },*/ plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') }), function () { this.plugin("done", function (stats) { stats = stats.toJson(); console.error(JSON.stringify({ assetsByChunkName: stats.assetsByChunkName })); }); } ] };
const path = require('path'); const webpack = require('webpack'); const Copy = require('copy-webpack-plugin'); const nodeEnv = process.env.NODE_ENV || 'development'; const isProd = nodeEnv === 'production'; module.exports = { resolve: { extensions: ['.js', '.jsx'] }, devtool: isProd ? 'hidden-source-map' : 'cheap-module-source-map', entry: './lib/index.js', output: { path: path.join(__dirname, 'app', 'renderer'), filename: 'bundle.js' }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json/, loader: 'json-loader' }, // for xterm.js { test: /\.css$/, loader: 'style-loader!css-loader' } ] }, plugins: [ new webpack.IgnorePlugin(/.*\.js.map$/i), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(nodeEnv) } }), new Copy([ { from: './assets', to: './assets' } ]) ], target: 'electron' };
/* * demi * https://github.com/enytc/demi * * Copyright (c) 2014 EnyTC Corporation * Licensed under the BSD license. */ 'use strict'; module.exports = { /* * GET /routes */ /* * GET /routes/index */ index: { method: 'GET', fn: function (req, res) { res.jsonp(200, { message: 'Request received successfully!', method: req.method }); } }, /* * POST /routes */ post: { method: 'POST', fn: function (req, res) { res.jsonp(200, { message: 'Request received successfully!', method: req.method }); } }, /* * PUT /routes */ put: { method: 'PUT', fn: function (req, res) { res.jsonp(200, { message: 'Request received successfully!', method: req.method }); } }, /* * DELETE /routes */ delete: { method: 'DELETE', fn: function (req, res) { res.jsonp(200, { message: 'Request received successfully!', method: req.method }); } } };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _jsxRuntime = require("../../lib/jsxRuntime"); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _classNames2 = require("../../lib/classNames"); var _ConfigProviderContext = require("../ConfigProvider/ConfigProviderContext"); var _Tappable = _interopRequireDefault(require("../Tappable/Tappable")); var _Title = _interopRequireDefault(require("../Typography/Title/Title")); var _Text = _interopRequireDefault(require("../Typography/Text/Text")); var _Subhead = _interopRequireDefault(require("../Typography/Subhead/Subhead")); var _Caption = _interopRequireDefault(require("../Typography/Caption/Caption")); var _usePlatform = require("../../hooks/usePlatform"); var _withAdaptivity = require("../../hoc/withAdaptivity"); var _platform = require("../../lib/platform"); var _Spinner = _interopRequireDefault(require("../Spinner/Spinner")); var _Headline = _interopRequireDefault(require("../Typography/Headline/Headline")); var _excluded = ["size", "sizeY", "platform"], _excluded2 = ["size", "mode", "appearance", "stretched", "align", "children", "before", "after", "getRootRef", "sizeY", "Component", "loading", "onClick"]; var ButtonTypography = function ButtonTypography(props) { var size = props.size, sizeY = props.sizeY, platform = props.platform, restProps = (0, _objectWithoutProperties2.default)(props, _excluded); var isCompact = sizeY === _withAdaptivity.SizeType.COMPACT; switch (size) { case "l": if (isCompact) { return (0, _jsxRuntime.createScopedElement)(_Text.default, (0, _extends2.default)({ weight: "medium" }, restProps)); } if (platform === _platform.ANDROID) { return (0, _jsxRuntime.createScopedElement)(_Headline.default, (0, _extends2.default)({ weight: "medium" }, restProps)); } return (0, _jsxRuntime.createScopedElement)(_Title.default, (0, _extends2.default)({ level: "3", weight: "2" }, restProps)); case "m": if (isCompact) { return (0, _jsxRuntime.createScopedElement)(_Subhead.default, (0, _extends2.default)({ weight: platform === _platform.VKCOM ? "regular" : "medium" }, restProps)); } return (0, _jsxRuntime.createScopedElement)(_Text.default, (0, _extends2.default)({ weight: "medium" }, restProps)); case "s": default: if (platform === _platform.IOS) { return (0, _jsxRuntime.createScopedElement)(_Subhead.default, (0, _extends2.default)({ weight: "medium" }, restProps)); } if (platform === _platform.VKCOM) { return (0, _jsxRuntime.createScopedElement)(_Caption.default, (0, _extends2.default)({ level: "1", weight: "regular" }, restProps)); } if (isCompact) { return (0, _jsxRuntime.createScopedElement)(_Caption.default, (0, _extends2.default)({ level: "1", weight: "medium" }, restProps)); } return (0, _jsxRuntime.createScopedElement)(_Subhead.default, (0, _extends2.default)({ weight: "medium" }, restProps)); } }; function resolveButtonAppearance(appearance, mode) { var resolvedAppearance = appearance; var resolvedMode = mode; if (appearance === undefined) { switch (mode) { case "tertiary": case "secondary": case "primary": case "outline": resolvedAppearance = "accent"; break; case "commerce": resolvedMode = "primary"; resolvedAppearance = "positive"; break; case "destructive": resolvedMode = "primary"; resolvedAppearance = "negative"; break; case "overlay_primary": resolvedMode = "primary"; resolvedAppearance = "overlay"; break; case "overlay_secondary": resolvedMode = "secondary"; resolvedAppearance = "overlay"; break; case "overlay_outline": resolvedMode = "outline"; resolvedAppearance = "overlay"; break; } } return { resolvedAppearance: resolvedAppearance, resolvedMode: resolvedMode }; } var Button = function Button(props) { var _classNames; var platform = (0, _usePlatform.usePlatform)(); var size = props.size, mode = props.mode, appearance = props.appearance, stretched = props.stretched, align = props.align, children = props.children, before = props.before, after = props.after, getRootRef = props.getRootRef, sizeY = props.sizeY, _props$Component = props.Component, Component = _props$Component === void 0 ? "button" : _props$Component, loading = props.loading, onClick = props.onClick, restProps = (0, _objectWithoutProperties2.default)(props, _excluded2); var hasIcons = Boolean(before || after); var _resolveButtonAppeara = resolveButtonAppearance(appearance, mode), resolvedMode = _resolveButtonAppeara.resolvedMode, resolvedAppearance = _resolveButtonAppeara.resolvedAppearance; var hasNewTokens = React.useContext(_ConfigProviderContext.ConfigProviderContext).hasNewTokens; return (0, _jsxRuntime.createScopedElement)(_Tappable.default, (0, _extends2.default)({}, restProps, { Component: restProps.href ? "a" : Component, onClick: loading ? undefined : onClick, focusVisibleMode: "outside", vkuiClass: (0, _classNames2.classNames)("Button", "Button--sz-".concat(size), "Button--lvl-".concat(resolvedMode), "Button--clr-".concat(resolvedAppearance), "Button--aln-".concat(align), "Button--sizeY-".concat(sizeY), (_classNames = {}, (0, _defineProperty2.default)(_classNames, "Button--stretched", stretched), (0, _defineProperty2.default)(_classNames, "Button--with-icon", hasIcons), (0, _defineProperty2.default)(_classNames, "Button--singleIcon", Boolean(!children && !after && before || !children && after && !before)), _classNames)), getRootRef: getRootRef, hoverMode: hasNewTokens ? "Button--hover" : "background", activeMode: hasNewTokens ? "Button--active" : "opacity" }), loading && (0, _jsxRuntime.createScopedElement)(_Spinner.default, { size: "small", vkuiClass: "Button__spinner" }), (0, _jsxRuntime.createScopedElement)("span", { vkuiClass: "Button__in" }, before && (0, _jsxRuntime.createScopedElement)("span", { vkuiClass: "Button__before" }, before), children && (0, _jsxRuntime.createScopedElement)(ButtonTypography, { size: size, sizeY: sizeY, platform: platform, vkuiClass: "Button__content", Component: "span" }, children), after && (0, _jsxRuntime.createScopedElement)("span", { vkuiClass: "Button__after" }, after))); }; Button.defaultProps = { mode: "primary", align: "center", size: "s", stretched: false, stopPropagation: true }; // eslint-disable-next-line import/no-default-export var _default = (0, _withAdaptivity.withAdaptivity)(Button, { sizeY: true }); exports.default = _default; //# sourceMappingURL=Button.js.map
import { _ as __vue_normalize__, r as registerComponent, u as use } from './chunk-cca88db8.js'; var script = { name: 'BCollapse', // deprecated, to replace with default 'value' in the next breaking change model: { prop: 'open', event: 'update:open' }, props: { open: { type: Boolean, default: true }, animation: { type: String, default: 'fade' }, ariaId: { type: String, default: '' }, position: { type: String, default: 'is-top', validator: function validator(value) { return ['is-top', 'is-bottom'].indexOf(value) > -1; } } }, data: function data() { return { isOpen: this.open }; }, watch: { open: function open(value) { this.isOpen = value; } }, methods: { /** * Toggle and emit events */ toggle: function toggle() { this.isOpen = !this.isOpen; this.$emit('update:open', this.isOpen); this.$emit(this.isOpen ? 'open' : 'close'); } }, render: function render(createElement) { var trigger = createElement('div', { staticClass: 'collapse-trigger', on: { click: this.toggle } }, this.$scopedSlots.trigger ? [this.$scopedSlots.trigger({ open: this.isOpen })] : [this.$slots.trigger]); var content = createElement('transition', { props: { name: this.animation } }, [createElement('div', { staticClass: 'collapse-content', attrs: { 'id': this.ariaId }, directives: [{ name: 'show', value: this.isOpen }] }, this.$slots.default)]); return createElement('div', { staticClass: 'collapse' }, this.position === 'is-top' ? [trigger, content] : [content, trigger]); } }; /* script */ const __vue_script__ = script; /* template */ /* style */ const __vue_inject_styles__ = undefined; /* scoped */ const __vue_scope_id__ = undefined; /* module identifier */ const __vue_module_identifier__ = undefined; /* functional template */ const __vue_is_functional_template__ = undefined; /* style inject */ /* style inject SSR */ var Collapse = __vue_normalize__( {}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined ); var Plugin = { install: function install(Vue) { registerComponent(Vue, Collapse); } }; use(Plugin); export default Plugin; export { Collapse as BCollapse };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import { elementTypeAcceptingRef } from '@material-ui/utils'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import ownerDocument from '../utils/ownerDocument'; import useEventCallback from '../utils/useEventCallback'; import { duration } from '../styles/transitions'; import useTheme from '../styles/useTheme'; import { getTransitionProps } from '../transitions/utils'; import NoSsr from '../NoSsr'; import SwipeArea from './SwipeArea'; // This value is closed to what browsers are using internally to // trigger a native scroll. var UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. var nodeThatClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeThatClaimedTheSwipe = null; } function calculateCurrentX(anchor, touches) { return anchor === 'right' ? document.body.offsetWidth - touches[0].pageX : touches[0].pageX; } function calculateCurrentY(anchor, touches) { return anchor === 'bottom' ? window.innerHeight - touches[0].clientY : touches[0].clientY; } function getMaxTranslate(horizontalSwipe, paperInstance) { return horizontalSwipe ? paperInstance.clientWidth : paperInstance.clientHeight; } function getTranslate(currentTranslate, startLocation, open, maxTranslate) { return Math.min(Math.max(open ? startLocation - currentTranslate : maxTranslate + startLocation - currentTranslate, 0), maxTranslate); } function getDomTreeShapes(element, rootNode) { // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L129 var domTreeShapes = []; while (element && element !== rootNode) { var style = window.getComputedStyle(element); if ( // Ignore the scroll children if the element is absolute positioned. style.getPropertyValue('position') === 'absolute' || // Ignore the scroll children if the element has an overflowX hidden style.getPropertyValue('overflow-x') === 'hidden') { domTreeShapes = []; } else if (element.clientWidth > 0 && element.scrollWidth > element.clientWidth || element.clientHeight > 0 && element.scrollHeight > element.clientHeight) { // Ignore the nodes that have no width. // Keep elements with a scroll domTreeShapes.push(element); } element = element.parentElement; } return domTreeShapes; } function findNativeHandler(_ref) { var domTreeShapes = _ref.domTreeShapes, start = _ref.start, current = _ref.current, anchor = _ref.anchor; // Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L175 var axisProperties = { scrollPosition: { x: 'scrollLeft', y: 'scrollTop' }, scrollLength: { x: 'scrollWidth', y: 'scrollHeight' }, clientLength: { x: 'clientWidth', y: 'clientHeight' } }; return domTreeShapes.some(function (shape) { // Determine if we are going backward or forward. var goingForward = current >= start; if (anchor === 'top' || anchor === 'left') { goingForward = !goingForward; } var axis = anchor === 'left' || anchor === 'right' ? 'x' : 'y'; var scrollPosition = shape[axisProperties.scrollPosition[axis]]; var areNotAtStart = scrollPosition > 0; var areNotAtEnd = scrollPosition + shape[axisProperties.clientLength[axis]] < shape[axisProperties.scrollLength[axis]]; if (goingForward && areNotAtEnd || !goingForward && areNotAtStart) { return shape; } return null; }); } var disableSwipeToOpenDefault = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent); var transitionDurationDefault = { enter: duration.enteringScreen, exit: duration.leavingScreen }; var useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; var SwipeableDrawer = React.forwardRef(function SwipeableDrawer(props, ref) { var _props$anchor = props.anchor, anchor = _props$anchor === void 0 ? 'left' : _props$anchor, _props$disableBackdro = props.disableBackdropTransition, disableBackdropTransition = _props$disableBackdro === void 0 ? false : _props$disableBackdro, _props$disableDiscove = props.disableDiscovery, disableDiscovery = _props$disableDiscove === void 0 ? false : _props$disableDiscove, _props$disableSwipeTo = props.disableSwipeToOpen, disableSwipeToOpen = _props$disableSwipeTo === void 0 ? disableSwipeToOpenDefault : _props$disableSwipeTo, hideBackdrop = props.hideBackdrop, _props$hysteresis = props.hysteresis, hysteresis = _props$hysteresis === void 0 ? 0.52 : _props$hysteresis, _props$minFlingVeloci = props.minFlingVelocity, minFlingVelocity = _props$minFlingVeloci === void 0 ? 450 : _props$minFlingVeloci, _props$ModalProps = props.ModalProps; _props$ModalProps = _props$ModalProps === void 0 ? {} : _props$ModalProps; var BackdropProps = _props$ModalProps.BackdropProps, ModalPropsProp = _objectWithoutProperties(_props$ModalProps, ["BackdropProps"]), onClose = props.onClose, onOpen = props.onOpen, open = props.open, _props$PaperProps = props.PaperProps, PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps, SwipeAreaProps = props.SwipeAreaProps, _props$swipeAreaWidth = props.swipeAreaWidth, swipeAreaWidth = _props$swipeAreaWidth === void 0 ? 20 : _props$swipeAreaWidth, _props$transitionDura = props.transitionDuration, transitionDuration = _props$transitionDura === void 0 ? transitionDurationDefault : _props$transitionDura, _props$variant = props.variant, variant = _props$variant === void 0 ? 'temporary' : _props$variant, other = _objectWithoutProperties(props, ["anchor", "disableBackdropTransition", "disableDiscovery", "disableSwipeToOpen", "hideBackdrop", "hysteresis", "minFlingVelocity", "ModalProps", "onClose", "onOpen", "open", "PaperProps", "SwipeAreaProps", "swipeAreaWidth", "transitionDuration", "variant"]); var theme = useTheme(); var _React$useState = React.useState(false), maybeSwiping = _React$useState[0], setMaybeSwiping = _React$useState[1]; var swipeInstance = React.useRef({ isSwiping: null }); var swipeAreaRef = React.useRef(); var backdropRef = React.useRef(); var paperRef = React.useRef(); var touchDetected = React.useRef(false); // Ref for transition duration based on / to match swipe speed var calculatedDurationRef = React.useRef(); // Use a ref so the open value used is always up to date inside useCallback. useEnhancedEffect(function () { calculatedDurationRef.current = null; }, [open]); var setPosition = React.useCallback(function (translate) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$mode = options.mode, mode = _options$mode === void 0 ? null : _options$mode, _options$changeTransi = options.changeTransition, changeTransition = _options$changeTransi === void 0 ? true : _options$changeTransi; var anchorRtl = getAnchor(theme, anchor); var rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchorRtl) !== -1 ? 1 : -1; var horizontalSwipe = isHorizontal(anchor); var transform = horizontalSwipe ? "translate(".concat(rtlTranslateMultiplier * translate, "px, 0)") : "translate(0, ".concat(rtlTranslateMultiplier * translate, "px)"); var drawerStyle = paperRef.current.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; var transition = ''; if (mode) { transition = theme.transitions.create('all', getTransitionProps({ timeout: transitionDuration }, { mode: mode })); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!disableBackdropTransition && !hideBackdrop) { var backdropStyle = backdropRef.current.style; backdropStyle.opacity = 1 - translate / getMaxTranslate(horizontalSwipe, paperRef.current); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } }, [anchor, disableBackdropTransition, hideBackdrop, theme, transitionDuration]); var handleBodyTouchEnd = useEventCallback(function (event) { if (!touchDetected.current) { return; } nodeThatClaimedTheSwipe = null; touchDetected.current = false; setMaybeSwiping(false); // The swipe wasn't started. if (!swipeInstance.current.isSwiping) { swipeInstance.current.isSwiping = null; return; } swipeInstance.current.isSwiping = null; var anchorRtl = getAnchor(theme, anchor); var horizontal = isHorizontal(anchor); var current; if (horizontal) { current = calculateCurrentX(anchorRtl, event.changedTouches); } else { current = calculateCurrentY(anchorRtl, event.changedTouches); } var startLocation = horizontal ? swipeInstance.current.startX : swipeInstance.current.startY; var maxTranslate = getMaxTranslate(horizontal, paperRef.current); var currentTranslate = getTranslate(current, startLocation, open, maxTranslate); var translateRatio = currentTranslate / maxTranslate; if (Math.abs(swipeInstance.current.velocity) > minFlingVelocity) { // Calculate transition duration to match swipe speed calculatedDurationRef.current = Math.abs((maxTranslate - currentTranslate) / swipeInstance.current.velocity) * 1000; } if (open) { if (swipeInstance.current.velocity > minFlingVelocity || translateRatio > hysteresis) { onClose(); } else { // Reset the position, the swipe was aborted. setPosition(0, { mode: 'exit' }); } return; } if (swipeInstance.current.velocity < -minFlingVelocity || 1 - translateRatio > hysteresis) { onOpen(); } else { // Reset the position, the swipe was aborted. setPosition(getMaxTranslate(horizontal, paperRef.current), { mode: 'enter' }); } }); var handleBodyTouchMove = useEventCallback(function (event) { // the ref may be null when a parent component updates while swiping if (!paperRef.current || !touchDetected.current) { return; } // We are not supposed to handle this touch move because the swipe was started in a scrollable container in the drawer if (nodeThatClaimedTheSwipe != null && nodeThatClaimedTheSwipe !== swipeInstance.current) { return; } var anchorRtl = getAnchor(theme, anchor); var horizontalSwipe = isHorizontal(anchor); var currentX = calculateCurrentX(anchorRtl, event.touches); var currentY = calculateCurrentY(anchorRtl, event.touches); if (open && paperRef.current.contains(event.target) && nodeThatClaimedTheSwipe == null) { var domTreeShapes = getDomTreeShapes(event.target, paperRef.current); var nativeHandler = findNativeHandler({ domTreeShapes: domTreeShapes, start: horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY, current: horizontalSwipe ? currentX : currentY, anchor: anchor }); if (nativeHandler) { nodeThatClaimedTheSwipe = nativeHandler; return; } nodeThatClaimedTheSwipe = swipeInstance.current; } // We don't know yet. if (swipeInstance.current.isSwiping == null) { var dx = Math.abs(currentX - swipeInstance.current.startX); var dy = Math.abs(currentY - swipeInstance.current.startY); // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { if (event.cancelable) { event.preventDefault(); } } var definitelySwiping = horizontalSwipe ? dx > dy && dx > UNCERTAINTY_THRESHOLD : dy > dx && dy > UNCERTAINTY_THRESHOLD; if (definitelySwiping === true || (horizontalSwipe ? dy > UNCERTAINTY_THRESHOLD : dx > UNCERTAINTY_THRESHOLD)) { swipeInstance.current.isSwiping = definitelySwiping; if (!definitelySwiping) { handleBodyTouchEnd(event); return; } // Shift the starting point. swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!disableDiscovery && !open) { if (horizontalSwipe) { swipeInstance.current.startX -= swipeAreaWidth; } else { swipeInstance.current.startY -= swipeAreaWidth; } } } } if (!swipeInstance.current.isSwiping) { return; } var maxTranslate = getMaxTranslate(horizontalSwipe, paperRef.current); var startLocation = horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY; if (open && !swipeInstance.current.paperHit) { startLocation = Math.min(startLocation, maxTranslate); } var translate = getTranslate(horizontalSwipe ? currentX : currentY, startLocation, open, maxTranslate); if (open) { if (!swipeInstance.current.paperHit) { var paperHit = horizontalSwipe ? currentX < maxTranslate : currentY < maxTranslate; if (paperHit) { swipeInstance.current.paperHit = true; swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; } else { return; } } else if (translate === 0) { swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; } } if (swipeInstance.current.lastTranslate === null) { swipeInstance.current.lastTranslate = translate; swipeInstance.current.lastTime = performance.now() + 1; } var velocity = (translate - swipeInstance.current.lastTranslate) / (performance.now() - swipeInstance.current.lastTime) * 1e3; // Low Pass filter. swipeInstance.current.velocity = swipeInstance.current.velocity * 0.4 + velocity * 0.6; swipeInstance.current.lastTranslate = translate; swipeInstance.current.lastTime = performance.now(); // We are swiping, let's prevent the scroll event on iOS. if (event.cancelable) { event.preventDefault(); } setPosition(translate); }); var handleBodyTouchStart = useEventCallback(function (event) { // We are not supposed to handle this touch move. // Example of use case: ignore the event if there is a Slider. if (event.defaultPrevented) { return; } // We can only have one node at the time claiming ownership for handling the swipe. if (event.muiHandled) { return; } // At least one element clogs the drawer interaction zone. if (open && !backdropRef.current.contains(event.target) && !paperRef.current.contains(event.target)) { return; } var anchorRtl = getAnchor(theme, anchor); var horizontalSwipe = isHorizontal(anchor); var currentX = calculateCurrentX(anchorRtl, event.touches); var currentY = calculateCurrentY(anchorRtl, event.touches); if (!open) { if (disableSwipeToOpen || event.target !== swipeAreaRef.current) { return; } if (horizontalSwipe) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } event.muiHandled = true; nodeThatClaimedTheSwipe = null; swipeInstance.current.startX = currentX; swipeInstance.current.startY = currentY; setMaybeSwiping(true); if (!open && paperRef.current) { // The ref may be null when a parent component updates while swiping. setPosition(getMaxTranslate(horizontalSwipe, paperRef.current) + (disableDiscovery ? 20 : -swipeAreaWidth), { changeTransition: false }); } swipeInstance.current.velocity = 0; swipeInstance.current.lastTime = null; swipeInstance.current.lastTranslate = null; swipeInstance.current.paperHit = false; touchDetected.current = true; }); React.useEffect(function () { if (variant === 'temporary') { var doc = ownerDocument(paperRef.current); doc.addEventListener('touchstart', handleBodyTouchStart); doc.addEventListener('touchmove', handleBodyTouchMove, { passive: false }); doc.addEventListener('touchend', handleBodyTouchEnd); return function () { doc.removeEventListener('touchstart', handleBodyTouchStart); doc.removeEventListener('touchmove', handleBodyTouchMove, { passive: false }); doc.removeEventListener('touchend', handleBodyTouchEnd); }; } return undefined; }, [variant, handleBodyTouchStart, handleBodyTouchMove, handleBodyTouchEnd]); React.useEffect(function () { return function () { // We need to release the lock. if (nodeThatClaimedTheSwipe === swipeInstance.current) { nodeThatClaimedTheSwipe = null; } }; }, []); React.useEffect(function () { if (!open) { setMaybeSwiping(false); } }, [open]); var handleBackdropRef = React.useCallback(function (instance) { // #StrictMode ready backdropRef.current = ReactDOM.findDOMNode(instance); }, []); var handlePaperRef = React.useCallback(function (instance) { // #StrictMode ready paperRef.current = ReactDOM.findDOMNode(instance); }, []); return React.createElement(React.Fragment, null, React.createElement(Drawer, _extends({ open: variant === 'temporary' && maybeSwiping ? true : open, variant: variant, ModalProps: _extends({ BackdropProps: _extends({}, BackdropProps, { ref: handleBackdropRef }) }, ModalPropsProp), PaperProps: _extends({}, PaperProps, { style: _extends({ pointerEvents: variant === 'temporary' && !open ? 'none' : '' }, PaperProps.style), ref: handlePaperRef }), anchor: anchor, transitionDuration: calculatedDurationRef.current || transitionDuration, onClose: onClose, ref: ref }, other)), !disableSwipeToOpen && variant === 'temporary' && React.createElement(NoSsr, null, React.createElement(SwipeArea, _extends({ anchor: anchor, ref: swipeAreaRef, width: swipeAreaWidth }, SwipeAreaProps)))); }); process.env.NODE_ENV !== "production" ? SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * The content of the component. */ children: PropTypes.node, /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers * navigation actions. Swipe to open is disabled on iOS browsers by default. */ disableSwipeToOpen: PropTypes.bool, /** * @ignore */ hideBackdrop: PropTypes.bool, /** * Affects how far the drawer must be opened/closed to change his state. * Specified as percent (0-1) of the width of the drawer */ hysteresis: PropTypes.number, /** * Defines, from which (average) velocity on, the swipe is * defined as complete although hysteresis isn't reached. * Good threshold is between 250 - 1000 px/s */ minFlingVelocity: PropTypes.number, /** * @ignore */ ModalProps: PropTypes.shape({ BackdropProps: PropTypes.shape({ component: elementTypeAcceptingRef }) }), /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback. */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.shape({ component: elementTypeAcceptingRef, style: PropTypes.object }), /** * Props applied to the swipe area element. */ SwipeAreaProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']) } : void 0; export default SwipeableDrawer;
'use strict' var path = require('path') , urltils = require('./util/urltils') , logger = require('./logger').child({component : 'error_tracer'}) , NAMES = require('./metrics/names') /* * * CONSTANTS * */ var MAX_ERRORS = 20 /** * Given either or both of a transaction and an exception, generate an error * trace in the JSON format expected by the collector. Since this will be * used by both the HTTP instrumentation, which uses HTTP status codes to * determine whether a transaction is in error, and the domain-based error * handler, which traps actual instances of Error, try to set sensible * defaults for everything. * * @param {Transaction} transaction The agent transaction, presumably * coming out of the instrumentation. * @param {Error} exception Something trapped by an error listener. * @param {object} customParameters Any custom parameters associated with * the request (optional). */ function createError(transaction, exception, customParameters, config) { // the collector throws this out, so don't bother setting it var timestamp = 0 , name = 'WebTransaction/Uri/*' , message = '' , type = 'Error' , params = { userAttributes : {}, agentAttributes : {}, intrinsics : {}, } if (transaction && transaction.name) name = transaction.name // NB: anything throwing / emitting strings is buggy, but it happens if (typeof exception === 'string') { message = exception } else if (exception && exception.message) { message = exception.message // only care about extracting the type if it's Error-like. if (exception && exception.constructor && exception.constructor.name) { type = exception.constructor.name } } else if (transaction && transaction.statusCode && urltils.isError(config, transaction.statusCode)) { message = 'HttpError ' + transaction.statusCode } if (transaction && transaction.url) { var url = transaction.url , statusCode = transaction.statusCode || 500 /* We need a name for this transaction, but since error-tracing can happen * in the middle of the request, and it's possible that the user will * recover from the error, name the transaction now, preserving the * necessary state to maintain any user-provided naming information. */ if (!transaction.name) { var partialName = transaction.partialName transaction.setName(url, statusCode) transaction.partialName = partialName } var custom = transaction.getTrace().custom Object.keys(custom).forEach(function (param) { params.userAttributes[param] = custom[param] }) name = transaction.name params.request_uri = url if (config.capture_params) { var reqParams = transaction.getTrace().parameters var urlParams = urltils.parseParameters(url) // clear out ignored params config.ignored_params.forEach(function cb_forEach(k) { // polymorphic hidden classes aren't an issue with data bags delete urlParams[k] delete reqParams[k] }) Object.keys(urlParams).forEach(function (param) { params.agentAttributes[param] = urlParams[param] }) Object.keys(reqParams).forEach(function (param) { params.agentAttributes[param] = reqParams[param] }) } } // this needs to be done *after* pulling custom params from transaction var isHighSec = config.high_security if (customParameters && !isHighSec) { var ignored = [] if (transaction) ignored = config.ignored_params Object.keys(customParameters).forEach(function cb_forEach(param) { if (ignored.indexOf(param) === -1) params.userAttributes[param] = customParameters[param] }) } var stack = exception && exception.stack // FIXME: doing this work should not be the agent's responsibility if (stack) params.stack_trace = ('' + stack).split(/[\n\r]/g) return [timestamp, name, message, type, params] } /** * This is a fairly simple-minded tracer that converts errored-out HTTP * transactions and JS Errors into the error traces expected by the collector. * * It also acts as a collector for the traced errors. */ function ErrorTracer(config) { this.config = config this.errorCount = 0 this.errors = [] this.seen = [] } /** * Every finished transaction goes through this handler, so do as * little as possible. */ ErrorTracer.prototype.onTransactionFinished = function onTransactionFinished(transaction, metrics) { if (!transaction) throw new Error("Error collector got a blank transaction.") if (!metrics) throw new Error("Error collector requires metrics to count errors.") if (urltils.isError(this.config, transaction.statusCode) || (transaction.statusCode < 1 && transaction.exceptions.length > 0)) { if (transaction.exceptions.length > 0) { transaction.exceptions.forEach(function cb_forEach(exception) { this.add(transaction, exception) }, this) } else { this.add(transaction) } var count = metrics.getOrCreateMetric(NAMES.ERRORS.PREFIX + transaction.name) count.incrementCallCount(1) } } /** * This function uses an array of seen exceptions to ensure errors don't get * double-counted. It can also be used as an unofficial means of marking that * user errors shouldn't be traced. * * For an error to be traced, at least one of the transaction or the error * must be present. * * NOTE: this interface is unofficial and may change in future. * * @param {Transaction} transaction Transaction associated with the error * (optional). * @param {Error} exception The error to be traced (optional). * @param {object} customParameters Any custom parameters associated with * the request (optional). */ ErrorTracer.prototype.add = function add(transaction, exception, customParameters) { if (!exception) { if (!transaction) return if (!transaction.statusCode) return if (transaction.error) return } else { if (this.seen.indexOf(exception) !== -1) return if (typeof exception !== 'string' && !exception.message && !exception.stack) { return } } this.errorCount++ // allow enabling & disabling the error tracer at runtime if (!this.config.collect_errors || !this.config.error_collector || !this.config.error_collector.enabled) return if (exception) { logger.trace(exception, "Got exception to trace:") // put the error on the transaction to show we've already traced it if (transaction) transaction.error = exception this.seen.push(exception) } if (this.errors.length < MAX_ERRORS) { var error = createError(transaction, exception, customParameters, this.config) logger.debug({error : error}, "Error to be sent to collector:") this.errors.push(error) } else { logger.debug("Already have %d errors to send to collector, not keeping.", MAX_ERRORS) } } /** * If the connection to the collector fails, retain as many as will fit without * overflowing the current error list. * * @param array errors Previously harvested errors. */ ErrorTracer.prototype.merge = function merge(errors) { if (!errors) return var len = Math.min(errors.length, MAX_ERRORS - this.errors.length) logger.warn("Merging %s (of %s) errors for next delivery.", len, errors.length) for (var i = 0; i < len; i++) this.errors.push(errors[i]) } module.exports = ErrorTracer
import { Observable } from 'rxjs/Observable'; import 'firebase/database'; import * as utils from './utils'; export class FirebaseListObservable extends Observable { constructor($ref, subscribe) { super(subscribe); this.$ref = $ref; } lift(operator) { const observable = new FirebaseListObservable(this.$ref); observable.source = this; observable.operator = operator; observable.$ref = this.$ref; return observable; } push(val) { if (!this.$ref) { throw new Error('No ref specified for this Observable!'); } return this.$ref.ref.push(val); } set(item, value) { return this._checkOperationCases(item, { stringCase: () => this.$ref.ref.child(item).set(value), firebaseCase: () => item.set(value), snapshotCase: () => item.ref.set(value), unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).set(value) }); } update(item, value) { return this._checkOperationCases(item, { stringCase: () => this.$ref.ref.child(item).update(value), firebaseCase: () => item.update(value), snapshotCase: () => item.ref.update(value), unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).update(value) }); } remove(item) { if (!item) { return this.$ref.ref.remove(); } return this._checkOperationCases(item, { stringCase: () => this.$ref.ref.child(item).remove(), firebaseCase: () => item.remove(), snapshotCase: () => item.ref.remove(), unwrappedSnapshotCase: () => this.$ref.ref.child(item.$key).remove() }); } _checkOperationCases(item, cases) { if (utils.isString(item)) { return cases.stringCase(); } else if (utils.isFirebaseRef(item)) { return cases.firebaseCase(); } else if (utils.isFirebaseDataSnapshot(item)) { return cases.snapshotCase(); } else if (utils.isAFUnwrappedSnapshot(item)) { return cases.unwrappedSnapshotCase(); } throw new Error(`Method requires a key, snapshot, reference, or unwrapped snapshot. Got: ${typeof item}`); } } //# sourceMappingURL=firebase_list_observable.js.map
KISSY.add(function(S,Cookie) { describe('cookie', function() { if (location.protocol === 'file:') { return; } describe('get', function() { document.cookie = '_ks_test_1=1'; document.cookie = '_ks_test_2='; document.cookie = '_ks_test_3='; it('should return the cookie value for the given name', function() { expect(Cookie.get('_ks_test_1')).toBe('1'); expect(Cookie.get('_ks_test_2')).toBe(''); expect(Cookie.get('_ks_test_3')).toBe(''); }); it('should return undefined for non-existing name', function() { expect(Cookie.get('_ks_test_none')).toBeUndefined(); expect(Cookie.get(true)).toBeUndefined(); expect(Cookie.get({})).toBeUndefined(); expect(Cookie.get(null)).toBeUndefined(); }); }); describe('set', function() { it('should set a cookie with a given name and value', function() { Cookie.set('_ks_test_11', 'xx'); expect(Cookie.get('_ks_test_11')).toBe('xx'); Cookie.set('_ks_test_12', 'xx', 0); expect(Cookie.get('_ks_test_12')).toBeUndefined(); Cookie.set('_ks_test_13', '1', new Date(2099, 1, 1), '', '/'); Cookie.set('_ks_test_13', '2', new Date(2099, 1, 1), '', '/'); expect(Cookie.get('_ks_test_13')).toBe('2'); Cookie.remove('_ks_test_14'); Cookie.set('_ks_test_14', '4', 1, document.domain, '/', true); expect(Cookie.get('_ks_test_14')).toBeUndefined(); }); }); describe('remove', function() { it('should remove a cookie from the machine', function() { Cookie.set('_ks_test_21', 'xx'); Cookie.remove('_ks_test_21'); expect(Cookie.get('_ks_test_21')).toBeUndefined(); Cookie.set('_ks_test_22', 'xx', new Date(2099, 1, 1), '', '/'); Cookie.remove('_ks_test_22', '', '/'); expect(Cookie.get('_ks_test_22')).toBeUndefined(); }); }); }); },{ requires:['cookie'] });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof2 = require('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _bluebird = require('bluebird'); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _fs = require('mz/fs'); var _fs2 = _interopRequireDefault(_fs); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _stringArgv = require('string-argv'); var _stringArgv2 = _interopRequireDefault(_stringArgv); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ProfileLoader = function () { function ProfileLoader(directory) { (0, _classCallCheck3.default)(this, ProfileLoader); this.directory = directory; } (0, _createClass3.default)(ProfileLoader, [{ key: 'getDefinitions', value: function () { var _ref = (0, _bluebird.coroutine)(function* () { var definitionsFilePath = _path2.default.join(this.directory, 'cucumber.js'); var exists = yield _fs2.default.exists(definitionsFilePath); if (!exists) { return {}; } var definitions = require(definitionsFilePath); if ((typeof definitions === 'undefined' ? 'undefined' : (0, _typeof3.default)(definitions)) !== 'object') { throw new Error(definitionsFilePath + ' does not export an object'); } return definitions; }); function getDefinitions() { return _ref.apply(this, arguments); } return getDefinitions; }() }, { key: 'getArgv', value: function () { var _ref2 = (0, _bluebird.coroutine)(function* (profiles) { var definitions = yield this.getDefinitions(); if (profiles.length === 0 && definitions['default']) { profiles = ['default']; } var argvs = profiles.map(function (profile) { if (!definitions[profile]) { throw new Error('Undefined profile: ' + profile); } return (0, _stringArgv2.default)(definitions[profile]); }); return _lodash2.default.flatten(argvs); }); function getArgv(_x) { return _ref2.apply(this, arguments); } return getArgv; }() }]); return ProfileLoader; }(); exports.default = ProfileLoader;
'use strict'; var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var config = require('../config'); module.exports = function (gulp) { gulp.task('test', ['lint'], function (cb) { gulp.src(['!' + config.paths.cliFile].concat(config.paths.lib)) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()) .on('finish', function () { gulp.src(config.paths.test) .pipe(mocha({reporter: 'spec'})) .pipe(istanbul.writeReports()) .pipe(istanbul.enforceThresholds({thresholds: {global: 100}})) .on('end', cb); }); }); };
import React, {Component, PropTypes} from 'react'; import RadioButton from '../RadioButton'; import warning from 'warning'; class RadioButtonGroup extends Component { static propTypes = { /** * Should be used to pass `RadioButton` components. */ children: PropTypes.node, /** * The CSS class name of the root element. */ className: PropTypes.string, /** * The `value` property of the radio button that will be * selected by default. This takes precedence over the `checked` property * of the `RadioButton` elements. */ defaultSelected: PropTypes.any, /** * Where the label will be placed for all child radio buttons. * This takes precedence over the `labelPosition` property of the * `RadioButton` elements. */ labelPosition: PropTypes.oneOf(['left', 'right']), /** * The name that will be applied to all child radio buttons. */ name: PropTypes.string.isRequired, /** * Callback function that is fired when a radio button has * been checked. * * @param {object} event `change` event targeting the selected * radio button. * @param {*} value The `value` of the selected radio button. */ onChange: PropTypes.func, /** * Override the inline-styles of the root element. */ style: PropTypes.object, /** * The `value` of the currently selected radio button. */ valueSelected: PropTypes.any, }; static defaultProps = { style: {}, }; static contextTypes = { muiTheme: PropTypes.object.isRequired, }; state = { numberCheckedRadioButtons: 0, selected: '', }; componentWillMount() { let cnt = 0; let selected = ''; const {valueSelected, defaultSelected} = this.props; if (valueSelected !== undefined) { selected = valueSelected; } else if (defaultSelected !== undefined) { selected = defaultSelected; } React.Children.forEach(this.props.children, (option) => { if (this.hasCheckAttribute(option)) cnt++; }, this); this.setState({ numberCheckedRadioButtons: cnt, selected, }); } componentWillReceiveProps(nextProps) { if (nextProps.hasOwnProperty('valueSelected')) { this.setState({ selected: nextProps.valueSelected, }); } } hasCheckAttribute(radioButton) { return radioButton.props.hasOwnProperty('checked') && radioButton.props.checked; } updateRadioButtons(newSelection) { if (this.state.numberCheckedRadioButtons === 0) { this.setState({selected: newSelection}); } else { warning(false, `Material-UI: Cannot select a different radio button while another radio button has the 'checked' property set to true.`); } } handleChange = (event, newSelection) => { this.updateRadioButtons(newSelection); // Successful update if (this.state.numberCheckedRadioButtons === 0) { if (this.props.onChange) this.props.onChange(event, newSelection); } }; getSelectedValue() { return this.state.selected; } setSelectedValue(newSelectionValue) { this.updateRadioButtons(newSelectionValue); } clearValue() { this.setSelectedValue(''); } render() { const {prepareStyles} = this.context.muiTheme; const options = React.Children.map(this.props.children, (option) => { const { name, // eslint-disable-line no-unused-vars value, // eslint-disable-line no-unused-vars label, // eslint-disable-line no-unused-vars onCheck, // eslint-disable-line no-unused-vars ...other } = option.props; return ( <RadioButton {...other} ref={option.props.value} name={this.props.name} key={option.props.value} value={option.props.value} label={option.props.label} labelPosition={this.props.labelPosition} onCheck={this.handleChange} checked={option.props.value === this.state.selected} /> ); }, this); return ( <div style={prepareStyles(Object.assign({}, this.props.style))} className={this.props.className} > {options} </div> ); } } export default RadioButtonGroup;
if(!dojo._hasResource["dojox.highlight.languages._all"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.highlight.languages._all"] = true; dojo.provide("dojox.highlight.languages._all"); /* groups of similar languages */ dojo.require("dojox.highlight.languages._static"); dojo.require("dojox.highlight.languages._dynamic"); dojo.require("dojox.highlight.languages._www"); }
var bunyan = require('bunyan'); var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); var config = { name: 'coregi', streams: [ { level: process.env.LOG_LEVEL || 'info', type: 'raw', stream: prettyStdOut }, { type: 'file', level:'info', path: 'coregi.log' } ], serializers: bunyan.stdSerializers }; module.exports = function() { return bunyan.createLogger(config); };
define([ "jquery", "underscore", "storage", "crel", "xregexp", "stacktrace", "FileSaver" ], function($, _, storage, crel, XRegExp, printStackTrace, saveAs) { var utils = {}; utils.msie = (function() { /** * IE 11 changed the format of the UserAgent string. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx */ var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10); if (isNaN(msie)) { msie = parseInt((/trident\/.*; rv:(\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10); } return msie; })(); utils.urlResolve = (function() { var urlParsingNode = document.createElement("a"); return function urlResolve(url) { var href = url; if (utils.msie) { // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; }; })(); // Faster than setTimeout (see http://dbaron.org/log/20100309-faster-timeouts) utils.defer = (function() { var timeouts = []; var messageName = "deferMsg"; window.addEventListener("message", function(evt) { if(evt.source == window && evt.data == messageName) { evt.stopPropagation(); if(timeouts.length > 0) { timeouts.shift()(); } } }, true); return function(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); }; })(); // Implements underscore debounce using our defer function utils.debounce = function(func, context) { var isExpected = false; function later() { isExpected = false; func.call(context); } return function() { if(isExpected === true) { return; } isExpected = true; utils.defer(later); }; }; // Generates a 24 char length random id var idAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; utils.id = function() { var result = []; for(var i = 0; i < 24; i++) { result.push(idAlphabet[Math.random() * idAlphabet.length | 0]); } return result.join(''); }; // Return a parameter from the URL utils.getURLParameter = function(name) { // Parameter can be either a search parameter (&name=...) or a hash fragment parameter (#!name=...) var regex = new RegExp("(?:\\?|\\#\\!|&)" + name + "=(.+?)(?:&|\\#|$)"); try { return decodeURIComponent(regex.exec(location.search + location.hash)[1]); } catch(e) { return undefined; } }; // Transform a selector into a jQuery object function jqElt(element) { if(_.isString(element) || !element.val) { return $(element); } return element; } // For input control function inputError(element, event) { if(event !== undefined) { element.stop(true, true).addClass("error").delay(3000).queue(function() { $(this).removeClass("error"); $(this).dequeue(); }); event.stopPropagation(); } } // Return input value utils.getInputValue = function(element) { element = jqElt(element); return element.val(); }; // Set input value utils.setInputValue = function(element, value) { element = jqElt(element); element.val(value); }; // Return input text value utils.getInputTextValue = function(element, event, validationRegex) { element = jqElt(element); var value = element.val(); if(value === undefined) { inputError(element, event); return undefined; } // trim value = utils.trim(value); if((value.length === 0) || (validationRegex !== undefined && !value.match(validationRegex))) { inputError(element, event); return undefined; } return value; }; // Return input number value function getInputNumValue(isFloat, element, event, min, max) { element = jqElt(element); var value = utils.getInputTextValue(element, event); if(value === undefined) { return undefined; } value = isFloat ? parseFloat(value) : parseInt(value, 10); if(isNaN(value) || (min !== undefined && value < min) || (max !== undefined && value > max)) { inputError(element, event); return undefined; } return value; } // Return input integer value utils.getInputIntValue = _.partial(getInputNumValue, false); // Return input float value utils.getInputFloatValue = _.partial(getInputNumValue, true); // Return input value and check that it's a valid RegExp utils.getInputRegExpValue = function(element, event) { element = jqElt(element); var value = utils.getInputTextValue(element, event); if(value === undefined) { return undefined; } try { new RegExp(value); } catch(e) { inputError(element, event); return undefined; } return value; }; // Return input value and check that it's a valid JavaScript object utils.getInputJsValue = function(element, event) { element = jqElt(element); var value = utils.getInputTextValue(element, event); if(value === undefined) { return undefined; } try { /*jshint evil:true */ eval("var test=" + value); /*jshint evil:false */ } catch(e) { inputError(element, event); return undefined; } return value; }; // Return input value and check that it's a valid JSON utils.getInputJSONValue = function(element, event) { element = jqElt(element); var value = utils.getInputTextValue(element, event); if(value === undefined) { return undefined; } try { JSON.parse(value); } catch(e) { inputError(element, event); return undefined; } return value; }; // Return checkbox boolean value utils.getInputChecked = function(element) { element = jqElt(element); return element.prop("checked"); }; // Set checkbox state utils.setInputChecked = function(element, checked) { element = jqElt(element); element.prop("checked", checked).change(); }; // Get radio button value utils.getInputRadio = function(name) { return $("input:radio[name=" + name + "]:checked").prop("value"); }; // Set radio button value utils.setInputRadio = function(name, value) { $("input:radio[name=" + name + "][value=" + value + "]").prop("checked", true).change(); }; // Reset input control in all modals utils.resetModalInputs = function() { $(".modal input[type=text]:not([disabled]), .modal input[type=password], .modal textarea").val(""); $(".modal input[type=checkbox]").prop("checked", false).change(); }; // Basic trim function utils.trim = function(str) { return $.trim(str); }; // Slug function var nonWordChars = XRegExp('[^\\p{L}\\p{N}-]', 'g'); utils.slugify = function(text) { return text.toLowerCase().replace(/\s/g, '-') // Replace spaces with - .replace(nonWordChars, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }; // Check an URL utils.checkUrl = function(url, addSlash) { if(!url) { return url; } if(url.indexOf("http") !== 0) { url = "http://" + url; } if(addSlash && url.indexOf("/", url.length - 1) === -1) { url += "/"; } return url; }; // Create the modal element and add to the body utils.addModal = function(id, content) { var modal = crel('div', { class: 'modal ' + id }); modal.innerHTML = content; document.body.appendChild(modal); }; // Create a backdrop and add to the body utils.createBackdrop = function(parent) { var result = crel('div', { 'class': 'modal-backdrop fade' }); parent = parent || document.body; parent.appendChild(result); result.offsetWidth; // force reflow result.className = result.className + ' in'; result.removeBackdrop = function() { result.className = 'modal-backdrop fade'; setTimeout(function() { result.parentNode.removeChild(result); }, 150); }; return result; }; var openedTooltip; utils.createTooltip = function(selector, content) { _.each(document.querySelectorAll(selector), function(tooltipElt) { var $tooltipElt = $(tooltipElt); $tooltipElt.tooltip({ html: true, container: $tooltipElt.parents('.modal-content'), placement: 'right', trigger: 'manual', title: content }).click(function() { var elt = this; if(openedTooltip && openedTooltip[0] === elt) { return; } utils.defer(function() { openedTooltip = $(elt).tooltip('show'); }); }); }); }; // Create an centered popup window utils.popupWindow = function(url, title, width, height) { var left = (screen.width / 2) - (width / 2); var top = (screen.height / 2) - (height / 2); return window.open(url, title, [ 'toolbar=no, ', 'location=no, ', 'directories=no, ', 'status=no, ', 'menubar=no, ', 'scrollbars=no, ', 'resizable=no, ', 'copyhistory=no, ', 'width=' + width + ', ', 'height=' + height + ', ', 'top=' + top + ', ', 'left=' + left ].join("")); }; var $windowElt = $(window); utils.iframe = function(url, width, height) { var $backdropElt = $(utils.createBackdrop()); var result = crel('iframe', { src: url, frameborder: 0, class: 'modal-content modal-iframe' }); document.body.appendChild(result); function placeIframe() { var actualWidth = window.innerWidth - 20; actualWidth > width && (actualWidth = width); var actualHeight = window.innerHeight - 50; actualHeight > height && (actualHeight = height); result.setAttribute('width', actualWidth); result.setAttribute('height', actualHeight); } placeIframe(); $windowElt.on('resize.iframe', placeIframe); function removeIframe() { $backdropElt.off('click.backdrop'); $backdropElt[0].removeBackdrop(); $windowElt.off('resize.iframe'); result.parentNode.removeChild(result); } result.removeIframe = removeIframe; $backdropElt.on('click.backdrop', removeIframe); return result; }; // Shows a dialog to force the user to click a button before opening oauth popup var redirectCallbackConfirm; var redirectCallbackCancel; utils.redirectConfirm = function(message, callbackConfirm, callbackCancel) { redirectCallbackConfirm = callbackConfirm; redirectCallbackCancel = callbackCancel; $('.modal-redirect-confirm .redirect-msg').html(message); $('.modal-redirect-confirm').modal("show"); }; utils.init = function() { $('.action-redirect-confirm').click(function() { redirectCallbackCancel = undefined; redirectCallbackConfirm(); }); $('.modal-redirect-confirm').on('hidden.bs.modal', function() { _.defer(function() { redirectCallbackCancel && redirectCallbackCancel(); }); }); $(document).on('click', function() { // Close opened tooltip if any openedTooltip && openedTooltip.tooltip('hide'); openedTooltip = undefined; }); $(document).on('click', '.tooltip', function(evt) { // Avoid tooltip to close when clicking inside evt.stopPropagation(); }); }; utils.lockUI = function(cb) { var eltsToHide = $([ '#wmd-input', '#preview-contents', '.navbar .file-title-navbar', '.navbar .left-buttons', '.navbar .right-buttons', '.navbar .buttons-dropdown' ].join(',')).hide(); return function() { eltsToHide.show(); cb && cb.apply(null, arguments); }; }; var entityMap = { "&": "&amp;", "<": "&lt;", //">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;', "\u00a0": ' ' }; // Escape HTML entities utils.escape = function(str) { return String(str).replace(/[&<"'\/\u00a0]/g, function(s) { return entityMap[s]; }); }; // Export data on disk utils.saveAs = function(content, filename) { if(saveAs !== undefined && !/constructor/i.test(window.HTMLElement) /* safari does not support saveAs */) { if(_.isString(content)) { content = new Blob([ content ], { type: "text/plain;charset=utf-8" }); } saveAs(content, filename); } else { if(_.isString(content)) { var uriContent = "data:application/octet-stream;base64," + utils.encodeBase64(content); window.open(uriContent, 'file'); } else { var reader = new FileReader(); reader.onload = function(event) { utils.redirectConfirm('You are opening a PDF document.', function() { var uriContent = 'data:application/pdf;' + event.target.result.substring(event.target.result.indexOf('base64')); window.open(uriContent, 'file'); }); }; reader.readAsDataURL(content); // Convert the blob to base64 } } }; // Time shared by others modules utils.updateCurrentTime = function() { utils.currentTime = Date.now(); }; utils.updateCurrentTime(); // Serialize sync/publish attributes and store it in the storage utils.storeAttributes = function(attributes) { var storeIndex = attributes.syncIndex || attributes.publishIndex; // Don't store sync/publish index var storedAttributes = _.omit(attributes, "syncIndex", "publishIndex", "provider"); // Store providerId instead of provider storedAttributes.provider = attributes.provider.providerId; storage[storeIndex] = JSON.stringify(storedAttributes); }; // Retrieve/parse an index array from storage utils.retrieveIndexArray = function(storeIndex) { try { return _.compact(storage[storeIndex].split(";")); } catch(e) { storage[storeIndex] = ";"; return []; } }; // Append an index to an array in storage utils.appendIndexToArray = function(storeIndex, index) { storage[storeIndex] += index + ";"; }; // Remove an index from an array in storage utils.removeIndexFromArray = function(storeIndex, index) { storage[storeIndex] = storage[storeIndex].replace(";" + index + ";", ";"); }; // Retrieve/parse an object from storage. Returns undefined if error. utils.retrieveIgnoreError = function(storeIndex) { try { return JSON.parse(storage[storeIndex]); } catch(e) { return undefined; } }; var eventList = []; utils.logValue = function(value) { eventList.unshift(value); if(eventList.length > 5) { eventList.pop(); } }; utils.logStackTrace = function() { eventList.unshift(printStackTrace()); if(eventList.length > 5) { eventList.pop(); } }; utils.formatEventList = function() { var result = []; _.each(eventList, function(event) { result.push("\n"); if(_.isString(event)) { result.push(event); } else if(_.isArray(event)) { result.push(event[5] || ""); result.push(event[6] || ""); } }); return result.join(""); }; function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) { num = '0' + num; } if (trim) { num = num.substr(num.length - digits); } return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) { value += offset; } if (value === 0 && offset == -12 ) { value = 12; } return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = (shortForm ? ('SHORT' + name) : name).toUpperCase(); return formats[get][value]; }; } var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/; var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true) }; var DATETIME_FORMATS = { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }; utils.formatDate = function(date) { var text = '', parts = [], fn, match; var interval = Date.now() - date; var format = 'HH:mm'; if(interval > 31556940000) { format = 'y'; } else if(interval > 86400000) { format = 'MMM d'; } date = new Date(date); while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = parts.concat(match.slice(1)); format = parts.pop(); } else { parts.push(format); format = null; } } parts.forEach(function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; // Base64 conversion utils.encodeBase64 = function(str) { if(str.length === 0) { return ""; } // UTF-8 to byte array var bytes = [], offset = 0, length, char; str = encodeURI(str); length = str.length; while(offset < length) { char = str[offset]; offset += 1; if('%' !== char) { bytes.push(char.charCodeAt(0)); } else { char = str[offset] + str[offset + 1]; bytes.push(parseInt(char, 16)); offset += 2; } } // byte array to base64 var padchar = '='; var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var i, b10; var x = []; var imax = bytes.length - bytes.length % 3; for(i = 0; i < imax; i += 3) { b10 = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; x.push(alpha.charAt(b10 >> 18)); x.push(alpha.charAt((b10 >> 12) & 0x3F)); x.push(alpha.charAt((b10 >> 6) & 0x3f)); x.push(alpha.charAt(b10 & 0x3f)); } switch(bytes.length - imax) { case 1: b10 = bytes[i] << 16; x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) + padchar + padchar); break; case 2: b10 = (bytes[i] << 16) | (bytes[i + 1] << 8); x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) + alpha.charAt((b10 >> 6) & 0x3f) + padchar); break; } return x.join(''); }; utils.decodeBase64 = function(str) { return decodeURIComponent(window.escape(window.atob(str))); }; // CRC32 algorithm var mHash = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918000, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ]; utils.crc32 = function(str) { var n = 0, crc = -1; str.split('').forEach(function(char) { n = (crc ^ char.charCodeAt(0)) & 0xFF; crc = (crc >>> 8) ^ mHash[n]; }); crc = crc ^ (-1); if(crc < 0) { crc = 0xFFFFFFFF + crc + 1; } return crc.toString(16); }; window.perfTest = function(cb) { var startTime = Date.now(); for(var i = 0; i < 10000; i++) { cb(); } console.log('Run 10,000 times in ' + (Date.now() - startTime) + 'ms'); }; return utils; });
// minifier: path aliases enyo.path.addPaths({layout: "C://Users/Jason/Documents/My Dropbox/Public/org.webosports.app.calculator-master/enyo/../lib/layout/", onyx: "C://Users/Jason/Documents/My Dropbox/Public/org.webosports.app.calculator-master/enyo/../lib/onyx/", onyx: "C://Users/Jason/Documents/My Dropbox/Public/org.webosports.app.calculator-master/enyo/../lib/onyx/source/"}); // FittableLayout.js enyo.kind({ name: "enyo.FittableLayout", kind: "Layout", calcFitIndex: function() { for (var e = 0, t = this.container.children, n; n = t[e]; e++) if (n.fit && n.showing) return e; }, getFitControl: function() { var e = this.container.children, t = e[this.fitIndex]; return t && t.fit && t.showing || (this.fitIndex = this.calcFitIndex(), t = e[this.fitIndex]), t; }, getLastControl: function() { var e = this.container.children, t = e.length - 1, n = e[t]; while ((n = e[t]) && !n.showing) t--; return n; }, _reflow: function(e, t, n, r) { this.container.addRemoveClass("enyo-stretch", !this.container.noStretch); var i = this.getFitControl(); if (!i) return; var s = 0, o = 0, u = 0, a, f = this.container.hasNode(); f && (a = enyo.dom.calcPaddingExtents(f), s = f[t] - (a[n] + a[r])); var l = i.getBounds(); o = l[n] - (a && a[n] || 0); var c = this.getLastControl(); if (c) { var h = enyo.dom.getComputedBoxValue(c.hasNode(), "margin", r) || 0; if (c != i) { var p = c.getBounds(), d = l[n] + l[e], v = p[n] + p[e] + h; u = v - d; } else u = h; } var m = s - (o + u); i.applyStyle(e, m + "px"); }, reflow: function() { this.orient == "h" ? this._reflow("width", "clientWidth", "left", "right") : this._reflow("height", "clientHeight", "top", "bottom"); } }), enyo.kind({ name: "enyo.FittableColumnsLayout", kind: "FittableLayout", orient: "h", layoutClass: "enyo-fittable-columns-layout" }), enyo.kind({ name: "enyo.FittableRowsLayout", kind: "FittableLayout", layoutClass: "enyo-fittable-rows-layout", orient: "v" }); // FittableRows.js enyo.kind({ name: "enyo.FittableRows", layoutKind: "FittableRowsLayout", noStretch: !1 }); // FittableColumns.js enyo.kind({ name: "enyo.FittableColumns", layoutKind: "FittableColumnsLayout", noStretch: !1 }); // FlyweightRepeater.js enyo.kind({ name: "enyo.FlyweightRepeater", published: { count: 0, noSelect: !1, multiSelect: !1, toggleSelected: !1, clientClasses: "", clientStyle: "" }, events: { onSetupItem: "" }, bottomUp: !1, components: [ { kind: "Selection", onSelect: "selectDeselect", onDeselect: "selectDeselect" }, { name: "client" } ], rowOffset: 0, create: function() { this.inherited(arguments), this.noSelectChanged(), this.multiSelectChanged(), this.clientClassesChanged(), this.clientStyleChanged(); }, noSelectChanged: function() { this.noSelect && this.$.selection.clear(); }, multiSelectChanged: function() { this.$.selection.setMulti(this.multiSelect); }, clientClassesChanged: function() { this.$.client.setClasses(this.clientClasses); }, clientStyleChanged: function() { this.$.client.setStyle(this.clientStyle); }, setupItem: function(e) { this.doSetupItem({ index: e, selected: this.isSelected(e) }); }, generateChildHtml: function() { var e = ""; this.index = null; for (var t = 0, n = 0; t < this.count; t++) n = this.rowOffset + (this.bottomUp ? this.count - t - 1 : t), this.setupItem(n), this.$.client.setAttribute("data-enyo-index", n), e += this.inherited(arguments), this.$.client.teardownRender(); return e; }, previewDomEvent: function(e) { var t = this.index = this.rowForEvent(e); e.rowIndex = e.index = t, e.flyweight = this; }, decorateEvent: function(e, t, n) { var r = t && t.index != null ? t.index : this.index; t && r != null && (t.index = r, t.flyweight = this), this.inherited(arguments); }, tap: function(e, t) { if (this.noSelect) return; this.toggleSelected ? this.$.selection.toggle(t.index) : this.$.selection.select(t.index); }, selectDeselect: function(e, t) { this.renderRow(t.key); }, getSelection: function() { return this.$.selection; }, isSelected: function(e) { return this.getSelection().isSelected(e); }, renderRow: function(e) { var t = this.fetchRowNode(e); t && (this.setupItem(e), t.innerHTML = this.$.client.generateChildHtml(), this.$.client.teardownChildren()); }, fetchRowNode: function(e) { if (this.hasNode()) { var t = this.node.querySelectorAll('[data-enyo-index="' + e + '"]'); return t && t[0]; } }, rowForEvent: function(e) { var t = e.target, n = this.hasNode().id; while (t && t.parentNode && t.id != n) { var r = t.getAttribute && t.getAttribute("data-enyo-index"); if (r !== null) return Number(r); t = t.parentNode; } return -1; }, prepareRow: function(e) { var t = this.fetchRowNode(e); enyo.FlyweightRepeater.claimNode(this.$.client, t); }, lockRow: function() { this.$.client.teardownChildren(); }, performOnRow: function(e, t, n) { t && (this.prepareRow(e), enyo.call(n || null, t), this.lockRow()); }, statics: { claimNode: function(e, t) { var n = t && t.querySelectorAll("#" + e.id); n = n && n[0], e.generated = Boolean(n || !e.tag), e.node = n, e.node && e.rendered(); for (var r = 0, i = e.children, s; s = i[r]; r++) this.claimNode(s, t); } } }); // List.js enyo.kind({ name: "enyo.List", kind: "Scroller", classes: "enyo-list", published: { count: 0, rowsPerPage: 50, bottomUp: !1, noSelect: !1, multiSelect: !1, toggleSelected: !1, fixedHeight: !1 }, events: { onSetupItem: "" }, handlers: { onAnimateFinish: "animateFinish" }, rowHeight: 0, listTools: [ { name: "port", classes: "enyo-list-port enyo-border-box", components: [ { name: "generator", kind: "FlyweightRepeater", canGenerate: !1, components: [ { tag: null, name: "client" } ] }, { name: "page0", allowHtml: !0, classes: "enyo-list-page" }, { name: "page1", allowHtml: !0, classes: "enyo-list-page" } ] } ], create: function() { this.pageHeights = [], this.inherited(arguments), this.getStrategy().translateOptimized = !0, this.bottomUpChanged(), this.noSelectChanged(), this.multiSelectChanged(), this.toggleSelectedChanged(); }, createStrategy: function() { this.controlParentName = "strategy", this.inherited(arguments), this.createChrome(this.listTools), this.controlParentName = "client", this.discoverControlParent(); }, rendered: function() { this.inherited(arguments), this.$.generator.node = this.$.port.hasNode(), this.$.generator.generated = !0, this.reset(); }, resizeHandler: function() { this.inherited(arguments), this.refresh(); }, bottomUpChanged: function() { this.$.generator.bottomUp = this.bottomUp, this.$.page0.applyStyle(this.pageBound, null), this.$.page1.applyStyle(this.pageBound, null), this.pageBound = this.bottomUp ? "bottom" : "top", this.hasNode() && this.reset(); }, noSelectChanged: function() { this.$.generator.setNoSelect(this.noSelect); }, multiSelectChanged: function() { this.$.generator.setMultiSelect(this.multiSelect); }, toggleSelectedChanged: function() { this.$.generator.setToggleSelected(this.toggleSelected); }, countChanged: function() { this.hasNode() && this.updateMetrics(); }, updateMetrics: function() { this.defaultPageHeight = this.rowsPerPage * (this.rowHeight || 100), this.pageCount = Math.ceil(this.count / this.rowsPerPage), this.portSize = 0; for (var e = 0; e < this.pageCount; e++) this.portSize += this.getPageHeight(e); this.adjustPortSize(); }, generatePage: function(e, t) { this.page = e; var n = this.$.generator.rowOffset = this.rowsPerPage * this.page, r = this.$.generator.count = Math.min(this.count - n, this.rowsPerPage), i = this.$.generator.generateChildHtml(); t.setContent(i); var s = t.getBounds().height; !this.rowHeight && s > 0 && (this.rowHeight = Math.floor(s / r), this.updateMetrics()); if (!this.fixedHeight) { var o = this.getPageHeight(e); o != s && s > 0 && (this.pageHeights[e] = s, this.portSize += s - o); } }, update: function(e) { var t = !1, n = this.positionToPageInfo(e), r = n.pos + this.scrollerHeight / 2, i = Math.floor(r / Math.max(n.height, this.scrollerHeight) + .5) + n.no, s = i % 2 === 0 ? i : i - 1; this.p0 != s && this.isPageInRange(s) && (this.generatePage(s, this.$.page0), this.positionPage(s, this.$.page0), this.p0 = s, t = !0), s = i % 2 === 0 ? Math.max(1, i - 1) : i, this.p1 != s && this.isPageInRange(s) && (this.generatePage(s, this.$.page1), this.positionPage(s, this.$.page1), this.p1 = s, t = !0), t && !this.fixedHeight && (this.adjustBottomPage(), this.adjustPortSize()); }, updateForPosition: function(e) { this.update(this.calcPos(e)); }, calcPos: function(e) { return this.bottomUp ? this.portSize - this.scrollerHeight - e : e; }, adjustBottomPage: function() { var e = this.p0 >= this.p1 ? this.$.page0 : this.$.page1; this.positionPage(e.pageNo, e); }, adjustPortSize: function() { this.scrollerHeight = this.getBounds().height; var e = Math.max(this.scrollerHeight, this.portSize); this.$.port.applyStyle("height", e + "px"); }, positionPage: function(e, t) { t.pageNo = e; var n = this.pageToPosition(e); t.applyStyle(this.pageBound, n + "px"); }, pageToPosition: function(e) { var t = 0, n = e; while (n > 0) n--, t += this.getPageHeight(n); return t; }, positionToPageInfo: function(e) { var t = -1, n = this.calcPos(e), r = this.defaultPageHeight; while (n >= 0) t++, r = this.getPageHeight(t), n -= r; return { no: t, height: r, pos: n + r }; }, isPageInRange: function(e) { return e == Math.max(0, Math.min(this.pageCount - 1, e)); }, getPageHeight: function(e) { return this.pageHeights[e] || this.defaultPageHeight; }, invalidatePages: function() { this.p0 = this.p1 = null, this.$.page0.setContent(""), this.$.page1.setContent(""); }, invalidateMetrics: function() { this.pageHeights = [], this.rowHeight = 0, this.updateMetrics(); }, scroll: function(e, t) { var n = this.inherited(arguments); return this.update(this.getScrollTop()), n; }, scrollToBottom: function() { this.update(this.getScrollBounds().maxTop), this.inherited(arguments); }, setScrollTop: function(e) { this.update(e), this.inherited(arguments), this.twiddle(); }, getScrollPosition: function() { return this.calcPos(this.getScrollTop()); }, setScrollPosition: function(e) { this.setScrollTop(this.calcPos(e)); }, scrollToRow: function(e) { var t = Math.floor(e / this.rowsPerPage), n = e % this.rowsPerPage, r = this.pageToPosition(t); this.updateForPosition(r), r = this.pageToPosition(t), this.setScrollPosition(r); if (t == this.p0 || t == this.p1) { var i = this.$.generator.fetchRowNode(e); if (i) { var s = i.offsetTop; this.bottomUp && (s = this.getPageHeight(t) - i.offsetHeight - s); var o = this.getScrollPosition() + s; this.setScrollPosition(o); } } }, scrollToStart: function() { this[this.bottomUp ? "scrollToBottom" : "scrollToTop"](); }, scrollToEnd: function() { this[this.bottomUp ? "scrollToTop" : "scrollToBottom"](); }, refresh: function() { this.invalidatePages(), this.update(this.getScrollTop()), this.stabilize(), enyo.platform.android === 4 && this.twiddle(); }, reset: function() { this.getSelection().clear(), this.invalidateMetrics(), this.invalidatePages(), this.stabilize(), this.scrollToStart(); }, getSelection: function() { return this.$.generator.getSelection(); }, select: function(e, t) { return this.getSelection().select(e, t); }, deselect: function(e) { return this.getSelection().deselect(e); }, isSelected: function(e) { return this.$.generator.isSelected(e); }, renderRow: function(e) { this.$.generator.renderRow(e); }, prepareRow: function(e) { this.$.generator.prepareRow(e); }, lockRow: function() { this.$.generator.lockRow(); }, performOnRow: function(e, t, n) { this.$.generator.performOnRow(e, t, n); }, animateFinish: function(e) { return this.twiddle(), !0; }, twiddle: function() { var e = this.getStrategy(); enyo.call(e, "twiddle"); } }); // PulldownList.js enyo.kind({ name: "enyo.PulldownList", kind: "List", touch: !0, pully: null, pulldownTools: [ { name: "pulldown", classes: "enyo-list-pulldown", components: [ { name: "puller", kind: "Puller" } ] } ], events: { onPullStart: "", onPullCancel: "", onPull: "", onPullRelease: "", onPullComplete: "" }, handlers: { onScrollStart: "scrollStartHandler", onScrollStop: "scrollStopHandler", ondragfinish: "dragfinish" }, pullingMessage: "Pull down to refresh...", pulledMessage: "Release to refresh...", loadingMessage: "Loading...", pullingIconClass: "enyo-puller-arrow enyo-puller-arrow-down", pulledIconClass: "enyo-puller-arrow enyo-puller-arrow-up", loadingIconClass: "", create: function() { var e = { kind: "Puller", showing: !1, text: this.loadingMessage, iconClass: this.loadingIconClass, onCreate: "setPully" }; this.listTools.splice(0, 0, e), this.inherited(arguments), this.setPulling(); }, initComponents: function() { this.createChrome(this.pulldownTools), this.accel = enyo.dom.canAccelerate(), this.translation = this.accel ? "translate3d" : "translate", this.inherited(arguments); }, setPully: function(e, t) { this.pully = t.originator; }, scrollStartHandler: function() { this.firedPullStart = !1, this.firedPull = !1, this.firedPullCancel = !1; }, scroll: function(e, t) { var n = this.inherited(arguments); this.completingPull && this.pully.setShowing(!1); var r = this.getStrategy().$.scrollMath, i = r.y; return r.isInOverScroll() && i > 0 && (enyo.dom.transformValue(this.$.pulldown, this.translation, "0," + i + "px" + (this.accel ? ",0" : "")), this.firedPullStart || (this.firedPullStart = !0, this.pullStart(), this.pullHeight = this.$.pulldown.getBounds().height), i > this.pullHeight && !this.firedPull && (this.firedPull = !0, this.firedPullCancel = !1, this.pull()), this.firedPull && !this.firedPullCancel && i < this.pullHeight && (this.firedPullCancel = !0, this.firedPull = !1, this.pullCancel())), n; }, scrollStopHandler: function() { this.completingPull && (this.completingPull = !1, this.doPullComplete()); }, dragfinish: function() { if (this.firedPull) { var e = this.getStrategy().$.scrollMath; e.setScrollY(e.y - this.pullHeight), this.pullRelease(); } }, completePull: function() { this.completingPull = !0, this.$.strategy.$.scrollMath.setScrollY(this.pullHeight), this.$.strategy.$.scrollMath.start(); }, pullStart: function() { this.setPulling(), this.pully.setShowing(!1), this.$.puller.setShowing(!0), this.doPullStart(); }, pull: function() { this.setPulled(), this.doPull(); }, pullCancel: function() { this.setPulling(), this.doPullCancel(); }, pullRelease: function() { this.$.puller.setShowing(!1), this.pully.setShowing(!0), this.doPullRelease(); }, setPulling: function() { this.$.puller.setText(this.pullingMessage), this.$.puller.setIconClass(this.pullingIconClass); }, setPulled: function() { this.$.puller.setText(this.pulledMessage), this.$.puller.setIconClass(this.pulledIconClass); } }), enyo.kind({ name: "enyo.Puller", classes: "enyo-puller", published: { text: "", iconClass: "" }, events: { onCreate: "" }, components: [ { name: "icon" }, { name: "text", tag: "span", classes: "enyo-puller-text" } ], create: function() { this.inherited(arguments), this.doCreate(), this.textChanged(), this.iconClassChanged(); }, textChanged: function() { this.$.text.setContent(this.text); }, iconClassChanged: function() { this.$.icon.setClasses(this.iconClass); } }); // AroundList.js enyo.kind({ name: "enyo.AroundList", kind: "enyo.List", listTools: [ { name: "port", classes: "enyo-list-port enyo-border-box", components: [ { name: "aboveClient" }, { name: "generator", kind: "enyo.FlyweightRepeater", canGenerate: !1, components: [ { tag: null, name: "client" } ] }, { name: "page0", allowHtml: !0, classes: "enyo-list-page" }, { name: "page1", allowHtml: !0, classes: "enyo-list-page" }, { name: "belowClient" } ] } ], aboveComponents: null, initComponents: function() { this.inherited(arguments), this.aboveComponents && this.$.aboveClient.createComponents(this.aboveComponents, { owner: this.owner }), this.belowComponents && this.$.belowClient.createComponents(this.belowComponents, { owner: this.owner }); }, updateMetrics: function() { this.defaultPageHeight = this.rowsPerPage * (this.rowHeight || 100), this.pageCount = Math.ceil(this.count / this.rowsPerPage), this.aboveHeight = this.$.aboveClient.getBounds().height, this.belowHeight = this.$.belowClient.getBounds().height, this.portSize = this.aboveHeight + this.belowHeight; for (var e = 0; e < this.pageCount; e++) this.portSize += this.getPageHeight(e); this.adjustPortSize(); }, positionPage: function(e, t) { t.pageNo = e; var n = this.pageToPosition(e), r = this.bottomUp ? this.belowHeight : this.aboveHeight; n += r, t.applyStyle(this.pageBound, n + "px"); }, scrollToContentStart: function() { var e = this.bottomUp ? this.belowHeight : this.aboveHeight; this.setScrollPosition(e); } }); // Slideable.js enyo.kind({ name: "enyo.Slideable", kind: "Control", published: { axis: "h", value: 0, unit: "px", min: 0, max: 0, accelerated: "auto", overMoving: !0, draggable: !0 }, events: { onAnimateFinish: "", onChange: "" }, preventDragPropagation: !1, tools: [ { kind: "Animator", onStep: "animatorStep", onEnd: "animatorComplete" } ], handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish" }, kDragScalar: 1, dragEventProp: "dx", unitModifier: !1, canTransform: !1, create: function() { this.inherited(arguments), this.acceleratedChanged(), this.transformChanged(), this.axisChanged(), this.valueChanged(), this.addClass("enyo-slideable"); }, initComponents: function() { this.createComponents(this.tools), this.inherited(arguments); }, rendered: function() { this.inherited(arguments), this.canModifyUnit(), this.updateDragScalar(); }, resizeHandler: function() { this.inherited(arguments), this.updateDragScalar(); }, canModifyUnit: function() { if (!this.canTransform) { var e = this.getInitialStyleValue(this.hasNode(), this.boundary); e.match(/px/i) && this.unit === "%" && (this.unitModifier = this.getBounds()[this.dimension]); } }, getInitialStyleValue: function(e, t) { var n = enyo.dom.getComputedStyle(e); return n ? n.getPropertyValue(t) : e && e.currentStyle ? e.currentStyle[t] : "0"; }, updateBounds: function(e, t) { var n = {}; n[this.boundary] = e, this.setBounds(n, this.unit), this.setInlineStyles(e, t); }, updateDragScalar: function() { if (this.unit == "%") { var e = this.getBounds()[this.dimension]; this.kDragScalar = e ? 100 / e : 1, this.canTransform || this.updateBounds(this.value, 100); } }, transformChanged: function() { this.canTransform = enyo.dom.canTransform(); }, acceleratedChanged: function() { enyo.platform.android > 2 || enyo.dom.accelerate(this, this.accelerated); }, axisChanged: function() { var e = this.axis == "h"; this.dragMoveProp = e ? "dx" : "dy", this.shouldDragProp = e ? "horizontal" : "vertical", this.transform = e ? "translateX" : "translateY", this.dimension = e ? "width" : "height", this.boundary = e ? "left" : "top"; }, setInlineStyles: function(e, t) { var n = {}; this.unitModifier ? (n[this.boundary] = this.percentToPixels(e, this.unitModifier), n[this.dimension] = this.unitModifier, this.setBounds(n)) : (t ? n[this.dimension] = t : n[this.boundary] = e, this.setBounds(n, this.unit)); }, valueChanged: function(e) { var t = this.value; this.isOob(t) && !this.isAnimating() && (this.value = this.overMoving ? this.dampValue(t) : this.clampValue(t)), enyo.platform.android > 2 && (this.value ? (e === 0 || e === undefined) && enyo.dom.accelerate(this, this.accelerated) : enyo.dom.accelerate(this, !1)), this.canTransform ? enyo.dom.transformValue(this, this.transform, this.value + this.unit) : this.setInlineStyles(this.value, !1), this.doChange(); }, getAnimator: function() { return this.$.animator; }, isAtMin: function() { return this.value <= this.calcMin(); }, isAtMax: function() { return this.value >= this.calcMax(); }, calcMin: function() { return this.min; }, calcMax: function() { return this.max; }, clampValue: function(e) { var t = this.calcMin(), n = this.calcMax(); return Math.max(t, Math.min(e, n)); }, dampValue: function(e) { return this.dampBound(this.dampBound(e, this.min, 1), this.max, -1); }, dampBound: function(e, t, n) { var r = e; return r * n < t * n && (r = t + (r - t) / 4), r; }, percentToPixels: function(e, t) { return Math.floor(t / 100 * e); }, pixelsToPercent: function(e) { var t = this.unitModifier ? this.getBounds()[this.dimension] : this.container.getBounds()[this.dimension]; return e / t * 100; }, shouldDrag: function(e) { return this.draggable && e[this.shouldDragProp]; }, isOob: function(e) { return e > this.calcMax() || e < this.calcMin(); }, dragstart: function(e, t) { if (this.shouldDrag(t)) return t.preventDefault(), this.$.animator.stop(), t.dragInfo = {}, this.dragging = !0, this.drag0 = this.value, this.dragd0 = 0, this.preventDragPropagation; }, drag: function(e, t) { if (this.dragging) { t.preventDefault(); var n = this.canTransform ? t[this.dragMoveProp] * this.kDragScalar : this.pixelsToPercent(t[this.dragMoveProp]), r = this.drag0 + n, i = n - this.dragd0; return this.dragd0 = n, i && (t.dragInfo.minimizing = i < 0), this.setValue(r), this.preventDragPropagation; } }, dragfinish: function(e, t) { if (this.dragging) return this.dragging = !1, this.completeDrag(t), t.preventTap(), this.preventDragPropagation; }, completeDrag: function(e) { this.value !== this.calcMax() && this.value != this.calcMin() && this.animateToMinMax(e.dragInfo.minimizing); }, isAnimating: function() { return this.$.animator.isAnimating(); }, play: function(e, t) { this.$.animator.play({ startValue: e, endValue: t, node: this.hasNode() }); }, animateTo: function(e) { this.play(this.value, e); }, animateToMin: function() { this.animateTo(this.calcMin()); }, animateToMax: function() { this.animateTo(this.calcMax()); }, animateToMinMax: function(e) { e ? this.animateToMin() : this.animateToMax(); }, animatorStep: function(e) { return this.setValue(e.value), !0; }, animatorComplete: function(e) { return this.doAnimateFinish(e), !0; }, toggleMinMax: function() { this.animateToMinMax(!this.isAtMin()); } }); // Arranger.js enyo.kind({ name: "enyo.Arranger", kind: "Layout", layoutClass: "enyo-arranger", accelerated: "auto", dragProp: "ddx", dragDirectionProp: "xDirection", canDragProp: "horizontal", incrementalPoints: !1, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) n._arranger = null; this.inherited(arguments); }, arrange: function(e, t) {}, size: function() {}, start: function() { var e = this.container.fromIndex, t = this.container.toIndex, n = this.container.transitionPoints = [ e ]; if (this.incrementalPoints) { var r = Math.abs(t - e) - 2, i = e; while (r >= 0) i += t < e ? -1 : 1, n.push(i), r--; } n.push(this.container.toIndex); }, finish: function() {}, calcArrangementDifference: function(e, t, n, r) {}, canDragEvent: function(e) { return e[this.canDragProp]; }, calcDragDirection: function(e) { return e[this.dragDirectionProp]; }, calcDrag: function(e) { return e[this.dragProp]; }, drag: function(e, t, n, r, i) { var s = this.measureArrangementDelta(-e, t, n, r, i); return s; }, measureArrangementDelta: function(e, t, n, r, i) { var s = this.calcArrangementDifference(t, n, r, i), o = s ? e / Math.abs(s) : 0; return o *= this.container.fromIndex > this.container.toIndex ? -1 : 1, o; }, _arrange: function(e) { this.containerBounds || this.reflow(); var t = this.getOrderedControls(e); this.arrange(t, e); }, arrangeControl: function(e, t) { e._arranger = enyo.mixin(e._arranger || {}, t); }, flow: function() { this.c$ = [].concat(this.container.getPanels()), this.controlsIndex = 0; for (var e = 0, t = this.container.getPanels(), n; n = t[e]; e++) { enyo.dom.accelerate(n, this.accelerated); if (enyo.platform.safari) { var r = n.children; for (var i = 0, s; s = r[i]; i++) enyo.dom.accelerate(s, this.accelerated); } } }, reflow: function() { var e = this.container.hasNode(); this.containerBounds = e ? { width: e.clientWidth, height: e.clientHeight } : {}, this.size(); }, flowArrangement: function() { var e = this.container.arrangement; if (e) for (var t = 0, n = this.container.getPanels(), r; r = n[t]; t++) this.flowControl(r, e[t]); }, flowControl: function(e, t) { enyo.Arranger.positionControl(e, t); var n = t.opacity; n != null && enyo.Arranger.opacifyControl(e, n); }, getOrderedControls: function(e) { var t = Math.floor(e), n = t - this.controlsIndex, r = n > 0, i = this.c$ || []; for (var s = 0; s < Math.abs(n); s++) r ? i.push(i.shift()) : i.unshift(i.pop()); return this.controlsIndex = t, i; }, statics: { positionControl: function(e, t, n) { var r = n || "px"; if (!this.updating) if (enyo.dom.canTransform() && !enyo.platform.android && enyo.platform.ie !== 10) { var i = t.left, s = t.top; i = enyo.isString(i) ? i : i && i + r, s = enyo.isString(s) ? s : s && s + r, enyo.dom.transform(e, { translateX: i || null, translateY: s || null }); } else e.setBounds(t, n); }, opacifyControl: function(e, t) { var n = t; n = n > .99 ? 1 : n < .01 ? 0 : n, enyo.platform.ie < 9 ? e.applyStyle("filter", "progid:DXImageTransform.Microsoft.Alpha(Opacity=" + n * 100 + ")") : e.applyStyle("opacity", n); } } }); // CardArranger.js enyo.kind({ name: "enyo.CardArranger", kind: "Arranger", layoutClass: "enyo-arranger enyo-arranger-fit", calcArrangementDifference: function(e, t, n, r) { return this.containerBounds.width; }, arrange: function(e, t) { for (var n = 0, r, i, s; r = e[n]; n++) s = n === 0 ? 1 : 0, this.arrangeControl(r, { opacity: s }); }, start: function() { this.inherited(arguments); var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) { var r = n.showing; n.setShowing(t == this.container.fromIndex || t == this.container.toIndex), n.showing && !r && n.resized(); } }, finish: function() { this.inherited(arguments); var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) n.setShowing(t == this.container.toIndex); }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.opacifyControl(n, 1), n.showing || n.setShowing(!0); this.inherited(arguments); } }); // CardSlideInArranger.js enyo.kind({ name: "enyo.CardSlideInArranger", kind: "CardArranger", start: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) { var r = n.showing; n.setShowing(t == this.container.fromIndex || t == this.container.toIndex), n.showing && !r && n.resized(); } var i = this.container.fromIndex; t = this.container.toIndex, this.container.transitionPoints = [ t + "." + i + ".s", t + "." + i + ".f" ]; }, finish: function() { this.inherited(arguments); var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) n.setShowing(t == this.container.toIndex); }, arrange: function(e, t) { var n = t.split("."), r = n[0], i = n[1], s = n[2] == "s", o = this.containerBounds.width; for (var u = 0, a = this.container.getPanels(), f, l; f = a[u]; u++) l = o, i == u && (l = s ? 0 : -o), r == u && (l = s ? o : 0), i == u && i == r && (l = 0), this.arrangeControl(f, { left: l }); }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.positionControl(n, { left: null }); this.inherited(arguments); } }); // CarouselArranger.js enyo.kind({ name: "enyo.CarouselArranger", kind: "Arranger", size: function() { var e = this.container.getPanels(), t = this.containerPadding = this.container.hasNode() ? enyo.dom.calcPaddingExtents(this.container.node) : {}, n = this.containerBounds, r, i, s, o, u; n.height -= t.top + t.bottom, n.width -= t.left + t.right; var a; for (r = 0, s = 0; u = e[r]; r++) o = enyo.dom.calcMarginExtents(u.hasNode()), u.width = u.getBounds().width, u.marginWidth = o.right + o.left, s += (u.fit ? 0 : u.width) + u.marginWidth, u.fit && (a = u); if (a) { var f = n.width - s; a.width = f >= 0 ? f : a.width; } for (r = 0, i = t.left; u = e[r]; r++) u.setBounds({ top: t.top, bottom: t.bottom, width: u.fit ? u.width : null }); }, arrange: function(e, t) { this.container.wrap ? this.arrangeWrap(e, t) : this.arrangeNoWrap(e, t); }, arrangeNoWrap: function(e, t) { var n, r, i, s, o = this.container.getPanels(), u = this.container.clamp(t), a = this.containerBounds.width; for (n = u, i = 0; s = o[n]; n++) { i += s.width + s.marginWidth; if (i > a) break; } var f = a - i, l = 0; if (f > 0) { var c = u; for (n = u - 1, r = 0; s = o[n]; n--) { r += s.width + s.marginWidth; if (f - r <= 0) { l = f - r, u = n; break; } } } var h, p; for (n = 0, p = this.containerPadding.left + l; s = o[n]; n++) h = s.width + s.marginWidth, n < u ? this.arrangeControl(s, { left: -h }) : (this.arrangeControl(s, { left: Math.floor(p) }), p += h); }, arrangeWrap: function(e, t) { for (var n = 0, r = this.containerPadding.left, i, s; s = e[n]; n++) this.arrangeControl(s, { left: r }), r += s.width + s.marginWidth; }, calcArrangementDifference: function(e, t, n, r) { var i = Math.abs(e % this.c$.length); return t[i].left - r[i].left; }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.positionControl(n, { left: null, top: null }), n.applyStyle("top", null), n.applyStyle("bottom", null), n.applyStyle("left", null), n.applyStyle("width", null); this.inherited(arguments); } }); // CollapsingArranger.js enyo.kind({ name: "enyo.CollapsingArranger", kind: "CarouselArranger", peekWidth: 0, size: function() { this.clearLastSize(), this.inherited(arguments); }, clearLastSize: function() { for (var e = 0, t = this.container.getPanels(), n; n = t[e]; e++) n._fit && e != t.length - 1 && (n.applyStyle("width", null), n._fit = null); }, constructor: function() { this.inherited(arguments), this.peekWidth = this.container.peekWidth != null ? this.container.peekWidth : this.peekWidth; }, arrange: function(e, t) { var n = this.container.getPanels(); for (var r = 0, i = this.containerPadding.left, s, o, u = 0; o = n[r]; r++) o.getShowing() && (this.arrangeControl(o, { left: i + u * this.peekWidth }), r >= t && (i += o.width + o.marginWidth - this.peekWidth), r == n.length - 1 && t < 0 && this.arrangeControl(o, { left: i - t }), u++); }, calcArrangementDifference: function(e, t, n, r) { var i = this.container.getPanels().length - 1; return Math.abs(r[i].left - t[i].left); }, flowControl: function(e, t) { this.inherited(arguments); if (this.container.realtimeFit) { var n = this.container.getPanels(), r = n.length - 1, i = n[r]; e == i && this.fitControl(e, t.left); } }, finish: function() { this.inherited(arguments); if (!this.container.realtimeFit && this.containerBounds) { var e = this.container.getPanels(), t = this.container.arrangement, n = e.length - 1, r = e[n]; this.fitControl(r, t[n].left); } }, fitControl: function(e, t) { e._fit = !0, e.applyStyle("width", this.containerBounds.width - t + "px"), e.resized(); } }); // OtherArrangers.js enyo.kind({ name: "enyo.LeftRightArranger", kind: "Arranger", margin: 40, axisSize: "width", offAxisSize: "height", axisPosition: "left", constructor: function() { this.inherited(arguments), this.margin = this.container.margin != null ? this.container.margin : this.margin; }, size: function() { var e = this.container.getPanels(), t = this.containerBounds[this.axisSize], n = t - this.margin - this.margin; for (var r = 0, i, s; s = e[r]; r++) i = {}, i[this.axisSize] = n, i[this.offAxisSize] = "100%", s.setBounds(i); }, start: function() { this.inherited(arguments); var e = this.container.fromIndex, t = this.container.toIndex, n = this.getOrderedControls(t), r = Math.floor(n.length / 2); for (var i = 0, s; s = n[i]; i++) e > t ? i == n.length - r ? s.applyStyle("z-index", 0) : s.applyStyle("z-index", 1) : i == n.length - 1 - r ? s.applyStyle("z-index", 0) : s.applyStyle("z-index", 1); }, arrange: function(e, t) { var n, r, i, s; if (this.container.getPanels().length == 1) { s = {}, s[this.axisPosition] = this.margin, this.arrangeControl(this.container.getPanels()[0], s); return; } var o = Math.floor(this.container.getPanels().length / 2), u = this.getOrderedControls(Math.floor(t) - o), a = this.containerBounds[this.axisSize] - this.margin - this.margin, f = this.margin - a * o; for (n = 0; r = u[n]; n++) s = {}, s[this.axisPosition] = f, this.arrangeControl(r, s), f += a; }, calcArrangementDifference: function(e, t, n, r) { if (this.container.getPanels().length == 1) return 0; var i = Math.abs(e % this.c$.length); return t[i][this.axisPosition] - r[i][this.axisPosition]; }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.positionControl(n, { left: null, top: null }), enyo.Arranger.opacifyControl(n, 1), n.applyStyle("left", null), n.applyStyle("top", null), n.applyStyle("height", null), n.applyStyle("width", null); this.inherited(arguments); } }), enyo.kind({ name: "enyo.TopBottomArranger", kind: "LeftRightArranger", dragProp: "ddy", dragDirectionProp: "yDirection", canDragProp: "vertical", axisSize: "height", offAxisSize: "width", axisPosition: "top" }), enyo.kind({ name: "enyo.SpiralArranger", kind: "Arranger", incrementalPoints: !0, inc: 20, size: function() { var e = this.container.getPanels(), t = this.containerBounds, n = this.controlWidth = t.width / 3, r = this.controlHeight = t.height / 3; for (var i = 0, s; s = e[i]; i++) s.setBounds({ width: n, height: r }); }, arrange: function(e, t) { var n = this.inc; for (var r = 0, i = e.length, s; s = e[r]; r++) { var o = Math.cos(r / i * 2 * Math.PI) * r * n + this.controlWidth, u = Math.sin(r / i * 2 * Math.PI) * r * n + this.controlHeight; this.arrangeControl(s, { left: o, top: u }); } }, start: function() { this.inherited(arguments); var e = this.getOrderedControls(this.container.toIndex); for (var t = 0, n; n = e[t]; t++) n.applyStyle("z-index", e.length - t); }, calcArrangementDifference: function(e, t, n, r) { return this.controlWidth; }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) n.applyStyle("z-index", null), enyo.Arranger.positionControl(n, { left: null, top: null }), n.applyStyle("left", null), n.applyStyle("top", null), n.applyStyle("height", null), n.applyStyle("width", null); this.inherited(arguments); } }), enyo.kind({ name: "enyo.GridArranger", kind: "Arranger", incrementalPoints: !0, colWidth: 100, colHeight: 100, size: function() { var e = this.container.getPanels(), t = this.colWidth, n = this.colHeight; for (var r = 0, i; i = e[r]; r++) i.setBounds({ width: t, height: n }); }, arrange: function(e, t) { var n = this.colWidth, r = this.colHeight, i = Math.max(1, Math.floor(this.containerBounds.width / n)), s; for (var o = 0, u = 0; u < e.length; o++) for (var a = 0; a < i && (s = e[u]); a++, u++) this.arrangeControl(s, { left: n * a, top: r * o }); }, flowControl: function(e, t) { this.inherited(arguments), enyo.Arranger.opacifyControl(e, t.top % this.colHeight !== 0 ? .25 : 1); }, calcArrangementDifference: function(e, t, n, r) { return this.colWidth; }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.positionControl(n, { left: null, top: null }), n.applyStyle("left", null), n.applyStyle("top", null), n.applyStyle("height", null), n.applyStyle("width", null); this.inherited(arguments); } }), enyo.kind({ name: "enyo.DockRightArranger", kind: "Arranger", basePanel: !1, size: function() { var e = this.container.getPanels(), t = this.containerPadding = this.container.hasNode() ? enyo.dom.calcPaddingExtents(this.container.node) : {}, n = this.containerBounds, r, i, s; n.width -= t.left + t.right; var o = n.width, u = e.length; this.container.transitionPositions = {}; for (r = 0; s = e[r]; r++) s.width = r === 0 && this.container.basePanel ? o : s.getBounds().width; for (r = 0; s = e[r]; r++) { r === 0 && this.container.basePanel && s.setBounds({ width: o }), s.setBounds({ top: t.top, bottom: t.bottom }); for (j = 0; s = e[j]; j++) { var a; if (r === 0 && this.container.basePanel) a = 0; else if (j < r) a = o; else { if (r !== j) break; a = o - e[r].width; } this.container.transitionPositions[r + "." + j] = a; } if (j < u) { var f = !1; for (k = r + 1; k < u; k++) { var l = 0; if (f) l = 0; else if (e[r].width + e[k].width > o) l = 0, f = !0; else { l = e[r].width; for (i = r; i < k; i++) { if (!(l + e[i + 1].width < o)) { l = o; break; } l += e[i + 1].width; } l = o - l; } this.container.transitionPositions[r + "." + k] = l; } } } }, arrange: function(e, t) { var n, r, i = this.container.getPanels(), s = this.container.clamp(t); for (n = 0; r = i[n]; n++) { var o = this.container.transitionPositions[n + "." + s]; this.arrangeControl(r, { left: o }); } }, calcArrangementDifference: function(e, t, n, r) { return this.containerBounds.width; }, destroy: function() { var e = this.container.getPanels(); for (var t = 0, n; n = e[t]; t++) enyo.Arranger.positionControl(n, { left: null, top: null }), n.applyStyle("top", null), n.applyStyle("bottom", null), n.applyStyle("left", null), n.applyStyle("width", null); this.inherited(arguments); } }); // Panels.js enyo.kind({ name: "enyo.Panels", classes: "enyo-panels", published: { index: 0, draggable: !0, animate: !0, wrap: !1, arrangerKind: "CardArranger", narrowFit: !0 }, events: { onTransitionStart: "", onTransitionFinish: "" }, handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish", onscroll: "domScroll" }, tools: [ { kind: "Animator", onStep: "step", onEnd: "completed" } ], fraction: 0, create: function() { this.transitionPoints = [], this.inherited(arguments), this.arrangerKindChanged(), this.narrowFitChanged(), this.indexChanged(), this.setAttribute("onscroll", enyo.bubbler); }, domScroll: function(e, t) { this.hasNode() && this.node.scrollLeft > 0 && (this.node.scrollLeft = 0); }, initComponents: function() { this.createChrome(this.tools), this.inherited(arguments); }, arrangerKindChanged: function() { this.setLayoutKind(this.arrangerKind); }, narrowFitChanged: function() { this.addRemoveClass("enyo-panels-fit-narrow", this.narrowFit); }, destroy: function() { this.destroying = !0, this.inherited(arguments); }, removeControl: function(e) { this.inherited(arguments), this.destroying && this.controls.length > 0 && this.isPanel(e) && (this.setIndex(Math.max(this.index - 1, 0)), this.flow(), this.reflow()); }, isPanel: function() { return !0; }, flow: function() { this.arrangements = [], this.inherited(arguments); }, reflow: function() { this.arrangements = [], this.inherited(arguments), this.refresh(); }, getPanels: function() { var e = this.controlParent || this; return e.children; }, getActive: function() { var e = this.getPanels(), t = this.index % e.length; return t < 0 ? t += e.length : enyo.nop, e[t]; }, getAnimator: function() { return this.$.animator; }, setIndex: function(e) { this.setPropertyValue("index", e, "indexChanged"); }, setIndexDirect: function(e) { this.setIndex(e), this.completed(); }, previous: function() { this.setIndex(this.index - 1); }, next: function() { this.setIndex(this.index + 1); }, clamp: function(e) { var t = this.getPanels().length - 1; return this.wrap ? e : Math.max(0, Math.min(e, t)); }, indexChanged: function(e) { this.lastIndex = e, this.index = this.clamp(this.index), !this.dragging && this.$.animator && (this.$.animator.isAnimating() && this.completed(), this.$.animator.stop(), this.hasNode() && (this.animate ? (this.startTransition(), this.$.animator.play({ startValue: this.fraction })) : this.refresh())); }, step: function(e) { this.fraction = e.value, this.stepTransition(); }, completed: function() { this.$.animator.isAnimating() && this.$.animator.stop(), this.fraction = 1, this.stepTransition(), this.finishTransition(); }, dragstart: function(e, t) { if (this.draggable && this.layout && this.layout.canDragEvent(t)) return t.preventDefault(), this.dragstartTransition(t), this.dragging = !0, this.$.animator.stop(), !0; }, drag: function(e, t) { this.dragging && (t.preventDefault(), this.dragTransition(t)); }, dragfinish: function(e, t) { this.dragging && (this.dragging = !1, t.preventTap(), this.dragfinishTransition(t)); }, dragstartTransition: function(e) { if (!this.$.animator.isAnimating()) { var t = this.fromIndex = this.index; this.toIndex = t - (this.layout ? this.layout.calcDragDirection(e) : 0); } else this.verifyDragTransition(e); this.fromIndex = this.clamp(this.fromIndex), this.toIndex = this.clamp(this.toIndex), this.fireTransitionStart(), this.layout && this.layout.start(); }, dragTransition: function(e) { var t = this.layout ? this.layout.calcDrag(e) : 0, n = this.transitionPoints, r = n[0], i = n[n.length - 1], s = this.fetchArrangement(r), o = this.fetchArrangement(i), u = this.layout ? this.layout.drag(t, r, s, i, o) : 0, a = t && !u; a, this.fraction += u; var f = this.fraction; if (f > 1 || f < 0 || a) (f > 0 || a) && this.dragfinishTransition(e), this.dragstartTransition(e), this.fraction = 0; this.stepTransition(); }, dragfinishTransition: function(e) { this.verifyDragTransition(e), this.setIndex(this.toIndex), this.dragging && this.fireTransitionFinish(); }, verifyDragTransition: function(e) { var t = this.layout ? this.layout.calcDragDirection(e) : 0, n = Math.min(this.fromIndex, this.toIndex), r = Math.max(this.fromIndex, this.toIndex); if (t > 0) { var i = n; n = r, r = i; } n != this.fromIndex && (this.fraction = 1 - this.fraction), this.fromIndex = n, this.toIndex = r; }, refresh: function() { this.$.animator && this.$.animator.isAnimating() && this.$.animator.stop(), this.startTransition(), this.fraction = 1, this.stepTransition(), this.finishTransition(); }, startTransition: function() { this.fromIndex = this.fromIndex != null ? this.fromIndex : this.lastIndex || 0, this.toIndex = this.toIndex != null ? this.toIndex : this.index, this.layout && this.layout.start(), this.fireTransitionStart(); }, finishTransition: function() { this.layout && this.layout.finish(), this.transitionPoints = [], this.fraction = 0, this.fromIndex = this.toIndex = null, this.fireTransitionFinish(); }, fireTransitionStart: function() { var e = this.startTransitionInfo; this.hasNode() && (!e || e.fromIndex != this.fromIndex || e.toIndex != this.toIndex) && (this.startTransitionInfo = { fromIndex: this.fromIndex, toIndex: this.toIndex }, this.doTransitionStart(enyo.clone(this.startTransitionInfo))); }, fireTransitionFinish: function() { var e = this.finishTransitionInfo; this.hasNode() && (!e || e.fromIndex != this.lastIndex || e.toIndex != this.index) && (this.finishTransitionInfo = { fromIndex: this.lastIndex, toIndex: this.index }, this.doTransitionFinish(enyo.clone(this.finishTransitionInfo))), this.lastIndex = this.index; }, stepTransition: function() { if (this.hasNode()) { var e = this.transitionPoints, t = (this.fraction || 0) * (e.length - 1), n = Math.floor(t); t -= n; var r = e[n], i = e[n + 1], s = this.fetchArrangement(r), o = this.fetchArrangement(i); this.arrangement = s && o ? enyo.Panels.lerp(s, o, t) : s || o, this.arrangement && this.layout && this.layout.flowArrangement(); } }, fetchArrangement: function(e) { return e != null && !this.arrangements[e] && this.layout && (this.layout._arrange(e), this.arrangements[e] = this.readArrangement(this.getPanels())), this.arrangements[e]; }, readArrangement: function(e) { var t = []; for (var n = 0, r = e, i; i = r[n]; n++) t.push(enyo.clone(i._arranger)); return t; }, statics: { isScreenNarrow: function() { return enyo.dom.getWindowWidth() <= 800; }, lerp: function(e, t, n) { var r = []; for (var i = 0, s = enyo.keys(e), o; o = s[i]; i++) r.push(this.lerpObject(e[o], t[o], n)); return r; }, lerpObject: function(e, t, n) { var r = enyo.clone(e), i, s; if (t) for (var o in e) i = e[o], s = t[o], i != s && (r[o] = i - (i - s) * n); return r; } } }); // Node.js enyo.kind({ name: "enyo.Node", published: { expandable: !1, expanded: !1, icon: "", onlyIconExpands: !1, selected: !1 }, style: "padding: 0 0 0 16px;", content: "Node", defaultKind: "Node", classes: "enyo-node", components: [ { name: "icon", kind: "Image", showing: !1 }, { kind: "Control", name: "caption", Xtag: "span", style: "display: inline-block; padding: 4px;", allowHtml: !0 }, { kind: "Control", name: "extra", tag: "span", allowHtml: !0 } ], childClient: [ { kind: "Control", name: "box", classes: "enyo-node-box", Xstyle: "border: 1px solid orange;", components: [ { kind: "Control", name: "client", classes: "enyo-node-client", Xstyle: "border: 1px solid lightblue;" } ] } ], handlers: { ondblclick: "dblclick" }, events: { onNodeTap: "nodeTap", onNodeDblClick: "nodeDblClick", onExpand: "nodeExpand", onDestroyed: "nodeDestroyed" }, create: function() { this.inherited(arguments), this.selectedChanged(), this.iconChanged(); }, destroy: function() { this.doDestroyed(), this.inherited(arguments); }, initComponents: function() { this.expandable && (this.kindComponents = this.kindComponents.concat(this.childClient)), this.inherited(arguments); }, contentChanged: function() { this.$.caption.setContent(this.content); }, iconChanged: function() { this.$.icon.setSrc(this.icon), this.$.icon.setShowing(Boolean(this.icon)); }, selectedChanged: function() { this.addRemoveClass("enyo-selected", this.selected); }, rendered: function() { this.inherited(arguments), this.expandable && !this.expanded && this.quickCollapse(); }, addNodes: function(e) { this.destroyClientControls(); for (var t = 0, n; n = e[t]; t++) this.createComponent(n); this.$.client.render(); }, addTextNodes: function(e) { this.destroyClientControls(); for (var t = 0, n; n = e[t]; t++) this.createComponent({ content: n }); this.$.client.render(); }, tap: function(e, t) { return this.onlyIconExpands ? t.target == this.$.icon.hasNode() ? this.toggleExpanded() : this.doNodeTap() : (this.toggleExpanded(), this.doNodeTap()), !0; }, dblclick: function(e, t) { return this.doNodeDblClick(), !0; }, toggleExpanded: function() { this.setExpanded(!this.expanded); }, quickCollapse: function() { this.removeClass("enyo-animate"), this.$.box.applyStyle("height", "0"); var e = this.$.client.getBounds().height; this.$.client.setBounds({ top: -e }); }, _expand: function() { this.addClass("enyo-animate"); var e = this.$.client.getBounds().height; this.$.box.setBounds({ height: e }), this.$.client.setBounds({ top: 0 }), setTimeout(enyo.bind(this, function() { this.expanded && (this.removeClass("enyo-animate"), this.$.box.applyStyle("height", "auto")); }), 225); }, _collapse: function() { this.removeClass("enyo-animate"); var e = this.$.client.getBounds().height; this.$.box.setBounds({ height: e }), setTimeout(enyo.bind(this, function() { this.addClass("enyo-animate"), this.$.box.applyStyle("height", "0"), this.$.client.setBounds({ top: -e }); }), 25); }, expandedChanged: function(e) { if (!this.expandable) this.expanded = !1; else { var t = { expanded: this.expanded }; this.doExpand(t), t.wait || this.effectExpanded(); } }, effectExpanded: function() { this.$.client && (this.expanded ? this._expand() : this._collapse()); } }); // ImageViewPin.js enyo.kind({ name: "enyo.ImageViewPin", kind: "enyo.Control", published: { highlightAnchorPoint: !1, anchor: { top: 0, left: 0 }, position: { top: 0, left: 0 } }, style: "position:absolute;z-index:1000;width:0px;height:0px;", handlers: { onPositionPin: "reAnchor" }, create: function() { this.inherited(arguments), this.styleClientControls(), this.positionClientControls(), this.highlightAnchorPointChanged(), this.anchorChanged(); }, styleClientControls: function() { var e = this.getClientControls(); for (var t = 0; t < e.length; t++) e[t].applyStyle("position", "absolute"); }, positionClientControls: function() { var e = this.getClientControls(); for (var t = 0; t < e.length; t++) for (p in this.position) e[t].applyStyle(p, this.position[p] + "px"); }, highlightAnchorPointChanged: function() { this.highlightAnchorPoint ? this.addClass("pinDebug") : this.removeClass("pinDebug"); }, anchorChanged: function() { var e = null, t = null; for (t in this.anchor) { e = this.anchor[t].toString().match(/^(\d+(?:\.\d+)?)(.*)$/); if (!e) continue; this.anchor[t + "Coords"] = { value: e[1], units: e[2] || "px" }; } }, reAnchor: function(e, t) { var n = t.scale, r = t.bounds, i = this.anchor.right ? this.anchor.rightCoords.units == "px" ? r.width + r.x - this.anchor.rightCoords.value * n : r.width * (100 - this.anchor.rightCoords.value) / 100 + r.x : this.anchor.leftCoords.units == "px" ? this.anchor.leftCoords.value * n + r.x : r.width * this.anchor.leftCoords.value / 100 + r.x, s = this.anchor.bottom ? this.anchor.bottomCoords.units == "px" ? r.height + r.y - this.anchor.bottomCoords.value * n : r.height * (100 - this.anchor.bottomCoords.value) / 100 + r.y : this.anchor.topCoords.units == "px" ? this.anchor.topCoords.value * n + r.y : r.height * this.anchor.topCoords.value / 100 + r.y; this.applyStyle("left", i + "px"), this.applyStyle("top", s + "px"); } }); // ImageView.js enyo.kind({ name: "enyo.ImageView", kind: enyo.Scroller, touchOverscroll: !1, thumb: !1, animate: !0, verticalDragPropagation: !0, horizontalDragPropagation: !0, published: { scale: "auto", disableZoom: !1, src: undefined }, events: { onZoom: "" }, touch: !0, preventDragPropagation: !1, handlers: { ondragstart: "dragPropagation" }, components: [ { name: "animator", kind: "Animator", onStep: "zoomAnimationStep", onEnd: "zoomAnimationEnd" }, { name: "viewport", style: "overflow:hidden;min-height:100%;min-width:100%;", classes: "enyo-fit", ongesturechange: "gestureTransform", ongestureend: "saveState", ontap: "singleTap", ondblclick: "doubleClick", onmousewheel: "mousewheel", components: [ { kind: "Image", ondown: "down" } ] } ], create: function() { this.inherited(arguments), this.canTransform = enyo.dom.canTransform(), this.canTransform || this.$.image.applyStyle("position", "relative"), this.canAccelerate = enyo.dom.canAccelerate(), this.bufferImage = new Image, this.bufferImage.onload = enyo.bind(this, "imageLoaded"), this.bufferImage.onerror = enyo.bind(this, "imageError"), this.srcChanged(), this.getStrategy().setDragDuringGesture(!1), this.getStrategy().$.scrollMath.start(); }, down: function(e, t) { t.preventDefault(); }, dragPropagation: function(e, t) { var n = this.getStrategy().getScrollBounds(), r = n.top === 0 && t.dy > 0 || n.top >= n.maxTop - 2 && t.dy < 0, i = n.left === 0 && t.dx > 0 || n.left >= n.maxLeft - 2 && t.dx < 0; return !(r && this.verticalDragPropagation || i && this.horizontalDragPropagation); }, mousewheel: function(e, t) { t.pageX |= t.clientX + t.target.scrollLeft, t.pageY |= t.clientY + t.target.scrollTop; var n = (this.maxScale - this.minScale) / 10, r = this.scale; if (t.wheelDelta > 0 || t.detail < 0) this.scale = this.limitScale(this.scale + n); else if (t.wheelDelta < 0 || t.detail > 0) this.scale = this.limitScale(this.scale - n); return this.eventPt = this.calcEventLocation(t), this.transformImage(this.scale), r != this.scale && this.doZoom({ scale: this.scale }), this.ratioX = this.ratioY = null, t.preventDefault(), !0; }, srcChanged: function() { this.src && this.src.length > 0 && this.bufferImage && this.src != this.bufferImage.src && (this.bufferImage.src = this.src); }, imageLoaded: function(e) { this.originalWidth = this.bufferImage.width, this.originalHeight = this.bufferImage.height, this.scaleChanged(), this.$.image.setSrc(this.bufferImage.src), enyo.dom.transformValue(this.getStrategy().$.client, "translate3d", "0px, 0px, 0"), this.positionClientControls(this.scale); }, resizeHandler: function() { this.inherited(arguments), this.$.image.src && this.scaleChanged(); }, scaleChanged: function() { var e = this.hasNode(); if (e) { this.containerWidth = e.clientWidth, this.containerHeight = e.clientHeight; var t = this.containerWidth / this.originalWidth, n = this.containerHeight / this.originalHeight; this.minScale = Math.min(t, n), this.maxScale = this.minScale * 3 < 1 ? 1 : this.minScale * 3, this.scale == "auto" ? this.scale = this.minScale : this.scale == "width" ? this.scale = t : this.scale == "height" ? this.scale = n : (this.maxScale = Math.max(this.maxScale, this.scale), this.scale = this.limitScale(this.scale)); } this.eventPt = this.calcEventLocation(), this.transformImage(this.scale); }, imageError: function(e) { enyo.error("Error loading image: " + this.src), this.bubble("onerror", e); }, gestureTransform: function(e, t) { this.eventPt = this.calcEventLocation(t), this.transformImage(this.limitScale(this.scale * t.scale)); }, calcEventLocation: function(e) { var t = { x: 0, y: 0 }; if (e && this.hasNode()) { var n = this.node.getBoundingClientRect(); t.x = Math.round(e.pageX - n.left - this.imageBounds.x), t.x = Math.max(0, Math.min(this.imageBounds.width, t.x)), t.y = Math.round(e.pageY - n.top - this.imageBounds.y), t.y = Math.max(0, Math.min(this.imageBounds.height, t.y)); } return t; }, transformImage: function(e) { this.tapped = !1; var t = this.imageBounds || this.innerImageBounds(e); this.imageBounds = this.innerImageBounds(e), this.scale > this.minScale ? this.$.viewport.applyStyle("cursor", "move") : this.$.viewport.applyStyle("cursor", null), this.$.viewport.setBounds({ width: this.imageBounds.width + "px", height: this.imageBounds.height + "px" }), this.ratioX = this.ratioX || (this.eventPt.x + this.getScrollLeft()) / t.width, this.ratioY = this.ratioY || (this.eventPt.y + this.getScrollTop()) / t.height; var n, r; this.$.animator.ratioLock ? (n = this.$.animator.ratioLock.x * this.imageBounds.width - this.containerWidth / 2, r = this.$.animator.ratioLock.y * this.imageBounds.height - this.containerHeight / 2) : (n = this.ratioX * this.imageBounds.width - this.eventPt.x, r = this.ratioY * this.imageBounds.height - this.eventPt.y), n = Math.max(0, Math.min(this.imageBounds.width - this.containerWidth, n)), r = Math.max(0, Math.min(this.imageBounds.height - this.containerHeight, r)); if (this.canTransform) { var i = { scale: e }; this.canAccelerate ? i = enyo.mixin({ translate3d: Math.round(this.imageBounds.left) + "px, " + Math.round(this.imageBounds.top) + "px, 0px" }, i) : i = enyo.mixin({ translate: this.imageBounds.left + "px, " + this.imageBounds.top + "px" }, i), enyo.dom.transform(this.$.image, i); } else this.$.image.setBounds({ width: this.imageBounds.width + "px", height: this.imageBounds.height + "px", left: this.imageBounds.left + "px", top: this.imageBounds.top + "px" }); this.setScrollLeft(n), this.setScrollTop(r), this.positionClientControls(e); }, limitScale: function(e) { return this.disableZoom ? e = this.scale : e > this.maxScale ? e = this.maxScale : e < this.minScale && (e = this.minScale), e; }, innerImageBounds: function(e) { var t = this.originalWidth * e, n = this.originalHeight * e, r = { x: 0, y: 0, transX: 0, transY: 0 }; return t < this.containerWidth && (r.x += (this.containerWidth - t) / 2), n < this.containerHeight && (r.y += (this.containerHeight - n) / 2), this.canTransform && (r.transX -= (this.originalWidth - t) / 2, r.transY -= (this.originalHeight - n) / 2), { left: r.x + r.transX, top: r.y + r.transY, width: t, height: n, x: r.x, y: r.y }; }, saveState: function(e, t) { var n = this.scale; this.scale *= t.scale, this.scale = this.limitScale(this.scale), n != this.scale && this.doZoom({ scale: this.scale }), this.ratioX = this.ratioY = null; }, doubleClick: function(e, t) { enyo.platform.ie == 8 && (this.tapped = !0, t.pageX = t.clientX + t.target.scrollLeft, t.pageY = t.clientY + t.target.scrollTop, this.singleTap(e, t), t.preventDefault()); }, singleTap: function(e, t) { setTimeout(enyo.bind(this, function() { this.tapped = !1; }), 300), this.tapped ? (this.tapped = !1, this.smartZoom(e, t)) : this.tapped = !0; }, smartZoom: function(e, t) { var n = this.hasNode(), r = this.$.image.hasNode(); if (n && r && this.hasNode() && !this.disableZoom) { var i = this.scale; this.scale != this.minScale ? this.scale = this.minScale : this.scale = this.maxScale, this.eventPt = this.calcEventLocation(t); if (this.animate) { var s = { x: (this.eventPt.x + this.getScrollLeft()) / this.imageBounds.width, y: (this.eventPt.y + this.getScrollTop()) / this.imageBounds.height }; this.$.animator.play({ duration: 350, ratioLock: s, baseScale: i, deltaScale: this.scale - i }); } else this.transformImage(this.scale), this.doZoom({ scale: this.scale }); } }, zoomAnimationStep: function(e, t) { var n = this.$.animator.baseScale + this.$.animator.deltaScale * this.$.animator.value; this.transformImage(n); }, zoomAnimationEnd: function(e, t) { this.doZoom({ scale: this.scale }), this.$.animator.ratioLock = undefined; }, positionClientControls: function(e) { this.waterfallDown("onPositionPin", { scale: e, bounds: this.imageBounds }); } }); // ImageCarousel.js enyo.kind({ name: "enyo.ImageCarousel", kind: enyo.Panels, arrangerKind: "enyo.CarouselArranger", defaultScale: "auto", disableZoom: !1, lowMemory: !1, published: { images: [] }, handlers: { onTransitionStart: "transitionStart", onTransitionFinish: "transitionFinish" }, create: function() { this.inherited(arguments), this.imageCount = this.images.length, this.images.length > 0 && (this.initContainers(), this.loadNearby()); }, initContainers: function() { for (var e = 0; e < this.images.length; e++) this.$["container" + e] || (this.createComponent({ name: "container" + e, style: "height:100%; width:100%;" }), this.$["container" + e].render()); for (e = this.images.length; e < this.imageCount; e++) this.$["image" + e] && this.$["image" + e].destroy(), this.$["container" + e].destroy(); this.imageCount = this.images.length; }, loadNearby: function() { this.images.length > 0 && (this.loadImageView(this.index - 1), this.loadImageView(this.index), this.loadImageView(this.index + 1)); }, loadImageView: function(e) { return this.wrap && (e = (e % this.images.length + this.images.length) % this.images.length), e >= 0 && e <= this.images.length - 1 && (this.$["image" + e] ? (this.$["image" + e].src != this.images[e] && this.$["image" + e].setSrc(this.images[e]), this.$["image" + e].setScale(this.defaultScale), this.$["image" + e].setDisableZoom(this.disableZoom)) : (this.$["container" + e].createComponent({ name: "image" + e, kind: "ImageView", scale: this.defaultScale, disableZoom: this.disableZoom, src: this.images[e], verticalDragPropagation: !1, style: "height:100%; width:100%;" }, { owner: this }), this.$["image" + e].render())), this.$["image" + e]; }, setImages: function(e) { this.setPropertyValue("images", e, "imagesChanged"); }, imagesChanged: function() { this.initContainers(), this.loadNearby(); }, indexChanged: function() { this.loadNearby(), this.lowMemory && this.cleanupMemory(), this.inherited(arguments); }, transitionStart: function(e, t) { if (t.fromIndex == t.toIndex) return !0; }, transitionFinish: function(e, t) { this.loadImageView(this.index - 1), this.loadImageView(this.index + 1), this.lowMemory && this.cleanupMemory(); }, getActiveImage: function() { return this.getImageByIndex(this.index); }, getImageByIndex: function(e) { return this.$["image" + e] || this.loadImageView(e); }, cleanupMemory: function() { for (var e = 0; e < this.images.length; e++) (e < this.index - 1 || e > this.index + 1) && this.$["image" + e] && this.$["image" + e].destroy(); } }); // Icon.js enyo.kind({ name: "onyx.Icon", published: { src: "", disabled: !1 }, classes: "onyx-icon", create: function() { this.inherited(arguments), this.src && this.srcChanged(), this.disabledChanged(); }, disabledChanged: function() { this.addRemoveClass("disabled", this.disabled); }, srcChanged: function() { this.applyStyle("background-image", "url(" + enyo.path.rewrite(this.src) + ")"); } }); // Button.js enyo.kind({ name: "onyx.Button", kind: "enyo.Button", classes: "onyx-button enyo-unselectable" }); // IconButton.js enyo.kind({ name: "onyx.IconButton", kind: "onyx.Icon", published: { active: !1 }, classes: "onyx-icon-button", rendered: function() { this.inherited(arguments), this.activeChanged(); }, tap: function() { if (this.disabled) return !0; this.setActive(!0); }, activeChanged: function() { this.bubble("onActivate"); } }); // Checkbox.js enyo.kind({ name: "onyx.Checkbox", classes: "onyx-checkbox", kind: enyo.Checkbox, tag: "div", handlers: { ondown: "downHandler", onclick: "" }, downHandler: function(e, t) { return this.disabled || (this.setChecked(!this.getChecked()), this.bubble("onchange")), !0; }, tap: function(e, t) { return !this.disabled; } }); // Drawer.js enyo.kind({ name: "onyx.Drawer", published: { open: !0, orient: "v", animated: !0 }, style: "overflow: hidden; position: relative;", tools: [ { kind: "Animator", onStep: "animatorStep", onEnd: "animatorEnd" }, { name: "client", style: "position: relative;", classes: "enyo-border-box" } ], create: function() { this.inherited(arguments), this.animatedChanged(), this.openChanged(); }, initComponents: function() { this.createChrome(this.tools), this.inherited(arguments); }, animatedChanged: function() { !this.animated && this.hasNode() && this.$.animator.isAnimating() && (this.$.animator.stop(), this.animatorEnd()); }, openChanged: function() { this.$.client.show(); if (this.hasNode()) if (this.$.animator.isAnimating()) this.$.animator.reverse(); else { var e = this.orient == "v", t = e ? "height" : "width", n = e ? "top" : "left"; this.applyStyle(t, null); var r = this.hasNode()[e ? "scrollHeight" : "scrollWidth"]; this.animated ? this.$.animator.play({ startValue: this.open ? 0 : r, endValue: this.open ? r : 0, dimension: t, position: n }) : this.animatorEnd(); } else this.$.client.setShowing(this.open); }, animatorStep: function(e) { if (this.hasNode()) { var t = e.dimension; this.node.style[t] = this.domStyles[t] = e.value + "px"; } var n = this.$.client.hasNode(); if (n) { var r = e.position, i = this.open ? e.endValue : e.startValue; n.style[r] = this.$.client.domStyles[r] = e.value - i + "px"; } this.container && this.container.resized(); }, animatorEnd: function() { if (!this.open) this.$.client.hide(); else { var e = this.orient == "v", t = e ? "height" : "width", n = e ? "top" : "left", r = this.$.client.hasNode(); r && (r.style[n] = this.$.client.domStyles[n] = null), this.node && (this.node.style[t] = this.domStyles[t] = null); } this.container && this.container.resized(); } }); // Grabber.js enyo.kind({ name: "onyx.Grabber", classes: "onyx-grabber" }); // Groupbox.js enyo.kind({ name: "onyx.Groupbox", classes: "onyx-groupbox" }), enyo.kind({ name: "onyx.GroupboxHeader", classes: "onyx-groupbox-header" }); // Input.js enyo.kind({ name: "onyx.Input", kind: "enyo.Input", classes: "onyx-input" }); // Popup.js enyo.kind({ name: "onyx.Popup", kind: "Popup", classes: "onyx-popup", published: { scrimWhenModal: !0, scrim: !1, scrimClassName: "" }, statics: { count: 0 }, defaultZ: 120, showingChanged: function() { this.showing ? (onyx.Popup.count++, this.applyZIndex()) : onyx.Popup.count > 0 && onyx.Popup.count--, this.showHideScrim(this.showing), this.inherited(arguments); }, showHideScrim: function(e) { if (this.floating && (this.scrim || this.modal && this.scrimWhenModal)) { var t = this.getScrim(); if (e) { var n = this.getScrimZIndex(); this._scrimZ = n, t.showAtZIndex(n); } else t.hideAtZIndex(this._scrimZ); enyo.call(t, "addRemoveClass", [ this.scrimClassName, t.showing ]); } }, getScrimZIndex: function() { return this.findZIndex() - 1; }, getScrim: function() { return this.modal && this.scrimWhenModal && !this.scrim ? onyx.scrimTransparent.make() : onyx.scrim.make(); }, applyZIndex: function() { this._zIndex = onyx.Popup.count * 2 + this.findZIndex() + 1, this.applyStyle("z-index", this._zIndex); }, findZIndex: function() { var e = this.defaultZ; return this._zIndex ? e = this._zIndex : this.hasNode() && (e = Number(enyo.dom.getComputedStyleValue(this.node, "z-index")) || e), this._zIndex = e; } }); // TextArea.js enyo.kind({ name: "onyx.TextArea", kind: "enyo.TextArea", classes: "onyx-textarea" }); // RichText.js enyo.kind({ name: "onyx.RichText", kind: "enyo.RichText", classes: "onyx-richtext" }); // InputDecorator.js enyo.kind({ name: "onyx.InputDecorator", kind: "enyo.ToolDecorator", tag: "label", classes: "onyx-input-decorator", published: { alwaysLooksFocused: !1 }, handlers: { onDisabledChange: "disabledChange", onfocus: "receiveFocus", onblur: "receiveBlur" }, create: function() { this.inherited(arguments), this.updateFocus(!1); }, alwaysLooksFocusedChanged: function(e) { this.updateFocus(this.focus); }, updateFocus: function(e) { this.focused = e, this.addRemoveClass("onyx-focused", this.alwaysLooksFocused || this.focused); }, receiveFocus: function() { this.updateFocus(!0); }, receiveBlur: function() { this.updateFocus(!1); }, disabledChange: function(e, t) { this.addRemoveClass("onyx-disabled", t.originator.disabled); } }); // Tooltip.js enyo.kind({ name: "onyx.Tooltip", kind: "onyx.Popup", classes: "onyx-tooltip below left-arrow", autoDismiss: !1, showDelay: 500, defaultLeft: -6, handlers: { onRequestShowTooltip: "requestShow", onRequestHideTooltip: "requestHide" }, requestShow: function() { return this.showJob = setTimeout(enyo.bind(this, "show"), this.showDelay), !0; }, cancelShow: function() { clearTimeout(this.showJob); }, requestHide: function() { return this.cancelShow(), this.inherited(arguments); }, showingChanged: function() { this.cancelShow(), this.adjustPosition(!0), this.inherited(arguments); }, applyPosition: function(e) { var t = ""; for (var n in e) t += n + ":" + e[n] + (isNaN(e[n]) ? "; " : "px; "); this.addStyles(t); }, adjustPosition: function(e) { if (this.showing && this.hasNode()) { var t = this.node.getBoundingClientRect(); t.top + t.height > window.innerHeight ? (this.addRemoveClass("below", !1), this.addRemoveClass("above", !0)) : (this.addRemoveClass("above", !1), this.addRemoveClass("below", !0)), t.left + t.width > window.innerWidth && (this.applyPosition({ "margin-left": -t.width, bottom: "auto" }), this.addRemoveClass("left-arrow", !1), this.addRemoveClass("right-arrow", !0)); } }, resizeHandler: function() { this.applyPosition({ "margin-left": this.defaultLeft, bottom: "auto" }), this.addRemoveClass("left-arrow", !0), this.addRemoveClass("right-arrow", !1), this.adjustPosition(!0), this.inherited(arguments); } }); // TooltipDecorator.js enyo.kind({ name: "onyx.TooltipDecorator", defaultKind: "onyx.Button", classes: "onyx-popup-decorator", handlers: { onenter: "enter", onleave: "leave" }, enter: function() { this.requestShowTooltip(); }, leave: function() { this.requestHideTooltip(); }, tap: function() { this.requestHideTooltip(); }, requestShowTooltip: function() { this.waterfallDown("onRequestShowTooltip"); }, requestHideTooltip: function() { this.waterfallDown("onRequestHideTooltip"); } }); // MenuDecorator.js enyo.kind({ name: "onyx.MenuDecorator", kind: "onyx.TooltipDecorator", defaultKind: "onyx.Button", classes: "onyx-popup-decorator enyo-unselectable", handlers: { onActivate: "activated", onHide: "menuHidden" }, activated: function(e, t) { this.requestHideTooltip(), t.originator.active && (this.menuActive = !0, this.activator = t.originator, this.activator.addClass("active"), this.requestShowMenu()); }, requestShowMenu: function() { this.waterfallDown("onRequestShowMenu", { activator: this.activator }); }, requestHideMenu: function() { this.waterfallDown("onRequestHideMenu"); }, menuHidden: function() { this.menuActive = !1, this.activator && (this.activator.setActive(!1), this.activator.removeClass("active")); }, enter: function(e) { this.menuActive || this.inherited(arguments); }, leave: function(e, t) { this.menuActive || this.inherited(arguments); } }); // Menu.js enyo.kind({ name: "onyx.Menu", kind: "onyx.Popup", modal: !0, defaultKind: "onyx.MenuItem", classes: "onyx-menu", published: { maxHeight: 200, scrolling: !0 }, handlers: { onActivate: "itemActivated", onRequestShowMenu: "requestMenuShow", onRequestHideMenu: "requestHide" }, childComponents: [ { name: "client", kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy" } ], showOnTop: !1, scrollerName: "client", create: function() { this.inherited(arguments), this.maxHeightChanged(); }, initComponents: function() { this.scrolling ? this.createComponents(this.childComponents, { isChrome: !0 }) : enyo.nop, this.inherited(arguments); }, getScroller: function() { return this.$[this.scrollerName]; }, maxHeightChanged: function() { this.scrolling ? this.getScroller().setMaxHeight(this.maxHeight + "px") : enyo.nop; }, itemActivated: function(e, t) { return t.originator.setActive(!1), !0; }, showingChanged: function() { this.inherited(arguments), this.scrolling ? this.getScroller().setShowing(this.showing) : enyo.nop, this.adjustPosition(!0); }, requestMenuShow: function(e, t) { if (this.floating) { var n = t.activator.hasNode(); if (n) { var r = this.activatorOffset = this.getPageOffset(n); this.applyPosition({ top: r.top + (this.showOnTop ? 0 : r.height), left: r.left, width: r.width }); } } return this.show(), !0; }, applyPosition: function(e) { var t = ""; for (n in e) t += n + ":" + e[n] + (isNaN(e[n]) ? "; " : "px; "); this.addStyles(t); }, getPageOffset: function(e) { var t = e.getBoundingClientRect(), n = window.pageYOffset === undefined ? document.documentElement.scrollTop : window.pageYOffset, r = window.pageXOffset === undefined ? document.documentElement.scrollLeft : window.pageXOffset, i = t.height === undefined ? t.bottom - t.top : t.height, s = t.width === undefined ? t.right - t.left : t.width; return { top: t.top + n, left: t.left + r, height: i, width: s }; }, adjustPosition: function() { if (this.showing && this.hasNode()) { this.scrolling && !this.showOnTop ? this.getScroller().setMaxHeight(this.maxHeight + "px") : enyo.nop, this.removeClass("onyx-menu-up"), this.floating ? enyo.nop : this.applyPosition({ left: "auto" }); var e = this.node.getBoundingClientRect(), t = e.height === undefined ? e.bottom - e.top : e.height, n = window.innerHeight === undefined ? document.documentElement.clientHeight : window.innerHeight, r = window.innerWidth === undefined ? document.documentElement.clientWidth : window.innerWidth; this.menuUp = e.top + t > n && n - e.bottom < e.top - t, this.addRemoveClass("onyx-menu-up", this.menuUp); if (this.floating) { var i = this.activatorOffset; this.menuUp ? this.applyPosition({ top: i.top - t + (this.showOnTop ? i.height : 0), bottom: "auto" }) : e.top < i.top && i.top + (this.showOnTop ? 0 : i.height) + t < n && this.applyPosition({ top: i.top + (this.showOnTop ? 0 : i.height), bottom: "auto" }); } e.right > r && (this.floating ? this.applyPosition({ left: r - e.width }) : this.applyPosition({ left: -(e.right - r) })), e.left < 0 && (this.floating ? this.applyPosition({ left: 0, right: "auto" }) : this.getComputedStyleValue("right") == "auto" ? this.applyPosition({ left: -e.left }) : this.applyPosition({ right: e.left })); if (this.scrolling && !this.showOnTop) { e = this.node.getBoundingClientRect(); var s; this.menuUp ? s = this.maxHeight < e.bottom ? this.maxHeight : e.bottom : s = e.top + this.maxHeight < n ? this.maxHeight : n - e.top, this.getScroller().setMaxHeight(s + "px"); } } }, resizeHandler: function() { this.inherited(arguments), this.adjustPosition(); }, requestHide: function() { this.setShowing(!1); } }); // MenuItem.js enyo.kind({ name: "onyx.MenuItem", kind: "enyo.Button", events: { onSelect: "" }, classes: "onyx-menu-item", tag: "div", tap: function(e) { this.inherited(arguments), this.bubble("onRequestHideMenu"), this.doSelect({ selected: this, content: this.content }); } }); // PickerDecorator.js enyo.kind({ name: "onyx.PickerDecorator", kind: "onyx.MenuDecorator", classes: "onyx-picker-decorator", defaultKind: "onyx.PickerButton", handlers: { onChange: "change" }, change: function(e, t) { this.waterfallDown("onChange", t); } }); // PickerButton.js enyo.kind({ name: "onyx.PickerButton", kind: "onyx.Button", handlers: { onChange: "change" }, change: function(e, t) { t.content !== undefined && this.setContent(t.content); } }); // Picker.js enyo.kind({ name: "onyx.Picker", kind: "onyx.Menu", classes: "onyx-picker enyo-unselectable", published: { selected: null }, events: { onChange: "" }, floating: !0, showOnTop: !0, initComponents: function() { this.setScrolling(!0), this.inherited(arguments); }, showingChanged: function() { this.getScroller().setShowing(this.showing), this.inherited(arguments), this.showing && this.selected && this.scrollToSelected(); }, scrollToSelected: function() { this.getScroller().scrollToControl(this.selected, !this.menuUp); }, itemActivated: function(e, t) { return this.processActivatedItem(t.originator), this.inherited(arguments); }, processActivatedItem: function(e) { e.active && this.setSelected(e); }, selectedChanged: function(e) { e && e.removeClass("selected"), this.selected && (this.selected.addClass("selected"), this.doChange({ selected: this.selected, content: this.selected.content })); }, resizeHandler: function() { this.inherited(arguments), this.adjustPosition(); } }); // FlyweightPicker.js enyo.kind({ name: "onyx.FlyweightPicker", kind: "onyx.Picker", classes: "onyx-flyweight-picker", published: { count: 0 }, events: { onSetupItem: "", onSelect: "" }, handlers: { onSelect: "itemSelect" }, components: [ { name: "scroller", kind: "enyo.Scroller", strategyKind: "TouchScrollStrategy", components: [ { name: "flyweight", kind: "FlyweightRepeater", ontap: "itemTap" } ] } ], scrollerName: "scroller", initComponents: function() { this.controlParentName = "flyweight", this.inherited(arguments); }, create: function() { this.inherited(arguments), this.countChanged(); }, rendered: function() { this.inherited(arguments), this.selectedChanged(); }, scrollToSelected: function() { var e = this.$.flyweight.fetchRowNode(this.selected); this.getScroller().scrollToNode(e, !this.menuUp); }, countChanged: function() { this.$.flyweight.count = this.count; }, processActivatedItem: function(e) { this.item = e; }, selectedChanged: function(e) { if (!this.item) return; e !== undefined && (this.item.removeClass("selected"), this.$.flyweight.renderRow(e)), this.item.addClass("selected"), this.$.flyweight.renderRow(this.selected), this.item.removeClass("selected"); var t = this.$.flyweight.fetchRowNode(this.selected); this.doChange({ selected: this.selected, content: t && t.textContent || this.item.content }); }, itemTap: function(e, t) { this.setSelected(t.rowIndex), this.doSelect({ selected: this.item, content: this.item.content }); }, itemSelect: function(e, t) { if (t.originator != this) return !0; } }); // DatePicker.js enyo.kind({ name: "onyx.DatePicker", classes: "onyx-toolbar-inline", published: { disabled: !1, locale: "en_us", dayHidden: !1, monthHidden: !1, yearHidden: !1, minYear: 1900, maxYear: 2099, value: null }, events: { onSelect: "" }, create: function() { this.inherited(arguments), enyo.g11n && (this.locale = enyo.g11n.currentLocale().getLocale()), this.initDefaults(); }, initDefaults: function() { var e = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ]; enyo.g11n && (this._tf = new enyo.g11n.Fmts({ locale: this.locale }), e = this._tf.getMonthFields()), this.setupPickers(this._tf ? this._tf.getDateFieldOrder() : "mdy"), this.dayHiddenChanged(), this.monthHiddenChanged(), this.yearHiddenChanged(); var t = this.value = this.value || new Date; for (var n = 0, r; r = e[n]; n++) this.$.monthPicker.createComponent({ content: r, value: n, active: n == t.getMonth() }); var i = t.getFullYear(); this.$.yearPicker.setSelected(i - this.minYear), this.$.year.setContent(i); for (n = 1; n <= this.monthLength(t.getYear(), t.getMonth()); n++) this.$.dayPicker.createComponent({ content: n, value: n, active: n == t.getDate() }); }, monthLength: function(e, t) { return 32 - (new Date(e, t, 32)).getDate(); }, setupYear: function(e, t) { this.$.year.setContent(this.minYear + t.index); }, setupPickers: function(e) { var t = e.split(""), n, r, i; for (r = 0, i = t.length; r < i; r++) { n = t[r]; switch (n) { case "d": this.createDay(); break; case "m": this.createMonth(); break; case "y": this.createYear(); break; default: } } }, createYear: function() { var e = this.maxYear - this.minYear; this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateYear", components: [ { classes: "onyx-datepicker-year", name: "yearPickerButton", disabled: this.disabled }, { name: "yearPicker", kind: "onyx.FlyweightPicker", count: ++e, onSetupItem: "setupYear", components: [ { name: "year" } ] } ] }); }, createMonth: function() { this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateMonth", components: [ { classes: "onyx-datepicker-month", name: "monthPickerButton", disabled: this.disabled }, { name: "monthPicker", kind: "onyx.Picker" } ] }); }, createDay: function() { this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateDay", components: [ { classes: "onyx-datepicker-day", name: "dayPickerButton", disabled: this.disabled }, { name: "dayPicker", kind: "onyx.Picker" } ] }); }, localeChanged: function() { this.refresh(); }, dayHiddenChanged: function() { this.$.dayPicker.getParent().setShowing(this.dayHidden ? !1 : !0); }, monthHiddenChanged: function() { this.$.monthPicker.getParent().setShowing(this.monthHidden ? !1 : !0); }, yearHiddenChanged: function() { this.$.yearPicker.getParent().setShowing(this.yearHidden ? !1 : !0); }, minYearChanged: function() { this.refresh(); }, maxYearChanged: function() { this.refresh(); }, valueChanged: function() { this.refresh(); }, disabledChanged: function() { this.$.yearPickerButton.setDisabled(this.disabled), this.$.monthPickerButton.setDisabled(this.disabled), this.$.dayPickerButton.setDisabled(this.disabled); }, updateDay: function(e, t) { var n = this.calcDate(this.value.getFullYear(), this.value.getMonth(), t.selected.value); return this.doSelect({ name: this.name, value: n }), this.setValue(n), !0; }, updateMonth: function(e, t) { var n = this.calcDate(this.value.getFullYear(), t.selected.value, this.value.getDate()); return this.doSelect({ name: this.name, value: n }), this.setValue(n), !0; }, updateYear: function(e, t) { if (t.originator.selected != -1) { var n = this.calcDate(this.minYear + t.originator.selected, this.value.getMonth(), this.value.getDate()); this.doSelect({ name: this.name, value: n }), this.setValue(n); } return !0; }, calcDate: function(e, t, n) { return new Date(e, t, n, this.value.getHours(), this.value.getMinutes(), this.value.getSeconds(), this.value.getMilliseconds()); }, refresh: function() { this.destroyClientControls(), this.initDefaults(), this.render(); } }); // TimePicker.js enyo.kind({ name: "onyx.TimePicker", classes: "onyx-toolbar-inline", published: { disabled: !1, locale: "en_us", is24HrMode: null, value: null }, events: { onSelect: "" }, create: function() { this.inherited(arguments), enyo.g11n && (this.locale = enyo.g11n.currentLocale().getLocale()), this.initDefaults(); }, initDefaults: function() { var e = "AM", t = "PM"; this.is24HrMode == null && (this.is24HrMode = !1), enyo.g11n && (this._tf = new enyo.g11n.Fmts({ locale: this.locale }), e = this._tf.getAmCaption(), t = this._tf.getPmCaption(), this.is24HrMode == null && (this.is24HrMode = !this._tf.isAmPm())), this.setupPickers(this._tf ? this._tf.getTimeFieldOrder() : "hma"); var n = this.value = this.value || new Date, r; if (!this.is24HrMode) { var i = n.getHours(); i = i === 0 ? 12 : i; for (r = 1; r <= 12; r++) this.$.hourPicker.createComponent({ content: r, value: r, active: r == (i > 12 ? i % 12 : i) }); } else for (r = 0; r < 24; r++) this.$.hourPicker.createComponent({ content: r, value: r, active: r == n.getHours() }); for (r = 0; r <= 59; r++) this.$.minutePicker.createComponent({ content: r < 10 ? "0" + r : r, value: r, active: r == n.getMinutes() }); n.getHours() >= 12 ? this.$.ampmPicker.createComponents([ { content: e }, { content: t, active: !0 } ]) : this.$.ampmPicker.createComponents([ { content: e, active: !0 }, { content: t } ]), this.$.ampmPicker.getParent().setShowing(!this.is24HrMode); }, setupPickers: function(e) { var t = e.split(""), n, r, i; for (r = 0, i = t.length; r < i; r++) { n = t[r]; switch (n) { case "h": this.createHour(); break; case "m": this.createMinute(); break; case "a": this.createAmPm(); break; default: } } }, createHour: function() { this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateHour", components: [ { classes: "onyx-timepicker-hour", name: "hourPickerButton", disabled: this.disabled }, { name: "hourPicker", kind: "onyx.Picker" } ] }); }, createMinute: function() { this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateMinute", components: [ { classes: "onyx-timepicker-minute", name: "minutePickerButton", disabled: this.disabled }, { name: "minutePicker", kind: "onyx.Picker" } ] }); }, createAmPm: function() { this.createComponent({ kind: "onyx.PickerDecorator", onSelect: "updateAmPm", components: [ { classes: "onyx-timepicker-ampm", name: "ampmPickerButton", disabled: this.disabled }, { name: "ampmPicker", kind: "onyx.Picker" } ] }); }, disabledChanged: function() { this.$.hourPickerButton.setDisabled(this.disabled), this.$.minutePickerButton.setDisabled(this.disabled), this.$.ampmPickerButton.setDisabled(this.disabled); }, localeChanged: function() { this.is24HrMode = null, this.refresh(); }, is24HrModeChanged: function() { this.refresh(); }, valueChanged: function() { this.refresh(); }, updateHour: function(e, t) { var n = t.selected.value; if (!this.is24HrMode) { var r = this.$.ampmPicker.getParent().controlAtIndex(0).content; n = n + (n == 12 ? -12 : 0) + (this.isAm(r) ? 0 : 12); } return this.value = this.calcTime(n, this.value.getMinutes()), this.doSelect({ name: this.name, value: this.value }), !0; }, updateMinute: function(e, t) { return this.value = this.calcTime(this.value.getHours(), t.selected.value), this.doSelect({ name: this.name, value: this.value }), !0; }, updateAmPm: function(e, t) { var n = this.value.getHours(); return this.is24HrMode || (n += n > 11 ? this.isAm(t.content) ? -12 : 0 : this.isAm(t.content) ? 0 : 12), this.value = this.calcTime(n, this.value.getMinutes()), this.doSelect({ name: this.name, value: this.value }), !0; }, calcTime: function(e, t) { return new Date(this.value.getFullYear(), this.value.getMonth(), this.value.getDate(), e, t, this.value.getSeconds(), this.value.getMilliseconds()); }, isAm: function(e) { var t, n, r; try { t = this._tf.getAmCaption(), n = this._tf.getPmCaption(); } catch (i) { t = "AM", n = "PM"; } return e == t ? !0 : !1; }, refresh: function() { this.destroyClientControls(), this.initDefaults(), this.render(); } }); // RadioButton.js enyo.kind({ name: "onyx.RadioButton", kind: "Button", classes: "onyx-radiobutton" }); // RadioGroup.js enyo.kind({ name: "onyx.RadioGroup", kind: "Group", defaultKind: "onyx.RadioButton", highlander: !0 }); // ToggleButton.js enyo.kind({ name: "onyx.ToggleButton", classes: "onyx-toggle-button", published: { active: !1, value: !1, onContent: "On", offContent: "Off", disabled: !1 }, events: { onChange: "" }, handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish" }, components: [ { name: "contentOn", classes: "onyx-toggle-content on" }, { name: "contentOff", classes: "onyx-toggle-content off" }, { classes: "onyx-toggle-button-knob" } ], create: function() { this.inherited(arguments), this.value = Boolean(this.value || this.active), this.onContentChanged(), this.offContentChanged(), this.disabledChanged(); }, rendered: function() { this.inherited(arguments), this.updateVisualState(); }, updateVisualState: function() { this.addRemoveClass("off", !this.value), this.$.contentOn.setShowing(this.value), this.$.contentOff.setShowing(!this.value), this.setActive(this.value); }, valueChanged: function() { this.updateVisualState(), this.doChange({ value: this.value }); }, activeChanged: function() { this.setValue(this.active), this.bubble("onActivate"); }, onContentChanged: function() { this.$.contentOn.setContent(this.onContent || ""), this.$.contentOn.addRemoveClass("empty", !this.onContent); }, offContentChanged: function() { this.$.contentOff.setContent(this.offContent || ""), this.$.contentOff.addRemoveClass("empty", !this.onContent); }, disabledChanged: function() { this.addRemoveClass("disabled", this.disabled); }, updateValue: function(e) { this.disabled || this.setValue(e); }, tap: function() { this.updateValue(!this.value); }, dragstart: function(e, t) { if (t.horizontal) return t.preventDefault(), this.dragging = !0, this.dragged = !1, !0; }, drag: function(e, t) { if (this.dragging) { var n = t.dx; return Math.abs(n) > 10 && (this.updateValue(n > 0), this.dragged = !0), !0; } }, dragfinish: function(e, t) { this.dragging = !1, this.dragged && t.preventTap(); } }); // ToggleIconButton.js enyo.kind({ name: "onyx.ToggleIconButton", kind: "onyx.Icon", published: { active: !1, value: !1 }, events: { onChange: "" }, classes: "onyx-icon-button onyx-icon-toggle", activeChanged: function() { this.addRemoveClass("active", this.value), this.bubble("onActivate"); }, updateValue: function(e) { this.disabled || (this.setValue(e), this.doChange({ value: this.value })); }, tap: function() { this.updateValue(!this.value); }, valueChanged: function() { this.setActive(this.value); }, create: function() { this.inherited(arguments), this.value = Boolean(this.value || this.active); }, rendered: function() { this.inherited(arguments), this.valueChanged(), this.removeClass("onyx-icon"); } }); // Toolbar.js enyo.kind({ name: "onyx.Toolbar", classes: "onyx onyx-toolbar onyx-toolbar-inline", create: function() { this.inherited(arguments), this.hasClass("onyx-menu-toolbar") && enyo.platform.android >= 4 && this.applyStyle("position", "static"); } }); // Tooltip.js enyo.kind({ name: "onyx.Tooltip", kind: "onyx.Popup", classes: "onyx-tooltip below left-arrow", autoDismiss: !1, showDelay: 500, defaultLeft: -6, handlers: { onRequestShowTooltip: "requestShow", onRequestHideTooltip: "requestHide" }, requestShow: function() { return this.showJob = setTimeout(enyo.bind(this, "show"), this.showDelay), !0; }, cancelShow: function() { clearTimeout(this.showJob); }, requestHide: function() { return this.cancelShow(), this.inherited(arguments); }, showingChanged: function() { this.cancelShow(), this.adjustPosition(!0), this.inherited(arguments); }, applyPosition: function(e) { var t = ""; for (var n in e) t += n + ":" + e[n] + (isNaN(e[n]) ? "; " : "px; "); this.addStyles(t); }, adjustPosition: function(e) { if (this.showing && this.hasNode()) { var t = this.node.getBoundingClientRect(); t.top + t.height > window.innerHeight ? (this.addRemoveClass("below", !1), this.addRemoveClass("above", !0)) : (this.addRemoveClass("above", !1), this.addRemoveClass("below", !0)), t.left + t.width > window.innerWidth && (this.applyPosition({ "margin-left": -t.width, bottom: "auto" }), this.addRemoveClass("left-arrow", !1), this.addRemoveClass("right-arrow", !0)); } }, resizeHandler: function() { this.applyPosition({ "margin-left": this.defaultLeft, bottom: "auto" }), this.addRemoveClass("left-arrow", !0), this.addRemoveClass("right-arrow", !1), this.adjustPosition(!0), this.inherited(arguments); } }); // TooltipDecorator.js enyo.kind({ name: "onyx.TooltipDecorator", defaultKind: "onyx.Button", classes: "onyx-popup-decorator", handlers: { onenter: "enter", onleave: "leave" }, enter: function() { this.requestShowTooltip(); }, leave: function() { this.requestHideTooltip(); }, tap: function() { this.requestHideTooltip(); }, requestShowTooltip: function() { this.waterfallDown("onRequestShowTooltip"); }, requestHideTooltip: function() { this.waterfallDown("onRequestHideTooltip"); } }); // ProgressBar.js enyo.kind({ name: "onyx.ProgressBar", classes: "onyx-progress-bar", published: { progress: 0, min: 0, max: 100, barClasses: "", showStripes: !0, animateStripes: !0 }, events: { onAnimateProgressFinish: "" }, components: [ { name: "progressAnimator", kind: "Animator", onStep: "progressAnimatorStep", onEnd: "progressAnimatorComplete" }, { name: "bar", classes: "onyx-progress-bar-bar" } ], create: function() { this.inherited(arguments), this.progressChanged(), this.barClassesChanged(), this.showStripesChanged(), this.animateStripesChanged(); }, barClassesChanged: function(e) { this.$.bar.removeClass(e), this.$.bar.addClass(this.barClasses); }, showStripesChanged: function() { this.$.bar.addRemoveClass("striped", this.showStripes); }, animateStripesChanged: function() { this.$.bar.addRemoveClass("animated", this.animateStripes); }, progressChanged: function() { this.progress = this.clampValue(this.min, this.max, this.progress); var e = this.calcPercent(this.progress); this.updateBarPosition(e); }, clampValue: function(e, t, n) { return Math.max(e, Math.min(n, t)); }, calcRatio: function(e) { return (e - this.min) / (this.max - this.min); }, calcPercent: function(e) { return this.calcRatio(e) * 100; }, updateBarPosition: function(e) { this.$.bar.applyStyle("width", e + "%"); }, animateProgressTo: function(e) { this.$.progressAnimator.play({ startValue: this.progress, endValue: e, node: this.hasNode() }); }, progressAnimatorStep: function(e) { return this.setProgress(e.value), !0; }, progressAnimatorComplete: function(e) { return this.doAnimateProgressFinish(e), !0; } }); // ProgressButton.js enyo.kind({ name: "onyx.ProgressButton", kind: "onyx.ProgressBar", classes: "onyx-progress-button", events: { onCancel: "" }, components: [ { name: "progressAnimator", kind: "Animator", onStep: "progressAnimatorStep", onEnd: "progressAnimatorComplete" }, { name: "bar", classes: "onyx-progress-bar-bar onyx-progress-button-bar" }, { name: "client", classes: "onyx-progress-button-client" }, { kind: "onyx.Icon", src: "$lib/onyx/images/progress-button-cancel.png", classes: "onyx-progress-button-icon", ontap: "cancelTap" } ], cancelTap: function() { this.doCancel(); } }); // Scrim.js enyo.kind({ name: "onyx.Scrim", showing: !1, classes: "onyx-scrim enyo-fit", floating: !1, create: function() { this.inherited(arguments), this.zStack = [], this.floating && this.setParent(enyo.floatingLayer); }, showingChanged: function() { this.floating && this.showing && !this.hasNode() && this.render(), this.inherited(arguments); }, addZIndex: function(e) { enyo.indexOf(e, this.zStack) < 0 && this.zStack.push(e); }, removeZIndex: function(e) { enyo.remove(e, this.zStack); }, showAtZIndex: function(e) { this.addZIndex(e), e !== undefined && this.setZIndex(e), this.show(); }, hideAtZIndex: function(e) { this.removeZIndex(e); if (!this.zStack.length) this.hide(); else { var t = this.zStack[this.zStack.length - 1]; this.setZIndex(t); } }, setZIndex: function(e) { this.zIndex = e, this.applyStyle("z-index", e); }, make: function() { return this; } }), enyo.kind({ name: "onyx.scrimSingleton", kind: null, constructor: function(e, t) { this.instanceName = e, enyo.setObject(this.instanceName, this), this.props = t || {}; }, make: function() { var e = new onyx.Scrim(this.props); return enyo.setObject(this.instanceName, e), e; }, showAtZIndex: function(e) { var t = this.make(); t.showAtZIndex(e); }, hideAtZIndex: enyo.nop, show: function() { var e = this.make(); e.show(); } }), new onyx.scrimSingleton("onyx.scrim", { floating: !0, classes: "onyx-scrim-translucent" }), new onyx.scrimSingleton("onyx.scrimTransparent", { floating: !0, classes: "onyx-scrim-transparent" }); // Slider.js enyo.kind({ name: "onyx.Slider", kind: "onyx.ProgressBar", classes: "onyx-slider", published: { value: 0, lockBar: !0, tappable: !0 }, events: { onChange: "", onChanging: "", onAnimateFinish: "" }, showStripes: !1, handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish" }, moreComponents: [ { kind: "Animator", onStep: "animatorStep", onEnd: "animatorComplete" }, { classes: "onyx-slider-taparea" }, { name: "knob", classes: "onyx-slider-knob" } ], create: function() { this.inherited(arguments), this.createComponents(this.moreComponents), this.valueChanged(); }, valueChanged: function() { this.value = this.clampValue(this.min, this.max, this.value); var e = this.calcPercent(this.value); this.updateKnobPosition(e), this.lockBar && this.setProgress(this.value); }, updateKnobPosition: function(e) { this.$.knob.applyStyle("left", e + "%"); }, calcKnobPosition: function(e) { var t = e.clientX - this.hasNode().getBoundingClientRect().left; return t / this.getBounds().width * (this.max - this.min) + this.min; }, dragstart: function(e, t) { if (t.horizontal) return t.preventDefault(), this.dragging = !0, !0; }, drag: function(e, t) { if (this.dragging) { var n = this.calcKnobPosition(t); return this.setValue(n), this.doChanging({ value: this.value }), !0; } }, dragfinish: function(e, t) { return this.dragging = !1, t.preventTap(), this.doChange({ value: this.value }), !0; }, tap: function(e, t) { if (this.tappable) { var n = this.calcKnobPosition(t); return this.tapped = !0, this.animateTo(n), !0; } }, animateTo: function(e) { this.$.animator.play({ startValue: this.value, endValue: e, node: this.hasNode() }); }, animatorStep: function(e) { return this.setValue(e.value), !0; }, animatorComplete: function(e) { return this.tapped && (this.tapped = !1, this.doChange({ value: this.value })), this.doAnimateFinish(e), !0; } }); // RangeSlider.js enyo.kind({ name: "onyx.RangeSlider", kind: "onyx.ProgressBar", classes: "onyx-slider", published: { rangeMin: 0, rangeMax: 100, rangeStart: 0, rangeEnd: 100, increment: 0, beginValue: 0, endValue: 0 }, events: { onChange: "", onChanging: "" }, showStripes: !1, showLabels: !1, handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish", ondown: "down" }, moreComponents: [ { name: "startKnob", classes: "onyx-slider-knob" }, { name: "endKnob", classes: "onyx-slider-knob onyx-range-slider-knob" } ], create: function() { this.inherited(arguments), this.createComponents(this.moreComponents), this.initControls(); }, rendered: function() { this.inherited(arguments); var e = this.calcPercent(this.beginValue); this.updateBarPosition(e); }, initControls: function() { this.$.bar.applyStyle("position", "relative"), this.refreshRangeSlider(), this.showLabels && (this.$.startKnob.createComponent({ name: "startLabel", kind: "onyx.RangeSliderKnobLabel" }), this.$.endKnob.createComponent({ name: "endLabel", kind: "onyx.RangeSliderKnobLabel" })); }, refreshRangeSlider: function() { this.beginValue = this.calcKnobPercent(this.rangeStart), this.endValue = this.calcKnobPercent(this.rangeEnd), this.beginValueChanged(), this.endValueChanged(); }, calcKnobRatio: function(e) { return (e - this.rangeMin) / (this.rangeMax - this.rangeMin); }, calcKnobPercent: function(e) { return this.calcKnobRatio(e) * 100; }, beginValueChanged: function(e) { if (e === undefined) { var t = this.calcPercent(this.beginValue); this.updateKnobPosition(t, this.$.startKnob); } }, endValueChanged: function(e) { if (e === undefined) { var t = this.calcPercent(this.endValue); this.updateKnobPosition(t, this.$.endKnob); } }, calcKnobPosition: function(e) { var t = e.clientX - this.hasNode().getBoundingClientRect().left; return t / this.getBounds().width * (this.max - this.min) + this.min; }, updateKnobPosition: function(e, t) { t.applyStyle("left", e + "%"), this.updateBarPosition(); }, updateBarPosition: function() { if (this.$.startKnob !== undefined && this.$.endKnob !== undefined) { var e = this.calcKnobPercent(this.rangeStart), t = this.calcKnobPercent(this.rangeEnd) - e; this.$.bar.applyStyle("left", e + "%"), this.$.bar.applyStyle("width", t + "%"); } }, calcIncrement: function(e) { return Math.ceil(e / this.increment) * this.increment; }, calcRangeRatio: function(e) { return e / 100 * (this.rangeMax - this.rangeMin) + this.rangeMin - this.increment / 2; }, swapZIndex: function(e) { e === "startKnob" ? (this.$.startKnob.applyStyle("z-index", 1), this.$.endKnob.applyStyle("z-index", 0)) : e === "endKnob" && (this.$.startKnob.applyStyle("z-index", 0), this.$.endKnob.applyStyle("z-index", 1)); }, down: function(e, t) { this.swapZIndex(e.name); }, dragstart: function(e, t) { if (t.horizontal) return t.preventDefault(), this.dragging = !0, !0; }, drag: function(e, t) { if (this.dragging) { var n = this.calcKnobPosition(t); if (e.name === "startKnob" && n >= 0) { if (n <= this.endValue && t.xDirection === -1 || n <= this.endValue) { this.setBeginValue(n); var r = this.calcRangeRatio(this.beginValue), i = this.increment ? this.calcIncrement(r) : r, s = this.calcKnobPercent(i); this.updateKnobPosition(s, this.$.startKnob), this.setRangeStart(i), this.doChanging({ value: i }); } } else if (e.name === "endKnob" && n <= 100) if (n >= this.beginValue && t.xDirection === 1 || n >= this.beginValue) { this.setEndValue(n); var r = this.calcRangeRatio(this.endValue), i = this.increment ? this.calcIncrement(r) : r, s = this.calcKnobPercent(i); this.updateKnobPosition(s, this.$.endKnob), this.setRangeEnd(i), this.doChanging({ value: i }); } return !0; } }, dragfinish: function(e, t) { this.dragging = !1, t.preventTap(); if (e.name === "startKnob") { var n = this.calcRangeRatio(this.beginValue); this.doChange({ value: n, startChanged: !0 }); } else if (e.name === "endKnob") { var n = this.calcRangeRatio(this.endValue); this.doChange({ value: n, startChanged: !1 }); } return !0; }, rangeMinChanged: function() { this.refreshRangeSlider(); }, rangeMaxChanged: function() { this.refreshRangeSlider(); }, rangeStartChanged: function() { this.refreshRangeSlider(); }, rangeEndChanged: function() { this.refreshRangeSlider(); }, setStartLabel: function(e) { this.$.startKnob.waterfallDown("onSetLabel", e); }, setEndLabel: function(e) { this.$.endKnob.waterfallDown("onSetLabel", e); } }), enyo.kind({ name: "onyx.RangeSliderKnobLabel", classes: "onyx-range-slider-label", handlers: { onSetLabel: "setLabel" }, setLabel: function(e, t) { this.setContent(t); } }); // Item.js enyo.kind({ name: "onyx.Item", classes: "onyx-item", tapHighlight: !0, handlers: { onhold: "hold", onrelease: "release" }, hold: function(e, t) { this.tapHighlight && onyx.Item.addFlyweightClass(this.controlParent || this, "onyx-highlight", t); }, release: function(e, t) { this.tapHighlight && onyx.Item.removeFlyweightClass(this.controlParent || this, "onyx-highlight", t); }, statics: { addFlyweightClass: function(e, t, n, r) { var i = n.flyweight; if (i) { var s = r !== undefined ? r : n.index; i.performOnRow(s, function() { e.hasClass(t) ? e.setClassAttribute(e.getClassAttribute()) : e.addClass(t); }), e.removeClass(t); } }, removeFlyweightClass: function(e, t, n, r) { var i = n.flyweight; if (i) { var s = r !== undefined ? r : n.index; i.performOnRow(s, function() { e.hasClass(t) ? e.removeClass(t) : e.setClassAttribute(e.getClassAttribute()); }); } } } }); // Spinner.js enyo.kind({ name: "onyx.Spinner", classes: "onyx-spinner", stop: function() { this.setShowing(!1); }, start: function() { this.setShowing(!0); }, toggle: function() { this.setShowing(!this.getShowing()); } }); // MoreToolbar.js enyo.kind({ name: "onyx.MoreToolbar", classes: "onyx-toolbar onyx-more-toolbar", menuClass: "", movedClass: "", layoutKind: "FittableColumnsLayout", noStretch: !0, handlers: { onHide: "reflow" }, published: { clientLayoutKind: "FittableColumnsLayout" }, tools: [ { name: "client", noStretch: !0, fit: !0, classes: "onyx-toolbar-inline" }, { name: "nard", kind: "onyx.MenuDecorator", showing: !1, onActivate: "activated", components: [ { kind: "onyx.IconButton", classes: "onyx-more-button" }, { name: "menu", kind: "onyx.Menu", scrolling: !1, classes: "onyx-more-menu" } ] } ], initComponents: function() { this.menuClass && this.menuClass.length > 0 && !this.$.menu.hasClass(this.menuClass) && this.$.menu.addClass(this.menuClass), this.createChrome(this.tools), this.inherited(arguments), this.$.client.setLayoutKind(this.clientLayoutKind); }, clientLayoutKindChanged: function() { this.$.client.setLayoutKind(this.clientLayoutKind); }, reflow: function() { this.inherited(arguments), this.isContentOverflowing() ? (this.$.nard.show(), this.popItem() && this.reflow()) : this.tryPushItem() ? this.reflow() : this.$.menu.children.length || (this.$.nard.hide(), this.$.menu.hide()); }, activated: function(e, t) { this.addRemoveClass("active", t.originator.active); }, popItem: function() { var e = this.findCollapsibleItem(); if (e) { this.movedClass && this.movedClass.length > 0 && !e.hasClass(this.movedClass) && e.addClass(this.movedClass), this.$.menu.addChild(e, null); var t = this.$.menu.hasNode(); return t && e.hasNode() && e.insertNodeInParent(t), !0; } }, pushItem: function() { var e = this.$.menu.children, t = e[0]; if (t) { this.movedClass && this.movedClass.length > 0 && t.hasClass(this.movedClass) && t.removeClass(this.movedClass), this.$.client.addChild(t); var n = this.$.client.hasNode(); if (n && t.hasNode()) { var r, i; for (var s = 0; s < this.$.client.children.length; s++) { var o = this.$.client.children[s]; if (o.toolbarIndex !== undefined && o.toolbarIndex != s) { r = o, i = s; break; } } if (r && r.hasNode()) { t.insertNodeInParent(n, r.node); var u = this.$.client.children.pop(); this.$.client.children.splice(i, 0, u); } else t.appendNodeToParent(n); } return !0; } }, tryPushItem: function() { if (this.pushItem()) { if (!this.isContentOverflowing()) return !0; this.popItem(); } }, isContentOverflowing: function() { if (this.$.client.hasNode()) { var e = this.$.client.children, t = e[e.length - 1].hasNode(); if (t) return this.$.client.reflow(), t.offsetLeft + t.offsetWidth > this.$.client.node.clientWidth; } }, findCollapsibleItem: function() { var e = this.$.client.children; for (var t = e.length - 1; c = e[t]; t--) { if (!c.unmoveable) return c; c.toolbarIndex === undefined && (c.toolbarIndex = t); } } }); // App.js enyo.kind({ name: "App", layoutKind: "FittableRowsLayout", classes: "calculator-bookmarklet enyo-unselectable", fit: !0, components: [ { kind: "FittableRows", style: "border: 5px solid #333; background-color: #777; padding: 10px; color: white; border-radius: 16px; text-align: right; height:100%; width:100%;", components: [ { kind: "onyx.Toolbar", style: "margin-bottom: 5px;height: 54px;", components: [ { name: "Result", style: "font-size: 1em; font-weight: bold;" } ] }, { kind: "FittableColumns", style: "margin-bottom: 15px;", components: [ { kind: "onyx.Toolbar", style: "width: 75%; height: 48px; margin-left: 12.5%; margin-right: 5px; text-align: right;", fit: !0, components: [ { name: "Formula", style: "font-size: 100%;" } ] }, { kind: "onyx.Button", style: "width: 48px; height: 48px; border-radius: 24px;", classes: "onyx-toolbar", content: "<", ontap: "backspaceTapped" } ] }, { kind: "FittableRows", fit: !0, defaultKind: enyo.kind({ kind: "FittableColumns", style: "height: 18.7%; margin: 0.5%;", defaultKind: enyo.kind({ kind: "onyx.Button", classes: "onyx-toolbar", style: "width: 24%; margin: 0.5%; border-radius: 8px; font-size:1.2em;font-weight: bold;", ontap: "keyTapped" }) }), components: [ { components: [ { content: "(" }, { content: ")" }, { content: "" }, { content: "C", style: "margin-right: 0;", ontap: "cancelTapped" } ] }, { components: [ { content: "7", classes: "number-button" }, { content: "8", classes: "number-button" }, { content: "9", classes: "number-button" }, { content: "+", style: "margin-right: 0;" } ] }, { components: [ { content: "4", classes: "number-button" }, { content: "5", classes: "number-button" }, { content: "6", classes: "number-button" }, { content: "-", style: "margin-right: 0;" } ] }, { components: [ { content: "1", classes: "number-button" }, { content: "2", classes: "number-button" }, { content: "3", classes: "number-button" }, { content: "*", style: "margin-right: 0;" } ] }, { components: [ { content: "." }, { content: "0", classes: "number-button" }, { content: "=", ontap: "equalsTapped" }, { content: "/", style: "margin-right: 0;" } ] } ] } ] } ], keyTapped: function(e, t) { var n = this.$.Result.getContent(); this.isOperationKey(e.getContent()) && n != "Invalid Input" && n != "" ? (this.$.Formula.setContent(this.$.Result.getContent() + e.getContent()), this.$.Result.setContent("")) : this.$.Formula.setContent(this.$.Formula.getContent() + e.getContent()); }, isOperationKey: function(e) { return e == "+" || e == "-" || e == "*" || e == "/"; }, equalsTapped: function() { this.$.Result.setContent(this.calculate(this.$.Formula.getContent())); }, calculate: function(formula) { try { var parsed; return parsed = formula.replace("sqrt", "Math.sqrt"), eval(parsed); } catch (err) { return enyo.log(err), "Invalid Input"; } }, cancelTapped: function() { this.$.Result.setContent(""), this.$.Formula.setContent(""); }, sqrtTapped: function() { this.$.Result.setContent(""), this.$.Formula.setContent("sqrt("); }, lnTapped: function() { this.$.Result.setContent(""), this.$.Formula.setContent("ln("); }, logTapped: function() { this.$.Result.setContent(""), this.$.Formula.setContent("log("); }, backspaceTapped: function() { var e = this.$.Formula; e.setContent(e.getContent().substr(0, e.getContent().length - 1)); } }); // Bookmarklet.js enyo.kind({ name: "enyo.Bookmarklet", kind: window.onyx ? "onyx.Popup" : "enyo.Popup", centered: !1, position: undefined, draggable: !0, edgePadding: "20px", unstyled: !1, width: undefined, height: undefined, modal: !1, defaultZ:1000000, showing: !0, classes: "enyo-bookmarklet", style: "position:fixed;", handlers: { ondrag: "dragBookmarklet", ondragfinish: "dragfinishBookmarklet" }, components: [ { kind: "enyo.Signals", onBookmarkletRelaunch: "relaunch" }, { name: "appContainer", style: "width:100%; height:100%;", ondown: "preventBubble", ondragstart: "preventBubble", ondrag: "preventBubble", ondragfinish: "preventBubble", components: [ { kind: "App" } ] } ], constructor: function(e) { enyo.mixin(this, e || {}), this.position = this.position || { top: 10, right: 10 }, this.vAnchor = this.position.top != undefined ? "top" : "bottom", this.hAnchor = this.position.left != undefined ? "left" : "right", this.inherited(arguments); }, create: function() { this.inherited(arguments), this.unstyled && this.removeClass("onyx-popup"), this.width != undefined && this.applyStyle("width", this.width), this.height != undefined && this.applyStyle("height", this.height), this.centered || (this.applyStyle(this.vAnchor, this.position[this.vAnchor] + "px"), this.applyStyle(this.hAnchor, this.position[this.hAnchor] + "px")), this.draggable && (this.applyStyle("cursor", "move"), this.$.appContainer.applyStyle("cursor", "default"), this.applyStyle("padding", this.edgePadding)); }, relaunch: function(e, t) { this.showing ? this.hide() : this.show(); }, preventBubble: function(e, t) { return !this.wholeDrag; }, updatePosition: function() { if (!this.centered) this.applyStyle(this.vAnchor, this.position[this.vAnchor] + "px"), this.applyStyle(this.hAnchor, this.position[this.hAnchor] + "px"); else { this.inherited(arguments); var e = this.getBounds(); this.position.top = e.top, this.position.left = e.left, this.vAnchor = "top", this.hAnchor = "left"; } }, down: function(e, t) { this.inherited(arguments), t.dispatchTarget.isDescendantOf(this) && t.preventDefault(); }, dragstart: function(e, t) { return this.draggable && this.$.appContainer.applyStyle("cursor", "move"), this.inherited(arguments); }, dragBookmarklet: function(e, t) { if (this.draggable) return t.dy != 0 && (this.vAnchor == "top" ? this.applyStyle("top", this.position.top + t.dy + "px") : this.applyStyle("bottom", this.position.bottom - t.dy + "px")), t.dx != 0 && (this.hAnchor == "left" ? this.applyStyle("left", this.position.left + t.dx + "px") : this.applyStyle("right", this.position.right - t.dx + "px")), !0; }, dragfinishBookmarklet: function(e, t) { if (this.draggable) { if (t.dy != 0 || t.dx != 0) this.position[this.vAnchor] += this.vAnchor == "top" ? t.dy : -1 * t.dy, this.position[this.hAnchor] += this.hAnchor == "left" ? t.dx : -1 * t.dx, this.centered = !1; return this.applyStyle(this.vAnchor, this.position[this.vAnchor] + "px"), this.applyStyle(this.hAnchor, this.position[this.hAnchor] + "px"), this.$.appContainer.applyStyle("cursor", "default"), !0; } } });
const { join } = require('path') const { existsSync } = require('fs-extra') module.exports = ({ base, template }) => { const localPath = join(base, 'templates', template) const npmPath = join(base, 'node_modules', template) if (existsSync(localPath)) { return localPath } let name = template try { // eslint-disable-next-line global-require, import/no-dynamic-require name = require(npmPath).template || template } catch (e) { // ignore } const templatePath = join(npmPath, 'templates', name) if (existsSync(templatePath)) { return templatePath } throw new Error(`Template no exist: ${template}`) }
(function() { 'use strict'; app.controller('profileCtrl', ['api', 'constants','commonFactory','url', 'localStorageService', function(api, constants,commonFactory, url, localStorageService) { var profile = this; var profileCallConfig = { url: url.user.me }; api.executeCall(profileCallConfig,function(response) { profile.user = response.data; }); profile.validateAndSave = function() { profileCallConfig.method = constants.method.post; profileCallConfig.data = profile.user; api.executeCall(profileCallConfig,function(response) { if(response.data.user_id){ localStorageService.set('user', response.data); profile.profileError = {type:'success',message:'Profile updated successfully.'}; } },function(err){ profile.error = err.data; }); }; }]); })();
import BaseSyntax from './base.js'; /** * The class to define the TemplateElement syntax * * @class TemplateElement */ export default class TemplateElement extends BaseSyntax { /** * Create a template literal * * @constructor */ constructor() { super('TemplateElement'); this.value = {raw: '', cooked: ''}; this.tail = false; } setValue(value) { this.setRaw(value); this.setCooked(value); } setRaw(raw) { this.value.raw = raw; } setCooked(cooked) { this.value.cooked = cooked; } }
// // Sets up intial project settings, middleware, mounted apps, and // global configuration such as overriding Backbone.sync and // populating sharify data // var express = require('express'), Backbone = require('backbone'), sharify = require('sharify'), path = require('path'), fs = require('fs'); module.exports = function(app) { // Inject some configuration & constant data into sharify var sd = sharify.data = { API_URL: process.env.API_URL, NODE_ENV: process.env.NODE_ENV, JS_EXT: 'production' == process.env.NODE_ENV ? '.min.js' : '.js', CSS_EXT: 'production' == process.env.NODE_ENV ? '.min.css' : '.css' }; // Override Backbone to use server-side sync Backbone.sync = require('backbone-super-sync'); // Mount sharify app.use(sharify); // Development only if ('development' == sd.NODE_ENV) { // Compile assets on request in development app.use(require('stylus').middleware({ src: path.resolve(__dirname, '../'), dest: path.resolve(__dirname, '../public') })); app.use(require('browserify-dev-middleware')({ src: path.resolve(__dirname, '../'), transforms: [require('jadeify')] })); } // Test only if('test' == sd.NODE_ENV) { // Mount fake API server app.use('/__api', require('../test/helpers/integration.js').api); } // Mount apps app.use('/', function(req, res) { res.send('Start by writing an app in /apps and mounting it in /lib/setup!'); }); // Mount static middleware for sub apps, components, and project-wide fs.readdirSync(path.resolve(__dirname, '../apps')).forEach(function(fld) { app.use(express.static(path.resolve(__dirname, '../apps/' + fld + '/public'))); }); fs.readdirSync(path.resolve(__dirname, '../components')).forEach(function(fld) { app.use(express.static(path.resolve(__dirname, '../components/' + fld + '/public'))); }); app.use(express.static(path.resolve(__dirname, '../public'))); }
'use strict'; const rp = require('minimal-request-promise'); const prompt = require('souffleur'); const tlReply = require('./reply'); const tlParse = require('./parse'); const color = require('../console-colors'); module.exports = function tlSetup(api, bot, logError, optionalParser, optionalResponder) { let parser = optionalParser || tlParse; let responder = optionalResponder || tlReply; api.post('/telegram', request => { let tlMessage = request.body; let parsedMessage = parser(tlMessage); if (!parsedMessage){ return Promise.resolve('ok'); } return Promise.resolve(parsedMessage).then(parsedMessage => bot(parsedMessage, request)) .then(botResponse => responder(parsedMessage, botResponse, request.env.telegramAccessToken)) .catch(logError); }); api.addPostDeployStep('telegram', (options, lambdaDetails, utils) => { return Promise.resolve() .then(() => { if (options['configure-telegram-bot']) { console.log(`\n\n${color.green}Telegram setup${color.reset}\n`); console.log(`\nFollowing info is required for the setup, for more info check the documentation.\n`); console.log(`\nYour Telegram bot Request URL (POST only) is ${color.cyan}${lambdaDetails.apiUrl}/telegram${color.reset}\n`); console.log(`\nIf you want your bot to receive inline queries\n just send /setinline to the @BotFather on your Telegram client and choose your bot\n`); return prompt(['Telegram Access Token']) .then(results => { const deployment = { restApiId: lambdaDetails.apiId, stageName: lambdaDetails.alias, variables: { telegramAccessToken: results['Telegram Access Token'] } }; return utils.apiGatewayPromise.createDeploymentPromise(deployment) .then(() => { let options = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: `${lambdaDetails.apiUrl}/telegram` }) }; return rp.post(`https://api.telegram.org/bot${deployment.variables.telegramAccessToken}/setWebhook`, options); }); }); } }) .then(() => `${lambdaDetails.apiUrl}/telegram`); }); };
import inatjs from "inaturalistjs"; import { showAlert } from "./alert_actions"; const POST_COMMENT = "post_comment"; function postComment( params ) { return function ( dispatch ) { const body = Object.assign( {}, params ); // TODO handle error state return inatjs.comments.create( body ).catch( e => { dispatch( showAlert( I18n.t( "failed_to_save_record" ), { title: I18n.t( "request_failed" ) } ) ); throw e; } ); }; } function deleteComment( comment ) { return function ( ) { return inatjs.comments.delete( comment ); }; } export { postComment, POST_COMMENT, deleteComment };
"use strict"; var dgram = require("dgram"); var mersenne = require("./mersenne"); var mt = new mersenne.MersenneTwister19937(); var EPHEMERAL_LIFETIME_MS = 1000; var Client = function(host, port, socket, options) { this.host = host || "localhost"; this.port = port || 8125; // optional shared socket this.socket = socket; // when a *shared* socked isn't provided, an ephemeral // socket is demand allocated. This ephemeral socket is closed // after being idle for EPHEMERAL_LIFETIME_MS. this.ephemeral_socket = this.last_used_timer = null; options = options || {}; this.global_tags = options.global_tags; }; Client.prototype.timing = function(stat, time, sample_rate, tags) { var self = this; var stats = {}; stats[stat] = time + "|ms"; self.send(stats, sample_rate, tags); }; Client.prototype.increment = function(stats, sample_rate, tags) { var self = this; self.update_stats(stats, 1, sample_rate, tags); }; Client.prototype.incrementBy = function(stats, value, tags) { var self = this; if (value === 0) return; self.update_stats(stats, value, undefined, tags); }; Client.prototype.decrement = function(stats, sample_rate, tags) { var self = this; self.update_stats(stats, - 1, sample_rate, tags); }; Client.prototype.decrementBy = function(stats, value, tags) { var self = this; if (value === 0) return; self.update_stats(stats, -value, undefined, tags); }; Client.prototype.gauge = function(stat, value, sample_rate, tags) { var self = this; var stats = {}; stats[stat] = value + "|g"; self.send(stats, sample_rate, tags); }; Client.prototype.histogram = function(stat, value, sample_rate, tags) { var self = this; var stats = {}; stats[stat] = value + "|h"; self.send(stats, sample_rate, tags); }; Client.prototype.set = function(stat, value, sample_rate, tags) { var self = this; var stats = {}; stats[stat] = value + "|s"; self.send(stats, sample_rate, tags); }; Client.prototype.update_stats = function(stats, delta, sampleRate, tags) { var self = this; if (typeof(stats) === "string") stats = [stats]; if (!delta) delta = 1; var data = {}; for (var i = 0; i < stats.length; i++) data[stats[i]] = delta + "|c"; self.send(data, sampleRate, tags); }; // An internal function update the last time the socket was // used. This function is called when the socket is used // and causes demand allocated ephemeral sockets to be closed // after a period of inactivity. Client.prototype._update_last_used = function () { if (!this.ephemeral_socket) return; if (this.last_used_timer) clearTimeout(this.last_used_timer); var self = this; this.last_used_timer = setTimeout(function() { if (self.ephemeral_socket) self.ephemeral_socket.close(); delete self.ephemeral_socket; }, EPHEMERAL_LIFETIME_MS); }; Client.prototype.send_data = function (buf) { var socket; if (!this.socket) { if (!this.ephemeral_socket) { this.ephemeral_socket = dgram.createSocket("udp4"); this.ephemeral_socket.on("error", function() {}); } socket = this.ephemeral_socket; } else { socket = this.socket; } this._update_last_used(); socket.send(buf, 0, buf.length, this.port, this.host); }; Client.prototype.send = function(data, sample_rate, tags) { if (!tags && Array.isArray(sample_rate)) { tags = sample_rate; sample_rate = undefined; } if (!sample_rate) sample_rate = 1; var value; var sampled_data = {}; if (sample_rate < 1) { if (mt.genrand_real2(0, 1) <= sample_rate) { for (stat in data) { value = data[stat]; sampled_data[stat] = value + "|@" + sample_rate; } } } else sampled_data = data; if (this.global_tags || tags) { var merged_tags = []; if (Array.isArray(this.global_tags)) merged_tags = merged_tags.concat(this.global_tags); if (Array.isArray(tags)) merged_tags = merged_tags.concat(tags); if (merged_tags.length > 0) { var merged_tags_str = merged_tags.join(','); for (stat in sampled_data) sampled_data[stat] = sampled_data[stat] + "|#" + merged_tags_str; } } for (var stat in sampled_data) { var send_data = stat + ":" + sampled_data[stat]; this.send_data(new Buffer(send_data)); } }; Client.prototype.close = function() { if (this.socket) this.socket.close(); if (this.ephemeral_socket) this.ephemeral_socket.close(); if (this.last_used_timer) clearTimeout(this.last_used_timer); this.ephemeral_socket = this.last_used_timer = this.socket = null; }; exports.StatsD = Client;
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import TimePickerPanel from 'rc-time-picker/es/Panel'; import classNames from 'classnames'; import { generateShowHourMinuteSecond } from '../time-picker'; import warning from '../_util/warning'; import { getComponentLocale } from '../_util/getLocale'; function getColumns(_ref) { var showHour = _ref.showHour, showMinute = _ref.showMinute, showSecond = _ref.showSecond, use12Hours = _ref.use12Hours; var column = 0; if (showHour) { column += 1; } if (showMinute) { column += 1; } if (showSecond) { column += 1; } if (use12Hours) { column += 1; } return column; } export default function wrapPicker(Picker, defaultFormat) { return _a = function (_React$Component) { _inherits(PickerWrapper, _React$Component); function PickerWrapper() { _classCallCheck(this, PickerWrapper); var _this = _possibleConstructorReturn(this, (PickerWrapper.__proto__ || Object.getPrototypeOf(PickerWrapper)).apply(this, arguments)); _this.handleOpenChange = function (open) { var _this$props = _this.props, onOpenChange = _this$props.onOpenChange, toggleOpen = _this$props.toggleOpen; onOpenChange(open); if (toggleOpen) { warning(false, '`toggleOpen` is deprecated and will be removed in the future, ' + 'please use `onOpenChange` instead, see: https://u.ant.design/date-picker-on-open-change'); toggleOpen({ open: open }); } }; return _this; } _createClass(PickerWrapper, [{ key: 'render', value: function render() { var _classNames2; var props = this.props; var prefixCls = props.prefixCls, inputPrefixCls = props.inputPrefixCls; var pickerClass = classNames(_defineProperty({}, prefixCls + '-picker', true)); var pickerInputClass = classNames(prefixCls + '-picker-input', inputPrefixCls, (_classNames2 = {}, _defineProperty(_classNames2, inputPrefixCls + '-lg', props.size === 'large'), _defineProperty(_classNames2, inputPrefixCls + '-sm', props.size === 'small'), _defineProperty(_classNames2, inputPrefixCls + '-disabled', props.disabled), _classNames2)); var locale = getComponentLocale(props, this.context, 'DatePicker', function () { return require('./locale/zh_CN'); }); var timeFormat = props.showTime && props.showTime.format || 'HH:mm:ss'; var rcTimePickerProps = _extends({}, generateShowHourMinuteSecond(timeFormat), { format: timeFormat, use12Hours: props.showTime && props.showTime.use12Hours }); var columns = getColumns(rcTimePickerProps); var timePickerCls = prefixCls + '-time-picker-column-' + columns; var timePicker = props.showTime ? React.createElement(TimePickerPanel, _extends({}, rcTimePickerProps, props.showTime, { prefixCls: prefixCls + '-time-picker', className: timePickerCls, placeholder: locale.timePickerLocale.placeholder, transitionName: 'slide-up' })) : null; return React.createElement(Picker, _extends({}, props, { pickerClass: pickerClass, pickerInputClass: pickerInputClass, locale: locale, timePicker: timePicker, onOpenChange: this.handleOpenChange })); } }]); return PickerWrapper; }(React.Component), _a.contextTypes = { antLocale: PropTypes.object }, _a.defaultProps = { format: defaultFormat || 'YYYY-MM-DD', transitionName: 'slide-up', popupStyle: {}, onChange: function onChange() {}, onOk: function onOk() {}, onOpenChange: function onOpenChange() {}, locale: {}, prefixCls: 'ant-calendar', inputPrefixCls: 'ant-input' }, _a; var _a; }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /* jshint latedef:false */ /* jshint forin:false */ /* jshint noempty:false */ 'use strict'; var msRestAzure = require('ms-rest-azure'); exports.BaseResource = msRestAzure.BaseResource; exports.CloudError = msRestAzure.CloudError; exports.PolicySku = require('./policySku'); exports.PolicyAssignment = require('./policyAssignment'); exports.ErrorResponse = require('./errorResponse'); exports.PolicyDefinitionReference = require('./policyDefinitionReference'); exports.PolicySetDefinition = require('./policySetDefinition'); exports.PolicyDefinition = require('./policyDefinition'); exports.PolicyAssignmentListResult = require('./policyAssignmentListResult'); exports.PolicySetDefinitionListResult = require('./policySetDefinitionListResult'); exports.PolicyDefinitionListResult = require('./policyDefinitionListResult');
/*! * Ext JS Connect * Copyright(c) 2010 Sencha Inc. * MIT Licensed */ /** * Module dependencies. */ var Buffer = require('buffer').Buffer; /** * Cache in memory for the given `cacheDuration`. * * @param {Number} cacheDuration * @return {Function} * @api public */ module.exports = function cache(cacheDuration){ var cache = {}, queue = {}; return function cache(req, res, next) { // Skip all requests that are not GET method if (req.method !== "GET") { next(); return; } var key = req.headers["accept-encoding"] + req.url, writeHead = res.writeHead, write = res.write, end = res.end, code, headers, chunks = [], totalSize = 0; function serve() { var resp = cache[key]; var headers = resp.headers; headers["Content-Length"] = resp.body.length; if (localQueue) { // Send everyone in the wait queue the response. for (var i = 0, l = localQueue.length; i < l; i++) { var localRes = localQueue[i]; localRes.writeHead(resp.code, headers); localRes.end(resp.body); } // Kill the wait queue delete queue[key]; } else { res.writeHead(resp.code, headers); res.end(resp.body); } } // If there is a cache-hit, serve it right away! if (cache[key]) { serve(); return; } var localQueue = queue[key]; if (localQueue) { localQueue[localQueue.length] = res; return; } localQueue = queue[key] = [res]; // Defer the call to writeHead res.writeHead = function (setCode, setHeaders) { code = setCode; headers = setHeaders; }; // Buffer the response body as an array of Buffer objects res.write = function (chunk, encoding) { if (typeof chunk === 'string') { var length; if (!encoding || encoding === 'utf8') { length = Buffer.byteLength(chunk); } var buffer = new Buffer(length); buffer.write(chunk, encoding); chunks.push(buffer); } else { chunks.push(chunk); } totalSize += chunk.length; }; res.end = function (chunk, encoding) { if (chunk) { res.write(chunk, encoding); } // Combine the buffer array into a single buffer var body = new Buffer(totalSize); var offset = 0; chunks.forEach(function (chunk) { chunk.copy(body, offset); offset += chunk.length; }); // Store the result in the cache cache[key] = { body: body, code: code, headers: headers }; // Put the original methods back in place res.writeHead = writeHead; res.write = write; res.end = end; // Serve the response from the cache serve(); if (cacheDuration) { // Expire the ram cache after 100ms or the specified length setTimeout(function(){ delete cache[key]; }, cacheDuration); } else { // When the timeout is zero, just kill it right away delete cache[key]; } }; next(); }; };
/** * @file * User related utility functions. */ var userHelper = module.exports = { createUser: function(application, roles, callback) { var User = application.type('user'); var account = userHelper.sample(); account.roles = roles; User.validateAndSave(account, function(error, user) { callback(error, user, account); }); }, // Generate sample user data used in tests. sample: function (confirmation) { var user = { username: 'user', password: 'password', roles: [], email: 'email@email.com' }; if (confirmation) { user['password-confirm'] = 'password'; } return user; }, // Generate credentials used in tests. credentials: function () { return { username: 'user', password: 'password' }; } };
'use strict'; var SfTextSettingsPage = function() { // currently this page is called questions-settings.html but will be refactored. IJH 2014-06 this.tabs = { editText: element(by.linkText('Edit Text')), archiveQuestions: element(by.linkText('Archived Questions')), audioFile: element(by.linkText('Audio File')), paratextExport: element(by.linkText('ParaTExt Export')) }; this.editTextTab = { title: element(by.model('editedText.title')), usxText: element(by.model('editedText.content')), letMeEditLink: element(by.partialLinkText('Edit previous text')), contentEditor: element(by.model('editedText.content')), saveButton: element(by.partialButtonText('Save')), }; this.archivedQuestionsTab = { questionNames: element.all(by.repeater('question in visibleArchivedQuestions').column('calculatedTitle')), questionList: element.all(by.repeater('question in visibleArchivedQuestions')), publishButton: element(by.partialButtonText('Re-publish Questions')), questionLink: function(title) { return element(by.linkText(title)); } }; // getFirstCheckbox has to be a function because the .first() method will actually resolve the finder this.archivedQuestionsTabGetFirstCheckbox = function() { return this.archivedQuestionsTab.questionList.first().element(by.css('input[type="checkbox"]')); }; this.audioFileTab = { }; this.paratextExportTab = { exportAnswers: element(by.id('exportAnswers')), exportComments: element(by.model('exportConfig.exportComments')), exportFlagged: element(by.model('exportConfig.exportFlagged')), prepareButton: element(by.partialButtonText('Prepare')), noExportMsg: element(by.id('noExportMsg')), answerCount: element(by.binding('download.answerCount')), commentCount: element(by.binding('download.commentCount')), downloadButton: element(by.partialButtonText('Download')), }; }; module.exports = new SfTextSettingsPage();
/*!jQuery Knob*/ /** * Downward compatible, touchable dial * * Version: 1.2.0 (15/07/2012) * Requires: jQuery v1.7+ * * Copyright (c) 2012 Anthony Terrien * Under MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to vor, eskimoblood, spiffistan, FabrizioC */ (function($) { /** * Kontrol library */ "use strict"; /** * Definition of globals and core */ var k = {}, // kontrol max = Math.max, min = Math.min; k.c = {}; k.c.d = $(document); k.c.t = function (e) { return e.originalEvent.touches.length - 1; }; /** * Kontrol Object * * Definition of an abstract UI control * * Each concrete component must call this one. * <code> * k.o.call(this); * </code> */ k.o = function () { var s = this; this.o = null; // array of options this.$ = null; // jQuery wrapped element this.i = null; // mixed HTMLInputElement or array of HTMLInputElement this.g = null; // 2D graphics context for 'pre-rendering' this.v = null; // value ; mixed array or integer this.cv = null; // change value ; not commited value this.x = 0; // canvas x position this.y = 0; // canvas y position this.$c = null; // jQuery canvas element this.c = null; // rendered canvas context this.t = 0; // touches index this.isInit = false; this.fgColor = null; // main color this.pColor = null; // previous color this.dH = null; // draw hook this.cH = null; // change hook this.eH = null; // cancel hook this.rH = null; // release hook this.run = function () { var cf = function (e, conf) { var k; for (k in conf) { s.o[k] = conf[k]; } s.init(); s._configure() ._draw(); }; if(this.$.data('kontroled')) return; this.$.data('kontroled', true); this.extend(); this.o = $.extend( { // Config min : this.$.data('min') || 0, max : this.$.data('max') || 100, stopper : true, readOnly : this.$.data('readonly'), // UI cursor : (this.$.data('cursor') === true && 30) || this.$.data('cursor') || 0, thickness : this.$.data('thickness') || 0.35, lineCap : this.$.data('linecap') || 'butt', width : this.$.data('width') || 200, height : this.$.data('height') || 260, displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'), displayPrevious : this.$.data('displayprevious'), fgColor : this.$.data('fgcolor') || '#87CEEB', inputColor: this.$.data('inputcolor') || this.$.data('fgcolor') || '#87CEEB', inline : false, step : this.$.data('step') || 1, // Hooks draw : null, // function () {} change : null, // function (value) {} cancel : null, // function () {} release : null // function (value) {} }, this.o ); // routing value if(this.$.is('fieldset')) { // fieldset = array of integer this.v = {}; this.i = this.$.find('input') this.i.each(function(k) { var $this = $(this); s.i[k] = $this; s.v[k] = $this.val(); $this.bind( 'change' , function () { var val = {}; val[k] = $this.val(); s.val(val); } ); }); this.$.find('legend').remove(); } else { // input = integer this.i = this.$; this.v = this.$.val(); (this.v == '') && (this.v = this.o.min); this.$.bind( 'change' , function () { s.val(s._validate(s.$.val())); } ); } (!this.o.displayInput) && this.$.hide(); this.$c = $('<canvas width="' + this.o.width + 'px" height="' + this.o.height + 'px"></canvas>'); this.c = this.$c[0].getContext("2d"); this.$ .wrap($('<div style="' + (this.o.inline ? 'display:inline;' : '') + 'width:' + this.o.width + 'px;height:' + this.o.height + 'px; margin-right: 20px;"></div>')) .before(this.$c); if (this.v instanceof Object) { this.cv = {}; this.copy(this.v, this.cv); } else { this.cv = this.v; } this.$ .bind("configure", cf) .parent() .bind("configure", cf); this._listen() ._configure() ._xy() .init(); this.isInit = true; this._draw(); return this; }; this._draw = function () { // canvas pre-rendering var d = true, c = document.createElement('canvas'); c.width = s.o.width; c.height = s.o.height; s.g = c.getContext('2d'); s.clear(); s.dH && (d = s.dH()); (d !== false) && s.draw(); s.c.drawImage(c, 0, 0); c = null; }; this._touch = function (e) { var touchMove = function (e) { var v = s.xy2val( e.originalEvent.touches[s.t].pageX, e.originalEvent.touches[s.t].pageY ); if (v == s.cv) return; if ( s.cH && (s.cH(v) === false) ) return; s.change(s._validate(v)); s._draw(); }; // get touches index this.t = k.c.t(e); // First touch touchMove(e); // Touch events listeners k.c.d .bind("touchmove.k", touchMove) .bind( "touchend.k" , function () { k.c.d.unbind('touchmove.k touchend.k'); if ( s.rH && (s.rH(s.cv) === false) ) return; s.val(s.cv); } ); return this; }; this._mouse = function (e) { var mouseMove = function (e) { var v = s.xy2val(e.pageX, e.pageY); if (v == s.cv) return; if ( s.cH && (s.cH(v) === false) ) return; s.change(s._validate(v)); s._draw(); }; // First click mouseMove(e); // Mouse events listeners k.c.d .bind("mousemove.k", mouseMove) .bind( // Escape key cancel current change "keyup.k" , function (e) { if (e.keyCode === 27) { k.c.d.unbind("mouseup.k mousemove.k keyup.k"); if ( s.eH && (s.eH() === false) ) return; s.cancel(); } } ) .bind( "mouseup.k" , function (e) { k.c.d.unbind('mousemove.k mouseup.k keyup.k'); if ( s.rH && (s.rH(s.cv) === false) ) return; s.val(s.cv); } ); return this; }; this._xy = function () { var o = this.$c.offset(); this.x = o.left; this.y = o.top; return this; }; this._listen = function () { if (!this.o.readOnly) { this.$c .bind( "mousedown" , function (e) { e.preventDefault(); s._xy()._mouse(e); } ) .bind( "touchstart" , function (e) { e.preventDefault(); s._xy()._touch(e); } ); this.listen(); } else { this.$.attr('readonly', 'readonly'); } return this; }; this._configure = function () { // Hooks if (this.o.draw) this.dH = this.o.draw; if (this.o.change) this.cH = this.o.change; if (this.o.cancel) this.eH = this.o.cancel; if (this.o.release) this.rH = this.o.release; if (this.o.displayPrevious) { this.pColor = this.h2rgba(this.o.fgColor, "0.4"); this.fgColor = this.h2rgba(this.o.fgColor, "0.6"); } else { this.fgColor = this.o.fgColor; } return this; }; this._clear = function () { this.$c[0].width = this.$c[0].width; }; this._validate = function(v) { return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step; }; // Abstract methods this.listen = function () {}; // on start, one time this.extend = function () {}; // each time configure triggered this.init = function () {}; // each time configure triggered this.change = function (v) {}; // on change this.val = function (v) {}; // on release this.xy2val = function (x, y) {}; // this.draw = function () {}; // on change / on release this.clear = function () { this._clear(); }; // Utils this.h2rgba = function (h, a) { var rgb; h = h.substring(1,7) rgb = [parseInt(h.substring(0,2),16) ,parseInt(h.substring(2,4),16) ,parseInt(h.substring(4,6),16)]; return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")"; }; this.copy = function (f, t) { for (var i in f) { t[i] = f[i]; } }; }; /** * k.Dial */ k.Dial = function () { k.o.call(this); this.startAngle = null; this.xy = null; this.radius = null; this.lineWidth = null; this.cursorExt = null; this.w2 = null; this.PI2 = 2*Math.PI; this.extend = function () { this.o = $.extend( { bgColor : this.$.data('bgcolor') || '#EEEEEE', angleOffset : this.$.data('angleoffset') || 0, angleArc : this.$.data('anglearc') || 360, inline : true }, this.o ); }; this.val = function (v) { if (null != v) { this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v; this.v = this.cv; this.$.val(this.v); this._draw(); } else { return this.v; } }; this.xy2val = function (x, y) { var a, ret; a = Math.atan2( x - (this.x + this.w2) , - (y - this.y - this.w2) ) - this.angleOffset; if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) { // if isset angleArc option, set to min if .5 under min a = 0; } else if (a < 0) { a += this.PI2; } ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc)) + this.o.min; this.o.stopper && (ret = max(min(ret, this.o.max), this.o.min)); return ret; }; this.listen = function () { // bind MouseWheel var s = this, mw = function (e) { e.preventDefault(); var ori = e.originalEvent ,deltaX = ori.detail || ori.wheelDeltaX ,deltaY = ori.detail || ori.wheelDeltaY ,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0); if ( s.cH && (s.cH(v) === false) ) return; s.val(v); } , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step}; this.$ .bind( "keydown" ,function (e) { var kc = e.keyCode; // numpad support if(kc >= 96 && kc <= 105) { kc = e.keyCode = kc - 48; } kval = parseInt(String.fromCharCode(kc)); if (isNaN(kval)) { (kc !== 13) // enter && (kc !== 8) // bs && (kc !== 9) // tab && (kc !== 189) // - && e.preventDefault(); // arrows if ($.inArray(kc,[37,38,39,40]) > -1) { e.preventDefault(); var v = parseInt(s.$.val()) + kv[kc] * m; s.o.stopper && (v = max(min(v, s.o.max), s.o.min)); s.change(v); s._draw(); // long time keydown speed-up to = window.setTimeout( function () { m*=2; } ,30 ); } } } ) .bind( "keyup" ,function (e) { if (isNaN(kval)) { if (to) { window.clearTimeout(to); to = null; m = 1; s.val(s.$.val()); } } else { // kval postcond (s.$.val() > s.o.max && s.$.val(s.o.max)) || (s.$.val() < s.o.min && s.$.val(s.o.min)); } } ); this.$c.bind("mousewheel DOMMouseScroll", mw); this.$.bind("mousewheel DOMMouseScroll", mw) }; this.init = function () { if ( this.v < this.o.min || this.v > this.o.max ) this.v = this.o.min; this.$.val(this.v); this.w2 = this.o.width / 2; this.cursorExt = this.o.cursor / 100; this.xy = this.w2; this.lineWidth = this.xy * this.o.thickness; this.lineCap = this.o.lineCap; this.radius = this.xy - this.lineWidth / 2; this.o.angleOffset && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset); this.o.angleArc && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc); // deg to rad this.angleOffset = this.o.angleOffset * Math.PI / -180; this.angleArc = this.o.angleArc * Math.PI / -180; // compute start and end angles this.startAngle = 1.5 * Math.PI + this.angleOffset; this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc; var s = max( String(Math.abs(this.o.max)).length , String(Math.abs(this.o.min)).length , 2 ) + 2; this.o.displayInput && this.i.css({ 'width' : ((this.o.width / 2 + 4) >> 0) + 'px' ,'height' : ((this.o.width / 3) >> 0) + 'px' ,'position' : 'absolute' ,'vertical-align' : 'middle' ,'margin-top' : ((this.o.width / 3) >> 0) + 'px' ,'margin-left' : '-' + ((this.o.width * 3 / 4 + 2) >> 0) + 'px' ,'border' : 0 ,'background' : 'none' ,'font' : 'bold ' + ((this.o.width / s) >> 0) + 'px Arial' ,'text-align' : 'center' ,'color' : this.o.inputColor || this.o.fgColor ,'padding' : '0px' ,'-webkit-appearance': 'none' }) || this.i.css({ 'width' : '0px' ,'visibility' : 'hidden' }); }; this.change = function (v) { this.cv = v; this.$.val(v); }; this.angle = function (v) { return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min); }; this.draw = function () { var c = this.g, // context a = this.angle(this.cv) // Angle , sat = this.startAngle // Start angle , eat = sat + a // End angle , sa, ea // Previous angles , r = 1; c.lineWidth = this.lineWidth; c.lineCap = this.lineCap; this.o.cursor && (sat = eat - this.cursorExt) && (eat = eat + this.cursorExt); c.beginPath(); c.strokeStyle = this.o.bgColor; c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true); c.stroke(); if (this.o.displayPrevious) { ea = this.startAngle + this.angle(this.v); sa = this.startAngle; this.o.cursor && (sa = ea - this.cursorExt) && (ea = ea + this.cursorExt); c.beginPath(); c.strokeStyle = this.pColor; c.arc(this.xy, this.xy, this.radius, sa, ea, false); c.stroke(); r = (this.cv == this.v); } c.beginPath(); c.strokeStyle = r ? this.o.fgColor : this.fgColor ; c.arc(this.xy, this.xy, this.radius, sat, eat, false); c.stroke(); }; this.cancel = function () { this.val(this.v); }; }; $.fn.dial = $.fn.knob = function (o) { return this.each( function () { var d = new k.Dial(); d.o = o; d.$ = $(this); d.run(); } ).parent(); }; })(jQuery);
const personalData = require('./personalData'); const webModel = require('./webModel'); const robotModel = require('./robotModel'); const webModelFunctions = require('./webModelFunctions'); const EddystoneBeaconScanner = require('eddystone-beacon-scanner'); const inRoomDistance = 15; const lostSignalTimeout = 120; // Seconds; const leftRoomTimeout = 5; // Seconds var possibleSignalLoss; var possiblyLeftTheRoom; const delayLostSignalResponse = function () { if (possiblyLeftTheRoom) { clearTimeout(possiblyLeftTheRoom); possiblyLeftTheRoom = undefined; } webModelFunctions.updateRobotMasterStatus('isInRoom', false); webModelFunctions.updateRobotMasterStatus('isClose', false); possibleSignalLoss = undefined; }; const delayLeftRoomResponse = function () { webModelFunctions.updateRobotMasterStatus('isInRoom', false); possiblyLeftTheRoom = undefined; }; var workingAverage; var previousValue; var threwOneOut = false; EddystoneBeaconScanner.on('found', function (beacon) { if (possibleSignalLoss) { clearTimeout(possibleSignalLoss); possibleSignalLoss = undefined; } workingAverage = beacon.distance; previousValue = beacon.distance; // console.log('found Eddystone Beacon:\n', JSON.stringify(beacon, null, 2)); console.log(`Beacon distance: ${Math.round(beacon.distance)} NEW`); webModelFunctions.updateRobotMasterStatus('isClose', true); }); EddystoneBeaconScanner.on('updated', function (beacon) { // console.log('updated Eddystone Beacon:\n', JSON.stringify(beacon, null, 2)); // TODO: Move the constants up in the program // Throw out single instance spikes. const spikeThreshold = 20; if (!threwOneOut && Math.abs(beacon.distance - previousValue) > spikeThreshold) { threwOneOut = true; } else { previousValue = beacon.distance; threwOneOut = false; } var newValue = previousValue; // Smooth out the changes // This must be below 1. The closer to 1 it is, the more it smooths out the number. const smoothingFactor = 0.20; workingAverage = (newValue * smoothingFactor) + ( workingAverage * ( 1.0 - smoothingFactor) ); console.log(`Beacon distance: ${Math.round(workingAverage)} ${Math.round(beacon.distance)}`); if (workingAverage < inRoomDistance) { if (possiblyLeftTheRoom) { clearTimeout(possiblyLeftTheRoom); possiblyLeftTheRoom = undefined; } if (!robotModel.master.isInRoom) { webModelFunctions.updateRobotMasterStatus('isInRoom', true); } } else { if (!possiblyLeftTheRoom) { possiblyLeftTheRoom = setTimeout(delayLeftRoomResponse, leftRoomTimeout * 1000); } } }); EddystoneBeaconScanner.on('lost', function (beacon) { // console.log('lost Eddystone beacon:\n', JSON.stringify(beacon, null, 2)); console.log(`Beacon lost.`); if (!possibleSignalLoss) { possibleSignalLoss = setTimeout(delayLostSignalResponse, lostSignalTimeout * 1000); } }); EddystoneBeaconScanner.startScanning(true); /* Sample output: found Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -91, "distance": 0.35481338923357547, "lastSeen": 1465710587440 } found Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -91, "distance": 0.35481338923357547, "lastSeen": 1465710587440 } found Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -86, "distance": 0.19952623149688797, "lastSeen": 1465710585429 } updated Eddystone Beacon: { "txPower": -59, "url": "https://goo.gl/wl2NJt", "id": "ecb428720d14", "type": "url", "rssi": -91, "distance": 0.35481338923357547, "lastSeen": 1465710587440 } */
define({ "_widgetLabel": "適合性モデラー", "general": { "clear": "消去", "cancel": "キャンセル", "save": "実行", "saveAs": "エクスポート" }, "saveModel": { "save": "エクスポート", "title": "タイトル: ", "summary": "サマリー: ", "description": "説明: ", "tags": "タグ: ", "folder": "フォルダー: ", "homeFolderPattern": "{username} (ホーム)", "failed": "エクスポートできません。" }, "util": { "colorRamp": { "1": "極めて低い", "2": "非常に低い", "3": "低", "4": "やや低い", "5": "中", "6": "やや高い", "7": "高", "8": "非常に高い", "9": "極めて高い", "low": "低", "high": "高", "tipPattern": "{label} ({value})", "flipCaption": "反転" } }, "wro": { "caption": "適合性モデラー", "browsePrompt": "加重オーバーレイ サービス", "selectLayersCaption": "レイヤーの選択", "selectLayers": "レイヤー", "designModelCaption": "モデルの設計", "designModel": "モデルの設計", "transparency": "透過表示", "visible": "表示", "total": "合計", "unableToLoad": "モデルを読み込めません。", "projectNotOpen": "プロジェクトが開いていません。", "readMore": "詳細", "validation": { "validating": "整合チェックしています...", "invalidItemCaption": "加重オーバーレイ サービスの警告", "notAnImageService": "このアイテムはイメージ サービスではありません。", "notAWroService": "このアイテムは加重オーバーレイ サービスではありません。", "undefinedUrl": "このアイテムの URL が定義されていません。", "inaccessible": "サービスにアクセスできません。", "generalError": "アイテムを開けません。", "missingFieldPattern": "{field} は必須フィールドです。", "notAllowRasterFunction": "[allowRasterFunction] を [true] に設定する必要があります。", "notNearestResampling": "[defaultResamplingMethod] を [最近隣内挿法] に設定する必要があります。", "notIsWeightedOverlayProp": "主要プロパティの [IsWeightedOverlay] を [true] に設定する必要があります。", "invalidLink": "URL が無効です。 選択したレイヤーのサイトを開けませんでした。", "unexpectedError": "予期しない状態が発生しました。", "rangeMessage": "値は ${0} ~ ${1} の間でなければなりません", "rangeMessage100": "値は 0 ~ 100 の間でなければなりません", "maxLayers": "サービスで許可されているレイヤーの最大数は ${0} です。新しいレイヤーを追加するには、レイヤーを削除する必要があります。", "notFound": "加重オーバーレイ サービスでレイヤー ${0} が見つかりません", "wroServiceNotDefined": "モデルに加重オーバーレイ サービスが定義されていません。", "overlayLayerOutputInvalid": "オーバーレイ レイヤー [${0}] の再分類範囲 [${1}] の出力値がない、または無効です", "overlayLayerInputInvalid": "オーバーレイ レイヤー [${0}] の再分類範囲 [${1}] の入力最小値/最大値がない、または無効です", "overlayLayerRangesMissing": "オーバーレイ レイヤー [${0}] に再分類範囲がありません", "overlayLayerWeight": "オーバーレイ レイヤーの加重を合計 100 にする必要があります", "overlayLayerRequired": "少なくとも 1 つのオーバーレイ レイヤーが必要です", "overlayLayerNotDefined": "オーバーレイ レイヤーが定義されていません", "requiresColormap": "このラスター関数にはカラーマップが必要ですが、モデルに有効なカラーマップ定義がありません", "createModelError": "モデルの作成中にエラーが発生しました", "invalidModel": "モデルが有効ではありません", "imageServiceNotDefined": "イメージ サービス レイヤーが定義されていません", "imageLayerNotDefined": "イメージ サービス レイヤーが定義されていません", "histogramNotDefined": "加重オーバーレイ ヒストグラム関数が定義されていません。" }, "colorRampLabel": { "Green Yellow Red": "緑 黄 赤", "Red Yellow Green": "赤 黄 緑", "Yellow to Dark Red": "黄から濃い赤", "Dark Red to Yellow": "濃い赤から黄", "Light Gray to Dark Gray": "ライト グレーからダーク グレー", "Dark Gray to Light Gray": "ダーク グレーからライト グレー", "Light Brown to Dark Brown": "ライト ブラウンからダーク ブラウン", "Dark Brown to Light Brown": "ダーク ブラウンからライト ブラウン", "Full Spectrum - Bright Red to Blue": "フル スペクトル - 明るい赤から青", "Full Spectrum - Bright Blue to Red": "フル スペクトル - 明るい青から赤", "Partial Spectrum - Yellow to Blue": "部分スペクトル - 黄から青", "Partial Spectrum - Blue to Yellow": "部分スペクトル - 青から黄", "Yellow-Green to Dark Blue": "黄緑から濃い青", "Dark Blue to Yellow-Green": "濃い青から黄緑", "Cold to Hot Diverging": "寒色から暖色に分散", "Hot to Cold Diverging": "暖色から寒色に分散", "Surface - Low to High": "サーフェス - 低から高", "Surface - High to Low": "サーフェス - 高から低" } }, "tabs": { "layers": "レイヤー", "model": "モデル", "chart": "チャート" }, "chart": { "prompt": "機能", "working": "更新しています...", "polygonTool": "ポリゴンを描画", "freehandPolygonTool": "フリーハンド ポリゴンの描画", "selectTool": "レイヤーから選択", "panTool": "Pan", "clearButton": "解除", "noModelLayer": "モデルなし", "noSubjectLayers": "マップにポリゴン レイヤーがありません。", "tipPattern": "${category} - ${label}: ${percent}%", "tipPattern2": "${category}: ${percent}%", "labelPattern": "${category} - ${label}" } });
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ var CircleSprite = cc.Sprite.extend({ _degree:0, ctor:function () { this._super(); }, draw:function () { cc.drawingUtil.setDrawColor4B(255,255,255,255); if (this._degree < 0) this._degree = 360; cc.drawingUtil.drawCircle(cc.PointZero(), 30, cc.DEGREES_TO_RADIANS(this._degree), 60, true); }, myUpdate:function (dt) { this._degree -= 6; } }); var Helloworld = cc.Layer.extend({ isMouseDown:false, helloImg:null, helloLabel:null, circle:null, sprite:null, init:function () { var selfPointer = this; ////////////////////////////// // 1. super init first this._super(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // ask director the window size var size = cc.Director.getInstance().getWinSize(); // add a "close" icon to exit the progress. it's an autorelease object var closeItem = cc.MenuItemImage.create( "res/CloseNormal.png", "res/CloseSelected.png", function () { history.go(-1); },this); closeItem.setAnchorPoint(cc.p(0.5, 0.5)); var menu = cc.Menu.create(closeItem); menu.setPosition(cc.PointZero()); this.addChild(menu, 1); closeItem.setPosition(cc.p(size.width - 20, 20)); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38); // position the label on the center of the screen this.helloLabel.setPosition(cc.p(size.width / 2, 0)); // add the label as a child to this layer this.addChild(this.helloLabel, 5); var lazyLayer = cc.Layer.create(); this.addChild(lazyLayer); // add "HelloWorld" splash screen" this.sprite = cc.Sprite.create("res/HelloWorld.png"); this.sprite.setPosition(cc.p(size.width / 2, size.height / 2)); this.sprite.setScale(0.5); this.sprite.setRotation(180); lazyLayer.addChild(this.sprite, 0); var rotateToA = cc.RotateTo.create(2, 0); var scaleToA = cc.ScaleTo.create(2, 1, 1); this.sprite.runAction(cc.Sequence.create(rotateToA, scaleToA)); this.circle = new CircleSprite(); this.circle.setPosition(cc.p(40, size.height - 60)); this.addChild(this.circle, 2); this.circle.schedule(this.circle.myUpdate, 1 / 60); this.helloLabel.runAction(cc.Spawn.create(cc.MoveBy.create(2.5, cc.p(0, size.height - 40)),cc.TintTo.create(2.5,255,125,0))); this.setTouchEnabled(true); return true; }, // a selector callback menuCloseCallback:function (sender) { cc.Director.getInstance().end(); }, onTouchesBegan:function (touches, event) { this.isMouseDown = true; }, onTouchesMoved:function (touches, event) { if (this.isMouseDown) { if (touches) { //this.circle.setPosition(cc.p(touches[0].getLocation().x, touches[0].getLocation().y)); } } }, onTouchesEnded:function (touches, event) { this.isMouseDown = false; }, onTouchesCancelled:function (touches, event) { console.log("onTouchesCancelled"); } }); var HelloWorldScene = cc.Scene.extend({ onEnter:function () { this._super(); var layer = new Helloworld(); layer.init(); this.addChild(layer); } });
define(['iframeResizer'], function(iFrameResize) { describe('Parent Page', function() { describe('reset Page', function() { var iframe; var log=LOG; var testId = 'parentPage1'; beforeEach(function(done){ loadIFrame('iframe600.html'); iframe = iFrameResize({ log:log, id:testId })[0]; spyOn(iframe.contentWindow,'postMessage').and.callFake(done); mockMsgFromIFrame(iframe,'reset'); }); afterEach(function(){ tearDown(iframe); }) it('receive message', function() { expect(iframe.contentWindow.postMessage).toHaveBeenCalledWith('[iFrameSizer]reset', 'http://localhost:9876'); }); }); describe('late load msg received', function() { var iframe; var log=LOG; var testId = 'parentPage2'; beforeEach(function(done){ loadIFrame('iframe600.html'); iframe = iFrameResize({ log:log, id:testId })[0]; spyOn(iframe.contentWindow,'postMessage').and.callFake(done); window.postMessage('[iFrameResizerChild]Ready','*'); }); afterEach(function(){ tearDown(iframe); }) it('receive message', function() { expect(iframe.contentWindow.postMessage).toHaveBeenCalledWith('[iFrameSizer]parentPage2:8:false:true:32:true:true:null:bodyOffset:null:null:0:false:parent:scroll', 'http://localhost:9876'); }); }); xdescribe('default resize', function() { var iframe; var log=LOG; var testId = 'defaultResize3'; it('receive message', function(done) { loadIFrame('iframe600.html'); iframe = iFrameResize({ log:log, id:testId, resizeCallback:function(){ setTimeout(tearDown.bind(null,iframe),1); done(); } })[0]; mockMsgFromIFrame(iframe,'foo'); }); }); }); });
const TetherBase = {modules: []}; let zeroElement = null; // Same as native getBoundingClientRect, except it takes into account parent <frame> offsets // if the element lies within a nested document (<frame> or <iframe>-like). function getActualBoundingClientRect(node) { let boundingRect = node.getBoundingClientRect(); // The original object returned by getBoundingClientRect is immutable, so we clone it // We can't use extend because the properties are not considered part of the object by hasOwnProperty in IE9 let rect = {}; for (var k in boundingRect) { rect[k] = boundingRect[k]; } if (node.ownerDocument !== document) { let frameElement = node.ownerDocument.defaultView.frameElement; if (frameElement) { let frameRect = getActualBoundingClientRect(frameElement); rect.top += frameRect.top; rect.bottom += frameRect.top; rect.left += frameRect.left; rect.right += frameRect.left; } } return rect; } function getScrollParents(el) { // In firefox if the el is inside an iframe with display: none; window.getComputedStyle() will return null; // https://bugzilla.mozilla.org/show_bug.cgi?id=548397 const computedStyle = getComputedStyle(el) || {}; const position = computedStyle.position; let parents = []; if (position === 'fixed') { return [el]; } let parent = el; while ((parent = parent.parentNode) && parent && parent.nodeType === 1) { let style; try { style = getComputedStyle(parent); } catch (err) {} if (typeof style === 'undefined' || style === null) { parents.push(parent); return parents; } const {overflow, overflowX, overflowY} = style; if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { if (position !== 'absolute' || ['relative', 'absolute', 'fixed'].indexOf(style.position) >= 0) { parents.push(parent) } } } parents.push(el.ownerDocument.body); // If the node is within a frame, account for the parent window scroll if (el.ownerDocument !== document) { parents.push(el.ownerDocument.defaultView); } return parents; } const uniqueId = (() => { let id = 0; return () => ++id; })(); const zeroPosCache = {}; const getOrigin = () => { // getBoundingClientRect is unfortunately too accurate. It introduces a pixel or two of // jitter as the user scrolls that messes with our ability to detect if two positions // are equivilant or not. We place an element at the top left of the page that will // get the same jitter, so we can cancel the two out. let node = zeroElement; if (!node) { node = document.createElement('div'); node.setAttribute('data-tether-id', uniqueId()); extend(node.style, { top: 0, left: 0, position: 'absolute' }); document.body.appendChild(node); zeroElement = node; } const id = node.getAttribute('data-tether-id'); if (typeof zeroPosCache[id] === 'undefined') { zeroPosCache[id] = getActualBoundingClientRect(node); // Clear the cache when this position call is done defer(() => { delete zeroPosCache[id]; }); } return zeroPosCache[id]; }; function removeUtilElements() { if (zeroElement) { document.body.removeChild(zeroElement); } zeroElement = null; }; function getBounds(el) { let doc; if (el === document) { doc = document; el = document.documentElement; } else { doc = el.ownerDocument; } const docEl = doc.documentElement; const box = getActualBoundingClientRect(el); const origin = getOrigin(); box.top -= origin.top; box.left -= origin.left; if (typeof box.width === 'undefined') { box.width = document.body.scrollWidth - box.left - box.right; } if (typeof box.height === 'undefined') { box.height = document.body.scrollHeight - box.top - box.bottom; } box.top = box.top - docEl.clientTop; box.left = box.left - docEl.clientLeft; box.right = doc.body.clientWidth - box.width - box.left; box.bottom = doc.body.clientHeight - box.height - box.top; return box; } function getOffsetParent(el) { return el.offsetParent || document.documentElement; } function getScrollBarSize() { const inner = document.createElement('div'); inner.style.width = '100%'; inner.style.height = '200px'; const outer = document.createElement('div'); extend(outer.style, { position: 'absolute', top: 0, left: 0, pointerEvents: 'none', visibility: 'hidden', width: '200px', height: '150px', overflow: 'hidden' }); outer.appendChild(inner); document.body.appendChild(outer); const widthContained = inner.offsetWidth; outer.style.overflow = 'scroll'; let widthScroll = inner.offsetWidth; if (widthContained === widthScroll) { widthScroll = outer.clientWidth; } document.body.removeChild(outer); const width = widthContained - widthScroll; return {width, height: width}; } function extend(out={}) { const args = []; Array.prototype.push.apply(args, arguments); args.slice(1).forEach(obj => { if (obj) { for (let key in obj) { if ({}.hasOwnProperty.call(obj, key)) { out[key] = obj[key]; } } } }); return out; } function removeClass(el, name) { if (typeof el.classList !== 'undefined') { name.split(' ').forEach(cls => { if (cls.trim()) { el.classList.remove(cls); } }); } else { const regex = new RegExp(`(^| )${ name.split(' ').join('|') }( |$)`, 'gi'); const className = getClassName(el).replace(regex, ' '); setClassName(el, className); } } function addClass(el, name) { if (typeof el.classList !== 'undefined') { name.split(' ').forEach(cls => { if (cls.trim()) { el.classList.add(cls); } }); } else { removeClass(el, name); const cls = getClassName(el) + ` ${name}`; setClassName(el, cls); } } function hasClass(el, name) { if (typeof el.classList !== 'undefined') { return el.classList.contains(name); } const className = getClassName(el); return new RegExp(`(^| )${ name }( |$)`, 'gi').test(className); } function getClassName(el) { // Can't use just SVGAnimatedString here since nodes within a Frame in IE have // completely separately SVGAnimatedString base classes if (el.className instanceof el.ownerDocument.defaultView.SVGAnimatedString) { return el.className.baseVal; } return el.className; } function setClassName(el, className) { el.setAttribute('class', className); } function updateClasses(el, add, all) { // Of the set of 'all' classes, we need the 'add' classes, and only the // 'add' classes to be set. all.forEach(cls => { if (add.indexOf(cls) === -1 && hasClass(el, cls)) { removeClass(el, cls); } }); add.forEach(cls => { if (!hasClass(el, cls)) { addClass(el, cls); } }); } const deferred = []; const defer = (fn) => { deferred.push(fn); }; const flush = () => { let fn; while(fn = deferred.pop()) { fn(); } }; class Evented { on(event, handler, ctx, once=false) { if (typeof this.bindings === 'undefined') { this.bindings = {}; } if (typeof this.bindings[event] === 'undefined') { this.bindings[event] = []; } this.bindings[event].push({handler, ctx, once}); } once(event, handler, ctx) { this.on(event, handler, ctx, true); } off(event, handler) { if (typeof this.bindings === 'undefined' || typeof this.bindings[event] === 'undefined') { return; } if (typeof handler === 'undefined') { delete this.bindings[event]; } else { let i = 0; while (i < this.bindings[event].length) { if (this.bindings[event][i].handler === handler) { this.bindings[event].splice(i, 1); } else { ++i; } } } } trigger(event, ...args) { if (typeof this.bindings !== 'undefined' && this.bindings[event]) { let i = 0; while (i < this.bindings[event].length) { const {handler, ctx, once} = this.bindings[event][i]; let context = ctx; if (typeof context === 'undefined') { context = this; } handler.apply(context, args); if (once) { this.bindings[event].splice(i, 1); } else { ++i; } } } } } TetherBase.Utils = { getActualBoundingClientRect, getScrollParents, getBounds, getOffsetParent, extend, addClass, removeClass, hasClass, updateClasses, defer, flush, uniqueId, Evented, getScrollBarSize, removeUtilElements }; export default TetherBase;
var isDate = require('../lang/isDate'); /** * return the day of the year (1..366) */ function dayOfTheYear(date){ return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 1)) / 86400000 + 1; } module.exports = dayOfTheYear;
module.exports = rotate /** * Rotates a mat2 by the given angle * * @alias mat2.rotate * @param {mat2} out the receiving matrix * @param {mat2} a the matrix to rotate * @param {Number} rad the angle to rotate the matrix by * @returns {mat2} out */ function rotate(out, a, rad) { var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3] var s = Math.sin(rad) var c = Math.cos(rad) out[0] = a0 * c + a2 * s out[1] = a1 * c + a3 * s out[2] = a0 * -s + a2 * c out[3] = a1 * -s + a3 * c return out }
// Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const { fork } = require('child_process'); const http = require('http'); if (process.argv[2] === 'child') { process.once('message', (req, socket) => { const res = new http.ServerResponse(req); res.assignSocket(socket); res.end(); }); process.send('ready'); return; } const { kTimeout } = require('internal/timers'); let child; let socket; const server = http.createServer(common.mustCall((req, res) => { const r = { method: req.method, headers: req.headers, path: req.path, httpVersionMajor: req.httpVersionMajor, query: req.query, }; socket = res.socket; child.send(r, socket); server.close(); })); server.listen(0, common.mustCall(() => { child = fork(__filename, [ 'child' ]); child.once('message', (msg) => { assert.strictEqual(msg, 'ready'); const req = http.request({ port: server.address().port, }, common.mustCall((res) => { res.on('data', () => {}); res.on('end', common.mustCall(() => { assert.strictEqual(socket[kTimeout], null); assert.strictEqual(socket.parser, null); assert.strictEqual(socket._httpMessage, null); })); })); req.end(); }); }));
/*jshint -W104 */ 'use strict'; const Transmitter = require('./transmitter'), RfxCom = require('./rfxcom'); /* * This is a class for controlling Lighting6 lights. */ class Lighting6 extends Transmitter { constructor(rfxcom, subtype, options) { super(rfxcom, subtype, options); this.packetType = "lighting6"; this.packetNumber = 0x15; this.cmdseqnbr = -1; // Will be incremented by the first call to nextCmdseqbr() } nextCmdseqnbr() { this.cmdseqnbr = this.cmdseqnbr + 1; if ((this.isSubtype('BLYSS') && this.cmdseqnbr >= 5) || (this.isSubtype('CUVEO') && this.cmdseqnbr >= 255)) { this.cmdseqnbr = 0; } return this.cmdseqnbr; } /* * Splits the device id into idBytes, group, unitCode. * */ _splitDeviceId(deviceId) { const parts = Transmitter.splitAtSlashes(deviceId); if (this.isSubtype(['BLYSS', 'CUVEO']) && parts.length !== 3) { throw new Error("Invalid deviceId format"); } const id = RfxCom.stringToBytes(parts[0], 2), unit = parseInt(parts[2]); let group = parts[1]; if (this.isSubtype('BLYSS')) { group = group.toUpperCase().charCodeAt(0); if (group < 0x41 || group > 0x50) { throw new Error("Invalid group code '" + parts[1] + "'") } if (unit < 0 || unit > 5) { throw new Error("Invalid unit number " + unit) } } else if (this.isSubtype('CUVEO')) { group = parseInt(group); if (group < 0x0 || group > 0x03) { throw new Error("Invalid group code '" + parts[1] + "'") } if ((group === 0 && (unit < 1 || unit > 2)) || (group > 0 && (unit < 1 || unit > 8))) { throw new Error("Invalid unit number " + unit) } } return { idBytes: id.bytes, groupCode: group, unitCode: unit }; }; _sendCommand(deviceId, command, callback) { const device = this._splitDeviceId(deviceId); if (device.unitCode === 0) { command = command + 2; } let buffer = [device.idBytes[0], device.idBytes[1], device.groupCode, device.unitCode, command, this.nextCmdseqnbr(), 0, 0]; return this.sendRaw(this.packetNumber, this.subtype, buffer, callback); }; /* * Switch on deviceId/unitCode */ switchOn(deviceId, callback) { return this._sendCommand(deviceId, 0x00, callback); }; /* * Switch off deviceId/unitCode */ switchOff(deviceId, callback) { return this._sendCommand(deviceId, 0x01, callback); }; } module.exports = Lighting6;
var Router = require('koa-router'); var Role = require('../../lib/role'); var Middleware = require('../../lib/middleware'); var router = module.exports = new Router(); router.use(Middleware.allow('admin.roles')); router.get('/admin/api/roles', function *() { var page = parseInt(this.request.query.page) || 1; var perPage = parseInt(this.request.query.perpage) || 100; var perms = this.request.query.permissions || false; var q = {}; try { q = JSON.parse(this.request.query.q); } catch(e) {} var conditions = {}; if (q.name) { conditions.name = new RegExp(q.name, 'i'); } // Setup options var _opts = { skip: (page - 1) * perPage, limit: perPage }; // Setup fields var _fields = [ 'name', 'desc', 'created' ]; if (perms) { _opts.populatedPermission = perms; _fields.push('permissions'); } // Fetching a list with specific condition var data = yield Role.list(conditions, _fields, _opts); this.body = { page: page, perPage: perPage, pageCount: Math.ceil(data.count / perPage), roles: data.roles }; }); router.post('/admin/api/roles', function *() { if (!this.request.body.name || !this.request.body.desc || !this.request.body.perms) { this.status = 401; return; } try { // Create a new role var role = yield Role.create({ name: this.request.body.name, desc: this.request.body.desc, perms: this.request.body.perms }); } catch(e) { console.log(e); } this.body = { role: { _id: role._id, name: role.name, desc: role.desc, perms: role.perms } }; });
angular .module('angularCancelOnNavigateModule', []) .config(function($httpProvider) { $httpProvider.interceptors.push('HttpRequestTimeoutInterceptor'); }) .run(function ($rootScope, HttpPendingRequestsService) { $rootScope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) { if (newUrl != oldUrl) { HttpPendingRequestsService.cancelAll(); } }) });
define([ 'matreshka_dir/core/var/core', 'matreshka_dir/core/var/sym', 'matreshka_dir/core/initmk' ], function(core, sym, initMK) { "use strict"; var unbindNode = core.unbindNode = function(object, key, node, evt) { if (!object || typeof object != 'object') return object; initMK(object); var type = typeof key, $nodes, keys, special = object[sym].special[key], i, indexOfDot, path, listenKey, _evt; if (key instanceof Array) { for (i = 0; i < key.length; i++) { evt = node; unbindNode(object, key[i][0], key[i][1] || evt, evt); } return object; } if (type == 'string') { keys = key.split(/\s/); if (keys.length > 1) { for (i = 0; i < keys.length; i++) { unbindNode(object, keys[i], node, evt); } return object; } } indexOfDot = key.indexOf('.'); if (~indexOfDot) { path = key.split('.'); var target = object; for (i = 0; i < path.length - 1; i++) { target = target[path[i]]; } core._undelegateListener(object, path.slice(0, path.length - 2), 'change:' + path[path.length - 2]); unbindNode(target, path[path.length - 1], node, evt); return object; } if (key === null) { for (key in object[sym].special) if (object[sym].special.hasOwnProperty(key)) { unbindNode(object, key, node, evt); } return object; } else if (type == 'object') { for (i in key) if (key.hasOwnProperty(i)) { unbindNode(object, i, key[i], node); } return object; } else if (!node) { if (special && special.$nodes) { return unbindNode(object, key, special.$nodes, evt); } else { return object; } } else if (node.length == 2 && !node[1].nodeName && (node[1].setValue || node[1].getValue || node[1].on)) { // It actually ignores binder. With such a syntax you can assign definite binders to some variable and then easily delete all at once using return unbindNode(object, key, node[0], evt); } else if (!special) { return object; } $nodes = core._getNodes(object, node); for (i = 0; i < $nodes.length; i++) { core.domEvents.remove({ key: key, node: $nodes[i], instance: object }); special.$nodes = special.$nodes.not($nodes[i]); (function(node) { core._removeListener(object, '_runbindings:' + key, null, null, { node: node, howToRemove: function(onData, offData) { return onData.node == offData.node; } }); })($nodes[i]); } if (object.isMK) { object.$nodes[key] = special.$nodes; object.nodes[key] = special.$nodes[0] || null; if (key == 'sandbox') { object.sandbox = special.$nodes[0] || null; object.$sandbox = special.$nodes; } } if (!evt || !evt.silent) { _evt = { key: key, $nodes: $nodes, node: $nodes[0] || null }; for (i in evt) { _evt[i] = evt[i]; } core._fastTrigger(object, 'unbind:' + key, _evt); core._fastTrigger(object, 'unbind', _evt); } return object; }; });
var exampleOutput = function(id, content) { var outputDiv = document.getElementById(id); if (outputDiv && outputDiv.childNodes && outputDiv.childNodes[0]) { outputDiv.replaceChild(document.createTextNode(content), outputDiv.childNodes[0]); } else { outputDiv.appendChild(document.createTextNode(content)); } }; module.exports = exampleOutput;
'use strict'; angular.module( 'QualityABTracker.services', [] ) .factory( 'trackerDataService', function( $http ) { var api = {}; return api; })
const { WebContentsView, app } = require('electron'); app.whenReady().then(function () { new WebContentsView({}) // eslint-disable-line app.quit(); });
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ const resolve = require('rollup-plugin-node-resolve'); const sourcemaps = require('rollup-plugin-sourcemaps'); const globals = { '@angular/core': 'ng.core', 'rxjs/BehaviorSubject': 'Rx', 'rxjs/ConnectableObservable': 'Rx', 'rxjs/Observable': 'Rx', 'rxjs/Subject': 'Rx', 'rxjs/observable/concat': 'Rx.Observable', 'rxjs/observable/defer': 'Rx.Observable', 'rxjs/observable/fromEvent': 'Rx.Observable', 'rxjs/observable/merge': 'Rx.Observable', 'rxjs/observable/of': 'Rx.Observable', 'rxjs/observable/throw': 'Rx.Observable', 'rxjs/operator/do': 'Rx.Observable.prototype', 'rxjs/operator/filter': 'Rx.Observable.prototype', 'rxjs/operator/map': 'Rx.Observable.prototype', 'rxjs/operator/publish': 'Rx.Observable.prototype', 'rxjs/operator/startWith': 'Rx.Observable.prototype', 'rxjs/operator/switchMap': 'Rx.Observable.prototype', 'rxjs/operator/take': 'Rx.Observable.prototype', 'rxjs/operator/toPromise': 'Rx.Observable.prototype', }; module.exports = { entry: '../../dist/packages-dist/service-worker/esm5/service-worker.js', dest: '../../dist/packages-dist/service-worker/bundles/service-worker.umd.js', format: 'umd', exports: 'named', moduleName: 'ng.serviceWorker', plugins: [resolve(), sourcemaps()], external: Object.keys(globals), globals: globals };
'use strict'; const sysPath = require('./path'); const fs = require('fs'); const anymatch = require('anymatch'); const promisify = require('micro-promisify'); const modules = require('./modules'); const xBrowserResolve = require('./resolve'); const loadGlobalsAndStyles = require('./load-globs-styles'); const explore = require('./explore'); const processFiles = require('./process'); const packages = require('./packages'); const DepGraph = require('./dep-graph'); const UsedShims = require('./used-shims'); const ProjectModuleMap = require('./project-module-map'); const readFile = promisify((path, callback) => fs.readFile(path, {encoding: 'utf8'}, callback)); const dir = sysPath.dirname(sysPath.dirname(require.resolve('..'))); const brunchRe = /\-brunch|brunch\-/; const packageRe = /node_modules/; const isNodeModule = path => packageRe.test(path); const isNotBrunchPlugin = path => !brunchRe.test(path); const isShim = path => path.indexOf(dir) === 0; const jsonRe = /\.json$/; const isJson = path => jsonRe.test(path); const jsJsonRe = /\.(json|js)$/; const isJsOrJson = path => jsJsonRe.test(path); const cssRe = /\.css$/; const isNotCss = path => !cssRe.test(path); const fileReflection = (statics, conventions) => { const isPackage = path => isNodeModule(path) && (statics || []).indexOf(path) === -1; const isVendor = path => isPackage(path) ? false : anymatch(conventions.vendor, path); const isApp = path => !anymatch(conventions.vendor, path); return {isPackage, isVendor, isApp}; }; class Deppack { constructor(config, json) { if (!json.overrides) json.overrides = {}; if (!json.dependencies) json.dependencies = {}; this.rootPackage = json; this.conventions = config.conventions; this.paths = config.paths; this.npm = config.npm || {}; this.isProduction = config._normalized.isProduction; this.globalPseudofile = '___globals___'; this.plugins = []; this.npmPlugins = []; this.allMatchers = []; this.rootMainCache = {}; this.usedShims = new UsedShims(); this.depGraph = new DepGraph(); this.modMap = new ProjectModuleMap(config.modules.nameCleaner); this.fileReflection = fileReflection(this.npm.static, this.conventions); this.resolve = xBrowserResolve.resolve(this.rootPackage, this.modMap, this.npm.aliases, this.globalPseudofile); this.getPackageJson = filePath => { return packages.packageJson(filePath, this.rootPackage); }; this.canCallDep = path => packages.canCallDep(this.getPackageJson, path); } init() { return xBrowserResolve.buildModMap(this.modMap, this.paths.watched, this.rootPackage) .then(() => loadGlobalsAndStyles(this.paths.root, this.depGraph, this.globalPseudofile, this.npm, this.resolve)); } setPlugins(plugins, npmPlugins) { this.plugins = plugins; this.npmPlugins = npmPlugins; const plugs = plugins.compilers.filter(x => x.type === 'javascript' && npmPlugins.indexOf(x.brunchPluginName) !== -1); const extensions = plugs.map(x => x.extension).filter(x => x); const patterns = plugs.map(x => x.pattern).filter(x => x); const extMatchers = extensions.map(x => new RegExp(`\\.${x}$`)); const allMatchers = patterns.concat(extMatchers); this.allMatchers = allMatchers; } exploreDeps(sourceFile) { return explore(this.depGraph, this.modMap, this.usedShims, this.canCallDep, this.isProduction, this.fileReflection, this.resolve, this.npm)(sourceFile); } processFiles(root, files, processor) { const filePaths = files.map(f => f.path); const requiredAliases = modules.requiredAliases(this.rootMainCache, this.getPackageJson, this.usedShims, filePaths); processFiles(this.npm.aliases || {}, this.npm.globals || {}, this.usedShims, requiredAliases)(root, files, processor); } wrapInModule(filePath) { filePath = sysPath.resolve('.', filePath); return readFile(filePath).then(src => this.wrapSourceInModule(src, filePath)); } wrapSourceInModule(src, filePath) { return modules.wrap(this.getPackageJson, this.rootMainCache, filePath, src); } needsProcessing(file) { return isNodeModule(file.path) && (isJsOrJson(file.path) || this.allMatchers.some(reg => reg.test(file.path))) && isNotBrunchPlugin(file.path) && this.fileReflection.isPackage(file.path) || this.isNpm(file.path); } isNpm(path) { return isNodeModule(path) && isNotBrunchPlugin(path) && isNotCss(path) && this.fileReflection.isPackage(path) || isShim(path); } isNpmJSON(path) { return this.isNpm(path) && isJson(path); } isShim(path) { return isShim(path); } getAllDependents(path) { const fileDeps = [path].concat(this.depGraph.recursiveDependents(path)); const globDeps = this.depGraph.recursiveDependents(this.globalPseudofile); return fileDeps.concat(globDeps); } graph() { return this.depGraph.serialize(this.modMap, this.fileReflection); } } module.exports = Deppack;
var gremlin = require('../src'); var client = gremlin.createClient(); var script = 'g.V().range(1, 2)'; // Callback style client.execute(script, function(err, res) { console.log(err, res); }); // Stream style var s = client.stream(script); s.on('data', function(result) { console.log(result); }); s.on('end', function() { console.log("All results fetched"); }); s.on('error', function(e) { console.log(e); });
describe('mdListItem directive', function() { var attachedElements = []; var $compile, $rootScope; beforeEach(module('material.components.list', 'material.components.checkbox', 'material.components.switch')); beforeEach(inject(function(_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; })); afterEach(function() { attachedElements.forEach(function(element) { element.remove(); }); attachedElements = []; }); function setup(html) { var el; inject(function($compile, $rootScope) { el = $compile(html)($rootScope); $rootScope.$apply(); }); attachedElements.push(el); return el; } describe('md-list-item', function() { it('should have `._md` class indicator', inject(function($compile, $rootScope) { var element = $compile('<md-list><md-list-item></md-list-item></md-list>')($rootScope.$new()); expect(element.find('md-list-item').hasClass('_md')).toBe(true); })); }); it('forwards click events for md-checkbox', function() { var listItem = setup( '<md-list-item>' + '<md-checkbox ng-model="modelVal"></md-checkbox>' + '</md-list-item>'); var cntr = listItem[0].querySelector('div'); cntr.click(); expect($rootScope.modelVal).toBe(true); cntr.click(); expect($rootScope.modelVal).toBe(false); }); it('forwards click events for md-switch', function() { var listItem = setup( '<md-list-item>' + '<md-switch ng-model="modelVal"></md-switch>' + '</md-list-item>'); var cntr = listItem[0].querySelector('div'); cntr.click(); expect($rootScope.modelVal).toBe(true); cntr.click(); expect($rootScope.modelVal).toBe(false); }); it('should not trigger the proxy element, when clicking on a slider', function() { var listItem = setup( '<md-list-item>' + '<md-slider></md-slider>' + '<md-switch ng-model="modelVal"></md-switch>' + '</md-list-item>'); var slider = listItem.find('md-slider')[0]; slider.click(); expect($rootScope.modelVal).toBeFalsy(); }); it('should convert spacebar keypress events as clicks', inject(function($mdConstant) { var listItem = setup( '<md-list-item>' + '<md-checkbox ng-model="modelVal"></md-checkbox>' + '</md-list-item>'); var checkbox = angular.element(listItem[0].querySelector('md-checkbox')); expect($rootScope.modelVal).toBeFalsy(); checkbox.triggerHandler({ type: 'keypress', keyCode: $mdConstant.KEY_CODE.SPACE }); expect($rootScope.modelVal).toBe(true); })); it('should not convert spacebar keypress for text areas', inject(function($mdConstant) { var listItem = setup( '<md-list-item>' + '<textarea ng-model="modelVal">' + '</md-list-item>'); var inputEl = angular.element(listItem[0].querySelector('textarea')[0]); expect($rootScope.modelVal).toBeFalsy(); inputEl.triggerHandler({ type: 'keypress', keyCode: $mdConstant.KEY_CODE.SPACE }); expect($rootScope.modelVal).toBeFalsy(); })); it('should not convert spacebar keypress for editable elements', inject(function($mdConstant) { var listItem = setup( '<md-list-item>' + '<div contenteditable="true"></div>' + '</md-list-item>'); var editableEl = listItem.find('div'); var onClickSpy = jasmine.createSpy('onClickSpy'); // We need to append our element to the DOM because the browser won't detect `contentEditable` when the element // is hidden in the DOM. See the related issue for chromium: // https://code.google.com/p/chromium/issues/detail?id=313082 document.body.appendChild(listItem[0]); editableEl.on('click', onClickSpy); // We need to dispatch the keypress natively, because otherwise the `keypress` won't be triggered in the list. var event = document.createEvent('Event'); event.keyCode = $mdConstant.KEY_CODE.SPACE; event.initEvent('keypress', true, true); editableEl[0].dispatchEvent(event); expect(onClickSpy).not.toHaveBeenCalled(); document.body.removeChild(listItem[0]); })); it('creates buttons when used with ng-click', function() { var listItem = setup( '<md-list-item ng-click="sayHello()" ng-disabled="true">' + '<p>Hello world</p>' + '</md-list-item>'); // List items, which are clickable always contain a button wrap at the top level. var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The button wrap should contain the button executor, the inner content and the // secondary item container as children. expect(buttonWrap.children().length).toBe(3); var buttonExecutor = buttonWrap.children()[0]; // The list item should forward the click and disabled attributes. expect(buttonExecutor.hasAttribute('ng-click')).toBe(true); expect(buttonExecutor.hasAttribute('ng-disabled')).toBe(true); var innerContent = buttonWrap.children()[1]; expect(innerContent.nodeName).toBe('DIV'); expect(innerContent.firstElementChild.nodeName).toBe('P'); }); it('creates buttons when used with ng-dblclick', function() { var listItem = setup( '<md-list-item ng-dblclick="sayHello()" ng-disabled="true">' + '<p>Hello world</p>' + '</md-list-item>'); // List items, which are clickable always contain a button wrap at the top level. var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The button wrap should contain the button executor, the inner content and the // secondary item container as children. expect(buttonWrap.children().length).toBe(3); var buttonExecutor = buttonWrap.children()[0]; // The list item should forward the click and disabled attributes. expect(buttonExecutor.hasAttribute('ng-dblclick')).toBe(true); expect(buttonExecutor.hasAttribute('ng-disabled')).toBe(true); var innerContent = buttonWrap.children()[1]; expect(innerContent.nodeName).toBe('DIV'); expect(innerContent.firstElementChild.nodeName).toBe('P'); }); it('creates buttons when used with ui-sref', function() { var listItem = setup( '<md-list-item ui-sref="somestate">' + '<p>Hello world</p>' + '</md-list-item>'); // List items, which are clickable always contain a button wrap at the top level. var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The button wrap should contain the button executor, the inner content and the // secondary item container as children. expect(buttonWrap.children().length).toBe(3); var buttonExecutor = buttonWrap.children()[0]; // The list item should forward the ui-sref attribute. expect(buttonExecutor.hasAttribute('ui-sref')).toBe(true); var innerContent = buttonWrap.children()[1]; expect(innerContent.nodeName).toBe('DIV'); expect(innerContent.firstElementChild.nodeName).toBe('P'); }); it('creates buttons when used with href', function() { var listItem = setup( '<md-list-item href="/somewhere">' + '<p>Hello world</p>' + '</md-list-item>'); // List items, which are clickable always contain a button wrap at the top level. var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The button wrap should contain the button executor, the inner content and the // secondary item container as children. expect(buttonWrap.children().length).toBe(3); var buttonExecutor = buttonWrap.children()[0]; // The list item should forward the href attribute. expect(buttonExecutor.hasAttribute('href')).toBe(true); var innerContent = buttonWrap.children()[1]; expect(innerContent.nodeName).toBe('DIV'); expect(innerContent.firstElementChild.nodeName).toBe('P'); }); it('should forward the md-no-focus class', function() { var listItem = setup( '<md-list-item ng-click="null" class="md-no-focus">' + '<p>Clickable - Without Focus Style</p>' + '</md-list-item>'); // List items, which are clickable always contain a button wrap at the top level. var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The button wrap should contain the button executor, the inner content and the // secondary item container as children. expect(buttonWrap.children().length).toBe(3); var buttonExecutor = buttonWrap.children(); // The list item should forward the href and md-no-focus-style attribute. expect(buttonExecutor.attr('ng-click')).toBeTruthy(); expect(buttonExecutor.hasClass('md-no-focus')).toBe(true); }); it('moves aria-label to primary action', function() { var listItem = setup('<md-list-item ng-click="sayHello()" aria-label="Hello"></md-list-item>'); var buttonWrap = listItem.children().eq(0); expect(listItem).toHaveClass('_md-button-wrap'); // The actual click button will be a child of the button.md-no-style wrapper. var buttonExecutor = buttonWrap.children()[0]; expect(buttonExecutor.nodeName).toBe('MD-BUTTON'); expect(buttonExecutor.getAttribute('aria-label')).toBe('Hello'); }); it('moves secondary items outside of the button', function() { var listItem = setup( '<md-list-item ng-click="sayHello()">' + '<p>Hello World</p>' + '<md-icon class="md-secondary" ng-click="goWild()"></md-icon>' + '</md-list-item>'); // First child is our button wrap var firstChild = listItem.children().eq(0); expect(firstChild[0].nodeName).toBe('DIV'); expect(listItem).toHaveClass('_md-button-wrap'); // It should contain three elements, the button overlay, inner content // and the secondary container. expect(firstChild.children().length).toBe(3); var secondaryContainer = firstChild.children().eq(2); expect(secondaryContainer).toHaveClass('md-secondary-container'); // The secondary container should contain the md-icon, // which has been transformed to an icon button. expect(secondaryContainer.children()[0].nodeName).toBe('MD-BUTTON'); }); it('should copy ng-show to the generated button parent of a clickable secondary item', function() { var listItem = setup( '<md-list-item ng-click="sayHello()">' + '<p>Hello World</p>' + '<md-icon class="md-secondary" ng-show="isShown" ng-click="goWild()"></md-icon>' + '</md-list-item>'); // First child is our button wrap var firstChild = listItem.children().eq(0); expect(firstChild[0].nodeName).toBe('DIV'); expect(listItem).toHaveClass('_md-button-wrap'); // It should contain three elements, the button overlay, inner content // and the secondary container. expect(firstChild.children().length).toBe(3); var secondaryContainer = firstChild.children().eq(2); expect(secondaryContainer).toHaveClass('md-secondary-container'); // The secondary container should contain the md-icon, // which has been transformed to an icon button. var iconButton = secondaryContainer.children()[0]; expect(iconButton.nodeName).toBe('MD-BUTTON'); expect(iconButton.hasAttribute('ng-show')).toBe(true); // The actual `md-icon` element, should not have the ng-show attribute anymore. expect(iconButton.firstElementChild.hasAttribute('ng-show')).toBe(false); }); it('moves multiple md-secondary items outside of the button', function() { var listItem = setup( '<md-list-item ng-click="sayHello()">' + '<p>Hello World</p>' + '<md-icon class="md-secondary" ng-click="goWild()"></md-icon>' + '<md-icon class="md-secondary" ng-click="goWild2()"></md-icon>' + '</md-list-item>'); // First child is our button wrap var firstChild = listItem.children().eq(0); expect(firstChild[0].nodeName).toBe('DIV'); expect(listItem).toHaveClass('_md-button-wrap'); // It should contain three elements, the button overlay, inner content, // and the secondary container. expect(firstChild.children().length).toBe(3); var secondaryContainer = firstChild.children().eq(2); expect(secondaryContainer).toHaveClass('md-secondary-container'); // The secondary container should hold the two secondary items. expect(secondaryContainer.children().length).toBe(2); expect(secondaryContainer.children()[0].nodeName).toBe('MD-BUTTON'); expect(secondaryContainer.children()[1].nodeName).toBe('MD-BUTTON'); }); it('should detect non-compiled md-buttons', function() { var listItem = setup('<md-list-item><md-button ng-click="sayHello()">Hello</md-button></md-list-item>'); expect(listItem.hasClass('md-no-proxy')).toBeFalsy(); }); it('should not detect secondary or excluded md-buttons', function() { var listItem = setup( '<md-list-item>' + ' <div>Content Here</div>' + ' <md-button class="md-secondary" ng-click="sayHello()">Hello</md-button>' + ' <md-button class="md-exclude" ng-click="sayHello()">Hello</md-button>' + '</md-list-item>' ); expect(listItem.hasClass('md-no-proxy')).toBeTruthy(); }); it('should copy md-icon.md-secondary attributes to the button', function() { var listItem = setup( '<md-list-item>' + ' <div>Content Here</div>' + ' <md-checkbox></md-checkbox>' + ' <md-icon class="md-secondary" ng-click="sayHello()" ng-disabled="true">Hello</md-icon>' + '</md-list-item>' ); var button = listItem.find('md-button'); expect(button[0].hasAttribute('ng-click')).toBeTruthy(); expect(button[0].hasAttribute('ng-disabled')).toBeTruthy(); }); describe('with a md-menu', function() { it('should forward click events on the md-menu trigger button', function() { var template = '<md-list-item>' + '<md-menu>' + '<md-button ng-click="openMenu()"></md-button>' + ' </md-menu>' + '</md-list-item>'; var listItem = setup(template); var cntr = listItem[0].querySelector('div'); var openMenu = jasmine.createSpy('openMenu'); $rootScope.openMenu = openMenu; if (cntr && cntr.click) { cntr.click(); expect(openMenu).toHaveBeenCalled(); } }); it('should detect the menu position mode when md-menu is aligned at right', function() { var template = '<md-list-item>' + '<span>Menu should be aligned right</span>' + '<md-menu>' + '<md-button ng-click="openMenu()"></md-button>' + '</md-menu>' + '</md-list-item>'; var listItem = setup(template); var mdMenu = listItem.find('md-menu'); expect(mdMenu.attr('md-position-mode')).toBe('right target'); }); it('should detect the menu position mode when md-menu is aligned at left', function() { var template = '<md-list-item>' + '<md-menu>' + '<md-button ng-click="openMenu()"></md-button>' + '</md-menu>' + '<span>Menu should be aligned left</span>' + '</md-list-item>'; var listItem = setup(template); var mdMenu = listItem.find('md-menu'); expect(mdMenu.attr('md-position-mode')).toBe('left target'); }); it('should apply an aria-label if not specified', function() { var template = '<md-list-item>' + '<span>Aria Label Menu</span>' + '<md-menu>' + '<md-button ng-click="openMenu()"></md-button>' + '</md-menu>' + '</md-list-item>'; var listItem = setup(template); var mdMenuButton = listItem[0].querySelector('md-menu > md-button'); expect(mdMenuButton.getAttribute('aria-label')).toBe('Open List Menu'); }); it('should apply $mdMenuOpen to the button if not present', function() { var template = '<md-list-item>' + '<span>Aria Label Menu</span>' + '<md-menu>' + '<md-button>Should Open the Menu</md-button>' + '</md-menu>' + '</md-list-item>'; var listItem = setup(template); var mdMenuButton = listItem[0].querySelector('md-menu > md-button'); expect(mdMenuButton.getAttribute('ng-click')).toBe('$mdOpenMenu($event)'); }); }); describe('with a clickable item', function() { it('should wrap secondary icons in a md-button', function() { var listItem = setup( '<md-list-item ng-click="something()">' + ' <p>Content Here</p>' + ' <md-icon class="md-secondary" ng-click="heart()">heart</md-icon>' + '</md-list-item>' ); var buttons = listItem.find('md-button'); // Check that we wrapped the icon expect(listItem[0].querySelector('md-button > md-icon')).toBeTruthy(); // Check the button actions expect(buttons[0].attributes['ng-click'].value).toBe("something()"); expect(buttons[1].attributes['ng-click'].value).toBe("heart()"); }); it('should not wrap secondary buttons in a md-button', function() { var listItem = setup( '<md-list-item ng-click="something()">' + ' <p>Content Here</p>' + ' <button class="md-secondary" ng-click="like()">Like</button>' + '</md-list-item>' ); // There should only be 1 md-button (the wrapper) and one button (the unwrapped one) expect(listItem.find('md-button').length).toBe(1); expect(listItem.find('button').length).toBe(1); // Check that we didn't wrap the button in an md-button expect(listItem[0].querySelector('md-button button.md-secondary')).toBeFalsy(); }); it('should not wrap secondary md-buttons in a md-button', function() { var listItem = setup( '<md-list-item ng-click="something()">' + ' <p>Content Here</p>' + ' <md-button class="md-secondary" ng-click="like()">Like</md-button>' + '</md-list-item>' ); // There should be 2 md-buttons that are siblings expect(listItem.find('md-button').length).toBe(2); // Check that we didn't wrap the md-button in an md-button expect(listItem[0].querySelector('md-button md-button.md-secondary')).toBeFalsy(); }); }); });
module.exports = function(grunt) { return grunt.file.readJSON('package.json'); };
//>>built (function(b,a){"object"===typeof exports&&"undefined"!==typeof module&&"function"===typeof require?a(require("../moment")):"function"===typeof define&&define.amd?define("moment/locale/dv",["../moment"],a):a(b.moment)})(this,function(b){var a="\u0796\u07ac\u0782\u07aa\u0787\u07a6\u0783\u07a9 \u078a\u07ac\u0784\u07b0\u0783\u07aa\u0787\u07a6\u0783\u07a9 \u0789\u07a7\u0783\u07a8\u0797\u07aa \u0787\u07ad\u0795\u07b0\u0783\u07a9\u078d\u07aa \u0789\u07ad \u0796\u07ab\u0782\u07b0 \u0796\u07aa\u078d\u07a6\u0787\u07a8 \u0787\u07af\u078e\u07a6\u0790\u07b0\u0793\u07aa \u0790\u07ac\u0795\u07b0\u0793\u07ac\u0789\u07b0\u0784\u07a6\u0783\u07aa \u0787\u07ae\u0786\u07b0\u0793\u07af\u0784\u07a6\u0783\u07aa \u0782\u07ae\u0788\u07ac\u0789\u07b0\u0784\u07a6\u0783\u07aa \u0791\u07a8\u0790\u07ac\u0789\u07b0\u0784\u07a6\u0783\u07aa".split(" "), d="\u0787\u07a7\u078b\u07a8\u0787\u07b0\u078c\u07a6 \u0780\u07af\u0789\u07a6 \u0787\u07a6\u0782\u07b0\u078e\u07a7\u0783\u07a6 \u0784\u07aa\u078b\u07a6 \u0784\u07aa\u0783\u07a7\u0790\u07b0\u078a\u07a6\u078c\u07a8 \u0780\u07aa\u0786\u07aa\u0783\u07aa \u0780\u07ae\u0782\u07a8\u0780\u07a8\u0783\u07aa".split(" ");return b.defineLocale("dv",{months:a,monthsShort:a,weekdays:d,weekdaysShort:d,weekdaysMin:"\u0787\u07a7\u078b\u07a8 \u0780\u07af\u0789\u07a6 \u0787\u07a6\u0782\u07b0 \u0784\u07aa\u078b\u07a6 \u0784\u07aa\u0783\u07a7 \u0780\u07aa\u0786\u07aa \u0780\u07ae\u0782\u07a8".split(" "), longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"D/M/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},meridiemParse:/\u0789\u0786|\u0789\u078a/,isPM:function(c){return"\u0789\u078a"===c},meridiem:function(c,a,b){return 12>c?"\u0789\u0786":"\u0789\u078a"},calendar:{sameDay:"[\u0789\u07a8\u0787\u07a6\u078b\u07aa] LT",nextDay:"[\u0789\u07a7\u078b\u07a6\u0789\u07a7] LT",nextWeek:"dddd LT",lastDay:"[\u0787\u07a8\u0787\u07b0\u0794\u07ac] LT",lastWeek:"[\u078a\u07a7\u0787\u07a8\u078c\u07aa\u0788\u07a8] dddd LT", sameElse:"L"},relativeTime:{future:"\u078c\u07ac\u0783\u07ad\u078e\u07a6\u0787\u07a8 %s",past:"\u0786\u07aa\u0783\u07a8\u0782\u07b0 %s",s:"\u0790\u07a8\u0786\u07aa\u0782\u07b0\u078c\u07aa\u0786\u07ae\u0785\u07ac\u0787\u07b0",m:"\u0789\u07a8\u0782\u07a8\u0793\u07ac\u0787\u07b0",mm:"\u0789\u07a8\u0782\u07a8\u0793\u07aa %d",h:"\u078e\u07a6\u0791\u07a8\u0787\u07a8\u0783\u07ac\u0787\u07b0",hh:"\u078e\u07a6\u0791\u07a8\u0787\u07a8\u0783\u07aa %d",d:"\u078b\u07aa\u0788\u07a6\u0780\u07ac\u0787\u07b0",dd:"\u078b\u07aa\u0788\u07a6\u0790\u07b0 %d", M:"\u0789\u07a6\u0780\u07ac\u0787\u07b0",MM:"\u0789\u07a6\u0790\u07b0 %d",y:"\u0787\u07a6\u0780\u07a6\u0783\u07ac\u0787\u07b0",yy:"\u0787\u07a6\u0780\u07a6\u0783\u07aa %d"},preparse:function(a){return a.replace(/\u060c/g,",")},postformat:function(a){return a.replace(/,/g,"\u060c")},week:{dow:7,doy:12}})});
// example - valid: true app.controller('MyController', MyController); function MyController($http, $q) { } // example - valid: true app.controller('MyController', function($http, $q) { }); // example - valid: true app.controller('MyController', [ '$http', '$q', function($http, $q) { }]); // example - valid: true app.controller('MyController', [ '$http', '$q', MyController]); function MyController($http, $q) { } // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', MyController); function MyController($http, $q) {} // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', function($http, $q) {}); // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', ['$http','$q', function($http, $q) { }]); // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', [ '$http', '$q', function($http, $q) {}]); // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', ['$http', '$q', MyController]); function MyController($http, $q) {} // example - valid: false, errorMessage: "Do not use multiple dependencies in one line" app.controller('MyController', [ '$http', '$q', MyController]); function MyController($http, $q) {} // example - valid: false, errorMessages: ["Do not use multiple dependencies in one line", "Do not use multiple dependencies in one line"] app.controller('MyController', ['$http', '$q', function($http, $q) {}]);
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes, integerPropType, deepmerge } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import experimentalStyled from '../styles/experimentalStyled'; import useThemeProps from '../styles/useThemeProps'; import { alpha } from '../styles/colorManipulator'; import useTheme from '../styles/useTheme'; import { getPaperUtilityClass } from './paperClasses'; // Inspired by https://github.com/material-components/material-components-ios/blob/bca36107405594d5b7b16265a5b0ed698f85a5ee/components/Elevation/src/UIColor%2BMaterialElevation.m#L61 import { jsx as _jsx } from "react/jsx-runtime"; var getOverlayAlpha = function getOverlayAlpha(elevation) { var alphaValue; if (elevation < 1) { alphaValue = 5.11916 * Math.pow(elevation, 2); } else { alphaValue = 4.5 * Math.log(elevation + 1) + 2; } return (alphaValue / 100).toFixed(2); }; var overridesResolver = function overridesResolver(props, styles) { var styleProps = props.styleProps; return deepmerge(_extends({}, styles[styleProps.variant], !styleProps.square && styles.rounded, styleProps.variant === 'elevation' && styles["elevation".concat(styleProps.elevation)]), styles.root || {}); }; var useUtilityClasses = function useUtilityClasses(styleProps) { var square = styleProps.square, elevation = styleProps.elevation, variant = styleProps.variant, classes = styleProps.classes; var slots = { root: ['root', variant, !square && 'rounded', variant === 'elevation' && "elevation".concat(elevation)] }; return composeClasses(slots, getPaperUtilityClass, classes); }; var PaperRoot = experimentalStyled('div', {}, { name: 'MuiPaper', slot: 'Root', overridesResolver: overridesResolver })(function (_ref) { var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({ /* Styles applied to the root element. */ backgroundColor: theme.palette.background.paper, color: theme.palette.text.primary, transition: theme.transitions.create('box-shadow') }, !styleProps.square && { borderRadius: theme.shape.borderRadius }, styleProps.variant === 'outlined' && { border: "1px solid ".concat(theme.palette.divider) }, styleProps.variant === 'elevation' && _extends({ boxShadow: theme.shadows[styleProps.elevation] }, theme.palette.mode === 'dark' && { backgroundImage: "linear-gradient(".concat(alpha('#fff', getOverlayAlpha(styleProps.elevation)), ", ").concat(alpha('#fff', getOverlayAlpha(styleProps.elevation)), ")") })); }); var Paper = /*#__PURE__*/React.forwardRef(function Paper(inProps, ref) { var props = useThemeProps({ props: inProps, name: 'MuiPaper' }); var className = props.className, _props$component = props.component, component = _props$component === void 0 ? 'div' : _props$component, _props$elevation = props.elevation, elevation = _props$elevation === void 0 ? 1 : _props$elevation, _props$square = props.square, square = _props$square === void 0 ? false : _props$square, _props$variant = props.variant, variant = _props$variant === void 0 ? 'elevation' : _props$variant, other = _objectWithoutProperties(props, ["className", "component", "elevation", "square", "variant"]); var styleProps = _extends({}, props, { component: component, elevation: elevation, square: square, variant: variant }); var classes = useUtilityClasses(styleProps); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks var theme = useTheme(); if (theme.shadows[elevation] === undefined) { console.error(["Material-UI: The elevation provided <Paper elevation={".concat(elevation, "}> is not available in the theme."), "Please make sure that `theme.shadows[".concat(elevation, "]` is defined.")].join('\n')); } } return /*#__PURE__*/_jsx(PaperRoot, _extends({ as: component, styleProps: styleProps, className: clsx(classes.root, className), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Paper.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * Shadow depth, corresponds to `dp` in the spec. * It accepts values between 0 and 24 inclusive. * @default 1 */ elevation: chainPropTypes(integerPropType, function (props) { var elevation = props.elevation, variant = props.variant; if (elevation > 0 && variant === 'outlined') { return new Error("Material-UI: Combining `elevation={".concat(elevation, "}` with `variant=\"").concat(variant, "\"` has no effect. Either use `elevation={0}` or use a different `variant`.")); } return null; }), /** * If `true`, rounded corners are disabled. * @default false */ square: PropTypes.bool, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The variant to use. * @default 'elevation' */ variant: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['elevation', 'outlined']), PropTypes.string]) } : void 0; export default Paper;
config_rs1 = { _id : "rs1", members : [ { _id:0, host:"localhost:27010", priority:1 }, { _id:1, host:"localhost:27017" } ] }; rs.initiate(config_rs1);
/* globals App: true */ App = {}
// Copyright IBM Corp. 2013,2016. All Rights Reserved. // Node module: strong-remoting // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 /** * Expose the `Meta` plugin. */ module.exports = Meta; /** * Module dependencies. */ var Remoting = require('../'); /** * Create a remotable Meta module for plugging into `RemoteObjects`. */ function Meta(remotes, options) { // Unfold options. var name = (options && options.name) || 'meta'; // We need a temporary REST adapter to discover our available routes. var adapter = remotes.handler('rest').adapter; var extension = {}; var helper = Remoting.extend(extension); helper.method(routes, { returns: { type: 'object', root: true }}); function routes(callback) { callback(null, adapter.allRoutes()); } helper.method(classes, { returns: { type: 'object', root: true }}); function classes(callback) { callback(null, remotes.classes()); } remotes.exports[name] = extension; return extension; }
/** * @fileoverview Tests for no-empty-label rule. * @author Ilya Volodin */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), ESLintTester = require("../../../lib/testers/eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/no-empty-label", { valid: [ "labeled: for (var i in {}) { }", { code: "labeled: for (var i of {}) { }", ecmaFeatures: { forOf: true } }, "labeled: for (var i=10; i; i--) { }", "labeled: while(i) {}", "labeled: do {} while (i)", "labeled: switch(i) { case 1: break; default: break; }" ], invalid: [ { code: "labeled: var a = 10;", errors: [{ message: "Unexpected label labeled", type: "LabeledStatement"}] } ] });
/** * bootstrap-table - An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3). * * @version v1.14.1 * @homepage https://bootstrap-table.com * @author wenzhixin <wenzhixin2010@gmail.com> (http://wenzhixin.net.cn/) * @license MIT */ (function(a,b){if('function'==typeof define&&define.amd)define([],b);else if('undefined'!=typeof exports)b();else{b(),a.bootstrapTableAfZA={exports:{}}.exports}})(this,function(){'use strict';(function(a){a.fn.bootstrapTable.locales['af-ZA']={formatLoadingMessage:function(){return'Besig om te laai, wag asseblief ...'},formatRecordsPerPage:function(a){return a+' rekords per bladsy'},formatShowingRows:function(a,b,c){return'Resultate '+a+' tot '+b+' van '+c+' rye'},formatSearch:function(){return'Soek'},formatNoMatches:function(){return'Geen rekords gevind nie'},formatPaginationSwitch:function(){return'Wys/verberg bladsy nummering'},formatRefresh:function(){return'Herlaai'},formatToggle:function(){return'Wissel'},formatColumns:function(){return'Kolomme'}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales['af-ZA'])})(jQuery)});
currnode = null; currrow = null; // swaps nodes jQuery.fn.swap = function(b){ b = jQuery(b)[0]; var a = this[0]; var t = a.parentNode.insertBefore(document.createTextNode(''), a); b.parentNode.insertBefore(a, b); t.parentNode.insertBefore(b, t); t.parentNode.removeChild(t); return this; }; // parse gettext (WIP) function parseGettext(html){ // remove start php tag html = global.replaceAll(html, '<?php print _("', ''); // remove end php tag html = global.replaceAll(html, '"); ?>', ''); // remove escaped quotes html = global.replaceAll(html, '/"', '"'); // return html return html; } // editor defaults var editorDefaults = { elementMenu: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu"><a class="config fa fa-cog"></a><a class="move fa fa-arrows"></a>'+ '<a class="remove fa fa-minus-circle"></a></div>', elementMenuTable: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu">' + '<a class="add-row fa fa-plus-square-o"></a><a class="remove-row fa fa-minus-square-o"></a>'+ '<a class="config fa fa-cog"></a><a class="move fa fa-arrows"></a>'+ '<a class="remove fa fa-minus-circle"></a></div>', elementMenuNoConfig: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu"><a class="move fa fa-arrows"></a><a class="remove fa fa-minus-circle"></a></div>', elementMenuList: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu"><a class="config-list fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', elementMenuPlugin: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu"><a class="config-plugin fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', elementMenuHtml: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu"><a class="config-html fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', elementMenuShelf: '<i class="expand-menu fa fa-ellipsis-v"></i>' + '<div class="element-menu"><a class="config-shelf fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', blockMenu: '<a class="expand-menu fa fa-ellipsis-v"></a>' + '<div class="element-menu">' + '<a class="up fa fa-chevron-up"></a><a class="down fa fa-chevron-down"></a>' + '<a class="config-block fa fa-cog"></a>'+ '<a class="remove-block fa fa-minus-circle"></a></div>', }; // editor plugin (function($){ $.fn.respondEdit = function () { // create menu var menu = '<nav class="editor-menu">' + '<a class="show-menu"><i class="fa fa-bars fa-lg"></i></a>' + '<div class="editor-actions"><div>' + '<a class="bold fa fa-bold" title="'+t('bold_text')+'"></a>' + '<a class="italic fa fa-italic" title="'+t('italic_text')+'"></a>' + '<a class="strike fa fa-strikethrough" title="'+t('strike_text')+'"></a>' + '<a class="subscript fa fa-subscript" title="'+t('subscript_text')+'"></a>' + '<a class="superscript fa fa-superscript" title="'+t('superscript_text')+'"></a>' + '<a class="underline fa fa-underline" title="'+t('underline_text')+'"></a>' + '<a class="align-left fa fa-align-left" title="'+t('align-left_text')+'" data-align="left"></a>' + '<a class="align-center fa fa-align-center" title="'+t('align-center_text')+'" data-align="center"></a>' + '<a class="align-right fa fa-align-right" title="'+t('align-right_text')+'" data-align="right"></a>' + '<a class="link fa fa-link" title="'+t('addLink')+'"></a>' + '<a class="code fa fa-code" title="'+t('addCode')+'"></a>' + '<a class="icon fa fa-flag" title="'+t('iconfa')+'"></a>' + // WIP, coming soon '<a class="h1" title="'+t('addHeadline')+'">H1</a>' + '<a class="h2" title="'+t('addHeadline')+'">H2</a>' + '<a class="h3" title="'+t('addHeadline')+'">H3</a>' + '<a class="p" title="'+t('addParagraph')+'">P</a>' + '<a class="q fa fa-quote-left" title="'+t('addquote')+'"></a>' + '<a class="ul fa fa-list" title="'+t('addlist')+'"></a>' + '<a class="table fa fa-table" title="'+t('addtable')+'"></a>' + '<a class="hr fa fa-minus" title="'+t('addhr')+'"></a>' + '<a class="img fa fa-picture-o" title="'+t('addimg')+'"></span>' + '<a class="slideshow fa fa-film" title="'+t('addslideshow')+'"></a>' + '<a class="map fa fa-map-marker" title="'+t('addmap')+'"></a>' + '<a class="twitter fa fa-twitter" title="'+t('addtwitter')+'"></a>' + '<a class="like fa fa-facebook" title="'+t('addfacebook')+'"></a>' + '<a class="comments fa fa-comments" title="'+t('fa-comments')+'"></a>' + '<a class="youtube fa fa-video-camera" title="'+t('youtube')+'"></span>' + '<a class="list fa fa-bars" title="'+t('list_pages')+'"></span>' + '<a class="featured fa fa-star" title="'+t('featured')+'"></a>' + '<a class="file fa fa-file-o" title="'+t('addFile')+'"></a>' + '<a class="shelf fa fa-tags" title="'+t('addSKUs')+'"></a>' + '<a class="form fa fa-check" title="'+t('addForm')+'"></a>' + '<a class="html fa fa-html5" title="'+t('addhtml')+'"></a>' + '<a class="syntax fa fa-terminal" title="'+t('addSyntax')+'"></a>' + '<a class="plugins fa fa-cogs" title="'+t('Plugins')+'"></a>' + '<a class="cols fa fa-columns" title="'+t('cols55')+'"><small>50/50</small></a>' + '<a class="single fa fa-columns" title="'+t('cols100')+'"><small>100</small></a>' + '<a class="cols73 fa fa-columns" title="'+t('cols73')+'"><small>70/30</small></a>' + '<a class="cols37 fa fa-columns" title="'+t('cols37')+'"><small>30/70</small></a>' + '<a class="cols333 fa fa-columns" title="'+t('cols333')+'"><small>3/3/3</small></a>' + '<a class="cols425 fa fa-columns" title="'+t('cols425')+'"><small>4*25</small></a>' + '</div></div>' + '<a class="next fs-next"><i class="fa fa-chevron-right"></i></a>' + '<a class="previous fs-prev"><i class="fa fa-chevron-left"></i></a>' + '<a class="primary-action alt preview" title="'+t('preview')+'"><i class="fa fa-play-circle"></i></a>' + '<a class="primary-action settings" title="'+t('settings')+'"><i class="fa fa-cog"></i></a>' + '</nav>'; var editor = ''; var context = this; // parse HTML, #parse function parseHTML(top){ function parseModules(node){ var children = $(node).children(); var response = ''; for(var x=0; x<children.length; x++){ var node = children[x]; var cssclass = ''; // parse P if(node.nodeName=='P'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='p-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; var alignclass = ''; if(cssclass.indexOf('align-left')!=-1){ alignclass = ' align-left'; } else if(cssclass.indexOf('align-center')!=-1){ alignclass = ' align-center'; } else if(cssclass.indexOf('align-right')!=-1){ alignclass = ' align-right'; } var h = $(node).html(); // remove gettext h = parseGettext(h); response+= '<div id="'+id+'" class="p'+alignclass+'" data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu + '<div class="content" contentEditable="true">' + h + '</div>' + '</div>'; } // parse TABLE if(node.nodeName=='TABLE'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='table-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; var columns = $(node).attr('data-columns'); var rows = ''; var tr = $(node).find('thead tr'); rows += '<thead><tr>'; var ths = $(tr).find('th'); for(var d=0; d<ths.length; d++){ rows += '<th contentEditable="true" class="col-'+(d+1)+'">'+$(ths[d]).html()+'</td>'; } rows += '</tr></thead>'; var trs = $(node).find('tbody tr'); rows += '<tbody>'; for(var t=0; t<trs.length; t++){ rows += '<tr class="row-'+(t+1)+'">'; var tds = $(trs[t]).find('td'); for(var d=0; d<tds.length; d++){ rows += '<td contentEditable="true" class="col-'+(d+1)+'">'+$(tds[d]).html()+'</td>'; } rows += '</tr>'; } rows += '</tbody>'; var table = '<div id="'+id+'" class="table" data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenuTable + '<table class="'+cssclass+'" data-columns="'+columns+'">' + rows + '</table>' + '</div>'; response += table; } // parse BLOCKQUOTE if(node.nodeName=='BLOCKQUOTE'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='bq-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; response+= '<div id="'+id+'" class="q" data-id="'+id+'" data-cssclass="'+cssclass+'"><i class="in-textbox fa fa-quote-left"></i>' + editorDefaults.elementMenu + '<div class="content" contentEditable="true">' + $(node).html() + '</div>' + '</div>'; } // parse UL if(node.nodeName=='UL'){ var lis = $(node).children(); var id = $(node).attr('id'); if(id==undefined || id=='')id='ul-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; response+= '<div id="'+id+'" class="ul" data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu; for(y=0; y<lis.length; y++){ response+= '<div class="content" contentEditable="true">' + $(lis[y]).html() + '</div>'; } response+= '</div>'; } // parse H1 if(node.nodeName=='H1'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='h1-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; var alignclass = ''; if(cssclass.indexOf('align-left')!=-1){ alignclass = ' align-left'; } else if(cssclass.indexOf('align-center')!=-1){ alignclass = ' align-center'; } else if(cssclass.indexOf('align-right')!=-1){ alignclass = ' align-right'; } response+= '<div id="'+id+'" class="h1'+alignclass+'" data-id="'+id+'" data-cssclass="'+cssclass+'">'+ editorDefaults.elementMenu + '<div contentEditable="true">' + $(node).html() + '</div>' + '</div>'; } // parse H4 if(node.nodeName=='HR'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='hr-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; response+= '<div id="'+id+'" class="hr" data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu + '<div></div>' + '</div>'; } // parse H2 if(node.nodeName=='H2'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='h2-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; var alignclass = ''; if(cssclass.indexOf('align-left')!=-1){ alignclass = ' align-left'; } else if(cssclass.indexOf('align-center')!=-1){ alignclass = ' align-center'; } else if(cssclass.indexOf('align-right')!=-1){ alignclass = ' align-right'; } response+= '<div id="'+id+'" class="h2'+alignclass+'" data-id="'+id+'" data-cssclass="'+cssclass+'">'+ editorDefaults.elementMenu + '<div contentEditable="true">' + $(node).html() + '</div>' + '</div>'; } // parse H3 if(node.nodeName=='H3'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='h3-'+parseInt(new Date().getTime() / 1000); cssclass = $(node).attr('class'); if(cssclass==undefined) cssclass=''; var alignclass = ''; if(cssclass.indexOf('align-left')!=-1){ alignclass = ' align-left'; } else if(cssclass.indexOf('align-center')!=-1){ alignclass = ' align-center'; } else if(cssclass.indexOf('align-right')!=-1){ alignclass = ' align-right'; } response+= '<div id="'+id+'" class="h3'+alignclass+'" data-id="'+id+'" data-cssclass="'+cssclass+'">'+ editorDefaults.elementMenu + '<div contentEditable="true">' + $(node).html() + '</div>' + '</div>'; } // parse PRE if(node.nodeName=='PRE'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='syntax-'+parseInt(new Date().getTime() / 1000); response+= '<div id="'+id+'" class="syntax" data-id="'+id+'" data-cssclass="prettyprint linenums pre-scrollable">'+ editorDefaults.elementMenuNoConfig + '<pre class="prettyprint linenums pre-scrollable">' + $(node).html() + '</pre>' + '<pre class="non-pretty">' + $(node).html() + '</pre>' + '</div>'; } // parse DIV if(node.nodeName=='DIV'){ var className = $(node).attr('class'); if(className=='l-image'){ className = ' left'; } else if(className=='r-image'){ className = ' right'; } else if(className=='o-image'){ className = ''; } var rel = $(node).find('a').attr('rel'); if(rel==undefined || rel==''){ rel=''; } var src = $(node).find('img').attr('src'); var href = $(node).find('a').attr('href'); var i_id = $(node).find('img').attr('id'); var html = $(node).find('p').html(); // set constraints var width = $(node).attr('data-width'); var height = $(node).attr('data-height'); var constraints = ''; if(width!=''&&height!=''){ if(!isNaN(width)&&!isNaN(height)){ // set constraints constraints = ' data-width="'+width+'" data-height="'+height+'"'; } } var id = $(node).attr('id'); if(id==undefined || id==''){ id='i-'+parseInt(new Date().getTime() / 1000); } if(className==' left'){ response+= '<div id="'+id+'" class="i' + className + '"'+constraints+ ' data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu; if(href==undefined){ response+='<div class="img"><img id="'+i_id+'" src="' + src + '"></div>'; } else{ response+='<div class="img hasUrl"><img id="'+i_id+'" src="' + src + '" data-url="' + href + '"></div>'; } response +='<div class="content" contentEditable="true">' + html + '</div></div>'; } else if(className==' right'){ response+= '<div id="'+id+'" class="i' + className + '"'+constraints+ ' data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu; response+='<div class="content" contentEditable="true">' + html + '</div>'; if(href==undefined){ response+='<div class="img"><img id="'+i_id+'" src="' + src + '"></div>'; } else{ response+='<div class="img hasUrl"><img id="'+i_id+'" src="' + src + '" data-url="' + href + '"></div>'; } response+='</div>'; } else{ response+= '<div id="'+id+'" class="i"'+constraints+' data-id="'+id+'" data-cssclass="'+cssclass+'">' + editorDefaults.elementMenu; if(href==undefined){ response+= '<div class="img"><img id="'+i_id+'" src="' + src + '"></div>'; } else{ response+= '<div class="img hasUrl"><img id="'+i_id+'" src="' + src + '" data-url="' + href + '"></div>'; } response+= '</div>'; } } // parse PLUGIN if(node.nodeName=='PLUGIN'){ var id = $(node).attr('id'); var type = $(node).attr('type'); var name = $(node).attr('name'); var render = $(node).attr('render'); var config = $(node).attr('config'); if(id==undefined || id=='')id='d-'+parseInt(new Date().getTime() / 1000); //var attrs = $(node).attr(); var nvps = ''; var attrs = $(node).get(0).attributes; $.each(attrs, function(i, attrib) { var name = attrib.name; var value = attrib.value; if(name != 'id' && name != 'type' && name != 'name' && name != 'render' && name != 'config'){ nvps += 'data-' + name + '="' + value +'" '; } }); response+= '<div id="'+id+'" data-type="'+type+'" data-name="'+name+'" data-render="'+render+'" data-config="'+config+'" ' + nvps + 'class="plugin">'; if(config=='true'){ response += editorDefaults.elementMenuPlugin; } else{ response += editorDefaults.elementMenuNoConfig; } response+='<div class="title"><i class="fa fa-cogs"></i> '+name+'</div></div>'; } // parse MODULE if(node.nodeName=='MODULE'){ var name = $(node).attr('name') || ''; var id = $(node).attr('id'); if(id==undefined || id=='')id='s-'+parseInt(new Date().getTime() / 1000); // parse SLIDESHOW MODULE if(name=='slideshow'){ var width = $(node).attr('width'); if(width==undefined || width==''){ width = '300'; } var height = $(node).attr('height'); if(height==undefined || height==''){ height = '200'; } var menu = $(context).find('a.slideshow'); var imgs = $(node).find('img'); response+= '<div id="' + id + '" class="slideshow" data-width="'+width+'" data-height="'+height+'">' + editorDefaults.elementMenuNoConfig + '<div class="images">'; for(var y=0; y<imgs.length; y++){ var caption = $(imgs[y]).attr('title'); imghtml = $('<div>').append($(imgs[y]).clone()).remove().html(); response +='<span class="image">' + imghtml + '<span class="caption"><input type="text" value="'+caption+'" placeholder="Enter caption" maxwidth="140" class="form-control"></span><a class="remove-image fa fa-minus-circle"></a></span>'; } response += '<button type="button" class="secondary-button add-image"><i class="fa fa-picture-o"></i></button></div></div>'; } // parse LIKE MODULE if(name=='like'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='f-'+parseInt(new Date().getTime() / 1000); response+= '<div id="'+id+'" class="like">' + editorDefaults.elementMenuNoConfig + '<div class="title"><i class="fa fa-facebook"></i>Facebook Like</div></div>'; } // parse COMMENTS MODULE if(name=='comments'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='c-'+parseInt(new Date().getTime() / 1000); response+= '<div id="'+id+'" class="comments">' + editorDefaults.elementMenuNoConfig + '<div class="title"><i class="fa fa-facebook"></i>Facebook comments</div></div>'; } // parse HTML MODULE if(name=='html'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='h-'+parseInt(new Date().getTime() / 1000); var desc = $(node).attr('desc'); if(desc==undefined || desc=='')desc='HTML Block'; var type = $(node).attr('type'); if(type==undefined || type=='')desc='html'; response+= '<div id="'+id+'" class="html" data-id="'+id+'" data-cssclass="prettyprint linenums pre-scrollable" data-desc="'+desc+'" data-type="'+type+'">'+ editorDefaults.elementMenuHtml + '<div class="title"><i class="fa fa-html5"></i>'+desc+' <i class="fa fa-angle-down"></i></div>' + '<pre class="prettyprint linenums pre-scrollable">' + $(node).html() + '</pre>' + '<pre class="non-pretty">' + $(node).html() + '</pre>' + '</div>'; } // parse YOUTUBE MODULE if(name=='youtube'){ var id = $(node).attr('id'); if(id==undefined || id=='')id='y-'+parseInt(new Date().getTime() / 1000); var h = $(node).html(); response+= '<div id="'+id+'" class="youtube">' + editorDefaults.elementMenuNoConfig + '<textarea placeholder="Paste HTML embed code here">'+h+'</textarea></div>'; } // parse MAP MODULE if(name=='map'){ var address = $(node).attr('address'); if(address==undefined)address=''; var id = $(node).attr('id'); if(id==undefined || id=='')id='m-'+parseInt(new Date().getTime() / 1000); response+= '<div id="'+id+'" class="map">' + editorDefaults.elementMenuNoConfig + '<div><i class="in-textbox fa fa-map-marker"></i><input type="text" value="' + address + '" spellcheck="false" maxlength="512" placeholder="1234 Main Street, Some City, LA 90210"></div></div>'; } // parse LIST MODULE if(name=='list'){ var display = $(node).attr('display'); var id = $(node).attr('id'); if(id==undefined || id==''){ id = 'list'+($(node).find('.list').length + 1); } var type = $(node).attr('type'); var label = $(node).attr('label'); var desclength = $(node).attr('desclength'); var length = $(node).attr('length'); var orderby = $(node).attr('orderby'); var category = $(node).attr('category'); var pageresults = $(node).attr('pageresults'); if(type==undefined)type=''; if(label==undefined)label=''; if(desclength==undefined)desclength='250'; if(length==undefined)length=''; if(orderby==undefined)orderby=''; if(pageresults==undefined)pageresults=''; chtml = '<div id="'+id+'" data-display="'+display+'" data-type="'+type+'" class="list"' + ' data-label="' + label + '"' + ' data-desclength="' + desclength + '"' + ' data-length="' + length + '" data-orderby="' + orderby + '" data-category="' + category + '" data-pageresults="' + pageresults + '">' + editorDefaults.elementMenuList + ' <div class="title"><i class="fa fa-bars"></i> List '+label+' </div></div>'; response += chtml; } // parse FEATURED MODULE if(name=='featured'){ var id = $(node).attr('id'); if(id==undefined || id==''){ id = 'list'+($(node).find('.featured').length + 1); } var pageName = $(node).attr('pagename'); var pageUniqId = $(node).attr('pageUniqId'); chtml = '<div id="'+id+'" data-pageuniqid="'+pageUniqId+'" data-pagename="'+pageName+'" class="featured">' + editorDefaults.elementMenuNoConfig + ' <div class="title"><i class="fa fa-star"></i> Featured content: '+pageName+' </div></div>'; response += chtml; } // parse FILE MODULE if(name=='file'){ var file = $(node).attr('file'); var desc = $(node).attr('description'); var id = $(node).attr('id'); if(id==undefined || id=='')id='f-'+parseInt(new Date().getTime() / 1000); response+= '<div id="'+id+'" class="file" data-filename="'+file+'">' + editorDefaults.elementMenuNoConfig + '<div><i class="in-textbox fa fa-file-o"></i><input type="text" value="'+desc+'" spellcheck="false" maxlength="256" placeholder="Description for the file"></div></div>'; } // parse FORM MODULE if(name=='form'){ var id = $(node).attr('id'); response+= '<div id="'+id+'" class="form">' + editorDefaults.elementMenuNoConfig + '<div class="field-list">'; var fields = $(node).find('.form-group'); for(y=0; y<fields.length; y++){ fhtml = $('<div>').append($(fields[y]).clone()).remove().html(); response += '<span class="field-container">' + editorDefaults.elementMenuNoConfig + fhtml + '</span>'; } response+= '</div><a class="add-field"><i class="fa fa-check"></i> Add Field</a></div>'; } // parse SHELF MODULE if(name=='shelf'){ var id = $(node).attr('id'); var items = $(node).find('.shelf-item'); var n_items = ''; for(y=0; y<items.length; y++){ var item = $(items[y]).html(); n_items += '<div class="shelf-item">' + editorDefaults.elementMenuShelf + item + '</div>'; } response+= '<div id="'+id+'" class="shelf">' + editorDefaults.elementMenuNoConfig + '<div class="shelf-items">'+ n_items + '</div>' + '<a class="add-sku"><i class="fa fa-tag"></i> Add SKU</a>' + '</div>'; } } } return response; } var html = ''; var blocks = $(top).find('div.block'); if(blocks.length==0){ html += '<div id="block-000" class="block sortable">'; html += parseModules(top); html += '<span class="block-actions"><span>#block-000 .block.row</span>' + editorDefaults.blockMenu + '</span></div>'; } else{ // walk through blocks for(var y=0; y<blocks.length; y++){ var id = $(blocks[y]).attr('id'); var cssclass = $(blocks[y]).attr('class'); var cssclass_readable = '.' + global.replaceAll(cssclass, ' ', '.'); cssclass = jQuery.trim(global.replaceAll(cssclass, 'block', '')); cssclass = jQuery.trim(global.replaceAll(cssclass, 'row', '')); if(id==undefined || id=='')id='undefined'; html += '<div id="'+id+'" class="block row" data-cssclass="' + cssclass + '">'; // determine if there are columns var cols = $(blocks[y]).find('.col'); for(var z=0; z<cols.length; z++){ var className = $(cols[z]).attr('class'); html += '<div class="'+className+' sortable">'; html += parseModules(cols[z]); html += '</div>'; } html += '<span class="block-actions"><span>#'+ id + ' ' + cssclass_readable + '</span>' + editorDefaults.blockMenu + '</span></div>'; } } return html; } // parse HTML var response = parseHTML(this); // set menu $('#editor-menu').html(menu); // set HTML $(this).html(response); // add editor class $(this).addClass('editor'); // create BOLD $('.editor-menu a.bold').click(function(){ document.execCommand("Bold", false, null); return false; }); // create ITALIC $('.editor-menu a.italic').click(function(){ document.execCommand("Italic", false, null); return false; }); // create STRIKE $('.editor-menu a.strike').click(function(){ document.execCommand("strikeThrough", false, null); return false; }); // create UNDELRINE $('.editor-menu a.underline').click(function(){ document.execCommand("underline", false, null); return false; }); // create SUBSCRIPT $('.editor-menu a.subscript').click(function(){ document.execCommand("subscript", false, null); return false; }); // create SUPERSCRIPT $('.editor-menu a.superscript').click(function(){ document.execCommand("superscript", false, null); return false; }); // create ALIGNMENT $('.editor-menu a.align-center, .editor-menu a.align-left, .editor-menu a.align-right').click(function(){ var alignclass = 'align-'+$(this).attr('data-align'); if($('*:focus').length>0){ var el = $('*:focus').parents('div.p, div.h1, div.h2, div.h3'); var cssclass = el.attr('data-cssclass'); cssclass = global.replaceAll(cssclass, 'align-left', ''); // replace other alignments cssclass = global.replaceAll(cssclass, 'align-right', ''); cssclass = global.replaceAll(cssclass, 'align-center', ''); cssclass += ' '+alignclass; cssclass = $.trim(cssclass); el.attr('data-cssclass', cssclass); el.removeClass('align-left'); el.removeClass('align-right'); el.removeClass('align-center'); el.addClass(alignclass); } return false; }); // create CODE $('.editor-menu a.code').click(function(){ var text = global.getSelectedText(); var html = '<code>'+text+'</code>'; document.execCommand("insertHTML", false, html); return false; }); // create FA $('.editor-menu a.icon').click(function(){ fontAwesomeDialog.show(); return false; }); // create SYNTAX $('.editor-menu a.syntax').click(function(){ codeBlockDialog.show(); return false; }); // create LINK $('.editor-menu a.link').click(function(){ linkDialog.show(); return false; }); // create LAYOUT $('.editor-menu a.load').click(function(){ loadLayoutDialog.show(); return false; }); // create PLUGINS $('.editor-menu a.plugins').click(function(){ pluginsDialog.show(); return false; }); // update PAGE SETTINGS $('.editor-menu a.settings').click(function(){ pageSettingsDialog.show(); return false; }); // create P $('.editor-menu a.p').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.p').length + 1; var uniqId = 'paragraph-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="p" data-id="'+uniqId+'" data-cssclass="">' + editorDefaults.elementMenu + '<div contentEditable="true"></div>' + '</div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create TABLE $('.editor-menu a.table').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('table').length + 1; var uniqId = 'table-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="table" data-id="'+uniqId+'" data-cssclass="">'+ editorDefaults.elementMenuTable + '<table class="table table-striped table-bordered col-2" data-columns="2">'+ '<thead><tr">'+ '<th contentEditable="true" class="col-1"></th>'+ '<th contentEditable="true" class="col-2"></th>'+ '</tr></thead>'+ '<tbody><tr class="row-1">'+ '<td contentEditable="true" class="col-1"></td>'+ '<td contentEditable="true" class="col-2"></td>'+ '</tr></tbody>'+ '</table>'+ '</div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create BLOCKQUOTE $('.editor-menu a.q').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.q').length + 1; var uniqId = 'quote-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="q" data-id="'+uniqId+'" data-cssclass=""><i class="in-textbox fa fa-quote-left"></i>'+ editorDefaults.elementMenu + '<div contentEditable="true"></div>' + '</div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create HTML BLOCK $('.editor-menu a.html').click(function(){ htmlDialog.show('HTML block', 'html', 'add', -1); return false; }); // create YOUTUBE $('.editor-menu a.youtube').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.youtube').length + 1; var uniqId = 'youtube-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="youtube">' + editorDefaults.elementMenuNoConfig + '<textarea placeholder="Paste HTML embed code here"></textarea></div>'); return false; }); // import LAYOUT $('.editor-menu a.layout').click(function(){ var editor = $('#desc').get(0); if($(this).hasClass('visible')){ $(editor).find('span.block-actions').css('display', 'none'); $(this).removeClass('visible'); $(editor).removeClass('advanced'); } else{ $(editor).find('span.block-actions').css('display', 'block'); $(this).addClass('visible'); $(editor).addClass('advanced'); } return false; }); // create UL $('.editor-menu a.ul').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.ul').length + 1; var uniqId = 'ul-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="ul" data-id="'+uniqId+'" data-cssclass="">' + editorDefaults.elementMenu + '<div contentEditable="true"></div>' + '</div>'); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create HR $('.editor-menu a.hr').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.hr').length + 1; var uniqId = 'hr-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="hr" data-id="'+uniqId+'" data-cssclass="">'+ editorDefaults.elementMenuNoConfig + '<div></div>' + '</div>'); return false; }); // create IMAGE $('.editor-menu a.img').click(function(){ imagesDialog.show('image', -1); return false; }); // create SLIDESHOW $('.editor-menu a.slideshow').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.slideshow').length + 1; var uniqId = 'slideshow-'+ length; slideshowDialog.show(uniqId); return false; }); // create MAP $('.editor-menu a.map').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.map').length + 1; var uniqId = 'map-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="map">' + editorDefaults.elementMenuNoConfig + '<div><i class="in-textbox fa fa-map-marker"></i><input type="text" value="" spellcheck="false" maxlength="512" placeholder="1234 Main Street, Some City, LA 90210"></div></div>' ); return false; }); // create TWITTER $('.editor-menu a.twitter').click(function(){ htmlDialog.show('Twitter Widget', 'twitter', 'add', -1); return false; }); // create LIKE $('.editor-menu a.like').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.like').length + 1; var uniqId = 'like-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="like">' + editorDefaults.elementMenu + '<div class="title"><i class="fa fa-facebook"></i> Facebook Like</div></div>' ); return false; }); // create COMMENTS $('.editor-menu a.comments').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.comments').length + 1; var uniqId = 'comments-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="comments">' + editorDefaults.elementMenuNoConfig + '<div class="title"><i class="fa fa-facebook"></i> Facebook Comments</div></div>' ); return false; }); // create FILES $('.editor-menu a.file').click(function(){ filesDialog.show(); return false; }); // create FORM $('.editor-menu a.form').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.form').length + 1; var uniqId = 'form-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="form">' + editorDefaults.elementMenuNoConfig + '<div class="field-list"></div><a class="add-field"><i class="fa fa-check"></i> Add Field</a></div>' ); // set up sorting on form elements $('.form div').sortable({handle: '.move', placeholder: 'editor-highlight', opacity:'0.6', axis:'y'}); return false; }); // create SHELF $('.editor-menu a.shelf').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.form').length + 1; var uniqId = 'shelf'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="shelf">' + editorDefaults.elementMenuNoConfig + '<div class="shelf-items"></div>' + '<a class="add-sku"><i class="fa fa-tag"></i> Add SKU</a></div>' ); // set up sorting on shelf items $('.shelf-items').sortable({handle: '.move', placeholder: 'editor-highlight', opacity:'0.6', axis:'y'}); return false; }); // create H1 $('.editor-menu a.h1').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.h1').length + 1; var uniqId = 'h1-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="h1" data-id="'+uniqId+'" data-cssclass="">' + editorDefaults.elementMenu + '<div contentEditable="true"></div></div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create H2 $('.editor-menu a.h2').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.h2').length + 1; var uniqId = 'h2-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="h2" data-id="'+uniqId+'" data-cssclass="">' + editorDefaults.elementMenu + '<div contentEditable="true"></div></div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create H3 $('.editor-menu a.h3').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.h3').length + 1; var uniqId = 'h3-'+ length; $(editor).respondAppend( '<div id="'+uniqId+'" class="h3" data-id="'+uniqId+'" data-cssclass="">'+ editorDefaults.elementMenu + '<div contentEditable="true"></div></div>' ); // setup paste filter $('#'+uniqId+' [contentEditable=true]').paste(); return false; }); // create COLS $('.editor-menu a.cols').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; $(editor).append( '<div id="'+uniqId+'" class="block row">' + '<div class="col col-md-6 sortable">' + '</div>' + '<div class="col col-md-6 sortable">' + '</div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>' ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create PREVIEW $('.editor-menu a.preview').click(function(){ var editor = $('#desc').get(0); contentModel.preview(); return false; }); // create COLS 7/3 $('.editor-menu a.cols73').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; var html = '<div id="'+uniqId+'" class="block row">' + '<div class="col col-md-9 sortable">' + '</div>' + '<div class="col col-md-3 sortable">' + '</div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>'; $(editor).append( html ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create COLS 3/7 $('.editor-menu a.cols37').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; var html = '<div id="'+uniqId+'" class="block row">' + '<div class="col col-md-3 sortable">' + '</div>' + '<div class="col col-md-9 sortable">' + '</div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>'; $(editor).append( html ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create COLS 3/3/3 $('.editor-menu a.cols333').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; var html = '<div id="'+uniqId+'" class="block row">' + '<div class="col col-md-4 sortable">' + '</div>' + '<div class="col col-md-4 sortable">' + '</div>' + '<div class="col col-md-4 sortable">' + '</div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>'; $(editor).append( html ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create COLS 4*25 $('.editor-menu a.cols425').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; var html = '<div id="'+uniqId+'" class="block row">' + '<div class="col col-md-3 sortable">' + '</div>' + '<div class="col col-md-3 sortable">' + '</div>' + '<div class="col col-md-3 sortable">' + '</div>' + '<div class="col col-md-3 sortable">' + '</div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>'; $(editor).append( html ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create SINGLE COL $('.editor-menu a.single').click(function(){ var editor = $('#desc').get(0); var length = $(editor).find('.block').length + 1; var uniqId = 'block-'+ length; $(editor).append( '<div id="'+uniqId+'" class="block row"><div class="col col-md-12 sortable"></div>' + '<span class="block-actions"><span>#'+ uniqId + ' .block.row</span>' + editorDefaults.blockMenu + '</span></div>' ); $('.block-actions').show(); // reset currnode (new content should be added to the end) currnode = null; // re-init sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); return false; }); // create LIST $('.editor-menu a.list').click(function(){ listDialog.show('add', -1); return false; }); // create FEATURED $('.editor-menu a.featured').click(function(){ featuredDialog.show(); return false; }); // #persistent events // setup context var context = this; // make blocks sortable $('.sortable').sortable({handle:'.move', connectWith: '.sortable', placeholder: 'editor-highlight', opacity:'0.6', tolerance: 'pointer'}); // handle remove-block $(this).on('click', '.remove-block', function(){ $(this.parentNode.parentNode.parentNode).remove(); $(context).find('.up').removeClass('disabled'); $(context).find('.up').first().addClass('disabled'); $(context).find('.down').removeClass('disabled'); $(context).find('.down').last().addClass('disabled'); return false; }); // handle expand-menu $(this).on('click', '.expand-menu', function(){ $(this).toggleClass('active'); $(this).next().toggleClass('active'); }); // add field $(this).on('click', '.add-field', function(){ var id = $(this.parentNode).attr('id'); fieldDialog.show(id); return false; }); // add sku $(this).on('click', '.add-sku', function(){ var id = $(this.parentNode).attr('id'); skuDialog.show(id); return false; }); // set currnode when div is focused $(this).on('focusin', '.sortable div', function(){ currnode = this; }); // set currrow when the th or td is focused $(this).on('focusin', 'th, td', function(){ currrow = this.parentNode; $('tr').removeClass('curr-row'); $(this.parentNode).addClass('curr-row'); }); // set currnode when textarea is focused $(this).on('focusin', '.sortable textarea, .sortable input', function(){ if(!$(this.parentNode).hasClass('field') && !$(this.parentNode).hasClass('caption')){ currnode = this.parentNode; } }); // add row $(this).on('click', '.add-row', function(){ var table = $(this).parent().parent().find('table'); var cols = $(table).attr('data-columns'); var html = '<tr>'; for(var x=0; x<cols; x++){ html += '<td contentEditable="true"></td>'; } html += '</tr>'; if(currrow){ $(currrow).after(html); } else{ $(table).find('tbody').append(html); } return false; }); // remove row $(this).on('click', '.remove-row', function(){ if(currrow){ $(currrow).remove(); } return false; }); // add column $(this).on('click', '.add-column', function(){ var table = $(this).parent().parent().find('table'); var cols = parseInt($(table).attr('data-columns')); var trs = table.find('tr'); for(var x=0; x<trs.length; x++){ if(trs[x].parentNode.nodeName=='THEAD'){ $(trs[x]).append('<th contentEditable="true"></th>'); } else{ $(trs[x]).append('<td contentEditable="true"></td>'); } } var n_cols = cols + 1; table.removeClass('col-'+cols); table.addClass('col-'+(n_cols)); table.attr('data-columns', (n_cols)); return false; }); // caption focus (for images) $(this).on('focus', '.caption input', function(){ $(this.parentNode.parentNode).addClass('edit'); }); // caption blur (for images) $(this).on('blur', '.caption input', function(){ var caption = $(this).val(); $(this.parentNode.parentNode).find('img').attr('title', caption); $(this.parentNode.parentNode).removeClass('edit'); }); // image click $(this).on('click', '.img', function(){ var moduleId = this.parentNode.id; var src = $('div#'+moduleId+' img').attr('src'); var uniqueName = $('div#'+moduleId+' img').attr('id'); aviaryDialog.show(uniqueName, src); return false; }); // remove click $(this).on('click', '.remove', function(){ $(this.parentNode.parentNode).remove(); context.find('a.'+this.parentNode.className).show(); currnode = null; return false; }); // remove-image click $(this).on('click', '.remove-image', function(){ $(this.parentNode).remove(); context.find('a.'+this.parentNode.className).show(); currnode = null; return false; }); // config click $(this).on('click', '.config', function(){ $(this.parentNode.parentNode).find('.expand-menu').toggleClass('active'); $(this.parentNode.parentNode).find('.element-menu').toggleClass('active'); var moduleId = $(this.parentNode.parentNode).attr('id'); var id = $(this.parentNode.parentNode).attr('data-id'); var cssClass = $(this.parentNode.parentNode).attr('data-cssclass'); elementConfigDialog.show(moduleId, id, cssClass); currnode = null; return false; }); // config block click $(this).on('click', '.config-block', function(){ var blockId = $(this.parentNode.parentNode.parentNode).attr('id'); var id = $(this.parentNode.parentNode.parentNode).attr('id'); var cssClass = $(this.parentNode.parentNode.parentNode).attr('data-cssclass'); blockConfigDialog.show(blockId, id, cssClass); currnode = null; return false; }); // remove field click $(this).on('click', '.remove-field', function(){ $(this.parentNode).remove(); return false; }); // add image click $(this).on('click', '.add-image', function(){ var d = this.parentNode.parentNode; var id = $(d).attr('id'); imagesDialog.show('slideshow', id); }); // config list click $(this).on('click', '.config-list', function(){ var id=$(this.parentNode.parentNode).attr('id'); listDialog.show('edit', id); return false; }); // config html click $(this).on('click', '.config-html', function(){ var id=$(this.parentNode.parentNode).attr('id'); var desc=$(this.parentNode.parentNode).attr('data-desc'); var type=$(this.parentNode.parentNode).attr('data-type'); htmlDialog.show(desc, type, 'edit', id); return false; }); // config plugin click $(this).on('click', '.config-plugin', function(){ var id=$(this.parentNode.parentNode).attr('id'); var type=$(this.parentNode.parentNode).attr('data-type'); configPluginsDialog.show(id, type); return false; }); // handle html div click $(this).on('click', '.html div', function(){ $(this).parent().toggleClass('active'); }); // handle switch $(this).on('click', '.switch', function(){ $(this.parentNode).find('a').removeClass('selected'); $(this).addClass('selected'); return false; }); // handle down $(this).on('click', '.down', function(){ if($(this).hasClass('disabled')){return false;} var curr = $(this.parentNode.parentNode.parentNode); var next = $(this.parentNode.parentNode.parentNode).next(); $(curr).swap(next); $(context).find('a.up').removeClass('disabled'); $(context).find('a.up').first().addClass('disabled'); $(context).find('a.down').removeClass('disabled'); $(context).find('a.down').last().addClass('disabled'); return false; }); // handle up $(this).on('click', '.up', function(){ if($(this).hasClass('disabled')){return false;} var curr = $(this.parentNode.parentNode.parentNode); var next = $(this.parentNode.parentNode.parentNode).prev(); $(curr).swap(next); $(context).find('a.up').removeClass('disabled'); $(context).find('a.up').first().addClass('disabled'); $(context).find('a.down').removeClass('disabled'); $(context).find('a.down').last().addClass('disabled'); return false; }); // handle key events $(this).on('keydown', '[contentEditable=true]', function(){ var editor = $(context).get(0); var el = $(this).parents('div')[0]; // ENTER KEY events if(event.keyCode == '13'){ if($(el).hasClass('ul')){ $(this).after( '<div contentEditable="true"></div>' ); $(this.nextSibling).focus(); } else if($(el).hasClass('table')){ // add row var table = $(el).find('table'); var cols = $(table).attr('data-columns'); var html = '<tr>'; for(var x=0; x<cols; x++){ html += '<td contentEditable="true"></td>'; } html += '</tr>'; var tr = $(this).parents('tr')[0]; $(tr).after(html); $(tr).next().find('[contentEditable=true]').get(0).focus(); } else{ $(el).after( '<div class="p">' + editorDefaults.elementMenu + '<div contentEditable="true"></div></div>' ); $(this.parentNode.nextSibling).find('div').focus(); } event.preventDefault(); return false; } else if(event.keyCode == '8'){ var h = $(this).html().trim(); h = global.replaceAll(h, '<br>', ''); if(h==''){ if($(el).hasClass('table')){ var previous = $(this.parentNode.previousSibling); $(this.parentNode).remove(); if(previous){ $(previous).find('td')[0].focus(); } return false; } if($(el).hasClass('ul')){ var parent = $(this.parentNode); var divs = $(this.parentNode).find('div'); if(divs.length>1){ $(this).remove(); var last = parent.find('div:last'); last.focus(); last.select(); return false; } } } } }); // setup sorting on .shelf-items, forms, slideshows $('.shelf-items').sortable({handle: '.move', placeholder: 'editor-highlight', opacity:'0.6', axis:'y'}); $('.form div').sortable({handle: '.move', placeholder: 'editor-highlight', opacity:'0.6', axis:'y'}); $('.slideshow div').sortable({handle:'img', items:'span.image', placeholder: 'editor-highlight', opacity:'0.6', axis:'x'}); // setup paste $('[contentEditable=true]').paste(); } })(jQuery); (function($){ $.fn.respondHtml = function () { var html = ''; // gets html for a given block function getBlockHtml(block){ var newhtml = ''; var divs = $(block).find('div'); for(var x=0; x<divs.length; x++){ // generate P if($(divs[x]).hasClass('p')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var h = jQuery.trim($(divs[x]).find('[contentEditable=true]').html()); newhtml += '<p id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>' + h + '</p>'; } // generate TABLE if($(divs[x]).hasClass('table')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var table = $(divs[x]).find('table'); var cols = $(table).attr('data-columns'); var cssclass = $(table).attr('class'); newhtml += '<table id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += ' data-columns="'+cols+'"'; newhtml += '>'; newhtml+='<thead>'; var tr = $(table).find('thead tr'); newhtml += '<tr>'; var ths = $(tr).find('th'); for(var d=0; d<ths.length; d++){ newhtml += '<th class="col-'+(d+1)+'">'+$(ths[d]).html()+'</th>'; } newhtml += '</tr>'; newhtml+='</thead>'; newhtml+='<tbody>'; var trs = $(table).find('tbody tr'); for(var t=0; t<trs.length; t++){ newhtml += '<tr class="row-'+(t+1)+'">'; var tds = $(trs[t]).find('td'); for(var d=0; d<tds.length; d++){ newhtml += '<td class="col-'+(d+1)+'">'+$(tds[d]).html()+'</td>'; } newhtml += '</tr>'; } newhtml += '</tbody></table>'; } // generate BLOCKQUOTE if($(divs[x]).hasClass('q')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var h = jQuery.trim($(divs[x]).find('[contentEditable=true]').html()); newhtml += '<blockquote id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>' + h + '</blockquote>'; } // genearate HTML if($(divs[x]).hasClass('html')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var desc = $(divs[x]).attr('data-desc'); if(desc==undefined || desc=='')desc='HTML block'; var type = $(divs[x]).attr('data-type'); if(type==undefined || type=='')type='html'; var h = jQuery.trim($(divs[x]).find('pre.non-pretty').html()); newhtml += '<module id="'+id+'" name="html" desc="'+desc+'" type="'+type+'">' + h + '</module>'; } // generate PLUGIN if($(divs[x]).hasClass('plugin')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var data = $(divs[x]).data(); var attrs = ''; for(var i in data){ if(i != 'sortableItem'){ attrs += i + '="' + data[i] + '" '; } } var html = '<plugin id="'+id+'" ' + attrs + '></plugin>'; newhtml += html; } // generate YOUTUBE if($(divs[x]).hasClass('youtube')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var h = jQuery.trim($(divs[x]).find('textarea').val()); newhtml += '<module id="'+id+'" name="youtube">' + h + '</module>'; } // generate VIMEO if($(divs[x]).hasClass('vimeo')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var h = jQuery.trim($(divs[x]).find('textarea').val()); newhtml += '<module id="'+id+'" name="vimeo">' + h + '</module>'; } // generate UL if($(divs[x]).hasClass('ul')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var lis = $(divs[x]).find('[contentEditable=true]'); newhtml += '<ul id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>'; for(var y=0; y<lis.length; y++){ newhtml += '<li>' + jQuery.trim($(lis[y]).html()) + '</li>'; } newhtml += '</ul>'; } // generate H1 if($(divs[x]).hasClass('h1')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var h = jQuery.trim($(divs[x]).find('[contentEditable=true]').html()); newhtml += '<h1 id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>' + h + '</h1>'; } // generate H2 if($(divs[x]).hasClass('h2')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var h = jQuery.trim($(divs[x]).find('[contentEditable=true]').html()); newhtml += '<h2 id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>' + h + '</h2>'; } // generate H3 if($(divs[x]).hasClass('h3')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; var h = jQuery.trim($(divs[x]).find('[contentEditable=true]').html()); newhtml += '<h3 id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '>' + h + '</h3>'; } // generate SYNTAX if($(divs[x]).hasClass('syntax')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var h = jQuery.trim($(divs[x]).find('pre.non-pretty').html()); newhtml += '<pre id="'+id+'" class="prettyprint linenums pre-scrollable">' + h + '</pre>'; } // generate images if($(divs[x]).hasClass('i')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var dir = 'o'; if($(divs[x]).hasClass('right')){ dir = 'r'; } else if($(divs[x]).hasClass('left')){ dir = 'l'; } var constraints = ''; var width = $(divs[x]).attr('data-width'); var height = $(divs[x]).attr('data-height'); if(width!=''&&height!=''){ if(!isNaN(width)&&!isNaN(height)){ // set constraints constraints = ' data-width="'+width+'" data-height="'+height+'"'; } } var i_id = $(divs[x]).find('img').attr('id'); var src = $(divs[x]).find('img').attr('src'); var url = $(divs[x]).find('img').attr('data-url'); var h = jQuery.trim($(divs[x]).find('div.content').html()); newhtml += '<div id="'+id+'" class="'+dir+'-image"'+constraints+'>'; if(url!=undefined){ newhtml += '<a href="'+url+'"'; newhtml += '>'; } newhtml += '<img id="'+i_id+'" src="'+src+'">'; if(url!=undefined)newhtml += '</a>'; if(dir=='o'){ newhtml += '</div>'; } else{ newhtml += '<p>'+h+'</p></div>'; } } // generate MODULES if($(divs[x]).hasClass('slideshow')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var width = $(divs[x]).attr('data-width'); if(width==undefined || width=='')width=300; var height = $(divs[x]).attr('data-height'); if(height==undefined || height=='')height=200; var imgs = $(divs[x]).find('span.image img'); newhtml += '<module id="'+id+'" name="slideshow" width="'+width+'" height="'+height+'">'; for(var y=0; y<imgs.length; y++){ var imghtml = $('<div>').append($(imgs[y]).clone()).remove().html(); newhtml += imghtml; } newhtml += '</module>'; } // generate LIST if($(divs[x]).hasClass('list')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var display = $(divs[x]).attr('data-display'); var type = $(divs[x]).attr('data-type'); var label = $(divs[x]).attr('data-label'); var desclength = $(divs[x]).attr('data-desclength'); var length = $(divs[x]).attr('data-length'); var orderby = $(divs[x]).attr('data-orderby'); var category = $(divs[x]).attr('data-category'); var pageresults = $(divs[x]).attr('data-pageresults'); newhtml += '<module id="'+id+'" name="list" display="'+display+'" type="'+type+'" label="' + label + '"' + ' desclength="'+desclength+'"' + ' length="'+length+'"' + ' orderby="'+orderby+'" category="'+category+'" pageresults="'+pageresults+'"' + '></module>'; } // generate FEATURED if($(divs[x]).hasClass('featured')){ var id = $(divs[x]).attr('id'); var pageUniqId = $(divs[x]).attr('data-pageuniqid'); var pageName = $(divs[x]).attr('data-pagename'); newhtml += '<module id="'+id+'" name="featured" pageuniqid="'+pageUniqId+'" pagename="'+pageName+'"></module>'; } // generate LIKE if($(divs[x]).hasClass('like')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); newhtml += '<module id="'+id+'" name="like"></module>'; } // generate COMMENTS if($(divs[x]).hasClass('comments')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); newhtml += '<module id="'+id+'" name="comments"></module>'; } // generate BLOG if($(divs[x]).hasClass('blog')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); newhtml += '<module id="'+id+'" name="blog"></module>'; } // generate H$ if($(divs[x]).hasClass('hr')){ var id = $(divs[x]).attr('data-id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var cssclass = $(divs[x]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; newhtml += '<hr id="'+id+'"'; if(cssclass!='')newhtml += ' class="'+cssclass+'"'; newhtml += '></hr>'; } // generate FORM if($(divs[x]).hasClass('form')){ var id= $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); newhtml += '<module id="'+id+'" name="form">'; var fields = $(divs[x]).find('span.field-container'); for(var y=0; y<fields.length; y++){ field = $(fields[y]).html(); field = global.replaceAll(field, editorDefaults.elementMenuNoConfig, ''); field = global.replaceAll(field, '<a class="expand-menu fa fa-ellipsis-v"></a><div class="element-menu ui-sortable"><a class="move fa fa-arrows"></a><a class="remove fa fa-minus-circle"></a></div>', ''); field = global.replaceAll(field, '<a class="expand-menu fa fa-ellipsis-v active"></a><div class="element-menu ui-sortable active"><a class="move fa fa-arrows"></a><a class="remove fa fa-minus-circle"></a></div>', ''); field = global.replaceAll(field, ' ui-sortable', ''); newhtml += field; } newhtml += '</module>'; } // generate SHELF if($(divs[x]).hasClass('shelf')){ var id= $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var items = $(divs[x]).find('.shelf-items').html(); items = global.replaceAll(items, editorDefaults.elementMenuShelf, ''); items = global.replaceAll(items, '<i class="expand-menu fa fa-ellipsis-v"></i>' + '<div class="element-menu"><a class="config-shelf fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', ''); items = global.replaceAll(items, '<i class="expand-menu fa fa-ellipsis-v active"></i>' + '<div class="element-menu active"><a class="config-shelf fa fa-cog"></a><a class="move fa fa-arrows"></a>' + '<a class="remove fa fa-minus-circle"></a></div>', ''); items = global.replaceAll(items, ' ui-sortable', ''); newhtml += '<module id="'+id+'" name="shelf">' + items + '</module>'; } // generate MAP if($(divs[x]).hasClass('map')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var address = $(divs[x]).find('input[type=text]').val(); newhtml += '<module id="'+id+'" name="map" address="'+address+'"></module>'; } // generate FILE if($(divs[x]).hasClass('file')){ var id = $(divs[x]).attr('id'); if(id==undefined || id=='')id=parseInt(new Date().getTime() / 1000); var desc = $(divs[x]).find('input[type=text]').val(); var file = $(divs[x]).attr('data-filename'); newhtml += '<module id="'+id+'" name="file" file="'+file+'" description="'+desc+'"></module>'; } } return newhtml; } var blocks = $(this).find('div.block'); // walk through blocks for(var y=0; y<blocks.length; y++){ var id = $(blocks[y]).attr('id'); var cssclass = $(blocks[y]).attr('data-cssclass'); if(cssclass==undefined || cssclass=='')cssclass = ''; if(cssclass!=''){ cssclass = ' ' + cssclass; } if(id==undefined || id=='')id='block-'+y; html += '<div id="'+id+'" class="block row' + cssclass + '">'; // determine if there are columns var cols = $(blocks[y]).find('.col'); if(cols.length==0){ html += getBlockHtml(blocks[y]); } else{ for(var z=0; z<cols.length; z++){ var className = $(cols[z]).attr('class').replace(' sortable', '').replace(' ui-sortable', ''); html += '<div class="'+className+'">'; html += getBlockHtml(cols[z]); html += '</div>'; } } html+= '</div>'; } return html; } })(jQuery); (function($){ $.fn.respondAppend = function(html){ var blocks = $(this).find('div.block'); var length = blocks.length; if(currnode){ // alert('boom'); var temp = $(currnode).after(html).get(0); var added = $(temp).next(); $('[contentEditable=true], input, textarea').blur(); $(added).find('[contentEditable=true], input, textarea').focus(); currnode = $(added); } else if(length>0){ var curr = blocks[length-1]; // get last block var cols = $(curr).find('div.col'); if(cols.length>0){ curr = $(cols[0]); currnode = $(html).appendTo(curr); } // arrh! focus! $(curr).find('[contentEditable=true], input, textarea').focus(); } } })(jQuery); (function($){ $.fn.respondHandleEvents = function(){ } })(jQuery); (function($){ $.fn.respondGetDesc = function(){ var divs = $(this).find('div.p'); var desc = ''; for(var x=0; x<divs.length; x++){ desc += jQuery.trim($(divs[x]).find('div').text()); } if(desc.length>200){ desc = desc.substring(0, 200) + '...'; } return desc; } })(jQuery); (function($){ $.fn.respondGetPrimaryImage = function(){ var imgs = $(this).find('div.block .img img'); if(imgs.length==0){ imgs = $(this).find('div.block span.image img'); } var image = ''; if(imgs && imgs.length>0){ var parts = imgs[0].src.split('/'); if(parts.length>0){ image = parts[parts.length-1]; } } return image; } })(jQuery); (function($){ $.fn.respondGetLocation = function(){ var inputs = $(this).find('div.map input'); var address=''; if(inputs.length>0){ address = $(inputs[0]).val(); } return address; } })(jQuery);
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ it.todo(() => {});
/* */ System.register(['aurelia-task-queue', './environment', './array-observation', './map-observation', './event-manager', './dirty-checking', './property-observation', './element-observation', 'aurelia-dependency-injection', './computed-observation'], function (_export) { var TaskQueue, hasObjectObserve, getArrayObserver, getMapObserver, EventManager, DirtyChecker, DirtyCheckProperty, SetterObserver, OoObjectObserver, OoPropertyObserver, SelectValueObserver, CheckedObserver, ValueAttributeObserver, XLinkAttributeObserver, DataAttributeObserver, StyleObserver, All, hasDeclaredDependencies, ComputedPropertyObserver, _classCallCheck, ObserverLocator, ObjectObservationAdapter; function createObserversLookup(obj) { var value = {}; try { Object.defineProperty(obj, '__observers__', { enumerable: false, configurable: false, writable: false, value: value }); } catch (_) {} return value; } function createObserverLookup(obj, observerLocator) { var value = new OoObjectObserver(obj, observerLocator); try { Object.defineProperty(obj, '__observer__', { enumerable: false, configurable: false, writable: false, value: value }); } catch (_) {} return value; } return { setters: [function (_aureliaTaskQueue) { TaskQueue = _aureliaTaskQueue.TaskQueue; }, function (_environment) { hasObjectObserve = _environment.hasObjectObserve; }, function (_arrayObservation) { getArrayObserver = _arrayObservation.getArrayObserver; }, function (_mapObservation) { getMapObserver = _mapObservation.getMapObserver; }, function (_eventManager) { EventManager = _eventManager.EventManager; }, function (_dirtyChecking) { DirtyChecker = _dirtyChecking.DirtyChecker; DirtyCheckProperty = _dirtyChecking.DirtyCheckProperty; }, function (_propertyObservation) { SetterObserver = _propertyObservation.SetterObserver; OoObjectObserver = _propertyObservation.OoObjectObserver; OoPropertyObserver = _propertyObservation.OoPropertyObserver; }, function (_elementObservation) { SelectValueObserver = _elementObservation.SelectValueObserver; CheckedObserver = _elementObservation.CheckedObserver; ValueAttributeObserver = _elementObservation.ValueAttributeObserver; XLinkAttributeObserver = _elementObservation.XLinkAttributeObserver; DataAttributeObserver = _elementObservation.DataAttributeObserver; StyleObserver = _elementObservation.StyleObserver; }, function (_aureliaDependencyInjection) { All = _aureliaDependencyInjection.All; }, function (_computedObservation) { hasDeclaredDependencies = _computedObservation.hasDeclaredDependencies; ComputedPropertyObserver = _computedObservation.ComputedPropertyObserver; }], execute: function () { 'use strict'; _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; if (typeof Object.getPropertyDescriptor !== 'function') { Object.getPropertyDescriptor = function (subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (typeof pd === 'undefined' && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }; } ObserverLocator = (function () { function ObserverLocator(taskQueue, eventManager, dirtyChecker, observationAdapters) { _classCallCheck(this, ObserverLocator); this.taskQueue = taskQueue; this.eventManager = eventManager; this.dirtyChecker = dirtyChecker; this.observationAdapters = observationAdapters; } ObserverLocator.inject = function inject() { return [TaskQueue, EventManager, DirtyChecker, All.of(ObjectObservationAdapter)]; }; ObserverLocator.prototype.getObserversLookup = function getObserversLookup(obj) { return obj.__observers__ || createObserversLookup(obj); }; ObserverLocator.prototype.getObserver = function getObserver(obj, propertyName) { var observersLookup = this.getObserversLookup(obj); if (propertyName in observersLookup) { return observersLookup[propertyName]; } return observersLookup[propertyName] = this.createPropertyObserver(obj, propertyName); }; ObserverLocator.prototype.getObservationAdapter = function getObservationAdapter(obj, propertyName, descriptor) { var i, ii, observationAdapter; for (i = 0, ii = this.observationAdapters.length; i < ii; i++) { observationAdapter = this.observationAdapters[i]; if (observationAdapter.handlesProperty(obj, propertyName, descriptor)) { return observationAdapter; } } return null; }; ObserverLocator.prototype.createPropertyObserver = function createPropertyObserver(obj, propertyName) { var observerLookup, descriptor, handler, observationAdapter, xlinkResult; if (obj instanceof Element) { handler = this.eventManager.getElementHandler(obj, propertyName); if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') { return new SelectValueObserver(obj, handler, this); } if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') { return new CheckedObserver(obj, handler, this); } if (handler) { return new ValueAttributeObserver(obj, propertyName, handler); } xlinkResult = /^xlink:(.+)$/.exec(propertyName); if (xlinkResult) { return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]); } if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof SVGElement) { return new DataAttributeObserver(obj, propertyName); } if (propertyName === 'style' || propertyName === 'css') { return new StyleObserver(obj, propertyName); } } descriptor = Object.getPropertyDescriptor(obj, propertyName); if (hasDeclaredDependencies(descriptor)) { return new ComputedPropertyObserver(obj, propertyName, descriptor, this); } if (descriptor && (descriptor.get || descriptor.set)) { observationAdapter = this.getObservationAdapter(obj, propertyName, descriptor); if (observationAdapter) { return observationAdapter.getObserver(obj, propertyName, descriptor); }return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } if (hasObjectObserve) { observerLookup = obj.__observer__ || createObserverLookup(obj, this); return observerLookup.getObserver(propertyName, descriptor); } if (obj instanceof Array) { if (propertyName === 'length') { return this.getArrayObserver(obj).getLengthObserver(); } else { return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } } else if (obj instanceof Map) { if (propertyName === 'size') { return this.getMapObserver(obj).getLengthObserver(); } else { return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } } return new SetterObserver(this.taskQueue, obj, propertyName); }; ObserverLocator.prototype.getArrayObserver = (function (_getArrayObserver) { function getArrayObserver(_x) { return _getArrayObserver.apply(this, arguments); } getArrayObserver.toString = function () { return _getArrayObserver.toString(); }; return getArrayObserver; })(function (array) { if ('__array_observer__' in array) { return array.__array_observer__; } return array.__array_observer__ = getArrayObserver(this.taskQueue, array); }); ObserverLocator.prototype.getMapObserver = (function (_getMapObserver) { function getMapObserver(_x2) { return _getMapObserver.apply(this, arguments); } getMapObserver.toString = function () { return _getMapObserver.toString(); }; return getMapObserver; })(function (map) { if ('__map_observer__' in map) { return map.__map_observer__; } return map.__map_observer__ = getMapObserver(this.taskQueue, map); }); return ObserverLocator; })(); _export('ObserverLocator', ObserverLocator); ObjectObservationAdapter = (function () { function ObjectObservationAdapter() { _classCallCheck(this, ObjectObservationAdapter); } ObjectObservationAdapter.prototype.handlesProperty = function handlesProperty(object, propertyName, descriptor) { throw new Error('BindingAdapters must implement handlesProperty(object, propertyName).'); }; ObjectObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) { throw new Error('BindingAdapters must implement createObserver(object, propertyName).'); }; return ObjectObservationAdapter; })(); _export('ObjectObservationAdapter', ObjectObservationAdapter); } }; });
/* Equation Editor Plugin for CKEditor v4 Version 2.1 This plugin allows equations to be created and edited from within CKEditor. For more information goto: http://www.codecogs.com/latex/integration/ckeditor_v4/install.php Copyright CodeCogs 2006-2013 Written by Will Bateman. Special Thanks to: - Kyle Jones for a fix to allow multiple editor to load on one page */ window.CCounter=0; CKEDITOR.dialog.add( 'eqneditorDialog', function(editor) { var http = ('https:' == document.location.protocol ? 'https://' : 'http://'); window.CCounter++; return { title : editor.lang.eqneditor.title, minWidth : 550, minHeight : 380, resizable: CKEDITOR.DIALOG_RESIZE_NONE, contents : [ { id : 'CCEquationEditor', label : 'EqnEditor', elements : [ { type: 'html', html: '<div id="CCtoolbar'+window.CCounter+'"></div>', style: 'margin-top:-9px' }, { type: 'html', html: '<label for="CClatex'+window.CCounter+'">Equation (LaTeX):</label>', }, { type: 'html', html: '<textarea id="CClatex'+window.CCounter+'" rows="5"></textarea>', style:'border:1px solid #8fb6bd; width:540px; font-size:16px; padding:5px; background-color:#ffc', }, { type: 'html', html: '<label for="CCequation'+window.CCounter+'">Preview:</label>' }, { type :'html', html: '<div style="position:absolute; left:5px; bottom:0; z-index:999"><a href="http://www.codecogs.com" target="_blank"><img src="'+http+'latex.codecogs.com/images/poweredbycc.gif" alt="Powered by CodeCogs" style="vertical-align:-4px; border:none"/></a> &nbsp; <a href="http://www.codecogs.com/latex/about.php" target="_blank">About</a> | <a href="http://www.codecogs.com/latex/popup.php" target="_blank">Install</a> | <a href="http://www.codecogs.com/pages/forums/forum_view.php?f=28" target="_blank">Forum</a> | <a href="http://www.codecogs.com" target="_blank">CodeCogs</a> &copy; 2007-2014</div><img id="CCequation'+window.CCounter+'" src="'+http+'www.codecogs.com/images/spacer.gif" />' } ] } ], onLoad : function() { EqEditor.embed('CCtoolbar'+window.CCounter,'','efull'); EqEditor.add(new EqTextArea('CCequation'+window.CCounter, 'CClatex'+window.CCounter),false); }, onShow : function() { var dialog = this, sel = editor.getSelection(), image = sel.getStartElement().getAscendant('img',true); // has the users selected an equation. Make sure we have the image element, include itself if(image) { var sName = image.getAttribute('src').match( /(gif|svg)\.latex\?(.*)/ ); if(sName!=null) EqEditor.getTextArea().setText(sName[2]); dialog.insertMode = true; } // set-up the field values based on selected or newly created image dialog.setupContent( dialog.image ); }, onOk : function() { var eqn = editor.document.createElement( 'img' ); eqn.setAttribute( 'alt', EqEditor.getTextArea().getLaTeX()); eqn.setAttribute( 'src', EqEditor.getTextArea().exportEquation('urlencoded')); editor.insertElement(eqn); EqEditor.Example.add_history(EqEditor.getTextArea().getLaTeX()); } }; });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'fakeobjects', 'fr-ca', { anchor: 'Ancre', flash: 'Animation Flash', hiddenfield: 'Champ caché', iframe: 'IFrame', unknown: 'Objet inconnu' });
exports.up = (pgm) => { pgm.renameTable('t2', 't2r') }
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); gulp.task('lint', function() { return gulp.src([ paths.src + '/**/*.js' ]) .pipe(jshint()) .pipe(jshint.reporter(stylish)) .pipe(jshint.reporter('fail')); }); var jscs = require('gulp-jscs'); gulp.task('code-style', function() { return gulp.src([ paths.src + '/**/*.js' ]) .pipe(jscs()); }); gulp.task('coding-standards', ['lint', 'code-style']);
// since it is a class both letter are capitilized // player class. Shows the image that the player is, the height and width //also the shape of it game.PlayerEntity = me.Entity.extend({ init: function(x, y, settings) { //leads to set super fuction below //use these fucntions to orgainize code this.setSuper(x, y); //leads to set player timer function this.setPlayerTimers(); //leads to the function attribute this.setAttributes(); //sets type so that creep can collide with it this.type = "PlayerEntity"; //leads to set flags function this.setFlags(); //where ever the player goes the screen follows me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //leads to add animation fucntion below //used to organize code this.addAnimation(); //sets currect animation this.renderable.setCurrentAnimation("idle"); }, //function sets up the super class setSuper: function (x, y){ this._super(me.Entity, 'init', [x, y, { image: "player", width: 64, height: 64, spritewidth: "64", spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 100, 70)).toPolygon(); } }]); }, //takes all the code from other parts and puts it in a function to make it more organized //timers set setPlayerTimers: function(){ //keeps track of what time it is for the game this.now = new Date().getTime(); //lets the character hit the other characters over and over again this.lastHit = this.now; //controls when the next spear spons this.lastSpear = this.now; //controls when the time of the last attack was this.lastAttack = new Date().getTime(); }, //set attributes function //leads up to line 11 setAttributes: function(){ //sets players health //uses the global variable that helps the player loose health //variable located in game.js this.heatlth = game.data.playerHealth; //sets the speed of the character this.body.setVelocity(game.data.playerMoveSpeed, 20); //a gold is added when the creep dies from attack this.attack = game.data.playerAttack; }, //used to organize our code //leads to line of code above setFlags: function(){ //keeps track of what direction your character is going this.facing = "right"; //players death function //what happens if the player dies this.dead = false; //linked to update class or attacking fuctnion //used to orgainze code this.attacking = false; }, //leads to add animation line of code above //used to orgainze code addAnimation: function(){ //this anmiantion is used for when we are just standing this.renderable.addAnimation("idle", [78]); //adds animation to orcs/ characters walk // 80 at the end is the speed of the walk // the numbers in the brackets are the different pics we are using for the animation this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80); //adds animation to the action attack this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80); }, update: function(delta){ //updates this.now this.now = new Date().getTime(); //checks to see if our player has or had not died //leads to function below //used to organize code this.dead = this.checkIfDead(); //leads to fucntion below //organizes code this.checkKeyPressesAndMove (); //checks the characters ability keys this.checkAbilityKeys(); //organizes our code this.setAnimation(); //checks for collisions me.collision.check(this, true, this.collideHandler.bind(this), true); // tells the code above to work this.body.update(delta); //another call to the parent class this._super(me.Entity, "update", [delta]); return true; }, //fucntion leads up to line of code //organizes our code checkIfDead: function(){ //makes the player die if (this.health <= 0){ return true; } return false; }, //organizes my code //leads up to code under update fucntion checkKeyPressesAndMove: function(){ //checks and sees if the right key is pressed if(me.input.isKeyPressed("right")){ //function below //organizes code this.moveRight(); //if we press the wrong button then the else statement will go into effect // if statement binds the left key so that we can move left }else if(me.input.isKeyPressed("left")){ //linked to fucntion below //organizes code this.moveLeft(); }else{ this.body.vel.x = 0; } //not in else statement because jumping involves the y axis not the x // binds the space bar so that we can jump if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){ //linked to code below //organizes code this.jump(); } //attack function //orgainzes update function this.attacking = me.input.isKeyPressed("attack"); }, //organizes code //linked to pressandmove fucntion moveRight: function(){ // adds the position of my x by adding the velocity defined above in // setVelocity() and multiplying it by me.timer.tick // me.timer.tick makes the movement look smooth this.body.vel.x += this.body.accel.x * me.timer.tick; //checks what way your character is going this.facing = "right"; //flips the character so he doesnt go backwards this.flipX(true); }, //organizes code //linked to pressandmove fucntion moveLeft: function(){ this.facing = "left"; this.body.vel.x -=this.body.accel.x * me.timer.tick; this.flipX(false); }, //organizes code //linked to pressandmove fucntion jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; me.audio.play("stomp"); }, //checks the players ability. Like if they are elligable for an update or more gold checkAbilityKeys: function(){ //checks if the skill key is pressed if(me.input.isKeyPressed("skill1")){ //this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ //this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, //enables the player to throw the spear throwSpear: function(){ //sets the spear timer to tell when the next spear can spon if((this.now-this.lastSpear) >= game.data.spearTimer*1000 && game.data.ability3 > 0){ //controls when the spear spons this.lastSpear = this.now; //bulids a spear and puts it into the world var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, //linked to attack fucntion in update class setAnimation: function(){ //if attack key is pressed character will attack //linked to checkKeyPressesandMove fucntion to organize code if(this.attacking){ //checks if it has gone through its animation stage if(!this.renderable.isCurrentAnimation("attack")){ //sets the current animation to attackand once that is over // goes back to the idle animation this.renderable.setCurrentAnimation("attack", "idle"); //makes it so that the next time we start this sequence we begin // from the the first animation, not wherever we left off when we // switched to another animation //this.renderable.setCurrentAnimationFrame(); me.audio.play("jump"); } } //checks if character is moving //checks that we dont have an attack animation going on else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //if statement checks to see whats going on with the character if(!this.renderable.isCurrentAnimation("walk")){ this.renderable.setCurrentAnimation("walk"); } }//else statement fixes the error of the character walking backwards else if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("idle"); } }, loseHealth: function(damage){ //player loses health this.health = this.health - damage; //prints out what our health is console.log(this.health); }, // tells us if we collide with the enemy base collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //organizes the code this.collideWithEnemyBase(response); //makes the creep loose health }else if(response.b.type==='EnemyCreep'){ //orgainzes the code this.collideWithEnemyCreep(response); } }, collideWithEnemyBase:function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; //checks to see when character collides with enemy base console.log("xdif " + xdif + "ydif " + ydif); //jumping through the top of the enemy base if(ydif<-40 && xdif< 70 && xdif>-35){ this.body.falling = false; this.body.vel.y = -1; } //the the player goes more than the number placed then it will stop moving //facing code allows us to move away from the base // xdif makes sure that both if statements wont trigger else if(xdif>-35 && this.facing==='right' && (xdif<0)){ //stops player from moving if they hit the base this.body.vel.x = 0; // moves player back a bit ////this.pos.x = this.pos.x - 1; //else if statement is used if the character is facing left }else if(xdif<70 && this.facing==='left' && xdif>0){ this.body.vel.x = 0; ////this.pos.x = this.pos.x +1; } //checks if the current animation is attack //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //cosole.log("tower Hit"); this.lastHit = this.now; //character dies/looses health when the player attacks the creep more than a certain number of attacks response.b.loseHealth(game.data.playerAttack); } }, collideWithEnemyCreep:function(response){ //lets you loose health if you are facing the x axis var xdif = this.pos.x - response.b.pos.x; //lets you loose health if you are facing the y axis var ydif = this.pos.y - response.b.pos.y; //orgainizes code this.stopMovement(xdif); //linked to check attack fucntion if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ //loose health if character comes in form the right or left //makes it so that we cant walk right into the base if (xdif>0){ ////this.pos.x = this.pos.x + 1; //keeps track of what way we are facing if(this.facing==="left"){ this.body.vel.x = 0; } }else{ this.pos.x = this.pos.x - 1; //keeps track of what way we are facing if(this.facing==="right"){ this.body.vel.x = 0; } } }, checkAttack: function(xdif, ydif){ //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer //checks the absolute value of the y and x difference && (Math.abs(ydif) <=40) && (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")) ){ //updates the timers this.lastHit = this.now; return true; } //if the attack check is false it will return false return false; }, hitCreep: function (response) { //linked to the line of code above //if the creepe health is less than our attack, execute code in if statement if(response.b.health <= game.data.playerAttack){ //adds one gold for a creep kill game.data.gold += 1; console.log("Current gold: " + game.data.gold); } //the player dies or looses health if it is attacking for too long //timer response.b.loseHealth(game.data.playerAttack); } });
var animalAppControllers = angular.module('HomelessController', []); animalApp.controller('HomelessController', function($scope) { });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'div', 'eo', { IdInputLabel: 'Id', advisoryTitleInputLabel: 'Priskriba Titolo', cssClassInputLabel: 'Stilfolioklasoj', edit: 'Redakti Div', inlineStyleInputLabel: 'Enlinia stilo', langDirLTRLabel: 'Maldekstre dekstren (angle LTR)', langDirLabel: 'Skribdirekto', langDirRTLLabel: 'Dekstre maldekstren (angle RTL)', languageCodeInputLabel: ' Lingvokodo', remove: 'Forigi Div', styleSelectLabel: 'Stilo', title: 'Krei DIV ujon', toolbar: 'Krei DIV ujon' });
import r from 'restructure'; import { LookupTable } from './aat'; let BslnSubtable = new r.VersionedStruct('format', { 0: { // Distance-based, no mapping deltas: new r.Array(r.int16, 32) }, 1: { // Distance-based, with mapping deltas: new r.Array(r.int16, 32), mappingData: new LookupTable(r.uint16) }, 2: { // Control point-based, no mapping standardGlyph: r.uint16, controlPoints: new r.Array(r.uint16, 32) }, 3: { // Control point-based, with mapping standardGlyph: r.uint16, controlPoints: new r.Array(r.uint16, 32), mappingData: new LookupTable(r.uint16) } }); export default new r.Struct({ version: r.fixed32, format: r.uint16, defaultBaseline: r.uint16, subtable: BslnSubtable });
var Substance = require('substance'); var Tool = Substance.Surface.Tool; var _ = require("substance/helpers"); var CiteTool = Tool.extend({ name: "cite", update: function(surface, sel) { this.surface = surface; // IMPORTANT! // Set disabled when not a property selection if (!surface.isEnabled() || sel.isNull() || !sel.isPropertySelection()) { return this.setDisabled(); } var newState = { surface: surface, sel: sel, disabled: false }; this.setToolState(newState); }, // Needs app context in order to request a state switch createCitation: function(citationTargetType) { var citation; var doc = this.context.doc; var citationType = doc.getSchema().getNodeClass(citationTargetType).static.citationType; var surface = this.surface; var editor = surface.getEditor(); console.log('citationType', citationType); surface.transaction(function(tx, args) { var selection = args.selection; var path = selection.start.path; var startOffset = selection.start.offset; if (!selection.isCollapsed) { var out = editor.delete(tx, args); args.selection = out.selection; } args.text = '$'; editor.insertText(tx, args); citation = tx.create({ id: Substance.uuid(citationType), "type": citationType, "targets": [], "path": path, "startOffset": startOffset, "endOffset": startOffset + 1, }); citation.label = "???"; args.selection = citation.getSelection(); return args; }); return citation; }, toggleTarget: function(citationId, targetId) { var doc = this.context.doc; var citation = doc.get(citationId); var newTargets = citation.targets.slice(); if (_.includes(newTargets, targetId)) { newTargets = _.without(newTargets, targetId); } else { newTargets.push(targetId); } this.surface.transaction(function(tx, args) { tx.set([citation.id, "targets"], newTargets); return args; }); } }); module.exports = CiteTool;
/** * Returns true if targetString ends with substring. Otherwise, returns false. * @param {string} targetString * @param {string} substring * @returns {boolean} */ function endsWith(targetString, substring) { return targetString.endsWith(substring); } module.exports = endsWith;
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.dtl.html"]){dojo._hasResource["dojox.dtl.html"]=true;dojo.provide("dojox.dtl.html");dojo.deprecated("dojox.dtl.html","All packages and classes in dojox.dtl that start with Html or html have been renamed to Dom or dom");dojo.require("dojox.dtl.dom");dojox.dtl.HtmlTemplate=dojox.dtl.DomTemplate;}
version https://git-lfs.github.com/spec/v1 oid sha256:c53d0bfa3a80a45737c7e7b26b6d39d855b48b5c6095d9418e70969b0680e922 size 30050
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M14 3.25l-10 10V17h3.75l10-10L14 3.25zM6.92 15H6v-.92l8-8 .92.92-8 8zM20.71 4.04c.39-.39.39-1.02 0-1.41L18.37.29a.9959.9959 0 0 0-1.41 0L15 2.25 18.75 6l1.96-1.96z" /><path fillOpacity=".36" d="M0 20h24v4H0v-4z" /></React.Fragment> , 'BorderColorOutlined');
/** * Copyright 2014 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["en-NZ"] = { name: "en-NZ", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["-$n","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "$" } }, calendars: { standard: { days: { names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"] }, months: { names: ["January","February","March","April","May","June","July","August","September","October","November","December",""], namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "d/MM/yyyy", D: "dddd, d MMMM yyyy", F: "dddd, d MMMM yyyy h:mm:ss tt", g: "d/MM/yyyy h:mm tt", G: "d/MM/yyyy h:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
/* Copyright (c) 2013 William Malone (www.williammalone.com) 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. */ /*global window, document, navigator */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.game = function (spec, element) { "use strict"; var game = BLOCKS.eventDispatcher(), clock = BLOCKS.clock(), gameContainer, gameCanvas, interactionContainer, paused = false, virtualKeyboard, motors = [], tickers = [], debugPressTimeout, lastUpdateTime, remainingUpdate, minWidth, minHeight, maxHeight, maxWidth, scaleLandscape, scalePortrait, debugLayer, gameTappedOnce, loaded, tickerIndex = 0, layerIndex = 0, maxLayers, prepared, wasMutedWhenPaused, loadStarted, handleTickers = function () { var i, tickerArr = [], callbacks = []; for (i = 0; i < tickers.length; i += 1) { tickers[i].curTick += 1; if (tickers[i].curTick >= tickers[i].totalTicks) { callbacks.push(tickers[i]); } else { tickerArr.push(tickers[i]); } } tickers = tickerArr; for (i = 0; i < callbacks.length; i += 1) { callbacks[i].callback(callbacks[i].parameters); } }, onOrientationChange = function () { // Remove the space on iPhone / iPod when in landscape and using minimal ui meta tag if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { if (window.orientation === 90 || window.orientation === -90) { window.scrollTo(0, 0); resizeGame(); } } }, onVisibilityChange = function () { if (document.hidden || document.webkitHidden || document.mozHidden || document.msHidden) { game.pause(); } else { game.unpause(); } }, onFirstTap = function () { if (!gameTappedOnce) { game.controller.removeEventListener("tap", onFirstTap); game.dispatchEvent("firstTap"); gameTappedOnce = true; if (game.introScreen) { game.state = "loading"; game.introScreen.destroy(); game.introScreen = null; } game.speaker.load(); checkLoadProgress(); checkInitialScreenProgress(); } }, init = function () { var i; if (spec && spec.scaleLandscape !== undefined) { scaleLandscape = spec.scaleLandscape; } else { scaleLandscape = true; } if (spec && spec.scalePortrait !== undefined) { scalePortrait = spec.scalePortrait; } else { scalePortrait = true; } if (game.element) { gameContainer = document.createElement("article"); gameContainer.id = "BlocksGameContainer"; if (spec && spec.minWidth) { minWidth = spec.minWidth; gameContainer.style.minWidth = minWidth + "px"; } if (spec && spec.minHeight) { minHeight = spec.minHeight; gameContainer.style.minHeight = minHeight + "px"; } if (spec && spec.maxWidth) { maxWidth = spec.maxWidth; gameContainer.style.maxWidth = maxWidth + "px"; } if (spec && spec.maxHeight) { maxHeight = spec.maxHeight; gameContainer.style.maxHeight = maxHeight + "px"; } game.element.appendChild(gameContainer); interactionContainer = document.createElement("article"); interactionContainer.id = "BlocksInteractionContainer"; gameContainer.appendChild(interactionContainer); } game.controller = BLOCKS.controller(interactionContainer); // Resize the game the first time to initialize the game scale propetries resizeGame(); // Create virtual keyboard if (game.debug && game.virtualKeyboardEnabled) { virtualKeyboard = BLOCKS.virtualKeyboard(game.controller, { layer: game.getLayer(), customKeys: spec.customVirtualKeys }); } window.addEventListener("orientationchange", onOrientationChange); window.addEventListener("resize", resizeGame); game.controller.addEventListener("keyUp", onKeyUp); game.controller.addEventListener("keyDown", onKeyDown); game.controller.addEventListener("tap", onTap); game.controller.addEventListener("drag", onDrag); game.controller.addEventListener("release", onRelease); game.controller.addEventListener("cancel", onRelease); // Note cancel is retreated as a release game.controller.addEventListener("touchStart", onTouchStart); game.controller.addEventListener("touchMove", onTouchMove); game.controller.addEventListener("touchEnd", onTouchEnd); game.controller.addEventListener("touchCancel", onTouchEnd); // Note cancel is retreated as a touch end game.controller.addEventListener("mouseDown", onMouseDown); game.controller.addEventListener("mouseMove", onMouseMove); game.controller.addEventListener("mouseUp", onMouseUp); game.controller.addEventListener("mouseCancel", onMouseUp); // Note cancel is retreated as a mouse up game.controller.addEventListener("mouseOut", onMouseOut); game.controller.addEventListener("mouseUpOutside", mouseUpOutside); // Listen to the first time the game is tapped game.controller.addEventListener("tap", onFirstTap); // Mute and pause the game when the browser is not visible if (typeof document.hidden !== "undefined") { document.addEventListener("visibilitychange", onVisibilityChange); } else if (typeof document.mozHidden !== "undefined") { document.addEventListener("mozvisibilitychange", onVisibilityChange); } else if (typeof document.msHidden !== "undefined") { document.addEventListener("msvisibilitychange", onVisibilityChange); } else if (typeof document.webkitHidden !== "undefined") { document.addEventListener("webkitvisibilitychange", onVisibilityChange); } window.onunload = game.destroy; }, gameUpdate = function () { var now; if (!paused) { now = + new Date(); remainingUpdate += (now - lastUpdateTime); lastUpdateTime = now; // If too much update then crop it if (remainingUpdate > game.maxLoopDuration) { BLOCKS.warn("Cannot keep up with game loop. Chopping " + Math.ceil((remainingUpdate - game.maxLoopDuration) / 60) + " frames."); remainingUpdate = game.maxLoopDuration; } //if (remainingUpdate < 16.666666666666) { // BLOCKS.debug("No update this time: " + remainingUpdate); //} while (remainingUpdate >= 16.666666666666) { remainingUpdate -= 16.666666666666; game.dispatchEvent("tick"); // Simulate a clock game.dispatchEvent("preUpdate"); if (game.debug && virtualKeyboard) { virtualKeyboard.update(); } handleTickers(); game.update(); game.dispatchEvent("postUpdate"); } } }, gameRender = function () { var e = { camera: game.camera }; if (!paused) { game.dispatchEvent("preRender", e); if (game.debug && virtualKeyboard) { virtualKeyboard.render(e); } game.render(e); game.dispatchEvent("postRender", e); } }, onClockTick = function () { gameUpdate(); gameRender(); }, onKeyDown = function (e) { if (game.keyDown) { game.keyDown(e); } }, onKeyUp = function (e) { if (game.keyUp) { game.keyUp(e); } }, onTap = function (pos) { if (game.debug && virtualKeyboard) { if (pos.x < 100 && pos.y < 100) { debugPressTimeout = window.setTimeout(function () { virtualKeyboard.visible = !virtualKeyboard.visible; virtualKeyboard.dirty = true; }, 1000); } virtualKeyboard.onTap(pos); } if (game.tap) { game.tap(pos); } }, onDrag = function (pos) { if (game.debug) { window.clearTimeout(debugPressTimeout); } if (game.drag) { game.drag(pos); } }, onRelease = function (pos) { if (game.debug) { window.clearTimeout(debugPressTimeout); } if (game.release) { game.release(pos); } }, onTouchStart = function (pos) { if (game.touchStart) { game.touchStart(pos); } }, onTouchMove = function (pos) { if (game.touchMove) { game.touchMove(pos); } }, onTouchEnd = function (pos) { if (game.touchEnd) { game.touchEnd(pos); } }, onMouseDown = function (pos) { if (game.mouseDown) { game.mouseDown(pos); } }, onMouseMove = function (pos) { if (game.mouseMove) { game.mouseMove(pos); } }, onMouseUp = function (pos) { if (game.mouseUp) { game.mouseUp(pos); } }, onMouseOut = function (pos) { if (game.mouseOut) { game.mouseOut(pos); } }, mouseUpOutside = function (pos) { if (game.mouseUpOutside) { game.mouseUpOutside(pos); } }, checkLoadProgress = function () { //BLOCKS.debug("checkLoadProgress: " + gameTappedOnce + " " + game.imageLoader.isLoaded() + " " + game.speaker.isReady()); if (!loaded) { if ((game.introScreen && gameTappedOnce) || !game.introScreen) { // If all images are loaded and all sounds (or number of sounds is zero) are laoded if (game.imageLoader.isLoaded() && (game.speaker.isReady() || game.speaker.getNumFiles() === 0)) { loaded = true; if (game.loadingScreen) { game.loadingScreen.destroy(); game.loadingScreen = null; } // If autoLoad is not turned off then load if (game.autoStart !== false) { game.start(); } game.dispatchEvent("loaded"); } } } }, // See wmalone.com/scale for an article discussing this scaling approach resizeGame = function () { var i, viewport, newGameWidth, newGameHeight, newGameX, newGameY; // Get the dimensions of the viewport if (game.element) { viewport = { width: game.element.offsetWidth, height: game.element.offsetHeight }; } else { viewport = { width: window.innerWidth * game.pixelMultiplier, height: window.innerHeight * game.pixelMultiplier }; } // If the viewport is greater than a minimum or maximum game dimension use that instead if (minWidth && viewport.width < minWidth) { viewport.width = minWidth; } if (minHeight && viewport.height < minHeight) { viewport.height = minHeight; } if (maxWidth && viewport.width > maxWidth) { viewport.width = maxWidth; } if (maxHeight && viewport.height > maxHeight) { viewport.height = maxHeight; } // If the game should not be scaled if (!scaleLandscape && Math.abs(window.orientation) === 90 || !scalePortrait && Math.abs(window.orientation) !== 90) { newGameHeight = game.height; newGameWidth = game.width; } else { // Determine game size if (game.height / game.width > viewport.height / viewport.width) { if (game.safeHeight / game.width > viewport.height / viewport.width) { // A newGameHeight = viewport.height * game.height / game.safeHeight; newGameWidth = newGameHeight * game.width / game.height; } else { // B newGameWidth = viewport.width; newGameHeight = newGameWidth * game.height / game.width; } } else { if (game.height / game.safeWidth > viewport.height / viewport.width) { // C newGameHeight = viewport.height; newGameWidth = newGameHeight * game.width / game.height; } else { // D newGameWidth = viewport.width * game.width / game.safeWidth; newGameHeight = newGameWidth * game.height / game.width; } } } newGameX = (viewport.width - newGameWidth) / 2; newGameY = (viewport.height - newGameHeight) / 2; // Save the game scale amount game.scale = newGameWidth / game.width; // Define the camera game.camera.offsetX = -Math.min(newGameX, 0) / game.scale; game.camera.offsetY = -Math.min(newGameY, 0) / game.scale; game.camera.width = (viewport.width - Math.max(newGameX, 0) * 2) / game.scale; game.camera.height = (viewport.height - Math.max(newGameY, 0) * 2) / game.scale; if (gameContainer) { // Resize the game container gameContainer.style.width = (viewport.width - Math.max(newGameX, 0) * 2) + "px"; gameContainer.style.height = (viewport.height - Math.max(newGameY, 0) * 2)+ "px"; // Set the new padding of the game so it will be centered gameContainer.style.padding = Math.max(newGameY, 0) + "px " + Math.max(newGameX, 0) + "px"; } // Tell the controller the game dimensions game.controller.scaleX = (game.width / newGameWidth) * game.pixelMultiplier; game.controller.scaleY = (game.height / newGameHeight) * game.pixelMultiplier; game.controller.offsetX = -game.camera.offsetX * game.scale / game.pixelMultiplier; game.controller.offsetY = -game.camera.offsetY * game.scale / game.pixelMultiplier; for (i = 0; i < game.layers.length; i += 1) { game.layers[i].width = game.camera.width; game.layers[i].height = game.camera.height; } if (!loaded && game.loadingScreen) { game.loadingScreen.dirty = true; } game.dispatchEvent("resize"); }, initLoad = function () { if (!loadStarted) { // If autoLoad is not turned off then load if (game.autoLoad !== false) { game.load(); } } }, checkInitialScreenProgress = function () { if (game.introScreen) { if (!game.introScreen.loaded) { //BLOCKS.debug("waiting for intro screen to load"); return; } } if (game.loadingScreen) { if (!game.loadingScreen.loaded) { //BLOCKS.debug("waiting for loading screen to load"); return; } } //BLOCKS.debug("load game"); initLoad(); }; // Define spec as empty object if it was specified as a parameter spec = spec || {}; // The element in which the game markup will be injected will be the element with // the "BlockGame" id unless specified via a parameter of the game game.element = (element !== undefined) ? element : document.getElementById("BlocksGame"); // If no game element found with matching id, look for one with a matching class name if (!game.element) { if (document.getElementsByClassName && document.getElementsByClassName("BlocksGame")) { game.element = document.getElementsByClassName("BlocksGame")[0]; } } if (!game.element && !spec.canvas) { BLOCKS.error("Game does not have a game element"); } // If there is no game element to scale for us we will need to scale manually game.pixelMultiplier = !game.element && window.devicePixelRatio ? window.devicePixelRatio : 1; // The scale property represents the amount the game is scaled game.scale = 1; // The singleLayer property will render everything to one layer game.singleLayer = spec.singleLayer !== undefined ? spec.singleLayer : false; game.layers = []; game.width = spec.width !== undefined ? spec.width : 1024; game.height = spec.height !== undefined ? spec.height : 768; game.safeWidth = spec.safeWidth || game.width; game.safeHeight = spec.safeHeight || game.height; game.debug = spec.debug !== undefined ? spec.debug : false; game.maxLoopDuration = spec.maxLoopDuration !== undefined ? spec.maxLoopDuration : 500; game.stage = BLOCKS.container(game); game.camera = BLOCKS.camera({ width: game.width, height: game.height }); game.autoLoad = spec.autoLoad !== undefined ? spec.autoLoad : true; game.autoStart = spec.autoStart !== undefined ? spec.autoStart : true; game.state = ""; // A canvas can be specified to be used for all rendering gameCanvas = spec.canvas; // If a canvas is specifed then only one layer will be allowed if (gameCanvas) { maxLayers = 1; } else { maxLayers = spec.maxLayers !== undefined ? spec.maxLayers : 10; } game.pause = function () { if (!paused) { //BLOCKS.debug("Game not visible so pause"); paused = true; if (game.speaker) { wasMutedWhenPaused = game.speaker.isMuted(); game.speaker.mute(); game.speaker.pause(); game.dispatchEvent("pause"); } } }; game.resize = function () { resizeGame(); }; game.unpause = function () { if (paused) { //BLOCKS.debug("Game is visible again so unpause"); paused = false; lastUpdateTime = + new Date(); if (game.speaker) { if (!wasMutedWhenPaused) { game.speaker.unmute(); } game.speaker.unpause(); game.dispatchEvent("unpause"); } } }; game.update = function () { game.stage.update(); }; game.render = function (e) { game.stage.render(e); }; game.clearLayers = function () { var i; for (i = 0; i < game.layers.length; i += 1) { game.layers[i].clear(); } }; // Label can match a layer's name or id or index game.getLayer = function (label) { var i, layer, index; if (label === undefined) { label = 0; } if (typeof label === "number") { index = label; // If the index is larger than the number of layers if (index > game.layers.length - 1) { if (index > maxLayers - 1) { layer = game.layers[game.layers.length - 1]; if (!gameCanvas) { BLOCKS.warn("Layer index larger than maximum layers, using the top layer instead."); } } else { // Create a new layer layer = game.addLayer("FrameworkGameLayer" + index); } } else { layer = game.layers[index]; } } else { // Return the layer with the layer with the matching name for (i = 0; i < game.layers.length; i += 1) { if (game.layers[i].name === label || game.layers[i].id === label) { layer = game.layers[i]; } } } return layer; }; game.createLayer = function (name, options) { options = options || {}; options.name = name; options.id = (+ new Date()).toString() + tickerIndex; options.canvas = gameCanvas; if (!game.element) { options.scale = game.pixelMultiplier / game.scale; } if (interactionContainer) { options.parentElement = interactionContainer; } if (!options.width) { options.width = game.camera.width; } if (!options.height) { options.height = game.camera.height; } return BLOCKS.layer(options); }; game.addLayer = function (name, options) { var layer; // If using one layer then return that if (gameCanvas && game.layers.length) { return game.getLayer(); } else { layer = game.createLayer(name, options); game.layers.push(layer); return layer; } }; game.destroyLayer = function (layer) { if (layer) { layer.destroy(); layer = null; } }; game.removeLayer = function (name) { var i; for (i = 0; i < game.layers.length; i += 1) { if (game.layers[i].name === name) { game.destroyLayer(game.layers[i]); game.layers.splice(i, 1); return true; } } }; game.addMotor = function (type) { var key, motor, spec = arguments[1] || {}; spec.type = type; if (spec.type === "drag") { spec.controller = game.controller; } else { spec.clock = game; } motor = BLOCKS.motor(spec); if (motor) { motor.type = type; if (spec.object) { spec.object.motorize(motor); } motor.addEventListener("destroyed", game.removeMotor); motors.push(motor); } return motor; }; game.removeMotor = function (motor) { var i; for (i = 0; i < motors.length; i += 1) { if (motors[i] === motor) { motors.splice(i, 1); return true; } } }; game.addTicker = function (callback, duration, parameters) { var id = (+ new Date()).toString() + tickerIndex; tickerIndex += 1; if (tickerIndex > 99999999) { tickerIndex = 0; } tickers.push({ id: id, curTick: 0, totalTicks: Math.ceil(duration * 60 / 1000), callback: callback, parameters: parameters }); return id; }; game.removeTicker = function (id) { var i, existingTickers = []; for (i = 0; i < tickers.length; i += 1) { if (tickers[i].id === id) { tickers[i] = null; } else { existingTickers.push(tickers[i]); } } tickers = existingTickers; }; game.clearTickers = function () { tickers = []; }; game.load = function () { var i; if (!loadStarted) { loadStarted = true; game.imageLoader.loadFromTree(spec); // Define game sounds if (spec.sounds) { for (i = 0; i < spec.sounds.length; i += 1) { game.speaker.createSound(spec.sounds[i]); } } game.imageLoader.addEventListener("update", function () { var assetsLoaded = game.imageLoader.getNumFilesLoaded() + game.speaker.getNumFilesLoaded(); if (game.loadingScreen) { game.loadingScreen.setProgress(assetsLoaded, game.imageLoader.getNumFiles() + game.speaker.getNumFiles()); } }); game.imageLoader.addEventListener("complete", function () { checkLoadProgress(); }); game.imageLoader.load(); } }; game.stop = function () { clock.removeEventListener("tick", onClockTick); clock.stop(); }; game.start = function () { var i; lastUpdateTime = + new Date(); remainingUpdate = 0; if (!prepared) { prepared = true; if (game.prepare) { game.prepare(); } } clock.removeEventListener("tick", onClockTick); clock.addEventListener("tick", onClockTick); clock.start(); }; game.destroy = function () { var i; clock.destroy(); if (game.speaker) { game.speaker.stop(); } if (game.introScreen) { game.introScreen.destroy(); } if (game.loadingScreen) { game.loadingScreen.destroy(); } for (i = 0; i < game.layers; i += 1) { game.removeLayer(game.layers[i]); } }; // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ (function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { window.clearTimeout(id); }; }()); init(); game.imageLoader = (spec && spec.imagesPath) ? BLOCKS.preloader(spec.imagesPath) : BLOCKS.preloader(); if (spec && spec.loading) { game.loadingScreen = BLOCKS.loadingScreen(spec.loading, game); game.intro = "loading"; } if (spec && spec.intro) { game.introScreen = BLOCKS.introScreen(spec.intro, game); game.intro = "intro"; } // Create sound player game.speaker = BLOCKS.speaker({ path: (spec && spec.audioPath !== undefined) ? spec.audioPath : "", src: (spec && spec.audioSpriteSrc !== undefined) ? spec.audioSpriteSrc : "", audioPlayerType: spec.audioPlayerType }); game.speaker.addEventListener("update", function (e) { var assetsLoaded = game.imageLoader.getNumFilesLoaded() + game.speaker.getNumFilesLoaded(); if (game.loadingScreen) { game.loadingScreen.setProgress(assetsLoaded, game.imageLoader.getNumFiles() + game.speaker.getNumFiles()); } }); game.speaker.addEventListener("ready", function () { checkLoadProgress(); }, true); Object.defineProperty(game, "paused", { get: function () { return paused; } }); if (game.loadingScreen) { game.loadingScreen.addEventListener("loaded", checkInitialScreenProgress); } if (game.introScreen) { game.introScreen.addEventListener("loaded", checkInitialScreenProgress); } checkInitialScreenProgress(); return game; };
define([ 'aeris/util', 'aeris/api/models/aerisapimodel' ], function(_, AerisApiModel) { /** * @publicApi * @class Advisory * @namespace aeris.api.models * @extends aeris.api.models.AerisApiModel * * @constructor * @override */ var Advisory = function(opt_attrs, opt_options) { var options = _.defaults(opt_options || {}, { endpoint: 'advisories' }); AerisApiModel.call(this, opt_attrs, options); }; _.inherits(Advisory, AerisApiModel); /** * @method parse */ Advisory.prototype.parse = function(resp) { // Note that a request to the advisories endpoint using an // an id returns an array of responses. return resp.response ? resp.response[0] : resp; }; return _.expose(Advisory, 'aeris.api.models.Advisory'); });