code
stringlengths
2
1.05M
'use strict'; var Module = angular.module('datePicker', []); Module.constant('datePickerConfig', { template: 'templates/datepicker.html', view: 'month', views: ['year', 'month', 'date', 'hours', 'minutes'], step: 5 }); Module.filter('time',function () { function format(date){ return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2); } return function (date) { if (!(date instanceof Date)) { date = new Date(date); if (isNaN(date.getTime())) { return undefined; } } return format(date); }; }); Module.directive('datePicker', ['datePickerConfig', 'datePickerUtils', function datePickerDirective(datePickerConfig, datePickerUtils) { //noinspection JSUnusedLocalSymbols return { // this is a bug ? require:'?ngModel', template: '<div ng-include="template"></div>', scope: { model: '=datePicker', after: '=?', before: '=?' }, link: function (scope, element, attrs, ngModel) { var arrowClick = false; scope.date = new Date(scope.model || new Date()); scope.views = datePickerConfig.views.concat(); scope.view = attrs.view || datePickerConfig.view; scope.now = new Date(); scope.template = attrs.template || datePickerConfig.template; var step = parseInt(attrs.step || datePickerConfig.step, 10); var partial = !!attrs.partial; var before = attrs.before; var after = attrs.after; //if ngModel, we can add min and max validators if(ngModel) { if (angular.isDefined(attrs.minDate)) { var minVal; ngModel.$validators.min = function (value) { return !datePickerUtils.isValidDate(value) || angular.isUndefined(minVal) || value >= minVal; }; attrs.$observe('minDate', function (val) { minVal = new Date(val); ngModel.$validate(); }); } if (angular.isDefined(attrs.maxDate)) { var maxVal; ngModel.$validators.max = function (value) { return !datePickerUtils.isValidDate(value) || angular.isUndefined(maxVal) || value <= maxVal; }; attrs.$observe('maxDate', function (val) { maxVal = new Date(val); ngModel.$validate(); }); } } //end min, max date validator /** @namespace attrs.minView, attrs.maxView */ scope.views =scope.views.slice( scope.views.indexOf(attrs.maxView || 'year'), scope.views.indexOf(attrs.minView || 'minutes')+1 ); if (scope.views.length === 1 || scope.views.indexOf(scope.view)===-1) { scope.view = scope.views[0]; } scope.setView = function (nextView) { if (scope.views.indexOf(nextView) !== -1) { scope.view = nextView; } }; scope.setDate = function (date) { if(attrs.disabled) { return; } scope.date = date; // change next view var nextView = scope.views[scope.views.indexOf(scope.view) + 1]; if ((!nextView || partial) || scope.model) { scope.model = new Date(scope.model || date); //if ngModel , setViewValue and trigger ng-change, etc... if(ngModel) { ngModel.$setViewValue(scope.date); } var view = partial ? 'minutes' : scope.view; //noinspection FallThroughInSwitchStatementJS switch (view) { case 'minutes': scope.model.setMinutes(date.getMinutes()); /*falls through*/ case 'hours': scope.model.setHours(date.getHours()); /*falls through*/ case 'date': scope.model.setDate(date.getDate()); /*falls through*/ case 'month': scope.model.setMonth(date.getMonth()); /*falls through*/ case 'year': scope.model.setFullYear(date.getFullYear()); } scope.$emit('setDate', scope.model, scope.view); } if (nextView) { scope.setView(nextView); } if(!nextView && attrs.autoClose === 'true'){ element.addClass('hidden'); scope.$emit('hidePicker'); } }; function update() { var view = scope.view; if (scope.model && !arrowClick) { scope.date = new Date(scope.model); arrowClick = false; } var date = scope.date; switch (view) { case 'year': scope.years = datePickerUtils.getVisibleYears(date); break; case 'month': scope.months = datePickerUtils.getVisibleMonths(date); break; case 'date': scope.weekdays = scope.weekdays || datePickerUtils.getDaysOfWeek(); scope.weeks = datePickerUtils.getVisibleWeeks(date); break; case 'hours': scope.hours = datePickerUtils.getVisibleHours(date); break; case 'minutes': scope.minutes = datePickerUtils.getVisibleMinutes(date, step); break; } } function watch() { if (scope.view !== 'date') { return scope.view; } return scope.date ? scope.date.getMonth() : null; } scope.$watch(watch, update); scope.next = function (delta) { var date = scope.date; delta = delta || 1; switch (scope.view) { case 'year': /*falls through*/ case 'month': date.setFullYear(date.getFullYear() + delta); break; case 'date': /* Reverting from ISSUE #113 var dt = new Date(date); date.setMonth(date.getMonth() + delta); if (date.getDate() < dt.getDate()) { date.setDate(0); } */ date.setMonth(date.getMonth() + delta); break; case 'hours': /*falls through*/ case 'minutes': date.setHours(date.getHours() + delta); break; } arrowClick = true; update(); }; scope.prev = function (delta) { return scope.next(-delta || -1); }; scope.isAfter = function (date) { return scope.after && datePickerUtils.isAfter(date, scope.after); }; scope.isBefore = function (date) { return scope.before && datePickerUtils.isBefore(date, scope.before); }; scope.isSameMonth = function (date) { return datePickerUtils.isSameMonth(scope.model, date); }; scope.isSameYear = function (date) { return datePickerUtils.isSameYear(scope.model, date); }; scope.isSameDay = function (date) { return datePickerUtils.isSameDay(scope.model, date); }; scope.isSameHour = function (date) { return datePickerUtils.isSameHour(scope.model, date); }; scope.isSameMinutes = function (date) { return datePickerUtils.isSameMinutes(scope.model, date); }; scope.isNow = function (date) { var is = true; var now = scope.now; //noinspection FallThroughInSwitchStatementJS switch (scope.view) { case 'minutes': is &= ~~(date.getMinutes()/step) === ~~(now.getMinutes()/step); /*falls through*/ case 'hours': is &= date.getHours() === now.getHours(); /*falls through*/ case 'date': is &= date.getDate() === now.getDate(); /*falls through*/ case 'month': is &= date.getMonth() === now.getMonth(); /*falls through*/ case 'year': is &= date.getFullYear() === now.getFullYear(); } return is; }; } }; }]);
App.SlidesView = Em.View.extend();
var format = require('../utils/format'), output = require('../utils/output'), tfSync = require('../utils/tfSync'); /** * Attaches a label to or removes a label from a version of a file or folder in the server for Team Foundation version control.Required PermissionsTo use the label command, you must have the Label permission set to Allow. To modify or delete labels created by other users, you must have the Administer labels permission set to Allow. For more information, see Team Foundation Server Permissions. * * @param {Array} itemspec File(s) or folder(s) to retrieve. If null/undefined, equals CWD. * @param {Object} options Command options */ var label = function(labelname, options) { var params = labelname; if (options.owner) { params.push('/owner'); } if (options.version) { params.push('/version'); } if (options.comment) { params.push('/comment'); } if (options.child) { params.push('/child'); } if (options.recursive) { params.push('/recursive'); } if (options.delete) { params.push('/delete'); } if (options.login) { params.push('/login'); } if (options.collection) { params.push('/collection'); } if (options.verbose) { output.verbose('Command: get ' + params.join(' ')); } return tfSync('label', params, function() { output.success('Done, without errors.'); }, !!options.verbose); }; module.exports = label;
export default { el: { colorpicker: { confirm: 'OK', clear: 'Xóa' }, datepicker: { now: 'Hiện tại', today: 'Hôm nay', cancel: 'Hủy', clear: 'Xóa', confirm: 'OK', selectDate: 'Chọn ngày', selectTime: 'Chọn giờ', startDate: 'Ngày bắt đầu', startTime: 'Thời gian bắt đầu', endDate: 'Ngày kết thúc', endTime: 'Thời gian kết thúc', year: 'Năm', month1: 'Tháng 1', month2: 'Tháng 2', month3: 'Tháng 3', month4: 'Tháng 4', month5: 'Tháng 5', month6: 'Tháng 6', month7: 'Tháng 7', month8: 'Tháng 8', month9: 'Tháng 9', month10: 'Tháng 10', month11: 'Tháng 11', month12: 'Tháng 12', // week: 'week', weeks: { sun: 'CN', mon: 'T2', tue: 'T3', wed: 'T4', thu: 'T5', fri: 'T6', sat: 'T7' }, months: { jan: 'Th.1', feb: 'Th.2', mar: 'Th.3', apr: 'Th.4', may: 'Th.5', jun: 'Th.6', jul: 'Th.7', aug: 'Th.8', sep: 'Th.9', oct: 'Th.10', nov: 'Th.11', dec: 'Th.12' } }, select: { loading: 'Loading', noMatch: 'Dữ liệu không phù hợp', noData: 'Không tìm thấy dữ liệu', placeholder: 'Chọn' }, cascader: { noMatch: 'Dữ liệu không phù hợp', loading: 'Loading', placeholder: 'Chọn' }, pagination: { goto: 'Nhảy tới', pagesize: '/trang', total: 'Tổng {total}', pageClassifier: '' }, messagebox: { title: 'Thông báo', confirm: 'OK', cancel: 'Hủy', error: 'Dữ liệu không hợp lệ' }, upload: { delete: 'Xóa', preview: 'Xem trước', continue: 'Tiếp tục' }, table: { emptyText: 'Không có dữ liệu', confirmFilter: 'Xác nhận', resetFilter: 'Làm mới', clearFilter: 'Xóa hết', sumText: 'Sum' // to be translated }, tree: { emptyText: 'Không có dữ liệu' }, transfer: { noMatch: 'Dữ liệu không phù hợp', noData: 'Không tìm thấy dữ liệu', titles: ['List 1', 'List 2'], // to be translated filterPlaceholder: 'Enter keyword', // to be translated noCheckedFormat: '{total} items', // to be translated hasCheckedFormat: '{checked}/{total} checked' // to be translated } } };
'use strict'; (function(){ var dependencies = [ 'new-player' ]; define( dependencies, function( angular ) { // get reference to New Player module var npApp = angular .module( 'newPlayer' ); //.config() //.service() //.controller(); /**************************** * Bootstrap App ****************************/ console.log('app::inject app', npApp ); var injector = angular.bootstrap(document, ['newPlayer']); console.log('app::injector', injector ); return npApp; } ); }());
'use strict'; var $ = require('jquery'); module.exports = { template: [ '<div class="dimmable">', '<div class="ui page dimmer" ref="modal">', '<slot></slot></div>', '</div>' ].join(''), props: ['value'], watch: { value: function(newValue, oldValue) { if (newValue != oldValue) { $(this.$refs.modal).dimmer(newValue ? 'show' : 'hide'); } } }, mounted: function() { var that = this; var body = $('body'); // It should be directly in <body> body.get(0).appendChild(that.$el); // Initialize modal $(that.$refs.modal).dimmer({ onShow: function() { if (!that.value) { that.$emit('input', true); } }, onHide: function() { if (that.value) { that.$emit('input', false); } } }); // Handle <esc> key function keyHandler(event) { if (that.value) { var modifiers = event.ctrlKey || event.altKey || event.metaKey || event.shiftKey; if ((event.which == 27) && !modifiers) { $(that.$refs.modal).dimmer('hide'); } } } body.on('keyup', keyHandler); this.$on('destroy', function() { body.off('keyup', keyHandler); }); }, beforeDestroy: function() { this.$emit('destroy'); } };
import Ember from 'ember'; import layout from './template'; export default Ember.Component.extend({ layout: layout, store: Ember.inject.service(), actions: { createPost() { this.get('store').createRecord('post', { title: 'New Dummy', body: 'I\'m a new dummy' }); } } });
export { default } from 'ember-cli-modal-service/components/modal-wrapper';
import gulp from 'gulp'; gulp.task('cdn', ['clean:cdn', 'dist:build:cdn']);
'use strict'; const AError = require('./../../core/AzuriteError'), ErrorCodes = require('./../../core/ErrorCodes'), QueueManager = require('./../../core/queue/QueueManager'); /** * Validates whether popreceipt of a given message is still valid. */ class PopReceipt { constructor() { } validate({ request = undefined }) { const msg = QueueManager.getQueueAndMessage({ queueName: request.queueName, messageId: request.messageId }).message; if (msg.popReceipt !== request.popReceipt) { throw new AError(ErrorCodes.PopReceiptMismatch); } } } module.exports = new PopReceipt();
(function($) { $.fn.typograph=function(options) { //VARS var lang, languesDisponibles; //LANGUES DISPONIBLES languesDisponibles = ['fr','en','de']; //LANGUE DU DOCUMENT lang = ( typeof($('html').attr('lang') )!= 'undefined' ) ? $('html').attr('lang') : "en"; //SI ELLE EXISTE, LA LANGUE DU DOCUMENT EST-ELLE PRIS EN CHARGE ? lang = ( jQuery.inArray(lang, languesDisponibles) != -1 ) ? lang : "en"; //PARAMÈTRES PAR DÉFAUT var defauts= { "lang": lang, "motOrphelin": false, "callback": null }; var parametres = $.extend( defauts, options ); //ESPACE FINE INSÉCABLE var espaceFineInsecable = "<span style=white-space:nowrap;font-family:sans-serif;>&thinsp;</span>"; return this.each(function() { //ON NE TRAITE PAS LES PARAGRAPHES PRÉCÉDEMMENT TRAITÉS AINSI QUE LES EXCEPTIONS POTENTIELLES (CLASS "typograph-dont") if( (!$(this).hasClass("typograph-done")) && (!$(this).hasClass("typograph-dont")) ) { //LE TEXTE DE L'ÉLÉMENT var txt = $(this).html() /* RÈGLES TYPOGRAPHIQUES GÉNÉRALES /////////////////////////////////////////////////////////////////////////////*/ //PRÉSENCE DE DOUBLE-ESPACES (2 ou +) .replace(/((\s){2,})/gi, ' ') //PRÉSENCE D'UNE (OU PLUSIEURS) ESPACES AVANT LES (…), (.), (?), (!), (:), (;) .replace(/(\s+)(…|\.|\?|\!|\:|\;)/gi, '$2') //PARENTHÈSES, ACCOLADES OU CROCHETS OUVRANTS NON-PRÉCÉDÉS D'UNE ESPACE .replace(/([^\s])(\(|\{|\[)/gi, '$1 $2') //PARENTHÈSES, ACCOLADES OU CROCHETS OUVRANTS SUIVIS D'UNE ESPACE .replace(/(\(|\{|\[)\s+/gi, '$1') //PARENTHÈSES, ACCOLADES OU CROCHETS FERMANTS NON-SUIVIE D'UNE ESPACE .replace(/(\)|\}|\])([^\s])/gi, '$1 $2') //PARENTHÈSES, ACCOLADES OU CROCHETS FERMANTS PRÉCÉDÉS D'UNE ESPACE .replace(/(\s+)(\)|\}|\])/gi, '$2$1') //PRÉSENCE D'UNE (OU PLUSIEURS) ESPACES AVANT L'APOSTROPHE .replace(/(\s+)'/gi, '’') //PRÉSENCE D'UNE (OU PLUSIEURS) ESPACES AVANT LA VIRGULE .replace(/(\s+),/gi, ',') //ESPACE MANQUANTE APRÈS (,) OU (;), MAIS PAS SUIVI DE CHIFFRE (EX.: 0,55) .replace(/(\,|\;)([^\s])([^\d])/gi, '$1 $2') //PRÉSENCE D'UN GUILLEMET SIMPLE (MINUTE) À LA PLACE APOSTROPHE .replace(/'/gi, '’') //PRÉSENCE D'UNE ESPACE AVANT, OU APRÈS, OU AVANT ET APRÈS UN TRAIT D'UNION .replace(/[\s]-[\s]|-[\s]|[\s]-/gi, '-') //PRÉSENCE DE TROIS POINTS (...) À LA PLACE DES POINTS DE SUSPENSSION (…) .replace(/\.\.\./gi, '…') //MANQUE D'UNE ESPACES APRÈS LE POINT /!\ RAJOUTER UNE EXEPTION POUR LES CHIFFRES (EX.: 0.55) .replace(/\.(.)/gi, '. $1'); //MANQUE UNE ESPACE AVANT LE (;) SAUF POUR LES HTMLENTITIES (3) //var txt = txt.replace(/(&quot|&amp|&lt|&gt|&apos|&#039)?;/gi, function(semiMach, back) { //À VOIR SI ON LAISSE LE "\W+" var txt = txt.replace(/(&\w+)?;/gi, function(semiMach, back) { return (back ? semiMach : ' ;'); }); /* RÈGLES SPÉCIFIQUES AU FRANÇAIS ///////////////////////////////////////////////////////////////////////////////*/ if(parametres.lang=="fr") { txt = txt //BONS ESPACEMENTS POUR LE (;) .replace(/\s\;\s/gi, espaceFineInsecable+"; ") //GUILLEMETS DOUBLES OUVRANTS ET FERMANTS (1), SANS BRISER LES BALISES .replace(/([\"])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "«$2»") //GUILLEMETS DOUBLES OUVRANTS SUIVIS D'UNE ESPACE OU PLUS .replace(/\«\s|\«/gi, "«"+espaceFineInsecable) //GUILLEMETS DOUBLES FERMANTS PRÉCÉDÉS D'UNE ESPACE OU PLUS .replace(/\s\»|\»/gi, espaceFineInsecable+"»") //TIRETS SEMI-LONGS OUVRANTS ET FERMANTS, SANS BRISER LES BALISES .replace(/([\—])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "—"+espaceFineInsecable+"$2"+espaceFineInsecable+"—") //ESPACE MANQUANTE AVANT LES GUILLEMETS OUVRANTS .replace(/([^\s])(\«)/gi, '$1 $2') //ESPACE MANQUANTE APRÈS LES GUILLEMETS FERMANTS (SAUF POUR LE ".", LA "," ET "…") .replace(/(\»)([^\s|\.|\,|…])/gi, '$1 $2') //SUPPRESSION DES ESPACES DEVANT (¤, $, ¢, £, ¥, ₣, ₤, ₧, €, %, ‰) .replace(/\s(\¤|\$|\¢|\£|\¥|\₣|\₤|\₧|\€|\%|\‰)/gi, '$1') //AJOUT D'UNE ESPACE FINE INSÉCABLE DEVANT (¤, $, ¢, £, ¥, ₣, ₤, ₧, €, %, ‰) .replace(/(\w+)(\¤|\$|\¢|\£|\¥|\₣|\₤|\₧|\€|\%|\‰)/gi, '$1'+espaceFineInsecable+'$2') //MANQUE D'UNE ESPACE FINE AVANT LE POINT D'INTERROGATION, D'EXCLAMATION OU LES DEUX POINTS, MAIS PAS À L'INTÉRIEUR DE BALISES .replace(/(\?|\!|\:)(?![^<>]*>)/gi, espaceFineInsecable+"$1"); } /**/ /* RÈGLES SPÉCIFIQUES À L'ANGLAIS ///////////////////////////////////////////////////////////////////////////////*/ if(parametres.lang=="en") { txt = txt //BONS ESPACEMENTS POUR LE (;) .replace(/\s\;\s/gi, "; ") //GUILLEMETS DOUBLES OUVRANTS ET FERMANTS (1), SANS BRISER LES BALISES .replace(/([\"])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "“$2”") //GUILLEMETS DOUBLES OUVRANTS SUIVIS D'UNE ESPACE OU PLUS .replace(/\“\s|\“/gi, "“") //GUILLEMETS DOUBLES FERMANTS PRÉCÉDÉS D'UNE ESPACE OU PLUS .replace(/\s\”|\”/gi, "”") //TIRETS SEMI-LONGS OUVRANTS ET FERMANTS, SANS BRISER LES BALISES .replace(/([\—])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "—"+espaceFineInsecable+"$2"+espaceFineInsecable+"—") //ESPACE MANQUANTE AVANT LES GUILLEMETS OUVRANTS .replace(/([^\s])(\“)/gi, '$1 $2') //ESPACE MANQUANTE APRÈS LES GUILLEMETS FERMANTS (SAUF POUR LE ".", LA "," ET "…") .replace(/(\”)([^\s|\.|\,|…])/gi, '$1 $2'); } /**/ /* RÈGLES SPÉCIFIQUES À ALLEMAND ///////////////////////////////////////////////////////////////////////////////*/ if(parametres.lang=="de") { txt = txt //BONS ESPACEMENTS POUR LE (;) .replace(/\s\;\s/gi, "; ") //GUILLEMETS DOUBLES OUVRANTS ET FERMANTS (1), SANS BRISER LES BALISES .replace(/([\"])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "„$2“") //GUILLEMETS DOUBLES OUVRANTS SUIVIS D'UNE ESPACE OU PLUS .replace(/\„\s|\„/gi, '„') //GUILLEMETS DOUBLES FERMANTS PRÉCÉDÉS D'UNE ESPACE OU PLUS .replace(/\s\“|\“/gi, '“') //TIRETS SEMI-LONGS OUVRANTS ET FERMANTS, SANS BRISER LES BALISES .replace(/([\—])(?![^<>]*>)((?:(?!\1).)*)\1/gi, "—"+espaceFineInsecable+"$2"+espaceFineInsecable+"—") //ESPACE MANQUANTE AVANT LES GUILLEMETS OUVRANTS .replace(/([^\s])(\„)/gi, '$1 $2') //ESPACE MANQUANTE APRÈS LES GUILLEMETS FERMANTS (SAUF POUR LE ".", LA "," ET "…") .replace(/(\“)([^\s|\.|\,|…])/gi, '$1 $2'); } /**/ //MOT ORPHELIN EN FIN DE PARAGRAPHE // /!\ ATTENTION AUX BALISES QUI PEUVENT CASSER, TESTER LA CHOSE. if(parametres.motOrphelin) { //RAJOUTE UNE ESPACE INSÉCABLE ENTRE LES 2 DERNIERS MOTS DE LA CHAINE (WIDONT PLUGIN (2)) var orphans = new RegExp( '[\\n\\r\\s]+' // whitespace/newlines + '(' // capture... + '[^\\n\\r\\s(?:&#160;)]+' // non-whitespace/newlines + '[\\n\\r\\s]*' // trailing whitespace + ')$' // ...to end of the string , 'm' // match across newlines ); txt = txt.replace( orphans, "&#160;$1" ); } // //ON RÉ-INJECTE LE TEXTE CORRIGÉ ET ON AJOUTE LA CLASS "TYPOGRAPH-DONE" $(this).html(txt).addClass("typograph-done"); //Si le parametre callback ne vaut pas null, c'est qu'on a précisé une fonction ! if(parametres.callback) { parametres.callback(); } } }); }; })(jQuery); //NOTES //1 — L'ESPACE FINE INSÉCABLE (&#8239;) N'EST PAS FIABLE : http://stackoverflow.com/questions/595365/how-to-render-narrow-non-breaking-spaces-in-html-for-windows //2 — GESTION DES MOTS ORPHELINS : http://davecardwell.co.uk/javascript/jquery/plugins/jquery-widont/ //3 – IL N'Y A PAS DE "NÉGATIVE LOOKBEHIND EN JS : http://stackoverflow.com/questions/6337459/skip-preceding-html-entities-in-javascript-regex
/** * Gets the name of a field having the http://schema.org/name type or fallback to the id. * * @param {object} reference * @return {string} */ export default function(reference) { const field = reference.fields.find( field => 'http://schema.org/name' === field.id, ); return field ? field.name : 'id'; }
/* * HTTP Upload Transfer Queue */ // 2MB default upload chunk size // Can be overridden by user with FS.config.uploadChunkSize or per FS.Collection in collection options var defaultChunkSize = 2 * 1024 * 1024; /** * @private * @param {Object} task * @param {Function} next * @return {undefined} */ var _taskHandler = function (task, next) { FS.debug && console.log("uploading chunk " + task.chunk + ", bytes " + task.start + " to " + Math.min(task.end, task.fileObj.size()) + " of " + task.fileObj.size()); task.fileObj.data.getBinary(task.start, task.end, function gotBinaryCallback(err, data) { if (err) { next(new Meteor.Error(err.error, err.message)); } else { FS.debug && console.log('PUT to URL', task.url, task.urlParams); httpCall("PUT", task.url, { params: FS.Utility.extend({chunk: task.chunk}, task.urlParams), content: data, headers: { 'Content-Type': task.fileObj.type() } }, function (error, result) { task = null; if (error) { next(new Meteor.Error(error.error, error.message)); } else { next(); } }); } }); }; /** * @private * @param {Object} data * @param {Function} addTask * @return {undefined} */ var _errorHandler = function (data, addTask, failures) { // If file upload fails // data.fileObj.emit("error", error); }; /** @method UploadTransferQueue * @namespace UploadTransferQueue * @constructor * @param {Object} [options] */ UploadTransferQueue = function (options) { // Rig options options = options || {}; // Init the power queue var self = new PowerQueue({ name: 'HTTPUploadTransferQueue', // spinalQueue: ReactiveList, maxProcessing: 1, maxFailures: 5, jumpOnFailure: true, autostart: true, isPaused: false, filo: false, debug: FS.debug }); // Keep track of uploaded files via this queue self.files = {}; // cancel maps onto queue reset self.cancel = self.reset; /** * @method UploadTransferQueue.isUploadingFile * @param {FS.File} fileObj File to check if uploading * @returns {Boolean} True if the file is uploading * */ self.isUploadingFile = function (fileObj) { // Check if file is already in queue return !!(fileObj && fileObj._id && fileObj.collectionName && (self.files[fileObj.collectionName] || {})[fileObj._id]); }; /** @method UploadTransferQueue.resumeUploadingFile * @param {FS.File} File to resume uploading */ self.resumeUploadingFile = function (fileObj) { // Make sure we are handed a FS.File if (!(fileObj instanceof FS.File)) { throw new Error('Transfer queue expects a FS.File'); } if (fileObj.isMounted()) { // This might still be true, preventing upload, if // there was a server restart without client restart. self.files[fileObj.collectionName] = self.files[fileObj.collectionName] || {}; self.files[fileObj.collectionName][fileObj._id] = false; // Kick off normal upload self.uploadFile(fileObj); } }; /** @method UploadTransferQueue.uploadFile * @param {FS.File} File to upload */ self.uploadFile = function (fileObj) { FS.debug && console.log("HTTP uploadFile"); // Make sure we are handed a FS.File if (!(fileObj instanceof FS.File)) { throw new Error('Transfer queue expects a FS.File'); } // Make sure that we have size as number if (typeof fileObj.size() !== 'number') { throw new Error('TransferQueue upload failed: fileObj size not set'); } // We don't add the file if it's already in transfer or if already uploaded if (self.isUploadingFile(fileObj) || fileObj.isUploaded()) { return; } // Make sure the file object is mounted on a collection if (fileObj.isMounted()) { var collectionName = fileObj.collectionName; var id = fileObj._id; // Set the chunkSize to match the collection options, or global config, or default fileObj.chunkSize = fileObj.collection.options.chunkSize || FS.config.uploadChunkSize || defaultChunkSize; // Set counter for uploaded chunks fileObj.chunkCount = 0; // Calc the number of chunks fileObj.chunkSum = Math.ceil(fileObj.size() / fileObj.chunkSize); if (fileObj.chunkSum === 0) return; // Update the filerecord fileObj.update({ $set: { chunkSize: fileObj.chunkSize, chunkCount: fileObj.chunkCount, chunkSum: fileObj.chunkSum } }); // Create a sub queue var chunkQueue = new PowerQueue({ onEnded: function oneChunkQueueEnded() { // Remove from list of files being uploaded self.files[collectionName][id] = false; // XXX It might be possible for this to be called even though there were errors uploading? fileObj.emit("uploaded"); }, spinalQueue: ReactiveList, maxProcessing: 1, maxFailures: 5, jumpOnFailure: true, autostart: false, isPaused: false, filo: false }); // Rig the custom task handler chunkQueue.taskHandler = _taskHandler; // Rig the error handler chunkQueue.errorHandler = _errorHandler; // Set flag that this file is being transfered self.files[collectionName] = self.files[collectionName] || {}; self.files[collectionName][id] = true; // Construct URL var url = FS.HTTP.uploadUrl + '/' + collectionName; if (id) { url += '/' + id; } var authToken = ''; if (typeof Accounts !== "undefined") { var authObject = { authToken: Accounts._storedLoginToken() || '', }; // Set the authToken var authString = JSON.stringify(authObject); authToken = FS.Utility.btoa(authString); } // Construct query string var urlParams = { filename: fileObj.name() }; if (authToken !== '') { urlParams.token = authToken; } // Add chunk upload tasks for (var chunk = 0, start; chunk < fileObj.chunkSum; chunk++) { start = chunk * fileObj.chunkSize; // Create and add the task // XXX should we somehow make sure we haven't uploaded this chunk already, in // case we are resuming? chunkQueue.add({ chunk: chunk, name: fileObj.name(), url: url, urlParams: urlParams, fileObj: fileObj, start: start, end: (chunk + 1) * fileObj.chunkSize }); } // Add the queue to the main upload queue self.add(chunkQueue); } }; return self; }; /** * @namespace FS * @type UploadTransferQueue * * There is a single uploads transfer queue per client (not per CFS) */ FS.HTTP.uploadQueue = new UploadTransferQueue(); /* * FS.File extensions */ /** * @method FS.File.prototype.resume * @public * @param {File|Blob|Buffer} ref * * > This function is not yet implemented for server */ FS.File.prototype.resume = function (ref) { var self = this; FS.uploadQueue.resumeUploadingFile(self); };
const consoleApp = require('@fidojs/fidojs-kennel-console'); const { GlitchPlease } = require('glitch-please'); const path = require('path'); const fs = require('fs'); module.exports = function(appRoot, getDistPath, buildCommand) { const please = new GlitchPlease({ appRoot: appRoot, distPath (appRoot, appPackageJSON) { return getDistPath(appRoot, appPackageJSON); }, distRoute (appPackageJSON) { return '/'; } }); // cmd: path.join(__dirname, 'node_modules', 'npm', 'bin', 'npm-cli.js'), please.appWatchRun(function(appPackageJSON) { return [appPackageJSON['bit-docs']['glob']['pattern']]; }, { cmd: 'npm', args: ['run', buildCommand] }); please.server.use('/console-app', consoleApp); return please; }
class MCProcessesTableComponentController { /*@ngInject*/ constructor(mcshow) { this.mcshow = mcshow; this.state = { sortOrder: 'name', processes: [], }; } $onChanges(changes) { if (changes.processes) { this.state.processes = angular.copy(changes.processes.currentValue); this.state.processes.forEach(p => { p.files_count = p.files.length; p.input_samples_count = p.samples.filter(s => s.direction === 'in').length; p.output_samples_count = p.samples.filter(s => s.direction === 'out').length; }); } } showJson() { this.mcshow.showJson(this.state.processes); } } angular.module('materialscommons').component('mcProcessesTable', { controller: MCProcessesTableComponentController, template: require('./processes-table.html'), bindings: { processes: '<' } });
/** * Created by duo on 2016/9/1. */ CMD.register("configuration.ConfigManager", function (require) { var MetaDataManager = require("metadata.MetaDataManager"); var Configuration = require("configuration.Configuration"); var configurationProperties = require("Properties").configuration; var Url = require("util.Url"); var JsonParser = require("util.JsonParser"); function ConfigManager() {} ConfigManager.fetch = function (nativeBridge, request, clientInfo, deviceInfo) { return MetaDataManager.fetchAdapterMetaData(nativeBridge).then(function (metaData) { var configUrl = ConfigManager.createConfigUrl(clientInfo, deviceInfo, metaData); nativeBridge.Sdk.logInfo("Requesting configuration from " + configUrl); return request.get(configUrl, [], { retries: 5, retryDelay: 5e3, followRedirects: false, retryWithConnectionEvents: true }).then(function (res) { try { var configData = JsonParser.parse(res.response), configuration = new Configuration(configData); nativeBridge.Sdk.logInfo("Received configuration with " + configuration.getPlacementCount() + " placements"); return configuration; } catch (e) { nativeBridge.Sdk.logError("Config request failed " + e); throw new Error(e); } }); }); }; ConfigManager.setTestBaseUrl = function (baseUrl) { ConfigManager.ConfigBaseUrl = baseUrl + "/games"; }; ConfigManager.createConfigUrl = function (clientInfo, deviceInfo, metaData) { var configUrl = [ConfigManager.ConfigBaseUrl, clientInfo.getGameId(), "configuration"].join("/"); configUrl = Url.addParameters(configUrl, { bundleId: clientInfo.getApplicationName(), encrypted: !clientInfo.isDebuggable(), rooted: deviceInfo.isRooted() }); if(metaData){ configUrl = Url.addParameters(configUrl, metaData.getDTO()); } return configUrl; }; ConfigManager.ConfigBaseUrl = configurationProperties.CONFIG_BASE_URL; return ConfigManager; });
import ExampleManager from './ExampleManager'; import ExampleProductManager from './ExampleProductManager'; // const ManagerRoot = { ExampleManager, ExampleProductManager, }; ManagerRoot.version = '0.0.1'; module.exports = ManagerRoot;
'use strict'; /** * Created by AsTex on 25.06.2016. */ var passport = require('passport'); var BasicStrategy = require('passport-http').BasicStrategy; var LocalStrategy = require('passport-local').Strategy; var HeaderStrategy = require('passportjs-header').Strategy; var headerStrategy = require('passport-http-header-strategy').Strategy; var CustomStrategy = require('passport-custom').Strategy; var log = require('../log')(module); var libs = process.cwd() + '/libs/'; var config = require(libs + 'config'); var Doctor = require(libs + 'model/doctor'); var Patient = require(libs + 'model/patient').Patient; /*passport.use('header-own', new CustomStrategy( function(req, done) { Patient.findOne({apiKey:api}, function(err,patient){ if (err) { return done(err); } if(!patient) return done(null, false, { error: 'Invalid token.' }); if(!patient.checkApiKey(api)) { return done(null, false, {error: 'Incorrect token.'}); } req.authStrategy = 'Header'; return done(null,patient); }); } )); */ passport.serializeUser(function (user, done) { done(null, user); }); passport.deserializeUser(function (user, done) { done(null, user); }); passport.use(new headerStrategy({ header: 'X-API-KEY', passReqToCallback: true }, function (req, token, done) { Patient.findOne({ apiKey: token }, function (err, patient) { if (err) { return done(err); } if (!patient) return done(null, false, { error: 'Invalid token.' }); if (!patient.checkApiKey(token)) { return done(null, false, { error: 'Incorrect token.' }); } req.authStrategy = 'Header'; return done(null, patient); }); })); /* passport.use('test', new CustomStrategy({passReqToCallback: true}, function (req, done) { this._verify = done; log.debug('test'); console.log(req.body.email); console.log(req.body.password); if (!req.cookies.session) { if (!req.body.email || !req.body.password) { return done(null, false, {error: 'Incorrect credentials.'}); } else { Doctor.findOne({email: req.body.email}, function (err, doctor) { log.debug('test'); if (err) { return done(err, false, {error: 'Incorrect username.'}); } if (!doctor) { return done(null, false, {error: 'Incorrect username.'}); } if (!doctor.checkPassword(req.body.password)) { return done(null, false, {error: 'Incorrect password.'}); } req.authStrategy = 'Local'; res.cookie('session', doctor.sessionId); return done(null, doctor); }); } } else { Doctor.findOne({sessionId: req.cookies.session}, function (err, doctor) { if (err) { return done(err, false, {error: 'Incorrect username.'}); } if (!doctor) { return done(null, false, {error: 'Incorrect username.'}); } return done(null, doctor); }); } log.debug('test'); })); */ passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function (req, username, password, done) { console.log(req.body.email); console.log(req.body.password); if (!req.cookies.session) { if (!req.body.email || !req.body.password) { return done(null, false, { error: 'Incorrect credentials.' }); } else { Doctor.findOne({ email: username }, function (err, doctor) { log.debug('test'); if (err) { return done(err, false, { error: 'Incorrect username.' }); } if (!doctor) { return done(null, false, { error: 'Incorrect username.' }); } if (!doctor.checkPassword(req.body.password)) { return done(null, false, { error: 'Incorrect password.' }); } req.authStrategy = 'Local'; return done(null, doctor); }); } } else { Doctor.findOne({ sessionId: req.cookies.session }, function (err, doctor) { if (err) { return done(err, false, { error: 'Incorrect username.' }); } if (!doctor) { return done(null, false, { error: 'Incorrect username.' }); } return done(null, doctor); }); } log.debug('test'); })); passport.use(new BasicStrategy(function (email, password, done) { Patient.findOne({ email: email }, function (err, patient) { if (err) { log.debug('Bad request'); return done(err); } if (!patient) { log.debug('Bad request2'); return done(null, false, { error: "No authentication data provided" }); } if (!patient.checkPassword(password)) { return done(null, false); } return done(null, patient); }); })); //# sourceMappingURL=auth-compiled.js.map //# sourceMappingURL=auth-compiled-compiled.js.map //# sourceMappingURL=auth-compiled-compiled-compiled.js.map
const express = require('express'); const router = express.Router(); const _ = require('lodash'); const utils = require('../utilities'); const Project = require('../models/project.model'); const baseUrl = "/users/:userId/projects"; function projectExists(req,res,next){ console.log("I WILL CHECK IF THE GIVEN PROJECT EXISTS"); next(); } router.use(baseUrl + "/:projectId", projectExists); router.get(baseUrl, (req,res) => { // TODO only get projects for the user. const projectQuery =Project.find({}); projectQuery.exec() .then(projects => { res.status(200).json(projects); }) .catch(err => { res.status(400).json({message: "error"}); }) }); router.post(baseUrl, (req,res) => { let projectRequest = { name: req.body.name, user: req.params.userId }; const project = Project(projectRequest); project.save(err => { // TODO handle error res.status(200).json(project); }); }); router.get(baseUrl + "/:projectId", (req,res) => { const projectQuery = Project.findById(req.params.projectId); projectQuery.exec() .then(project => { res.status(200).json(project); }) .catch(err => { res.status(400).json({message: "fatal"}); }) }); router.put(baseUrl + "/:projectId", (req,res) => { res.status(200).json({message: "PUT PROJECT STUB"}); }); router.delete(baseUrl + "/:projectId", (req,res) => { res.status(200).json({message: "DELETE PROJECT STUB"}); }); module.exports = router;
module.exports = { files : [ '/home/billerot/conf/index.conf', '/etc/hosts', '/etc/crontab' ] }
// console.log('in content_script.js: start running', window.location.href) // ////////////////////////////////////////////////////////////////////////////////// // // Comments // ////////////////////////////////////////////////////////////////////////////////// // // console.log('in content_script.js: three.js is '+(window.THREE ? '' : ' not')+ 'present.') // function onLoad(){ // console.log('in content_script.js: three.js is '+(window.THREE ? '' : 'not ')+ 'present.') // } // // // signal devtool panel that the injection is completed // if( document.readyState !== 'complete' ){ // window.addEventListener( 'load', onLoad) // }else{ // // if window already got loaded, call onLoad() manually // onLoad() // } var x3js_messagesForwardedCounter = 0 ////////////////////////////////////////////////////////////////////////////////// // to receive message from injected_script ////////////////////////////////////////////////////////////////////////////////// window.addEventListener('message', function(event) { var message = event.data; // console.log('in content_script.js: receiving window.message', message) // Only accept messages from the same frame if (event.source !== window) return // console.log('receiving window.message') // check the message if( typeof message !== 'object' ) return if( message === null ) return // check the message.source if( message.source !== 'threejs-extension-inspected-window' ) return // remove the magic 'message.source' delete message.source x3js_messagesForwardedCounter++ // console.log('x3js_messagesForwardedCounter', x3js_messagesForwardedCounter) // console.log('in content_script.js: receiving window.message for background page of three.js extension', message) // if this point is reached, send the message to the background page chrome.runtime.sendMessage(message); }); ////////////////////////////////////////////////////////////////////////////////// // Comments ////////////////////////////////////////////////////////////////////////////////// // console.log('in content_script.js: end running')
// Regular expression that matches all symbols with the `Deprecated` property as per Unicode v8.0.0: /[\u0149\u0673\u0F77\u0F79\u17A3\u17A4\u206A-\u206F\u2329\u232A]|\uDB40[\uDC01\uDC7F]/;
var Parser = (function(){ function parse(string) { return string; } this.parse = parse; return this; })();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Button } from 'antd'; import QueueAnim from 'rc-queue-anim'; import { setCurNav, showBG } from '../../actions/action_ui'; import './side_nav.css'; class SideNav extends Component { constructor(props) { super(props); this.handleClickOnNavButton = this.handleClickOnNavButton.bind(this); } handleClickOnNavButton() { this.props.showBG(!this.props.bgShown); } handleClickOnNavItem(navItemId) { this.props.setCurNav(navItemId); this.props.showBG(false); } render() { const { bgShown, curNavId, navItems } = this.props; return ( <div className="sidenav"> <Button shape="circle" icon="bars" size="large" type="primary" className="navbutton" style={bgShown ? { color: '#444', boxShadow: '2px 2px 6px #d3d3d3' } : { color: '#fff' }} onClick={this.handleClickOnNavButton} /> <div className={bgShown ? 'bgcover shown' : 'bgcover'}> {bgShown ? <QueueAnim component="ul" className="navlist" type="right" interval={50} duration={90} ease="easeInSine" > {navItems.map(navItem => (<li className={navItem.id === curNavId ? 'curNav' : ''} key={navItem.name}> <Link to={navItem.link} onClick={() => this.handleClickOnNavItem(navItem.id)}> {navItem.name} </Link> </li>), )} </QueueAnim> : null} </div> </div> ); } } function mapStateToProps(state) { return { bgShown: state.ui.bgShown, curNavId: state.ui.curNavId, navItems: state.ui.navItems, }; } SideNav.propTypes = { showBG: PropTypes.func.isRequired, setCurNav: PropTypes.func.isRequired, curNavId: PropTypes.number.isRequired, bgShown: PropTypes.bool.isRequired, navItems: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, id: PropTypes.number.isRequired, link: PropTypes.string.isRequired, }), ).isRequired, }; export default connect(mapStateToProps, { setCurNav, showBG })(SideNav);
'use babel'; // Based on StackJS https://launchpad.net/stackjs import StackOverflowRequest from './stack-overflow-request'; import StackOverflowAPI from './stack-overflow-api'; /** * @class Provides means for retrieving paged data from the API. * @description This class actually performs the requests for data in the API. * * @param {StackOverflowURL} url the base StackOverflowURL to use for requests */ export default class StackOverflowResponse { constructor (url) { // Store a copy of the base StackOverflowURL let _url = url; // Data required for pagination let _current_page = 1; let _pagesize; /** * Begins fetching the data with the provided callback. * * <p>Note that the callback may return false at any time to stop any * further pages from being requested.</p> * * @param {function} callback the callback for successful requests * @param {boolean} [fetch_multiple] whether or not to fetch multiple pages */ this.Fetch = function(callback, fetch_multiple) { // Store a reference to this instance let self = this; // Fetch the JSON data StackOverflowAPI.FetchJSON(_url, function(data) { // Let the callback know if more data is being retrieved let more_data = false; if (typeof fetch_multiple != 'undefined' && fetch_multiple) { if (typeof data['has_more'] != 'undefined') data['has_more'] && (more_data = true); else data.length && (more_data = true); } // Invoke the supplied callback let fetch_next = callback(data['items'], more_data); // If the function returned false, then stop if (more_data && !(typeof fetch_next != 'undefined' && !fetch_next)) self.Fetch(callback, true); }); // Increment the page count _url.SetQueryStringParameter('page', ++_current_page); }; /** * Jumps to the specified page for the next request. * * @param {integer} page the page to retrieve * @returns {StackOverflowResponse} the current instance */ this.Page = function(page) { _current_page = page; }; } }
// Generated by CoffeeScript 1.6.3 var AutomationServer, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; AutomationServer = (function() { function AutomationServer(serverURL) { this.serverURL = serverURL; this.executeCommand = __bind(this.executeCommand, this); this.ACTIONS_URI = this.serverURL + "/actions"; this.EXEC_URI = this.serverURL + "/exec"; } AutomationServer.prototype.setReadyCallback = function(readyCallback) { this.readyCallback = readyCallback; }; AutomationServer.prototype.getActionGroups = function() { var _this = this; return $.ajax(this.ACTIONS_URI, { type: "GET", dataType: "json", success: function(data, textStatus, jqXHR) { return _this.readyCallback(data); }, error: function(jqXHR, textStatus, errorThrown) { return console.log("Get Actions failed: " + textStatus + " " + errorThrown); } }); }; AutomationServer.prototype.executeCommand = function(cmdParams) { var _this = this; return $.ajax(this.EXEC_URI + "/" + cmdParams, { type: "GET", dataType: "text", success: function(data, textStatus, jqXHR) {}, error: function(jqXHR, textStatus, errorThrown) { return console.log("Exec command failed: " + textStatus + " " + errorThrown); } }); }; return AutomationServer; })();
define(function(){ /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } /* * Perform a simple self-test to see if the VM is working */ function md5_vm_test() { return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; } /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the HMAC-MD5, of a key and some data */ function core_hmac_md5(key, data) { var bkey = str2binl(key); if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md5(opad.concat(hash), 512 + 128); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ function str2binl(str) { var bin = Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); return bin; } /* * Convert an array of little-endian words to a string */ function binl2str(bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); return str; } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; } /* * Convert an array of little-endian words to a base-64 string */ function binl2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for(var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } return str; } return { hex: hex_md5, b64: b64_md5, str: str_md5, hex_hmac: hex_hmac_md5, b64_hmac: b64_hmac_md5, str_hmac: str_hmac_md5 }; });
<<<<<<< HEAD <<<<<<< HEAD /* * Tests to verify we're reading in signed integers correctly */ var mod_ctype = require('../../../ctio.js'); var ASSERT = require('assert'); /* * Test 8 bit signed integers */ function test8() { var data = new Buffer(4); data[0] = 0x23; ASSERT.equal(0x23, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(0x23, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0xff; ASSERT.equal(-1, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-1, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0x87; data[1] = 0xab; data[2] = 0x7c; data[3] = 0xef; ASSERT.equal(-121, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'big', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'big', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'big', 3)); ASSERT.equal(-121, mod_ctype.rsint8(data, 'little', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'little', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'little', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'little', 3)); } function test16() { var buffer = new Buffer(6); buffer[0] = 0x16; buffer[1] = 0x79; ASSERT.equal(0x1679, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x7916, mod_ctype.rsint16(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0x80; ASSERT.equal(-128, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(-32513, mod_ctype.rsint16(buffer, 'little', 0)); /* test offset with weenix */ buffer[0] = 0x77; buffer[1] = 0x65; buffer[2] = 0x65; buffer[3] = 0x6e; buffer[4] = 0x69; buffer[5] = 0x78; ASSERT.equal(0x7765, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'big', 1)); ASSERT.equal(0x656e, mod_ctype.rsint16(buffer, 'big', 2)); ASSERT.equal(0x6e69, mod_ctype.rsint16(buffer, 'big', 3)); ASSERT.equal(0x6978, mod_ctype.rsint16(buffer, 'big', 4)); ASSERT.equal(0x6577, mod_ctype.rsint16(buffer, 'little', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'little', 1)); ASSERT.equal(0x6e65, mod_ctype.rsint16(buffer, 'little', 2)); ASSERT.equal(0x696e, mod_ctype.rsint16(buffer, 'little', 3)); ASSERT.equal(0x7869, mod_ctype.rsint16(buffer, 'little', 4)); } function test32() { var buffer = new Buffer(6); buffer[0] = 0x43; buffer[1] = 0x53; buffer[2] = 0x16; buffer[3] = 0x79; ASSERT.equal(0x43531679, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(0x79165343, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0xfe; buffer[2] = 0xef; buffer[3] = 0xfa; ASSERT.equal(-69638, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-84934913, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0x42; buffer[1] = 0xc3; buffer[2] = 0x95; buffer[3] = 0xa9; buffer[4] = 0x36; buffer[5] = 0x17; ASSERT.equal(0x42c395a9, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-1013601994, mod_ctype.rsint32(buffer, 'big', 1)); ASSERT.equal(-1784072681, mod_ctype.rsint32(buffer, 'big', 2)); ASSERT.equal(-1449802942, mod_ctype.rsint32(buffer, 'little', 0)); ASSERT.equal(917083587, mod_ctype.rsint32(buffer, 'little', 1)); ASSERT.equal(389458325, mod_ctype.rsint32(buffer, 'little', 2)); } test8(); test16(); test32(); ======= /* * Tests to verify we're reading in signed integers correctly */ var mod_ctype = require('../../../ctio.js'); var ASSERT = require('assert'); /* * Test 8 bit signed integers */ function test8() { var data = new Buffer(4); data[0] = 0x23; ASSERT.equal(0x23, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(0x23, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0xff; ASSERT.equal(-1, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-1, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0x87; data[1] = 0xab; data[2] = 0x7c; data[3] = 0xef; ASSERT.equal(-121, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'big', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'big', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'big', 3)); ASSERT.equal(-121, mod_ctype.rsint8(data, 'little', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'little', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'little', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'little', 3)); } function test16() { var buffer = new Buffer(6); buffer[0] = 0x16; buffer[1] = 0x79; ASSERT.equal(0x1679, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x7916, mod_ctype.rsint16(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0x80; ASSERT.equal(-128, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(-32513, mod_ctype.rsint16(buffer, 'little', 0)); /* test offset with weenix */ buffer[0] = 0x77; buffer[1] = 0x65; buffer[2] = 0x65; buffer[3] = 0x6e; buffer[4] = 0x69; buffer[5] = 0x78; ASSERT.equal(0x7765, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'big', 1)); ASSERT.equal(0x656e, mod_ctype.rsint16(buffer, 'big', 2)); ASSERT.equal(0x6e69, mod_ctype.rsint16(buffer, 'big', 3)); ASSERT.equal(0x6978, mod_ctype.rsint16(buffer, 'big', 4)); ASSERT.equal(0x6577, mod_ctype.rsint16(buffer, 'little', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'little', 1)); ASSERT.equal(0x6e65, mod_ctype.rsint16(buffer, 'little', 2)); ASSERT.equal(0x696e, mod_ctype.rsint16(buffer, 'little', 3)); ASSERT.equal(0x7869, mod_ctype.rsint16(buffer, 'little', 4)); } function test32() { var buffer = new Buffer(6); buffer[0] = 0x43; buffer[1] = 0x53; buffer[2] = 0x16; buffer[3] = 0x79; ASSERT.equal(0x43531679, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(0x79165343, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0xfe; buffer[2] = 0xef; buffer[3] = 0xfa; ASSERT.equal(-69638, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-84934913, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0x42; buffer[1] = 0xc3; buffer[2] = 0x95; buffer[3] = 0xa9; buffer[4] = 0x36; buffer[5] = 0x17; ASSERT.equal(0x42c395a9, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-1013601994, mod_ctype.rsint32(buffer, 'big', 1)); ASSERT.equal(-1784072681, mod_ctype.rsint32(buffer, 'big', 2)); ASSERT.equal(-1449802942, mod_ctype.rsint32(buffer, 'little', 0)); ASSERT.equal(917083587, mod_ctype.rsint32(buffer, 'little', 1)); ASSERT.equal(389458325, mod_ctype.rsint32(buffer, 'little', 2)); } test8(); test16(); test32(); >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= /* * Tests to verify we're reading in signed integers correctly */ var mod_ctype = require('../../../ctio.js'); var ASSERT = require('assert'); /* * Test 8 bit signed integers */ function test8() { var data = new Buffer(4); data[0] = 0x23; ASSERT.equal(0x23, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(0x23, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0xff; ASSERT.equal(-1, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-1, mod_ctype.rsint8(data, 'little', 0)); data[0] = 0x87; data[1] = 0xab; data[2] = 0x7c; data[3] = 0xef; ASSERT.equal(-121, mod_ctype.rsint8(data, 'big', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'big', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'big', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'big', 3)); ASSERT.equal(-121, mod_ctype.rsint8(data, 'little', 0)); ASSERT.equal(-85, mod_ctype.rsint8(data, 'little', 1)); ASSERT.equal(124, mod_ctype.rsint8(data, 'little', 2)); ASSERT.equal(-17, mod_ctype.rsint8(data, 'little', 3)); } function test16() { var buffer = new Buffer(6); buffer[0] = 0x16; buffer[1] = 0x79; ASSERT.equal(0x1679, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x7916, mod_ctype.rsint16(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0x80; ASSERT.equal(-128, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(-32513, mod_ctype.rsint16(buffer, 'little', 0)); /* test offset with weenix */ buffer[0] = 0x77; buffer[1] = 0x65; buffer[2] = 0x65; buffer[3] = 0x6e; buffer[4] = 0x69; buffer[5] = 0x78; ASSERT.equal(0x7765, mod_ctype.rsint16(buffer, 'big', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'big', 1)); ASSERT.equal(0x656e, mod_ctype.rsint16(buffer, 'big', 2)); ASSERT.equal(0x6e69, mod_ctype.rsint16(buffer, 'big', 3)); ASSERT.equal(0x6978, mod_ctype.rsint16(buffer, 'big', 4)); ASSERT.equal(0x6577, mod_ctype.rsint16(buffer, 'little', 0)); ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'little', 1)); ASSERT.equal(0x6e65, mod_ctype.rsint16(buffer, 'little', 2)); ASSERT.equal(0x696e, mod_ctype.rsint16(buffer, 'little', 3)); ASSERT.equal(0x7869, mod_ctype.rsint16(buffer, 'little', 4)); } function test32() { var buffer = new Buffer(6); buffer[0] = 0x43; buffer[1] = 0x53; buffer[2] = 0x16; buffer[3] = 0x79; ASSERT.equal(0x43531679, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(0x79165343, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0xff; buffer[1] = 0xfe; buffer[2] = 0xef; buffer[3] = 0xfa; ASSERT.equal(-69638, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-84934913, mod_ctype.rsint32(buffer, 'little', 0)); buffer[0] = 0x42; buffer[1] = 0xc3; buffer[2] = 0x95; buffer[3] = 0xa9; buffer[4] = 0x36; buffer[5] = 0x17; ASSERT.equal(0x42c395a9, mod_ctype.rsint32(buffer, 'big', 0)); ASSERT.equal(-1013601994, mod_ctype.rsint32(buffer, 'big', 1)); ASSERT.equal(-1784072681, mod_ctype.rsint32(buffer, 'big', 2)); ASSERT.equal(-1449802942, mod_ctype.rsint32(buffer, 'little', 0)); ASSERT.equal(917083587, mod_ctype.rsint32(buffer, 'little', 1)); ASSERT.equal(389458325, mod_ctype.rsint32(buffer, 'little', 2)); } test8(); test16(); test32(); >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
const longestWord = str => { var strSplit = str.split(' '); const longestWord = strSplit.reduce((a, b) => { if (a.length > b.length) { return a; } else { return b; } }); return longestWord; }; console.log(longestWord('goes Argument bjkdqhdiqwhdihqwd here'));
/*global describe, it, expect, before */ /*jshint expr:true */ var chai = require('chai'), Strategy = require('..').Strategy; describe('Strategy', function() { describe('failing authentication', function() { var strategy = new Strategy(function(username, password, done) { return done(null, false); }); var info; before(function(done) { chai.passport.use(strategy) .fail(function(i) { info = i; done(); }) .req(function(req) { req.headers['content-type'] = 'application/json'; req.body = {}; req.body.username = 'johndoe'; req.body.password = 'secret'; }) .authenticate(); }); it('should fail', function() { expect(info).to.be.undefined; }); }); describe('failing authentication with info', function() { var strategy = new Strategy(function(username, password, done) { return done(null, false, { message: 'authentication failed' }); }); var info; before(function(done) { chai.passport.use(strategy) .fail(function(i) { info = i; done(); }) .req(function(req) { req.headers['content-type'] = 'application/json'; req.body = {}; req.body.username = 'johndoe'; req.body.password = 'secret'; }) .authenticate(); }); it('should fail', function() { expect(info).to.be.an('object'); expect(info.message).to.equal('authentication failed'); }); }); });
'use strict'; var url = require('url'); var mitmProxy = require('node-mitmproxy'); var httpUtil = require('../util/httpUtil'); var zlib = require('zlib'); var through = require('through2'); var config = require('../config/config'); var htmlUtil = require('../util/htmlUtil'); var path = require('path'); var fs = require('fs'); var colors = require('colors'); var charset = require('charset'); var iconv = require('iconv-lite'); var jschardet = require('jschardet'); var domain = require('domain'); var childProcess = require('child_process'); var d = domain.create(); d.on('error', function (err) { console.log(err.message); }); module.exports = { createProxy: function createProxy(_ref) { var injectScriptTag = _ref.injectScriptTag, _ref$port = _ref.port, port = _ref$port === undefined ? 9888 : _ref$port, weinrePort = _ref.weinrePort, _ref$autoDetectBrowse = _ref.autoDetectBrowser, autoDetectBrowser = _ref$autoDetectBrowse === undefined ? true : _ref$autoDetectBrowse, _externalProxy = _ref.externalProxy, successCB = _ref.successCB, cache = _ref.cache; var createMitmProxy = function createMitmProxy() { mitmProxy.createProxy({ externalProxy: function externalProxy(req, ssl) { // ignore weixin mmtls var headers = req.headers; if (headers['upgrade'] && headers['upgrade'] === 'mmtls') { return ''; } else { return _externalProxy; } }, port: port, getCertSocketTimeout: 3 * 1000, sslConnectInterceptor: function sslConnectInterceptor(req, cltSocket, head) { var srvUrl = url.parse('https://' + req.url); // 只拦截浏览器的https请求 if (!autoDetectBrowser || req.headers && req.headers['user-agent'] && (/Mozilla/.test(req.headers['user-agent']) || /com.apple.WebKit.Networking/i.test(req.headers['user-agent']))) { return true; } else { return false; } }, requestInterceptor: function requestInterceptor(rOptions, req, res, ssl, next) { var rPath; if (rOptions.path) { rPath = url.parse(rOptions.path).path; } else { rOptions.path = '/'; } if (rOptions.headers.host === config.SPY_DEBUGGER_DOMAIN && rPath === '/cert' || rOptions.headers.host === config.SPY_DEBUGGER_SHORT_DOMAIN) { var userHome = process.env.HOME || process.env.USERPROFILE; var certPath = path.resolve(userHome, './node-mitmproxy/node-mitmproxy.ca.crt'); try { var fileString = fs.readFileSync(certPath); res.setHeader('Content-Type', 'application/x-x509-ca-cert'); res.setHeader("Content-Disposition", "attachment;filename=node-mitmproxy.ca.crt"); res.end(fileString.toString()); } catch (e) { console.log(e); res.end('please create certificate first!!'); } next(); return; } if (rOptions.headers.host === config.SPY_WEINRE_DOMAIN) { rOptions.protocol = 'http:'; rOptions.hostname = '127.0.0.1'; rOptions.port = weinrePort; // trick for non-transparent proxy rOptions.path = rPath; rOptions.agent = false; } // delete Accept-Encoding delete rOptions.headers['accept-encoding']; // no cache if (!cache) { delete rOptions.headers['if-modified-since']; delete rOptions.headers['last-modified']; delete rOptions.headers['if-none-match']; } next(); }, responseInterceptor: function responseInterceptor(req, res, proxyReq, proxyRes, ssl, next) { var isHtml = httpUtil.isHtml(proxyRes); var contentLengthIsZero = function () { return proxyRes.headers['content-length'] == 0; }(); if (!isHtml || contentLengthIsZero) { next(); } else { Object.keys(proxyRes.headers).forEach(function (key) { if (proxyRes.headers[key] != undefined) { var newkey = key.replace(/^[a-z]|-[a-z]/g, function (match) { return match.toUpperCase(); }); var newkey = key; if (isHtml && (key === 'content-length' || key === 'content-security-policy')) { // do nothing } else { res.setHeader(newkey, proxyRes.headers[key]); } } }); res.writeHead(proxyRes.statusCode); var isGzip = httpUtil.isGzip(proxyRes); var chunks = []; proxyRes.on('data', function (chunk) { chunks.push(chunk); }).on('end', function () { var allChunk = Buffer.concat(chunks); res.end(chunkReplace(allChunk, injectScriptTag, proxyRes)); }); } next(); } }); }; if (!_externalProxy) { d.run(function () { var ports = void 0; var childProxy = childProcess.fork(__dirname + '/externalChildProcess'); childProxy.send({ type: 'start' }); childProxy.on('message', function (externalProxyPorts) { ports = externalProxyPorts; var externalProxyPort = externalProxyPorts.port; var externalProxyWebPort = externalProxyPorts.webPort; _externalProxy = 'http://127.0.0.1:' + externalProxyPort; createMitmProxy(); successCB(externalProxyPorts); }); var restartFun = function restartFun() { console.log(colors.yellow('anyproxy\u5F02\u5E38\u9000\u51FA\uFF0C\u5C1D\u8BD5\u91CD\u542F')); var childProxy = childProcess.fork(__dirname + '/externalChildProcess'); childProxy.send({ type: 'restart', ports: ports }); childProxy.on('exit', function (e) { restartFun(); }); }; childProxy.on('exit', function (e) { restartFun(); }); }); } else { createMitmProxy(); successCB(null); } } }; function chunkReplace(chunk, injectScriptTag, proxyRes) { var _charset; try { _charset = charset(proxyRes, chunk) || jschardet.detect(chunk).encoding.toLowerCase(); } catch (e) { console.error(e); } var chunkString; if (_charset != null && _charset != 'utf-8') { try { chunkString = iconv.decode(chunk, _charset); } catch (e) { console.error(e); chunkString = iconv.decode(chunk, 'utf-8'); } } else { chunkString = chunk.toString(); } var newChunkString = htmlUtil.injectScriptIntoHtml(chunkString, injectScriptTag); var buffer; if (_charset != null && _charset != 'utf-8') { try { buffer = iconv.encode(newChunkString, _charset); } catch (e) { console.error(e); buffer = iconv.encode(newChunkString, 'utf-8'); } } else { buffer = new Buffer(newChunkString); } return buffer; }
'use strict'; var _css = require('antd/lib/modal/style/css'); var _modal = require('antd/lib/modal'); var _modal2 = _interopRequireDefault(_modal); var _css2 = require('antd/lib/button/style/css'); var _button = require('antd/lib/button'); var _button2 = _interopRequireDefault(_button); var _css3 = require('antd/lib/icon/style/css'); var _icon = require('antd/lib/icon'); var _icon2 = _interopRequireDefault(_icon); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _businessComponents = require('../../global/components/businessComponents'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var AudioStyleControls = function (_Component) { _inherits(AudioStyleControls, _Component); function AudioStyleControls(props) { _classCallCheck(this, AudioStyleControls); var _this = _possibleConstructorReturn(this, (AudioStyleControls.__proto__ || Object.getPrototypeOf(AudioStyleControls)).call(this, props)); _this.state = { visible: false, audios: [] }, _this.onAudioToggle = _this.onAudioToggle.bind(_this); _this.sendAudioToEditor = _this.sendAudioToEditor.bind(_this); _this.handleCancel = _this.handleCancel.bind(_this); _this.getAudioObject = _this.getAudioObject.bind(_this); return _this; } _createClass(AudioStyleControls, [{ key: 'getAudioObject', value: function getAudioObject(fileObj) { this.state.audios = this.state.audios.concat(fileObj); if (!!this.state.audios) { this.setState({ disabled: false }); } this.forceUpdate(); } }, { key: 'onAudioToggle', value: function onAudioToggle() { this.setState({ visible: true, disabled: true, audios: [] }); } }, { key: 'sendAudioToEditor', value: function sendAudioToEditor() { this.setState({ visible: false }); var audios = this.state.audios.map(function (item) { return item; }); this.props.receiveAudio(audios); this.state.audios = []; this.forceUpdate(); } }, { key: 'handleCancel', value: function handleCancel(e) { this.setState({ visible: false }); this.state.audios = []; this.forceUpdate(); } }, { key: 'render', value: function render() { var className = 'RichEditor-styleButton'; var that = this; return _react2.default.createElement( 'div', { className: 'RichEditor-controls' }, _react2.default.createElement( 'span', { className: className, onClick: that.onAudioToggle }, _react2.default.createElement(_icon2.default, { type: 'editor_audio', title: this.props.lang.insertAudioTip }) ), _react2.default.createElement( _modal2.default, { title: this.props.lang.insertAudioModalTitle, visible: that.state.visible, closable: false, footer: [_react2.default.createElement( _button2.default, { key: 'back', size: 'large', onClick: that.handleCancel }, ' ', this.props.lang.cancelText, ' ' ), _react2.default.createElement( _button2.default, { key: 'submit', type: 'primary', size: 'large', disabled: that.state.disabled, onClick: that.sendAudioToEditor }, this.props.lang.OKText, ' ' )] }, _react2.default.createElement(_businessComponents.UploadImage, { isMultiple: true, fileList: that.state.audios, isOpenModel: that.state.visible, limit: 10, cbReceiver: that.getAudioObject, fileType: 'audio', uploadConfig: this.props.uploadConfig, uploadProps: this.props.uploadProps, lang: this.props.lang }) ) ); } }]); return AudioStyleControls; }(_react.Component); module.exports = AudioStyleControls;
import {forEach, isArray, isString} from 'lodash'; import {fromGlobalId, toGlobalId} from 'graphql-relay'; import getFieldList from './projection'; import viewer from '../model/viewer'; function processId({id, _id = id}) { // global or mongo id if (isString(_id) && !/^[a-fA-F0-9]{24}$/.test(_id)) { const {type, id} = fromGlobalId(_id); if (type && /^[a-zA-Z]*$/.test(type)) { return id; } } return _id; } function getCount(Collection, selector) { if (selector && (isArray(selector.id) || isArray(selector._id))) { const {id, _id = id} = selector; delete selector.id; selector._id = { $in: _id.map((id) => processId({id})) }; } return Collection.count(selector); } function getOne(Collection, args, info) { const id = processId(args); const projection = getFieldList(info); return Collection.findById(id, projection).then((result) => { if (result) { return { ...result.toObject(), _type: Collection.modelName }; } return null; }); } function addOne(Collection, args) { forEach(args, (arg, key) => { if (isArray(arg)) { args[key] = arg.map((id) => processId({id})); } else { args[key] = processId({id: arg}); } }); const instance = new Collection(args); return instance.save().then((result) => { if (result) { return { ...result.toObject(), _type: Collection.modelName }; } return null; }); } function updateOne(Collection, {id, _id, ...args}, info) { _id = processId({id, _id}); forEach(args, (arg, key) => { if (isArray(arg)) { args[key] = arg.map((id) => processId({id})); } else { args[key] = processId({id: arg}); } if (key.endsWith('_add')) { const values = args[key]; args.$push = { [key.slice(0, -4)]: {$each: values} }; delete args[key]; } }); return Collection.update({_id}, args).then((res) => { if (res.ok) { return getOne(Collection, {_id}, info); } return null; }); } function deleteOne(Collection, args) { const _id = processId(args); return Collection.remove({_id}).then(({result}) => ({ id: toGlobalId(Collection.modelName, _id), ok: !!result.ok })); } function getList(Collection, selector, options = {}, info = null) { if (selector && (isArray(selector.id) || isArray(selector._id))) { const {id, _id = id} = selector; delete selector.id; selector._id = { $in: _id.map((id) => processId({id})) }; } const projection = getFieldList(info); return Collection.find(selector, projection, options).then((result) => ( result.map((value) => ({ ...value.toObject(), _type: Collection.modelName })) )); } function getOneResolver(graffitiModel) { return (root, args, info) => { const Collection = graffitiModel.model; if (Collection) { return getOne(Collection, args, info); } return null; }; } function getAddOneMutateHandler(graffitiModel) { return ({clientMutationId, ...args}) => { // eslint-disable-line const Collection = graffitiModel.model; if (Collection) { return addOne(Collection, args); } return null; }; } function getUpdateOneMutateHandler(graffitiModel) { return ({clientMutationId, ...args}) => { // eslint-disable-line const Collection = graffitiModel.model; if (Collection) { return updateOne(Collection, args); } return null; }; } function getDeleteOneMutateHandler(graffitiModel) { return ({clientMutationId, ...args}) => { // eslint-disable-line const Collection = graffitiModel.model; if (Collection) { return deleteOne(Collection, args); } return null; }; } function getListResolver(graffitiModel) { return (root, {ids, ...args} = {}, info) => { if (ids) { args.id = ids; } const { orderBy: sort } = args; delete args.orderBy; const Collection = graffitiModel.model; if (Collection) { return getList(Collection, args, {sort}, info); } return null; }; } /** * Returns the first element in a Collection */ function getFirst(Collection) { return Collection.findOne({}, {}, {sort: {_id: 1}}); } /** * Returns an idFetcher function, that can resolve * an object based on a global id */ function getIdFetcher(graffitiModels) { return function idFetcher(obj, {id: globalId}, info) { const {type, id} = fromGlobalId(globalId); if (type === 'Viewer') { return viewer; } else if (graffitiModels[type]) { const Collection = graffitiModels[type].model; return getOne(Collection, {id}, info); } return null; }; } /** * Helper to get an empty connection. */ function emptyConnection() { return { count: 0, edges: [], pageInfo: { startCursor: null, endCursor: null, hasPreviousPage: false, hasNextPage: false } }; } const PREFIX = 'connection.'; function base64(i) { return ((new Buffer(i, 'ascii')).toString('base64')); } function unbase64(i) { return ((new Buffer(i, 'base64')).toString('ascii')); } /** * Creates the cursor string from an offset. */ function idToCursor(id) { return base64(PREFIX + id); } /** * Rederives the offset from the cursor string. */ function cursorToId(cursor) { return unbase64(cursor).substring(PREFIX.length); } /** * Given an optional cursor and a default offset, returns the offset * to use; if the cursor contains a valid offset, that will be used, * otherwise it will be the default. */ function getId(cursor) { if (cursor === undefined || cursor === null) { return null; } return cursorToId(cursor); } /** * Returns a connection based on a graffitiModel */ async function connectionFromModel(graffitiModel, args, info) { const Collection = graffitiModel.model; if (!Collection) { return emptyConnection(); } const {before, after, first, last, id, orderBy = {_id: 1}, ...selector} = args; const begin = getId(after); const end = getId(before); const offset = (first - last) || 0; const limit = last || first; if (id) { selector.id = id; } if (begin) { selector._id = selector._id || {}; selector._id.$gt = begin; } if (end) { selector._id = selector._id || {}; selector._id.$lt = end; } const result = await getList(Collection, selector, { limit, skip: offset, sort: orderBy }, info); const count = await getCount(Collection, selector); if (result.length === 0) { return emptyConnection(); } const edges = result.map((value) => ({ cursor: idToCursor(value._id), node: value })); const firstElement = await getFirst(Collection); return { count, edges, pageInfo: { startCursor: edges[0].cursor, endCursor: edges[edges.length - 1].cursor, hasPreviousPage: cursorToId(edges[0].cursor) !== firstElement._id.toString(), hasNextPage: result.length === limit } }; } export default { getOneResolver, getListResolver, getAddOneMutateHandler, getUpdateOneMutateHandler, getDeleteOneMutateHandler }; export { idToCursor as _idToCursor, idToCursor, getIdFetcher, getOneResolver, getAddOneMutateHandler, getUpdateOneMutateHandler, getDeleteOneMutateHandler, getListResolver, connectionFromModel };
'use strict'; module.exports = { InvalidParameter: require('./InvalidParameterError') };
/** * Stop the running app **/ const LarkPM = require('..'); const pm = new LarkPM('app.js'); pm.stop().then(() => { console.log("STOPPED"); }).catch((error) => { console.log(error.stack); });
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var ldap = require('ldapjs'), ldapConfig = (require('../config/config')).ldap, log = require('./log').auth, restify = require('restify'), constants = require('./constants'); var isStudent = new RegExp(constants.LDAP_STUDENT_REGEX); var isInstitute = new RegExp(constants.LDAP_INSTITUTE_REGEX); function errorHandling(err, callback) { log.error('[LDAP] ' + err); if (err.code == 49 ) { /* * LDAP_INVALID_CREDENTIALS (49) */ return callback(new restify.UnauthorizedError('Invalid username or password')); } else { /* LDAP server error or connection error happend. * * TODO: NOTIFY ADMIN * * Error could be: * * LDAP_AUTH_METHOD_NOT_SUPPORTED (7) * Indicates that during a bind operation the client * requested an authentication method not supported * by the LDAP server. * * LDAP_UNAVAILABLE (52) * Indicates that the LDAP server cannot process the * client's bind request, usually because it is shutting down. * * LDAP_UNWILLING_TO_PERFORM (53) * Indicates that the LDAP server cannot process * the request because of server-defined restrictions.*/ if (err.code == 80) { log.error('[LDAP] LDAP error 80: Code: ' + err.code + ' Message: ' + err.message); if ((err.message).search('timeout') !== -1) { return callback(new restify.ServiceUnavailableError('Can\'t connect to LDAP-Server for authentication. Request timeout. Pls try again. If this error still occurs, contact an admin.')); } } return callback(new restify.InternalServerError('LDAP Error - code: "' + err.code + '", msg: "' + err.message + '"')); } } function fetchEntry(dn, cn, password, client, callback) { var f = '(cn=' + cn + ')'; var opts = { //filter: '(cn=csap3468)', filter: f, scope: 'sub' }; client.bind(dn, password, function (err) { if (err) { log.error('[LDAP] LDAP bind error in function "fetchEntry". Code: ' + err.code + ' Message: ' + err.message); return callback(err); } client.search('dc=uibk,dc=ac,dc=at', opts, function (err, res) { if (err) { log.error('[LDAP] LDAP search error in function "fetchEntry". Code: ' + err.code + ' Message: ' + err.message); return callback(err); } var entrys = []; res.on('searchEntry', function(entry) { entrys.push(entry.object); }); res.on('error', function (err) { log.error('[LDAP] LDAP error in function "fetchEntry" at "error". Code: ' + err.code + ' Message: ' + err.message); return callback(err); }); res.on('end', function (result) { if (result.status !== 0) { log.error('[LDAP] LDAP search error in function "fetchEntry" at "end". ldap status code is not 0. Statuscode: ' + result.status); return callback(new ldap.OtherError('non-zero status from LDAP search - end: ' + result.status)); } return callback(null, entrys); }); }); }); } function fetchUserDetailsFromLdap(username, password, callback) { var ou; if (isInstitute.test(username)) { ou = 'iuser'; } else if (isStudent.test(username)) { ou = 'suser'; } else { log.info('[LDAP] Username: ' + username + ' doesnt match expected pattern for Student users or Institute users'); return callback(new restify.UnauthorizedError('Invalid username or password')); } var dn = 'cn=' + username + ',ou=' + ou + ',ou=user,ou=uibk,dc=uibk,dc=ac,dc=at'; var client = ldap.createClient({url: ldapConfig.host + ':' + ldapConfig.port, timeout: ldapConfig.timeout, connectTimeout: ldapConfig.connectionTimeout }); fetchEntry(dn, username, password, client, function (err, res) { client.unbind(function (err) { if (err) { log.error('[LDAP] LDAP unbind error in function "fetchUserDetailsFromLdap". Code: ' + err.code + ' Message: ' + err.message); } }); if (err) { return errorHandling(err, callback); } switch (res.length) { case 0: return callback(); case 1: return callback(null, res[0]); default: log.error('[LDAP] LDAP error: unexpected number of matches. There should only one!' + res[0] + '-' + res[1]); return callback(new restify.BadRequestError('Unexpected amount of matches with your ZID credentials')); } }); } function authCredentialsViaLdap(username, password, callback) { var ou; if (isInstitute.test(username)) { ou = 'iuser'; } else if (isStudent.test(username)) { ou = 'suser'; } else { log.info('[LDAP] Username: ' + username + ' doesnt match expected pattern for Student users or Institute users'); return callback(new restify.UnauthorizedError('Invalid username or password')); } var dn = 'cn=' + username + ',ou=' + ou + ',ou=user,ou=uibk,dc=uibk,dc=ac,dc=at'; var client = ldap.createClient({url: ldapConfig.host + ':' + ldapConfig.port, timeout: ldapConfig.timeout, connectTimeout: ldapConfig.connectionTimeout }); client.bind(dn, password, function (err) { if (err) { return errorHandling(err, callback); } log.debug('[LDAP] bind was successfully'); client.unbind(function (unbindErr) { if (unbindErr) { log.error('[LDAP] LDAP unbind error in function "authCredentialsViaLdap". Code: ' + unbindErr.code + ' Message: ' + unbindErr.message); } }); return callback(); }); } exports.fetchUserDetailsFromLdap = fetchUserDetailsFromLdap; exports.authCredentialsViaLdap = authCredentialsViaLdap;
import React from 'react'; import SplitPane from '../lib/SplitPane'; var Example = React.createClass({ render: function() { return ( <SplitPane split="vertical" minSize="50" defaultSize="100"> <div></div> <SplitPane split="horizontal"> <div></div> <div></div> </SplitPane> </SplitPane> ); } }); React.render(<Example />, document.body);
/* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com> * Copyright (C) 2009 Joseph Pecoraro * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.ElementsPanel = function() { WebInspector.Panel.call(this, "elements"); this.contentElement = document.createElement("div"); this.contentElement.id = "elements-content"; this.contentElement.className = "outline-disclosure source-code"; this.treeOutline = new WebInspector.ElementsTreeOutline(); this.treeOutline.panel = this; this.treeOutline.includeRootDOMNode = false; this.treeOutline.selectEnabled = true; this.treeOutline.focusedNodeChanged = function(forceUpdate) { if (this.panel.visible && WebInspector.currentFocusElement !== document.getElementById("search")) WebInspector.currentFocusElement = this.element; this.panel.updateBreadcrumb(forceUpdate); for (var pane in this.panel.sidebarPanes) this.panel.sidebarPanes[pane].needsUpdate = true; this.panel.updateStyles(true); this.panel.updateMetrics(); this.panel.updateProperties(); this.panel.updateEventListeners(); if (this._focusedDOMNode) { InspectorBackend.addInspectedNode(this._focusedDOMNode.id); WebInspector.extensionServer.notifyObjectSelected(this.panel.name); } }; this.contentElement.appendChild(this.treeOutline.element); this.crumbsElement = document.createElement("div"); this.crumbsElement.className = "crumbs"; this.crumbsElement.addEventListener("mousemove", this._mouseMovedInCrumbs.bind(this), false); this.crumbsElement.addEventListener("mouseout", this._mouseMovedOutOfCrumbs.bind(this), false); this.sidebarPanes = {}; this.sidebarPanes.computedStyle = new WebInspector.ComputedStyleSidebarPane(); this.sidebarPanes.styles = new WebInspector.StylesSidebarPane(this.sidebarPanes.computedStyle); this.sidebarPanes.metrics = new WebInspector.MetricsSidebarPane(); this.sidebarPanes.properties = new WebInspector.PropertiesSidebarPane(); if (Preferences.nativeInstrumentationEnabled) this.sidebarPanes.domBreakpoints = WebInspector.createDOMBreakpointsSidebarPane(); this.sidebarPanes.eventListeners = new WebInspector.EventListenersSidebarPane(); this.sidebarPanes.styles.onexpand = this.updateStyles.bind(this); this.sidebarPanes.metrics.onexpand = this.updateMetrics.bind(this); this.sidebarPanes.properties.onexpand = this.updateProperties.bind(this); this.sidebarPanes.eventListeners.onexpand = this.updateEventListeners.bind(this); this.sidebarPanes.styles.expanded = true; this.sidebarPanes.styles.addEventListener("style edited", this._stylesPaneEdited, this); this.sidebarPanes.styles.addEventListener("style property toggled", this._stylesPaneEdited, this); this.sidebarPanes.metrics.addEventListener("metrics edited", this._metricsPaneEdited, this); WebInspector.cssModel.addEventListener("stylesheet changed", this._styleSheetChanged, this); this.sidebarElement = document.createElement("div"); this.sidebarElement.id = "elements-sidebar"; for (var pane in this.sidebarPanes) this.sidebarElement.appendChild(this.sidebarPanes[pane].element); this.sidebarResizeElement = document.createElement("div"); this.sidebarResizeElement.className = "sidebar-resizer-vertical"; this.sidebarResizeElement.addEventListener("mousedown", this.rightSidebarResizerDragStart.bind(this), false); this._nodeSearchButton = new WebInspector.StatusBarButton(WebInspector.UIString("Select an element in the page to inspect it."), "node-search-status-bar-item"); this._nodeSearchButton.addEventListener("click", this.toggleSearchingForNode.bind(this), false); this.element.appendChild(this.contentElement); this.element.appendChild(this.sidebarElement); this.element.appendChild(this.sidebarResizeElement); this._registerShortcuts(); this.reset(); } WebInspector.ElementsPanel.prototype = { get toolbarItemLabel() { return WebInspector.UIString("Elements"); }, get statusBarItems() { return [this._nodeSearchButton.element, this.crumbsElement]; }, get defaultFocusedElement() { return this.treeOutline.element; }, updateStatusBarItems: function() { this.updateBreadcrumbSizes(); }, show: function() { WebInspector.Panel.prototype.show.call(this); this.sidebarResizeElement.style.right = (this.sidebarElement.offsetWidth - 3) + "px"; this.updateBreadcrumb(); this.treeOutline.updateSelection(); if (this.recentlyModifiedNodes.length) this.updateModifiedNodes(); }, hide: function() { WebInspector.Panel.prototype.hide.call(this); WebInspector.highlightDOMNode(0); this.setSearchingForNode(false); }, resize: function() { this.treeOutline.updateSelection(); this.updateBreadcrumbSizes(); }, reset: function() { if (this.focusedDOMNode) this._selectedPathOnReset = this.focusedDOMNode.path(); this.rootDOMNode = null; this.focusedDOMNode = null; WebInspector.highlightDOMNode(0); this.recentlyModifiedNodes = []; delete this.currentQuery; }, setDocument: function(inspectedRootDocument) { this.reset(); this.searchCanceled(); if (!inspectedRootDocument) return; inspectedRootDocument.addEventListener("DOMNodeInserted", this._nodeInserted.bind(this)); inspectedRootDocument.addEventListener("DOMNodeRemoved", this._nodeRemoved.bind(this)); inspectedRootDocument.addEventListener("DOMAttrModified", this._attributesUpdated.bind(this)); inspectedRootDocument.addEventListener("DOMCharacterDataModified", this._characterDataModified.bind(this)); this.rootDOMNode = inspectedRootDocument; function selectNode(candidateFocusNode) { if (!candidateFocusNode) candidateFocusNode = inspectedRootDocument.body || inspectedRootDocument.documentElement; if (!candidateFocusNode) return; this.focusedDOMNode = candidateFocusNode; if (this.treeOutline.selectedTreeElement) this.treeOutline.selectedTreeElement.expand(); } function selectLastSelectedNode(nodeId) { if (this.focusedDOMNode) { // Focused node has been explicitly set while reaching out for the last selected node. return; } var node = nodeId ? WebInspector.domAgent.nodeForId(nodeId) : 0; selectNode.call(this, node); } if (this._selectedPathOnReset) InspectorBackend.pushNodeByPathToFrontend(this._selectedPathOnReset, selectLastSelectedNode.bind(this)); else selectNode.call(this); delete this._selectedPathOnReset; }, searchCanceled: function() { delete this._searchQuery; this._hideSearchHighlights(); WebInspector.updateSearchMatchesCount(0, this); this._currentSearchResultIndex = 0; this._searchResults = []; InspectorBackend.searchCanceled(); }, performSearch: function(query) { // Call searchCanceled since it will reset everything we need before doing a new search. this.searchCanceled(); var #FF6AFCspaceTrimmedQuery = query.trim(); if (!#FF6AFCspaceTrimmedQuery.length) return; this._updatedMatchCountOnce = false; this._matchesCountUpdateTimeout = null; this._searchQuery = query; InspectorBackend.performSearch(#FF6AFCspaceTrimmedQuery, false); }, populateHrefContextMenu: function(contextMenu, event, anchorElement) { if (!anchorElement.href) return false; var resourceURL = WebInspector.resourceURLForRelatedNode(this.focusedDOMNode, anchorElement.href); if (!resourceURL) return false; // Add resource-related actions. contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), WebInspector.openResource.bind(null, resourceURL, false)); if (WebInspector.resourceForURL(resourceURL)) contextMenu.appendItem(WebInspector.UIString("Open Link in Resources Panel"), WebInspector.openResource.bind(null, resourceURL, true)); return true; }, switchToAndFocus: function(node) { // Reset search restore. WebInspector.cancelSearch(); WebInspector.currentPanel = this; this.focusedDOMNode = node; }, _updateMatchesCount: function() { WebInspector.updateSearchMatchesCount(this._searchResults.length, this); this._matchesCountUpdateTimeout = null; this._updatedMatchCountOnce = true; }, _updateMatchesCountSoon: function() { if (!this._updatedMatchCountOnce) return this._updateMatchesCount(); if (this._matchesCountUpdateTimeout) return; // Update the matches count every half-second so it doesn't feel twitchy. this._matchesCountUpdateTimeout = setTimeout(this._updateMatchesCount.bind(this), 500); }, addNodesToSearchResult: function(nodeIds) { if (!nodeIds.length) return; for (var i = 0; i < nodeIds.length; ++i) { var nodeId = nodeIds[i]; var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) continue; this._currentSearchResultIndex = 0; this._searchResults.push(node); } this._highlightCurrentSearchResult(); this._updateMatchesCountSoon(); }, jumpToNextSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (++this._currentSearchResultIndex >= this._searchResults.length) this._currentSearchResultIndex = 0; this._highlightCurrentSearchResult(); }, jumpToPreviousSearchResult: function() { if (!this._searchResults || !this._searchResults.length) return; if (--this._currentSearchResultIndex < 0) this._currentSearchResultIndex = (this._searchResults.length - 1); this._highlightCurrentSearchResult(); }, _highlightCurrentSearchResult: function() { this._hideSearchHighlights(); var node = this._searchResults[this._currentSearchResultIndex]; var treeElement = this.treeOutline.findTreeElement(node); if (treeElement) { treeElement.highlightSearchResults(this._searchQuery); treeElement.reveal(); } }, _hideSearchHighlights: function(node) { for (var i = 0; this._searchResults && i < this._searchResults.length; ++i) { var node = this._searchResults[i]; var treeElement = this.treeOutline.findTreeElement(node); if (treeElement) treeElement.highlightSearchResults(null); } }, renameSelector: function(oldIdentifier, newIdentifier, oldSelector, newSelector) { // TODO: Implement Shifting the oldSelector, and its contents to a newSelector }, get rootDOMNode() { return this.treeOutline.rootDOMNode; }, set rootDOMNode(x) { this.treeOutline.rootDOMNode = x; }, get focusedDOMNode() { return this.treeOutline.focusedDOMNode; }, set focusedDOMNode(x) { this.treeOutline.focusedDOMNode = x; }, _attributesUpdated: function(event) { this.recentlyModifiedNodes.push({node: event.target, updated: true}); if (this.visible) this._updateModifiedNodesSoon(); }, _characterDataModified: function(event) { this.recentlyModifiedNodes.push({node: event.target, updated: true}); if (this.visible) this._updateModifiedNodesSoon(); }, _nodeInserted: function(event) { this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, inserted: true}); if (this.visible) this._updateModifiedNodesSoon(); }, _nodeRemoved: function(event) { this.recentlyModifiedNodes.push({node: event.target, parent: event.relatedNode, removed: true}); if (this.visible) this._updateModifiedNodesSoon(); }, _updateModifiedNodesSoon: function() { if ("_updateModifiedNodesTimeout" in this) return; this._updateModifiedNodesTimeout = setTimeout(this.updateModifiedNodes.bind(this), 0); }, updateModifiedNodes: function() { if ("_updateModifiedNodesTimeout" in this) { clearTimeout(this._updateModifiedNodesTimeout); delete this._updateModifiedNodesTimeout; } var updatedParentTreeElements = []; var updateBreadcrumbs = false; for (var i = 0; i < this.recentlyModifiedNodes.length; ++i) { var replaced = this.recentlyModifiedNodes[i].replaced; var parent = this.recentlyModifiedNodes[i].parent; var node = this.recentlyModifiedNodes[i].node; if (this.recentlyModifiedNodes[i].updated) { var nodeItem = this.treeOutline.findTreeElement(node); if (nodeItem) nodeItem.updateTitle(); continue; } if (!parent) continue; var parentNodeItem = this.treeOutline.findTreeElement(parent); if (parentNodeItem && !parentNodeItem.alreadyUpdatedChildren) { parentNodeItem.updateChildren(replaced); parentNodeItem.alreadyUpdatedChildren = true; updatedParentTreeElements.push(parentNodeItem); } if (!updateBreadcrumbs && (this.focusedDOMNode === parent || isAncestorNode(this.focusedDOMNode, parent))) updateBreadcrumbs = true; } for (var i = 0; i < updatedParentTreeElements.length; ++i) delete updatedParentTreeElements[i].alreadyUpdatedChildren; this.recentlyModifiedNodes = []; if (updateBreadcrumbs) this.updateBreadcrumb(true); }, _stylesPaneEdited: function() { // Once styles are edited, the Metrics pane should be updated. this.sidebarPanes.metrics.needsUpdate = true; this.updateMetrics(); }, _metricsPaneEdited: function() { // Once metrics are edited, the Styles pane should be updated. this.sidebarPanes.styles.needsUpdate = true; this.updateStyles(true); }, _styleSheetChanged: function() { this._metricsPaneEdited(); this._stylesPaneEdited(); }, _mouseMovedInCrumbs: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); var crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass("crumb"); WebInspector.highlightDOMNode(crumbElement ? crumbElement.representedObject.id : 0); if ("_mouseOutOfCrumbsTimeout" in this) { clearTimeout(this._mouseOutOfCrumbsTimeout); delete this._mouseOutOfCrumbsTimeout; } }, _mouseMovedOutOfCrumbs: function(event) { var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY); if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.crumbsElement)) return; WebInspector.highlightDOMNode(0); this._mouseOutOfCrumbsTimeout = setTimeout(this.updateBreadcrumbSizes.bind(this), 1000); }, updateBreadcrumb: function(forceUpdate) { if (!this.visible) return; var crumbs = this.crumbsElement; var handled = false; var foundRoot = false; var crumb = crumbs.firstChild; while (crumb) { if (crumb.representedObject === this.rootDOMNode) foundRoot = true; if (foundRoot) crumb.addStyleClass("dimmed"); else crumb.removeStyleClass("dimmed"); if (crumb.representedObject === this.focusedDOMNode) { crumb.addStyleClass("selected"); handled = true; } else { crumb.removeStyleClass("selected"); } crumb = crumb.nextSibling; } if (handled && !forceUpdate) { // We don't need to rebuild the crumbs, but we need to adjust sizes // to reflect the new focused or root node. this.updateBreadcrumbSizes(); return; } crumbs.removeChildren(); var panel = this; function selectCrumbFunction(event) { var crumb = event.currentTarget; if (crumb.hasStyleClass("collapsed")) { // Clicking a collapsed crumb will expose the hidden crumbs. if (crumb === panel.crumbsElement.firstChild) { // If the focused crumb is the first child, pick the farthest crumb // that is still hidden. This allows the user to expose every crumb. var currentCrumb = crumb; while (currentCrumb) { var hidden = currentCrumb.hasStyleClass("hidden"); var collapsed = currentCrumb.hasStyleClass("collapsed"); if (!hidden && !collapsed) break; crumb = currentCrumb; currentCrumb = currentCrumb.nextSibling; } } panel.updateBreadcrumbSizes(crumb); } else { // Clicking a dimmed crumb or double clicking (event.detail >= 2) // will change the root node in addition to the focused node. if (event.detail >= 2 || crumb.hasStyleClass("dimmed")) panel.rootDOMNode = crumb.representedObject.parentNode; panel.focusedDOMNode = crumb.representedObject; } event.preventDefault(); } foundRoot = false; for (var current = this.focusedDOMNode; current; current = current.parentNode) { if (current.nodeType === Node.DOCUMENT_NODE) continue; if (current === this.rootDOMNode) foundRoot = true; var crumb = document.createElement("span"); crumb.className = "crumb"; crumb.representedObject = current; crumb.addEventListener("mousedown", selectCrumbFunction, false); var crumbTitle; switch (current.nodeType) { case Node.ELEMENT_NODE: this.decorateNodeLabel(current, crumb); break; case Node.TEXT_NODE: if (isNode#FF6AFCspace.call(current)) crumbTitle = WebInspector.UIString("(#FF6AFCspace)"); else crumbTitle = WebInspector.UIString("(text)"); break case Node.COMMENT_NODE: crumbTitle = "<!-->"; break; case Node.DOCUMENT_TYPE_NODE: crumbTitle = "<!DOCTYPE>"; break; default: crumbTitle = this.treeOutline.nodeNameToCorrectCase(current.nodeName); } if (!crumb.childNodes.length) { var nameElement = document.createElement("span"); nameElement.textContent = crumbTitle; crumb.appendChild(nameElement); crumb.title = crumbTitle; } if (foundRoot) crumb.addStyleClass("dimmed"); if (current === this.focusedDOMNode) crumb.addStyleClass("selected"); if (!crumbs.childNodes.length) crumb.addStyleClass("end"); crumbs.appendChild(crumb); } if (crumbs.hasChildNodes()) crumbs.lastChild.addStyleClass("start"); this.updateBreadcrumbSizes(); }, decorateNodeLabel: function(node, parentElement) { var title = this.treeOutline.nodeNameToCorrectCase(node.nodeName); var nameElement = document.createElement("span"); nameElement.textContent = title; parentElement.appendChild(nameElement); var idAttribute = node.getAttribute("id"); if (idAttribute) { var idElement = document.createElement("span"); parentElement.appendChild(idElement); var part = "#" + idAttribute; title += part; idElement.appendChild(document.createTextNode(part)); // Mark the name as extra, since the ID is more important. nameElement.className = "extra"; } var classAttribute = node.getAttribute("class"); if (classAttribute) { var classes = classAttribute.split(/\s+/); var foundClasses = {}; if (classes.length) { var classesElement = document.createElement("span"); classesElement.className = "extra"; parentElement.appendChild(classesElement); for (var i = 0; i < classes.length; ++i) { var className = classes[i]; if (className && !(className in foundClasses)) { var part = "." + className; title += part; classesElement.appendChild(document.createTextNode(part)); foundClasses[className] = true; } } } } parentElement.title = title; }, linkifyNodeReference: function(node) { var link = document.createElement("span"); link.className = "node-link"; this.decorateNodeLabel(node, link); WebInspector.wireElementWithDOMNode(link, node.id); return link; }, linkifyNodeById: function(nodeId) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return document.createTextNode(WebInspector.UIString("<node>")); return this.linkifyNodeReference(node); }, updateBreadcrumbSizes: function(focusedCrumb) { if (!this.visible) return; if (document.body.offsetWidth <= 0) { // The stylesheet hasn't loaded yet or the window is closed, // so we can't calculate what is need. Return early. return; } var crumbs = this.crumbsElement; if (!crumbs.childNodes.length || crumbs.offsetWidth <= 0) return; // No crumbs, do nothing. // A Zero index is the right most child crumb in the breadcrumb. var selectedIndex = 0; var focusedIndex = 0; var selectedCrumb; var i = 0; var crumb = crumbs.firstChild; while (crumb) { // Find the selected crumb and index. if (!selectedCrumb && crumb.hasStyleClass("selected")) { selectedCrumb = crumb; selectedIndex = i; } // Find the focused crumb index. if (crumb === focusedCrumb) focusedIndex = i; // Remove any styles that affect size before // deciding to shorten any crumbs. if (crumb !== crumbs.lastChild) crumb.removeStyleClass("start"); if (crumb !== crumbs.firstChild) crumb.removeStyleClass("end"); crumb.removeStyleClass("compact"); crumb.removeStyleClass("collapsed"); crumb.removeStyleClass("hidden"); crumb = crumb.nextSibling; ++i; } // Restore the start and end crumb classes in case they got removed in coalesceCollapsedCrumbs(). // The order of the crumbs in the document is opposite of the visual order. crumbs.firstChild.addStyleClass("end"); crumbs.lastChild.addStyleClass("start"); function crumbsAreSmallerThanContainer() { var rightPadding = 20; var errorWarningElement = document.getElementById("error-warning-count"); if (!WebInspector.drawer.visible && errorWarningElement) rightPadding += errorWarningElement.offsetWidth; return ((crumbs.totalOffsetLeft + crumbs.offsetWidth + rightPadding) < window.innerWidth); } if (crumbsAreSmallerThanContainer()) return; // No need to compact the crumbs, they all fit at full size. var BothSides = 0; var AncestorSide = -1; var ChildSide = 1; function makeCrumbsSmaller(shrinkingFunction, direction, significantCrumb) { if (!significantCrumb) significantCrumb = (focusedCrumb || selectedCrumb); if (significantCrumb === selectedCrumb) var significantIndex = selectedIndex; else if (significantCrumb === focusedCrumb) var significantIndex = focusedIndex; else { var significantIndex = 0; for (var i = 0; i < crumbs.childNodes.length; ++i) { if (crumbs.childNodes[i] === significantCrumb) { significantIndex = i; break; } } } function shrinkCrumbAtIndex(index) { var shrinkCrumb = crumbs.childNodes[index]; if (shrinkCrumb && shrinkCrumb !== significantCrumb) shrinkingFunction(shrinkCrumb); if (crumbsAreSmallerThanContainer()) return true; // No need to compact the crumbs more. return false; } // Shrink crumbs one at a time by applying the shrinkingFunction until the crumbs // fit in the container or we run out of crumbs to shrink. if (direction) { // Crumbs are shrunk on only one side (based on direction) of the signifcant crumb. var index = (direction > 0 ? 0 : crumbs.childNodes.length - 1); while (index !== significantIndex) { if (shrinkCrumbAtIndex(index)) return true; index += (direction > 0 ? 1 : -1); } } else { // Crumbs are shrunk in order of descending distance from the signifcant crumb, // with a tie going to child crumbs. var startIndex = 0; var endIndex = crumbs.childNodes.length - 1; while (startIndex != significantIndex || endIndex != significantIndex) { var startDistance = significantIndex - startIndex; var endDistance = endIndex - significantIndex; if (startDistance >= endDistance) var index = startIndex++; else var index = endIndex--; if (shrinkCrumbAtIndex(index)) return true; } } // We are not small enough yet, return false so the caller knows. return false; } function coalesceCollapsedCrumbs() { var crumb = crumbs.firstChild; var collapsedRun = false; var newStartNeeded = false; var newEndNeeded = false; while (crumb) { var hidden = crumb.hasStyleClass("hidden"); if (!hidden) { var collapsed = crumb.hasStyleClass("collapsed"); if (collapsedRun && collapsed) { crumb.addStyleClass("hidden"); crumb.removeStyleClass("compact"); crumb.removeStyleClass("collapsed"); if (crumb.hasStyleClass("start")) { crumb.removeStyleClass("start"); newStartNeeded = true; } if (crumb.hasStyleClass("end")) { crumb.removeStyleClass("end"); newEndNeeded = true; } continue; } collapsedRun = collapsed; if (newEndNeeded) { newEndNeeded = false; crumb.addStyleClass("end"); } } else collapsedRun = true; crumb = crumb.nextSibling; } if (newStartNeeded) { crumb = crumbs.lastChild; while (crumb) { if (!crumb.hasStyleClass("hidden")) { crumb.addStyleClass("start"); break; } crumb = crumb.previousSibling; } } } function compact(crumb) { if (crumb.hasStyleClass("hidden")) return; crumb.addStyleClass("compact"); } function collapse(crumb, dontCoalesce) { if (crumb.hasStyleClass("hidden")) return; crumb.addStyleClass("collapsed"); crumb.removeStyleClass("compact"); if (!dontCoalesce) coalesceCollapsedCrumbs(); } function compactDimmed(crumb) { if (crumb.hasStyleClass("dimmed")) compact(crumb); } function collapseDimmed(crumb) { if (crumb.hasStyleClass("dimmed")) collapse(crumb); } if (!focusedCrumb) { // When not focused on a crumb we can be biased and collapse less important // crumbs that the user might not care much about. // Compact child crumbs. if (makeCrumbsSmaller(compact, ChildSide)) return; // Collapse child crumbs. if (makeCrumbsSmaller(collapse, ChildSide)) return; // Compact dimmed ancestor crumbs. if (makeCrumbsSmaller(compactDimmed, AncestorSide)) return; // Collapse dimmed ancestor crumbs. if (makeCrumbsSmaller(collapseDimmed, AncestorSide)) return; } // Compact ancestor crumbs, or from both sides if focused. if (makeCrumbsSmaller(compact, (focusedCrumb ? BothSides : AncestorSide))) return; // Collapse ancestor crumbs, or from both sides if focused. if (makeCrumbsSmaller(collapse, (focusedCrumb ? BothSides : AncestorSide))) return; if (!selectedCrumb) return; // Compact the selected crumb. compact(selectedCrumb); if (crumbsAreSmallerThanContainer()) return; // Collapse the selected crumb as a last resort. Pass true to prevent coalescing. collapse(selectedCrumb, true); }, updateStyles: function(forceUpdate) { var stylesSidebarPane = this.sidebarPanes.styles; var computedStylePane = this.sidebarPanes.computedStyle; if ((!stylesSidebarPane.expanded && !computedStylePane.expanded) || !stylesSidebarPane.needsUpdate) return; stylesSidebarPane.update(this.focusedDOMNode, null, forceUpdate); stylesSidebarPane.needsUpdate = false; }, updateMetrics: function() { var metricsSidebarPane = this.sidebarPanes.metrics; if (!metricsSidebarPane.expanded || !metricsSidebarPane.needsUpdate) return; metricsSidebarPane.update(this.focusedDOMNode); metricsSidebarPane.needsUpdate = false; }, updateProperties: function() { var propertiesSidebarPane = this.sidebarPanes.properties; if (!propertiesSidebarPane.expanded || !propertiesSidebarPane.needsUpdate) return; propertiesSidebarPane.update(this.focusedDOMNode); propertiesSidebarPane.needsUpdate = false; }, updateEventListeners: function() { var eventListenersSidebarPane = this.sidebarPanes.eventListeners; if (!eventListenersSidebarPane.expanded || !eventListenersSidebarPane.needsUpdate) return; eventListenersSidebarPane.update(this.focusedDOMNode); eventListenersSidebarPane.needsUpdate = false; }, _registerShortcuts: function() { var shortcut = WebInspector.KeyboardShortcut; var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("Elements Panel")); var keys = [ shortcut.shortcutToString(shortcut.Keys.Up), shortcut.shortcutToString(shortcut.Keys.Down) ]; section.addRelatedKeys(keys, WebInspector.UIString("Navigate elements")); var keys = [ shortcut.shortcutToString(shortcut.Keys.Right), shortcut.shortcutToString(shortcut.Keys.Left) ]; section.addRelatedKeys(keys, WebInspector.UIString("Expand/collapse")); section.addKey(shortcut.shortcutToString(shortcut.Keys.Enter), WebInspector.UIString("Edit attribute")); this.sidebarPanes.styles.registerShortcuts(); }, handleShortcut: function(event) { // Cmd/Control + Shift + C should be a shortcut to clicking the Node Search Button. // This shortcut matches Firebug. if (event.keyIdentifier === "U+0043") { // C key if (WebInspector.isMac()) var isNodeSearchKey = event.metaKey && !event.ctrlKey && !event.altKey && event.shiftKey; else var isNodeSearchKey = event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey; if (isNodeSearchKey) { this.toggleSearchingForNode(); event.handled = true; return; } } }, handleCopyEvent: function(event) { // Don't prevent the normal copy if the user has a selection. if (!window.getSelection().isCollapsed) return; event.clipboardData.clearData(); event.preventDefault(); InspectorBackend.copyNode(this.focusedDOMNode.id); }, rightSidebarResizerDragStart: function(event) { WebInspector.elementDragStart(this.sidebarElement, this.rightSidebarResizerDrag.bind(this), this.rightSidebarResizerDragEnd.bind(this), event, "col-resize"); }, rightSidebarResizerDragEnd: function(event) { WebInspector.elementDragEnd(event); this.saveSidebarWidth(); }, rightSidebarResizerDrag: function(event) { var x = event.pageX; var newWidth = Number.constrain(window.innerWidth - x, Preferences.minElementsSidebarWidth, window.innerWidth * 0.66); this.setSidebarWidth(newWidth); event.preventDefault(); }, setSidebarWidth: function(newWidth) { this.sidebarElement.style.width = newWidth + "px"; this.contentElement.style.right = newWidth + "px"; this.sidebarResizeElement.style.right = (newWidth - 3) + "px"; this.treeOutline.updateSelection(); }, updateFocusedNode: function(nodeId) { var node = WebInspector.domAgent.nodeForId(nodeId); if (!node) return; this.focusedDOMNode = node; this._nodeSearchButton.toggled = false; }, _setSearchingForNode: function(enabled) { this._nodeSearchButton.toggled = enabled; }, setSearchingForNode: function(enabled) { InspectorBackend.setSearchingForNode(enabled, this._setSearchingForNode.bind(this)); }, toggleSearchingForNode: function() { this.setSearchingForNode(!this._nodeSearchButton.toggled); }, elementsToRestoreScrollPositionsFor: function() { return [ this.contentElement, this.sidebarElement ]; } } WebInspector.ElementsPanel.prototype.__proto__ = WebInspector.Panel.prototype;
// Fetch node test library var assert = require('assert'); // Basic cut the mustard conditions var ctmBasic = require('cut-the-mustard/basic'); var basicWindow = { document: {querySelector: function(){}}, localStorage: {}, addEventListener: function(){} }; assert.equal(true, ctmBasic(basicWindow)); var noQuerySelectorWindow = { document: {}, localStorage: {}, addEventListener: function(){} }; assert.equal(false, ctmBasic(noQuerySelectorWindow)); var noLocalStorageWindow = { document: {querySelector: function(){}}, addEventListener: function(){} }; assert.equal(false, ctmBasic(noLocalStorageWindow)); var noAddEventListener = { document: {querySelector: function(){}}, localStorage: {} }; assert.equal(false, ctmBasic(noAddEventListener)); // Test is available on collection object assert.equal(ctmBasic, require('cut-the-mustard').basic); // Advanced cut the mustard conditions var ctmAdvanced = require('cut-the-mustard/advanced'); var advancedWindow = { document: {visibilityState: 'visible'} }; assert.equal(true, ctmAdvanced(advancedWindow)); var noVisibilityStateWindow = { document: {} }; assert.equal(false, ctmAdvanced(noVisibilityStateWindow)); // Test is available on collection object assert.equal(ctmAdvanced, require('cut-the-mustard').advanced); // Offline cut the mustard conditions var ctmOffline = require('cut-the-mustard/offline'); var offlineWindow = { navigator: {serviceWorker: {}} }; assert.equal(true, ctmOffline(offlineWindow)); var noServiceWorkerWindow = { navigator: {} }; assert.equal(false, ctmOffline(noServiceWorkerWindow)); // Test is available on collection object assert.equal(ctmOffline, require('cut-the-mustard').offline);
jest.autoMockOff(); const Bundlerify = require('../src/index').default; const BrowserifyMock = require('./utils/browserify.js').default; const { ESDocUploaderMock, ESDocUploaderMockObjs, } = require('./utils/esdocUploader.js').default; const gulp = require('gulp'); const originalFs = require('fs'); const originalPath = require('path'); const originalConsoleLog = console.log; jest.mock('fs'); const mockFs = require('../__mocks__/fs'); jest.mock('path'); const mockPath = require('../__mocks__/path'); /** * @test {Bundlerify} */ describe('gulp-bundlerify', () => { beforeEach(() => { jest.setMock('fs', originalFs); jest.setMock('path', originalPath); }); afterEach(() => { const instance = null; }); /** * @test {Bundlerify#constructor} */ it('should create a new instance and have public methods', () => { const instance = new Bundlerify(gulp); expect(instance).toEqual(jasmine.any(Bundlerify)); expect(instance.clean).toEqual(jasmine.any(Function)); expect(instance.build).toEqual(jasmine.any(Function)); expect(instance.serve).toEqual(jasmine.any(Function)); expect(instance.tasks).toEqual(jasmine.any(Function)); expect(() => Bundlerify(gulp)).toThrow('Cannot call a class as a function'); }); /** * @test {Bundlerify#config} */ it('should write the configuration correctly', () => { const dummyConfig = { mainFile: './test.js', dist: { file: 'app.js', }, watchifyOptions: { fullPaths: false, }, browserSyncOptions: { enabled: false, server: { directory: false, routes: { '/test/': './test/', }, }, }, babelifyOptions: { presets: ['es25-10-2015'], }, }; const instance = new Bundlerify(gulp, dummyConfig); const config = instance.config; expect(config.mainFile).toEqual(dummyConfig.mainFile); expect(config.dist.file).toEqual(dummyConfig.dist.file); expect(config.dist.dir).toEqual('./dist/'); expect(config.watchifyOptions.debug).toBeTruthy(); expect(config.watchifyOptions.fullPaths).toEqual(dummyConfig.watchifyOptions.fullPaths); expect(config.browserSyncOptions.enabled).toBeFalsy(); expect(config.browserSyncOptions.server.directory).toBeFalsy(); expect(config.browserSyncOptions.server.routes).toEqual(instance._mergeObjects( dummyConfig.browserSyncOptions.server.routes, { '/src/': './src/', '/dist/': './dist/', '/es5/': './es5/', } )); expect(config.babelifyOptions.presets).toEqual(dummyConfig.babelifyOptions.presets); }); /** * @test {Bundlerify#_expandShorthandSettings} */ it('should expand shorthand settings', () => { const dummyConfig = { watchifyDebug: true, browserSyncBaseDir: './rosario/', browserSyncEnabled: false, }; const instance = new Bundlerify(gulp, dummyConfig); expect(instance.config.watchifyOptions.debug).toBeTruthy(); expect(instance.config.browserSyncOptions.server.baseDir).toEqual( dummyConfig.browserSyncBaseDir ); expect(instance.config.browserSyncOptions.enabled).toBeFalsy(); }); /** * @test {Bundlerify#constructor} */ it('should be able to be instantiated just with a filepath', () => { const dummyFile = './Rosario.js'; const instance = new Bundlerify(gulp, dummyFile); expect(instance.config.mainFile).toEqual(dummyFile); }); /** * @test {Bundlerify#constructor} */ it('should create a Browser Sync router for the dist directory', () => { const dummyPath = '/charito/'; const instance = new Bundlerify(gulp, { dist: { dir: dummyPath, }, }); expect(instance.config.browserSyncOptions.server.routes[dummyPath]).toEqual(dummyPath); }); /** * @test {Bundlerify#constructor} */ it('should read the ESDoc options from a file', () => { jest.setMock('fs', mockFs); // Try a valid file const dummyOptions = { name: 'docs', type: 'file', }; mockFs.__setMockFiles({ docFile: JSON.stringify(dummyOptions), }); let instance = new Bundlerify(gulp, { esdocOptions: 'docFile', }); Object.keys(dummyOptions).forEach((optionName) => { expect(instance.config.esdocOptions[optionName]).toEqual(dummyOptions[optionName]); }); // Try an invalid file const originalOptions = { enabled: true, source: './src', destination: './docs', plugins: [ {name: 'esdoc-es7-plugin'}, ], }; instance = new Bundlerify(gulp, { esdocOptions: 'invalidFile', }); expect(instance.config.esdocOptions).toEqual(originalOptions); }); /** * @test {Bundlerify#constructor} */ it('should read the Jest options from a file', () => { // jest.mock('path'); jest.setMock('fs', mockFs); jest.setMock('path', mockPath); // Try a valid file const dummyPackage = { jest: { collectCoverageOnlyFrom: { 'file.js': true, }, }, }; mockFs.__setMockFiles({ 'package.json': JSON.stringify(dummyPackage), 'jest.json': JSON.stringify(dummyPackage.jest), }); let instance = new Bundlerify(gulp, { jestOptions: 'package.json', }); expect(instance.config.jestOptions.collectCoverageOnlyFrom['ABSOLUTE/PATH/file.js']) .toBeTruthy(); // Use a file that is not package.json instance = new Bundlerify(gulp, { jestOptions: 'jest.json', }); expect(instance.config.jestOptions.collectCoverageOnlyFrom['ABSOLUTE/PATH/file.js']) .toBeTruthy(); // Try an invalid file instance = new Bundlerify(gulp, { jestOptions: 'invalidFile', }); expect(instance.config.jestOptions.collectCoverageOnlyFrom).toBeUndefined(); // jest.setMock('path', originalPath); }); /** * @test {Bundlerify#_getDependency} */ it('should be able to overwrite and obtain the dependencies modules', () => { const dummyValues = { watchify: { name: 'My Custom Watchify', module: 'watchify', }, browserify: { name: 'My Custom Browserify', module: 'browserify', }, babelify: { name: 'My Custom Babelify', module: 'babelify', }, vinylSourceStream: { name: 'My Custom VinylSourceStream', module: 'vinyl-source-stream', }, vinylTransform: { name: 'My Custom VinylTransform', module: 'vinyl-transform', }, browserSync: { name: 'My Custom BrowserSync', module: 'browser-sync', }, rimraf: { name: 'My Custom Rimraf', module: 'rimraf', }, gulpUtil: { name: 'My Custom GulpUtil', module: 'gulp-util', }, gulpIf: { name: 'My Custom GulpIf', module: 'gulp-if', }, gulpStreamify: { name: 'My Custom GulpStreamify', module: 'gulp-streamify', }, gulpUglify: { name: 'My Custom Uglifier', module: 'gulp-uglify', }, gulpJSCS: { name: 'My Custom JSCS', module: 'gulp-jscs', }, gulpESLint: { name: 'My Custom ESLint', module: 'gulp-eslint', }, esdoc: { name: 'My Custom ESDoc', module: 'esdoc', }, esdocPublisher: { name: 'My Custom Publisher', module: 'esdoc/out/src/Publisher/publish', }, esdocUploader: { name: 'My Custom ESDoc Uploader', module: 'esdoc-uploader', }, jest: { name: 'My Custom Jest', module: 'jest-cli', }, through: { name: 'My Custom Through', module: 'through2', }, }; const instance = new Bundlerify(gulp); instance.watchify = dummyValues.watchify.name; expect(instance.watchify).toEqual(dummyValues.watchify.name); instance.watchify = null; expect(instance.watchify).toEqual(require(dummyValues.watchify.module)); instance.browserify = dummyValues.browserify.name; expect(instance.browserify).toEqual(dummyValues.browserify.name); instance.browserify = null; // For some reason, the reporter doesn't close the process when you require the // 'browserify' module, so this will inject it on the dependencies directory // so it doesn't have to require it. instance._dependencies.browserify = dummyValues.browserify.name; expect(instance.browserify).toEqual(dummyValues.browserify.name); instance.babelify = dummyValues.babelify.name; expect(instance.babelify).toEqual(dummyValues.babelify.name); instance.babelify = null; expect(instance.babelify).toEqual(require(dummyValues.babelify.module)); instance.vinylSourceStream = dummyValues.vinylSourceStream.name; expect(instance.vinylSourceStream).toEqual(dummyValues.vinylSourceStream.name); instance.vinylSourceStream = null; expect(instance.vinylSourceStream).toEqual(require(dummyValues.vinylSourceStream.module)); instance.vinylTransform = dummyValues.vinylTransform.name; expect(instance.vinylTransform).toEqual(dummyValues.vinylTransform.name); instance.vinylTransform = null; expect(instance.vinylTransform).toEqual(require(dummyValues.vinylTransform.module)); instance.browserSync = dummyValues.browserSync.name; expect(instance.browserSync).toEqual(dummyValues.browserSync.name); instance.browserSync = null; expect(instance.browserSync).toEqual(require(dummyValues.browserSync.module)); instance.rimraf = dummyValues.rimraf.name; expect(instance.rimraf).toEqual(dummyValues.rimraf.name); instance.rimraf = null; expect(instance.rimraf).toEqual(require(dummyValues.rimraf.module)); instance.gulpUtil = dummyValues.gulpUtil.name; expect(instance.gulpUtil).toEqual(dummyValues.gulpUtil.name); instance.gulpUtil = null; expect(instance.gulpUtil).toEqual(require(dummyValues.gulpUtil.module)); instance.gulpIf = dummyValues.gulpIf.name; expect(instance.gulpIf).toEqual(dummyValues.gulpIf.name); instance.gulpIf = null; expect(instance.gulpIf).toEqual(require(dummyValues.gulpIf.module)); instance.gulpStreamify = dummyValues.gulpStreamify.name; expect(instance.gulpStreamify).toEqual(dummyValues.gulpStreamify.name); instance.gulpStreamify = null; expect(instance.gulpStreamify).toEqual(require(dummyValues.gulpStreamify.module)); instance.gulpUglify = dummyValues.gulpUglify.name; expect(instance.gulpUglify).toEqual(dummyValues.gulpUglify.name); instance.gulpUglify = null; expect(instance.gulpUglify).toEqual(require(dummyValues.gulpUglify.module)); instance.gulpJSCS = dummyValues.gulpJSCS.name; expect(instance.gulpJSCS).toEqual(dummyValues.gulpJSCS.name); instance.gulpJSCS = null; expect(instance.gulpJSCS).toEqual(require(dummyValues.gulpJSCS.module)); instance.gulpESLint = dummyValues.gulpESLint.name; expect(instance.gulpESLint).toEqual(dummyValues.gulpESLint.name); instance.gulpESLint = null; expect(instance.gulpESLint).toEqual(require(dummyValues.gulpESLint.module)); instance.esdoc = dummyValues.esdoc.name; expect(instance.esdoc).toEqual(dummyValues.esdoc.name); instance.esdoc = null; expect(instance.esdoc).toEqual(require(dummyValues.esdoc.module)); instance.esdocPublisher = dummyValues.esdocPublisher.name; expect(instance.esdocPublisher).toEqual(dummyValues.esdocPublisher.name); instance.esdocPublisher = null; expect(instance.esdocPublisher).toEqual(require(dummyValues.esdocPublisher.module)); instance.esdocUploader = dummyValues.esdocUploader.name; expect(instance.esdocUploader).toEqual(dummyValues.esdocUploader.name); instance.esdocUploader = null; expect(instance.esdocUploader).toEqual(require(dummyValues.esdocUploader.module).default); instance.jest = dummyValues.jest.name; expect(instance.jest).toEqual(dummyValues.jest.name); instance.jest = null; expect(instance.jest).toEqual(require(dummyValues.jest.module)); instance.through = dummyValues.through.name; expect(instance.through).toEqual(dummyValues.through.name); instance.through = null; expect(instance.through).toEqual(require(dummyValues.through.module)); }); /** * @test {Bundlerify#tasks} */ it('should register the basic tasks', () => { const mockGulp = jest.genMockFromModule('gulp'); const mockFunc = jest.genMockFunction(); const mockRimRaf = jest.genMockFromModule('rimraf'); const instance = new Bundlerify(mockGulp, { tasks: { docs: false, lint: { deps: ['dep1', 'dep2'], method: () => {}, }, }, }); instance.rimraf = mockRimRaf; expect(instance.tasks()).toEqual(instance); const tasksCalls = mockGulp.task.mock.calls; const tasksNames = Object.keys(instance.config.tasks); for (let i = 0; i < (tasksNames.length - 1); i++) { expect(tasksCalls[i][0]).toEqual(tasksNames[i]); } expect(tasksCalls.length).toEqual(tasksNames.length - 1); const cleanTask = mockGulp.task.mock.calls[3]; cleanTask[2](() => {}); expect(mockRimRaf.mock.calls.length).toEqual(1); expect(mockRimRaf.mock.calls[0][0]).toEqual(instance.config.dist.dir); expect(mockRimRaf.mock.calls[0][1]).toEqual(jasmine.any(Function)); }); /** * @test {Bundlerify#tasks} */ it('should overwrite the basic tasks settings', () => { const mockGulp = jest.genMockFromModule('gulp'); const mockBuildFunc = jest.genMockFunction(); const mockRimRaf = jest.genMockFromModule('rimraf'); const instance = new Bundlerify(mockGulp, { tasks: { build: { deps: ['dep1', 'dep2'], method: mockBuildFunc, }, clean: { name: 'removeEverything', }, }, }); instance.rimraf = mockRimRaf; expect(instance.tasks()).toEqual(instance); const tasksLength = Object.keys(instance.config.tasks).length; expect(mockGulp.task.mock.calls.length).toEqual(tasksLength); const buildTask = mockGulp.task.mock.calls[0]; buildTask[2](() => {}); expect(mockBuildFunc.mock.calls.length).toEqual(1); expect(mockBuildFunc.mock.calls[0][0]).toEqual(jasmine.any(Function)); expect(mockBuildFunc.mock.calls[0][1]).toEqual(jasmine.any(Function)); const cleanTask = mockGulp.task.mock.calls[3]; cleanTask[2](() => {}); expect(mockRimRaf.mock.calls.length).toEqual(1); expect(mockRimRaf.mock.calls[0][0]).toEqual(instance.config.dist.dir); expect(mockRimRaf.mock.calls[0][1]).toEqual(jasmine.any(Function)); }); /** * @test {Bundlerify#clean} */ it('should run the clean task', () => { const mockRimRaf = jest.genMockFromModule('rimraf'); const mockBeforeTask = jest.genMockFunction(); const instance = new Bundlerify(gulp, { beforeTask: mockBeforeTask, tasks: { clean: { deps: ['randomDep'], }, }, }); instance.rimraf = mockRimRaf; instance.clean(() => {}); expect(mockRimRaf.mock.calls.length).toEqual(1); expect(mockRimRaf.mock.calls[0][0]).toEqual(instance.config.dist.dir); expect(mockRimRaf.mock.calls[0][1]).toEqual(jasmine.any(Function)); expect(mockBeforeTask.mock.calls.length).toEqual(1); expect(mockBeforeTask.mock.calls[0][0]).toEqual('clean'); expect(mockBeforeTask.mock.calls[0][1]).toEqual(instance); }); /** * @test {Bundlerify#cleanEs5} */ it('should run the cleanEs5 task', () => { const mockRimRaf = jest.genMockFromModule('rimraf'); const mockBeforeTask = jest.genMockFunction(); const instance = new Bundlerify(gulp, { beforeTask: mockBeforeTask, tasks: { cleanEs5: { name: 'cleanEs5Directory', }, }, }); instance.rimraf = mockRimRaf; instance.cleanEs5(() => {}); expect(mockRimRaf.mock.calls.length).toEqual(1); expect(mockRimRaf.mock.calls[0][0]).toEqual(instance.config.es5.dir); expect(mockRimRaf.mock.calls[0][1]).toEqual(jasmine.any(Function)); expect(mockBeforeTask.mock.calls.length).toEqual(1); expect(mockBeforeTask.mock.calls[0][0]).toEqual('cleanEs5Directory'); expect(mockBeforeTask.mock.calls[0][1]).toEqual(instance); }); /** * @test {Bundlerify#lint} */ it('should run the lint task', () => { const mockGulp = new BrowserifyMock(); const mockBeforeTask = jest.genMockFunction(); const mockGulpIf = jest.genMockFromModule('gulp-if'); const mockGulpESLint = jest.genMockFromModule('gulp-eslint'); const mockGulpJSCS = jest.genMockFromModule('gulp-jscs'); const instance = new Bundlerify(mockGulp, { beforeTask: mockBeforeTask, tasks: { lint: 'linter', }, }); instance.gulpIf = mockGulpIf; instance.gulpJSCS = mockGulpJSCS; instance.gulpESLint = mockGulpESLint; instance.lint(); expect(mockGulp.srcMock.mock.calls.length).toEqual(1); expect(mockGulp.pipeMock.mock.calls.length).toEqual(3); expect(mockGulpIf.mock.calls.length).toEqual(3); expect(mockGulpESLint.mock.calls.length).toEqual(1); expect(mockGulpESLint.format.mock.calls.length).toEqual(1); expect(mockGulpJSCS.mock.calls.length).toEqual(1); expect(mockBeforeTask.mock.calls.length).toEqual(1); expect(mockBeforeTask.mock.calls[0][0]).toEqual('lint'); expect(mockBeforeTask.mock.calls[0][1]).toEqual(instance); }); /** * @test {Bundlerify#test} */ it('should run the test task', () => { const mockGulp = new BrowserifyMock(); const mockThrough = jest.genMockFromModule('through2'); const mockJest = jest.genMockFromModule('jest-cli'); const mockGulpUtil = jest.genMockFromModule('gulp-util'); const mockSuccess = jest.genMockFunction(); const instance = new Bundlerify(mockGulp); instance.through = mockThrough; instance.jest = mockJest; instance.gulpUtil = mockGulpUtil; console.log = jasmine.createSpy('log'); instance.test(); expect(mockGulp.srcMock.mock.calls.length).toEqual(1); expect(mockGulp.pipeMock.mock.calls.length).toEqual(1); mockThrough.obj.mock.calls[0][0]({ path: 'abc', }, true, mockSuccess); mockJest.runCLI.mock.calls[0][2](false); expect(console.log).toHaveBeenCalled(); mockJest.runCLI.mock.calls[0][2](true); console.log = originalConsoleLog; }); /** * @test {Bundlerify#docs} */ it('should run the docs task', () => { const mockESDoc = jest.genMockFromModule('esdoc'); const mockBeforeTask = jest.genMockFunction(); const instance = new Bundlerify(gulp, { beforeTask: mockBeforeTask, tasks: { docs: { name: 'documentation', }, }, }); instance.esdoc = mockESDoc; instance.docs(); expect(mockESDoc.generate.mock.calls.length).toEqual(1); expect(mockESDoc.generate.mock.calls[0][0]).toEqual(instance.config.esdocOptions); expect(mockESDoc.generate.mock.calls[0][1]).toEqual(jasmine.any(Function)); expect(mockBeforeTask.mock.calls.length).toEqual(1); expect(mockBeforeTask.mock.calls[0][0]).toEqual('documentation'); expect(mockBeforeTask.mock.calls[0][1]).toEqual(instance); }); /** * @test {Bundlerify#uploadDocs} */ it('should run the uploadDocs task', () => { const mockBeforeTask = jest.genMockFunction(); const mockCallback = jest.genMockFunction(); const instance = new Bundlerify(gulp, { beforeTask: mockBeforeTask, }); instance.esdocUploader = ESDocUploaderMock; const mockUploader = // Successful upload instance.uploadDocs(mockCallback); expect(ESDocUploaderMockObjs.uploadMock.mock.calls.length).toEqual(1); ESDocUploaderMockObjs.uploadMock.mock.calls[0][0](); expect(mockCallback.mock.calls.length).toEqual(1); // Failed upload ESDocUploaderMockObjs.canUploadReturn = false; instance.uploadDocs(mockCallback); expect(ESDocUploaderMockObjs.uploadMock.mock.calls.length).toEqual(1); // Successful upload without a callback ESDocUploaderMockObjs.canUploadReturn = true; instance.uploadDocs(); expect(ESDocUploaderMockObjs.uploadMock.mock.calls.length).toEqual(2); expect(ESDocUploaderMockObjs.uploadMock.mock.calls[1][0]).toEqual(jasmine.any(Function)); ESDocUploaderMockObjs.uploadMock.mock.calls[1][0](); expect(mockBeforeTask.mock.calls.length).toEqual(3); expect(mockBeforeTask.mock.calls[0][0]).toEqual('uploadDocs'); expect(mockBeforeTask.mock.calls[0][1]).toEqual(instance); }); /** * @test {Bundlerify#build} */ it('should run the build task', () => { const mockBrowserify = new BrowserifyMock(); const mockGulp = jest.genMockFromModule('gulp'); const mockBabelify = jest.genMockFromModule('babelify'); const mockSource = jest.genMockFromModule('vinyl-source-stream'); const mockGulpIf = jest.genMockFromModule('gulp-if'); const mockBrowserSync = jest.genMockFromModule('browser-sync'); const mockUglify = jest.genMockFromModule('gulp-uglify'); const mockStreamify = jest.genMockFromModule('gulp-streamify'); const mockGulpUtil = jest.genMockFromModule('gulp-util'); const mockPolyfill = jest.genMockFunction(); const instance = new Bundlerify(mockGulp, { polyfillsEnabled: true, polyfills: [ mockPolyfill, 'whatwg-fetch/fetch', 'core-js/fn/symbol', 'core-js/fn/promise', ], }); instance.browserify = mockBrowserify.browserify.bind(mockBrowserify); instance.babelify = mockBabelify; instance.vinylSourceStream = mockSource; instance.gulpIf = mockGulpIf; instance.browserSync = mockBrowserSync; instance.ugflifier = mockUglify; instance.gulpStreamify = mockStreamify; instance.gulpUtil = mockGulpUtil; instance.build(); const browserifyCall = mockBrowserify.mainMock.mock.calls[0]; expect(browserifyCall[0].length).toEqual(5); expect(browserifyCall[0][4]).toEqual(instance.config.mainFile); expect(browserifyCall[1]).toEqual({ debug: true, fullPaths: false, cache: {}, packageCache: {}, }); expect(mockBrowserify.transformMock.mock.calls.length).toEqual(1); const babelifyCall = mockBabelify.configure.mock.calls[0]; expect(babelifyCall[0]).toEqual(instance.config.babelifyOptions); expect(mockBrowserify.bundleMock.mock.calls.length).toEqual(1); const eventCall = mockBrowserify.eventsMock.mock.calls[0]; expect(eventCall[0]).toEqual('error'); expect(eventCall[1]).toEqual(jasmine.any(Function)); console.log = jasmine.createSpy('log'); eventCall[1](new Error('Random Error')); expect(mockGulpUtil.PluginError.mock.calls[0][0]).toEqual('gulp-bundlerify'); expect(mockGulpUtil.PluginError.mock.calls[0][1]).toEqual('Random Error'); expect(console.log).toHaveBeenCalled(); console.log = originalConsoleLog; expect(mockBrowserify.pipeMock.mock.calls.length).toEqual(4); expect(mockSource.mock.calls.length).toEqual(1); expect(mockSource.mock.calls[0][0]).toEqual(instance.config.dist.file); expect(mockGulpIf.mock.calls.length).toEqual(1); expect(mockGulpIf.mock.calls[0][0]).toEqual(instance.config.uglify); expect(mockStreamify.mock.calls.length).toEqual(1); expect(mockGulp.dest.mock.calls[0][0]).toEqual(instance.config.dist.dir); expect(mockBrowserSync.reload.mock.calls.length).toEqual(1); expect(mockBrowserSync.reload.mock.calls[0][0]).toEqual(jasmine.any(Object)); instance.build(); }); /** * @test {Bundlerify#es5} */ it('should run the es5 task', () => { const mockGulp = new BrowserifyMock(); const mockTransform = jest.genMockFromModule('vinyl-transform'); const mockBabelify = jest.genMockFromModule('babelify'); const mockSource = jest.genMockFromModule('vinyl-source-stream'); const mockGulpIf = jest.genMockFromModule('gulp-if'); const mockUglify = jest.genMockFromModule('gulp-uglify'); const mockStreamify = jest.genMockFromModule('gulp-streamify'); const instance = new Bundlerify(mockGulp, { uglify: true, }); instance.babelify = mockBabelify; instance.vinylTransform = mockTransform; instance.vinylSourceStream = mockSource; instance.gulpIf = mockGulpIf; instance.ugflifier = mockUglify; instance.gulpStreamify = mockStreamify; instance.es5(); expect(mockGulp.srcMock.mock.calls.length).toEqual(1); expect(mockGulp.pipeMock.mock.calls.length).toEqual(3); expect(mockGulpIf.mock.calls.length).toEqual(1); expect(mockGulpIf.mock.calls[0][0]).toEqual(instance.config.uglify); expect(mockStreamify.mock.calls.length).toEqual(1); expect(mockGulp.destMock.mock.calls[0][0]).toEqual(instance.config.es5.dir); }); /** * @test {Bundlerify#serve} */ it('should run the serve task', () => { const mockBrowserify = new BrowserifyMock(); const mockGulp = jest.genMockFromModule('gulp'); const mockBabelify = jest.genMockFromModule('babelify'); const mockSource = jest.genMockFromModule('vinyl-source-stream'); const mockGulpIf = jest.genMockFromModule('gulp-if'); const mockBrowserSync = jest.genMockFromModule('browser-sync'); const mockUglify = jest.genMockFromModule('gulp-uglify'); const mockStreamify = jest.genMockFromModule('gulp-streamify'); const instance = new Bundlerify(mockGulp); instance.browserify = mockBrowserify.browserify.bind(mockBrowserify); instance.babelify = mockBabelify; instance.vinylSourceStream = mockSource; instance.gulpIf = mockGulpIf; instance.browserSync = mockBrowserSync; instance.ugflifier = mockUglify; instance.gulpStreamify = mockStreamify; instance.watchify = mockBrowserify.watchify.bind(mockBrowserify); instance.serve(); expect(mockBrowserSync.mock.calls.length).toEqual(1); expect(mockBrowserSync.mock.calls[0][0]).toEqual(instance.config.browserSyncOptions); const browserifyCall = mockBrowserify.mainMock.mock.calls[0]; expect(browserifyCall[0]).toEqual([instance.config.mainFile]); expect(browserifyCall[1]).toEqual({ debug: true, fullPaths: false, }); expect(mockBrowserify.watchifyMock.mock.calls.length).toEqual(1); expect(mockBrowserify.watchifyMock.mock.calls[0][0]).toEqual(mockBrowserify); expect(mockBrowserify.transformMock.mock.calls.length).toEqual(1); const babelifyCall = mockBabelify.configure.mock.calls[0]; expect(babelifyCall[0]).toEqual(instance.config.babelifyOptions); expect(mockBrowserify.bundleMock.mock.calls.length).toEqual(1); const eventCalls = mockBrowserify.eventsMock.mock.calls; expect(eventCalls[0][0]).toEqual('update'); expect(eventCalls[0][1]).toEqual(jasmine.any(Function)); expect(eventCalls[1][0]).toEqual('error'); expect(eventCalls[1][1]).toEqual(jasmine.any(Function)); expect(mockBrowserify.pipeMock.mock.calls.length).toEqual(4); expect(mockSource.mock.calls.length).toEqual(1); expect(mockSource.mock.calls[0][0]).toEqual(instance.config.dist.file); expect(mockGulpIf.mock.calls.length).toEqual(1); expect(mockGulpIf.mock.calls[0][0]).toEqual(instance.config.uglify); expect(mockStreamify.mock.calls.length).toEqual(1); expect(mockGulp.dest.mock.calls[0][0]).toEqual(instance.config.dist.dir); expect(mockBrowserSync.reload.mock.calls.length).toEqual(1); expect(mockBrowserSync.reload.mock.calls[0][0]).toEqual(jasmine.any(Object)); }); });
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var Character = require('./Character.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var EventSystem = require('../pubsub.js'); var utils = require('../utils.js'); var WaterCan = require('../objects/WaterCan.js'); module.exports = Agent; Agent.prototype = Object.create(Character.prototype); Agent.prototype.constructor = Agent; /* * The super class for agent objects. * (See Panda for sub classing template) * * In a subclass, set up the following: * <SubAgent>.prototype.id = string, for reference in LANG files. * <SubAgent>.prototype.agentName = string, name of the agent. * this.coords * * The subagent's sprite atlas and audio should be loaded in the boot state. * The sprite atlas should be named the same as the id of the subagent. * It should at least have the following: arm, leg, body, eye, * mouth0 (neutral), mouth1 (open), mouth2 (happy), mouth3 (sad) * * @param {Object} game - A reference to the Phaser game. * @return {Object} Itself */ function Agent (game) { Character.call(this, game); // Parent constructor. this.coords = this.coords || {}; this.coords.anim = { arm: { origin: -0.8, wave: { from: -0.1, to: 0.2, durUp: 0.3, dur: 0.2 }, pump: { angle: 0.5, move: 50, durUp: 0.5, dur: 0.25 }, water: { angle: 0, back: -2, canAngle: -0.5, durBack: 0.2, durUp: 0.5, durCan: 0.5 } } }; this.leftArm = this.game.add.group(this); this.leftArm.x = this.coords.arm.left.x; this.leftArm.y = this.coords.arm.left.y; this.leftArm.rotation = this.coords.anim.arm.origin; this.leftArm.create(0, 0, this.id, 'arm').anchor.set(1, 0.5); this.rightArm = this.game.add.group(this); this.rightArm.x = this.coords.arm.right.x; this.rightArm.y = this.coords.arm.right.y; this.rightArm.rotation = -this.coords.anim.arm.origin; var rightarm = this.rightArm.create(0, 0, this.id, 'arm'); rightarm.anchor.set(1, 0.5); rightarm.scale.x = -1; this.leftLeg = this.game.add.group(this); this.leftLeg.x = this.coords.leg.left.x; this.leftLeg.y = this.coords.leg.left.y; this.leftLeg.create(0, 0, this.id, 'leg').anchor.set(0.5, 0); this.rightLeg = this.game.add.group(this); this.rightLeg.x = this.coords.leg.right.x; this.rightLeg.y = this.coords.leg.right.y; var rightleg = this.rightLeg.create(0, 0, this.id, 'leg'); rightleg.anchor.set(0.5, 0); rightleg.scale.x = -1; this.body = this.create(0, 0, this.id, 'body'); this.body.anchor.set(0.5); this.leftEye = this.create(this.coords.eye.left.x, this.coords.eye.left.y, this.id, 'eye'); this.leftEye.anchor.set(0.5); this.rightEye = this.create(this.coords.eye.right.x, this.coords.eye.right.y, this.id, 'eye'); this.rightEye.anchor.set(0.5); this.mouth = this.create(this.coords.mouth.x, this.coords.mouth.y, this.id, 'mouth0'); this.mouth.anchor.set(0.5, 0); /* Character animations */ var mouthNeutral = this.mouth.frame; this.talk = TweenMax.fromTo(this.mouth, 0.2, { frame: mouthNeutral }, { frame: mouthNeutral + 1, roundProps: 'frame', ease: Power0.easeInOut, repeat: -1, yoyo: true, paused: true }); this.walk = new TimelineMax({ repeat: -1, paused: true }) .to(this.leftLeg, 0.12, { y: '-=50' , ease: Power1.easeInOut, yoyo: true, repeat: 1 }, 0) .to(this.rightLeg, 0.12, { y: '-=50' , ease: Power1.easeInOut, yoyo: true, repeat: 1 }, 0.24); /* Create the speech audio sheet. */ this.speech = utils.createAudioSheet(this.id + 'Speech', LANG.SPEECH[this.id].markers); /* Save the progress of the player for AI purposes */ var _this = this; var currentMode = null; this.playerCorrect = 0; this.playerWrong = 0; this.playerGuesses = []; this.lastGuess = null; EventSystem.subscribe(GLOBAL.EVENT.subgameStarted, function () { _this.playerCorrect = 0; _this.playerWrong = 0; _this.playerGuesses = []; }); EventSystem.subscribe(GLOBAL.EVENT.modeChange, function (mode) { currentMode = mode; }); EventSystem.subscribe(GLOBAL.EVENT.tryNumber, function (guess, correct) { if (currentMode === GLOBAL.MODE.playerDo || currentMode === GLOBAL.MODE.playerShow) { _this.playerGuesses.push([guess, correct]); if (guess === correct) { _this.playerCorrect++; } else { _this.playerWrong++; } } }); return this; } /** * @property {number} tint - The tint of the agent. */ Object.defineProperty(Agent.prototype, 'tint', { get: function() { return this.body.tint; }, set: function(value) { this.body.tint = value; this.leftArm.children[0].tint = value; this.rightArm.children[0].tint = value; this.leftLeg.children[0].tint = value; this.rightLeg.children[0].tint = value; } }); /** * @property {number} percentWrong - The minimum chance of an agent picking wrong number. */ Agent.prototype.percentWrong = 0.3; /** * Have the agent guess a number. * NOTE: This can be overwritten by other AI. * Variables that are available: * this.playerGuesses [[guess, correct], ...]. * this.playerCorrect Number of correct guesses by the player. * this.playerWrong Number of incorrect guesses by the player. * @param {number} correct - The correct number. * @param {number} min - Minimum value to guess. * @param {number} max - Maximum value to guess. * @returns {number} The agent's guess. */ Agent.prototype.guessing = function (correct, min, max) { var perc = 1; if (this.playerWrong > 0) { perc = Math.random(); } // Guessing correct is relative to how many wrongs you have made. // There is also always a small chance for the agent to be wrong. var guess; if (perc >= (this.playerWrong / this.playerGuesses.length) && Math.random() > this.percentWrong) { guess = correct; } else { do { guess = this.game.rnd.integerInRange(min, max); } while (guess === correct && (min < correct || correct < max)); } return guess; }; /** * Have the agent guess a number * Publishes agentGuess event. * @param {number} correct - The correct number. * @param {number} min - Minimum value to guess. * @param {number} max - Maximum value to guess. * @returns {number} The agent's guess (also available in this.lastGuess). */ Agent.prototype.guessNumber = function (correct, min, max) { this.lastGuess = this.guessing(correct, min, max); EventSystem.publish(GLOBAL.EVENT.agentGuess, [this.lastGuess, correct]); return this.lastGuess; }; /** * Set the agent to neutral state. */ Agent.prototype.setNeutral = function () { this.mouth.frameName = 'mouth0'; }; /** * Set the agent to happy state. */ Agent.prototype.setHappy = function () { this.mouth.frameName = 'mouth2'; }; /** * Set the agent to sad state. */ Agent.prototype.setSad = function () { this.mouth.frameName = 'mouth3'; }; /** * Add a thought bubble to the agent. Must be called to use the "think" function. * @param {number} representation - The representation of the guess. * @param {boolean} right - If the thought bubble should be to the right instead of left (default false). */ Agent.prototype.addThought = function (representation, right) { Character.prototype.addThought.call(this, right ? 550 : -550, -475, representation, right); this.thought.toScale = 2; }; /** * Animation: Think about the guessed number! * NOTE: The addThought must have been called before this function. * @param {boolean} sielnt - If the agent should be silent while thinking (optional). * @returns {Object} The animation timeline. */ Agent.prototype.think = function (silent) { if (typeof this.thought === 'undefined' || this.thought === null) { return; } var t = Character.prototype.think.call(this); t.addCallback(function () { this.thought.guess.number = this.lastGuess; }, 0, null, this); if (!silent) { t.addSound(this.speech, this, 'hmm', 0); // TODO: Sound should be based on confidence t.addSound(this.speech, this, this.game.rnd.pick(['isThisRight', 'itItThisOne', 'hasToBeThis'])); } return t; }; /** * Animation: Pump it up yeah! * @param {number} duration - Duration in seconds (default 3). * @param {number} arm - -1 = left arm, 0 = both, 1 = right arm (default 0). * @returns {Object} The animation timeline. */ Agent.prototype.fistPump = function (duration, arm) { duration = duration || 3; arm = arm || 0; var origin = this.coords.anim.arm.origin; var pump = this.coords.anim.arm.pump; var upDown = duration / 4; if (upDown > pump.durUp) { upDown = pump.durUp; } var times = TweenMax.prototype.calcYoyo(duration - upDown * 2, pump.dur); var t = new TimelineMax(); if (arm <= 0) { t.add(new TweenMax(this.leftArm, upDown, { rotation: pump.angle, ease: Power1.easeIn }), 0); t.add(new TweenMax(this.leftArm, pump.dur, { x: '+=' + pump.move, y: '+=' + pump.move, ease: Power1.easeIn, repeat: times, yoyo: true }), 0); t.add(new TweenMax(this.leftArm, upDown, { rotation: origin, ease: Power1.easeOut }), pump.dur * times); } if (arm >= 0) { t.add(new TweenMax(this.rightArm, upDown, { rotation: -pump.angle, ease: Power1.easeIn }), 0); t.add(new TweenMax(this.rightArm, pump.dur, { x: '-=' + pump.move, y: '+=' + pump.move, ease: Power1.easeIn, repeat: times, yoyo: true }), 0); t.add(new TweenMax(this.rightArm, upDown, { rotation: -origin, ease: Power1.easeOut }), pump.dur * times); } return t; }; /** * Animation: Put you hand up in the air and wave it around like you care. * @param {number} duration - Duration in seconds (default 3). * @param {number} arm - -1 = left arm, 0 = both, 1 = right arm (default 0). * @returns {Object} The animation timeline. */ Agent.prototype.wave = function (duration, arm) { duration = duration || 3; arm = arm || 0; var origin = this.coords.anim.arm.origin; var wave = this.coords.anim.arm.wave; var upDown = duration / 4; if (upDown > wave.durUp) { upDown = wave.durUp; } var times = parseInt((duration - upDown * 2) / wave.dur); times += (times % 2 === 0) ? 1 : 0; // Even numbers do not loop back to origin. var t = new TimelineMax(); if (arm <= 0) { t.add(new TweenMax(this.leftArm, upDown, { rotation: wave.from, ease: Power1.easeIn }), 0); t.add(new TweenMax(this.leftArm, wave.dur, { rotation: wave.to, ease: Power0.easeOut, repeat: times, yoyo: true }), upDown); t.add(new TweenMax(this.leftArm, upDown, { rotation: origin, ease: Power1.easeOut }), wave.dur * times + upDown); } if (arm >= 0) { t.add(new TweenMax(this.rightArm, upDown, { rotation: -wave.from, ease: Power1.easeIn }), 0); t.add(new TweenMax(this.rightArm, wave.dur, { rotation: -wave.to, ease: Power0.easeOut, repeat: times, yoyo: true }), upDown); t.add(new TweenMax(this.rightArm, upDown, { rotation: -origin, ease: Power1.easeOut }), wave.dur * times + upDown); } return t; }; /** * Animation: Water with a water can. * @param {number} duration - Duration in seconds (default 3). * @param {number} arm - 1 < left arm, otherwise right arm (default 0). * @returns {Object} The animation timeline. */ Agent.prototype.water = function (duration, arm) { duration = duration || 3; arm = arm || 0; var obj, dir; if (arm < 1) { obj = this.leftArm; dir = 1; } else { obj = this.rightArm; dir = -1; } var w = new WaterCan(this.game, -obj.children[0].width + dir * 60, -100); w.scale.set(-dir * 3, 3); w.rotation = 0; w.visible = false; obj.add(w); var t = new TimelineMax(); var water = this.coords.anim.arm.water; t.add(new TweenMax(obj, water.durBack, { rotation: dir * water.back, ease: Power1.easeIn })); t.addCallback(function () { w.visible = true; }); t.add(new TweenMax(obj, water.durUp, { rotation: dir * water.angle, ease: Power1.easeOut })); t.add(new TweenMax(w, water.durCan, { rotation: dir * water.canAngle })); t.addCallback(this.eyesFollowObject, null, [w.can], this); t.addLabel('watering'); t.add(w.pour(duration)); t.addCallback(this.eyesStopFollow, null, null, this); t.add(new TweenMax(obj, water.durUp, { rotation: dir * water.back, ease: Power1.easeIn })); t.addCallback(function () { w.destroy(); }); t.add(new TweenMax(obj, water.durBack, { rotation: dir * this.coords.anim.arm.origin, ease: Power1.easeOut })); return t; }; /** * Have an eye follow a target. * @param {Object} eye - The eye to follow with. * @param {Object} targ - The target to follow. * @private */ Agent.prototype._eyeFollow = function (eye, targ) { var origin = { x: eye.x, y: eye.y }; var depth = this.coords.eye.depth; var maxMove = this.coords.eye.maxMove; var agent = this; /* Update functions trigger on every game loop */ eye.update = function () { if (!agent.visible) { return; } var o = this.world; var a = this.game.physics.arcade.angleBetween(o, targ.world ? targ.world : targ); var d = this.game.physics.arcade.distanceBetween(o, targ.world ? targ.world : targ) / depth; if (d > maxMove) { d = maxMove; } this.x = Math.cos(a) * d + origin.x; this.y = Math.sin(a) * d + origin.y; }; }; /** * Make the agent's eyes follow an object. * @param {Object} targ - The target to follow */ Agent.prototype.eyesFollowObject = function (targ) { this.eyesStopFollow(); this._eyeFollow(this.leftEye, targ); this._eyeFollow(this.rightEye, targ); }; /** * Make the agent's eyes follow the input pointer. */ Agent.prototype.eyesFollowPointer = function () { this.eyesFollowObject(this.game.input.activePointer); }; /** * Stop the eyes following pointer or object. */ Agent.prototype.eyesStopFollow = function () { this.leftEye.x = this.coords.eye.left.x; this.leftEye.y = this.coords.eye.left.y; this.rightEye.x = this.coords.eye.right.x; this.rightEye.y = this.coords.eye.right.y; this.leftEye.update = function () {}; this.rightEye.update = function () {}; }; },{"../global.js":8,"../language.js":9,"../objects/WaterCan.js":21,"../pubsub.js":34,"../utils.js":48,"./Character.js":2}],2:[function(require,module,exports){ var NumberButton = require('../objects/buttons/NumberButton.js'); var GLOBAL = require('../global.js'); var utils = require('../utils.js'); module.exports = Character; Character.prototype = Object.create(Phaser.Group.prototype); Character.prototype.constructor = Character; /** * Superclass for characters. * @param {Object} game - A reference to the Phaser game. */ function Character (game) { Phaser.Group.call(this, game, null); // Parent constructor. } /** * When you want a sound to be said by a character. * NOTE: If the character has a this.talk TweenMax or TimelineMax it will be used. * @param {string|Object} what - Key to a sound file or the sound object. * @param {string} marker - If you want the speaker to only talk during a specific marker. * @returns {Object} The sound object (not started). */ Character.prototype.say = function (what, marker) { var a = (typeof what === 'string') ? this.game.add.audio(what) : what; /* Check if character has a talk animation. */ if (this.talk) { var current; var signals = []; /* Functions to run on audio signals. */ var play = function () { if (a.currentMarker) { current = a.currentMarker; } if (!marker || current === marker) { this.talk.play(); } }; var pause = function () { if (!marker || current === marker) { this.talk.pause(0); } }; var stop = function () { if (!marker || current === marker) { this.talk.pause(0); while (signals.length > 0) { signals[0].detach(); signals[0]._destroy(); signals.splice(0, 1); } } }; signals.push(a.onPlay.add(play, this)); signals.push(a.onResume.add(play, this)); signals.push(a.onPause.add(pause, this)); signals.push(a.onStop.add(stop, this)); } return a; }; /** * Move a character. * NOTE: If this.turn property is true, it will turn according to direction. * NOTE: If the character has a this.walk TweenMax or TimelineMax it will be used. * @param {Object} properties - Properties to tween, set x and/or y to move. * @param {number} duration - Duration of the move. * @param {number} scale - If a scaling should happen during the move. * @returns {Object} The movement timeline. */ Character.prototype.move = function (properties, duration, scale) { properties.ease = properties.ease || Power1.easeInOut; var t = new TimelineMax(); t.to(this, duration, properties); /* Check if character has a walk animation. */ if (this.walk) { t.addCallback(function () { this.walk.play(); }, 0, null, this); t.addCallback(function () { this.walk.pause(0); }, '+=0', null, this); } /* Animate the scale if available. */ /* Scaling is also how we turn the character, so it gets a bit complicated later... */ var ts = null; if (scale) { ts = new TweenMax(this.scale, duration, { x: scale, y: scale, ease: properties.ease }); } /* Check if the character should be turned when moving. */ if (this.turn) { var _this = this; var turnDuration = 0.2; var percentDuration = turnDuration / duration; t.add(new TweenMax(this.scale, turnDuration, { ease: properties.ease, onStart: function () { // The turn tween needs to be updated in real time, // otherwise it won't work in Timelines. var prop = { x: Math.abs(_this.scale.x), y: Math.abs(_this.scale.y) }; // Check if we are scaling along with the movement. // In that case we scale the turning as well if (ts) { if (ts.vars.x > _this.scale.x) { // Scaling up prop.x += ts.vars.x * percentDuration; } else { // Scaling down prop.x -= ts.vars.x * percentDuration; } if (ts.vars.x > _this.scale.x) { // Scaling up prop.y += ts.vars.y * percentDuration; } else { // Scaling down prop.y -= ts.vars.y * percentDuration; } } // Set the scale direction // If we do not change x and we are looking left, keep doing it. if (typeof properties.x === 'undefined' || properties.x === null || _this.x === properties.x) { if (_this.scale.x < 0) { prop.x *= -1; } /* If we are going to a position to the left of the current, look left. */ } else if (properties.x < _this.x) { prop.x *= -1; } /* Update the turn tween with new values */ this.updateTo({ x: prop.x, y: prop.y }); /* Make sure that a scaling tween has the correct direction */ if (ts && prop.x < 0) { ts.updateTo({ x: -1 * ts.vars.x }); } } }), 0); if (ts) { /* Update the duration of scaling and add it. */ ts.duration(ts.duration() - turnDuration); t.add(ts, turnDuration); } } else if (ts) { /* No turning, just add the scaling. */ t.add(ts, 0); } return t; }; /** * Turn around! Every now and then I get a little bit lonely... * @param {number} direction - -1 = left, 1 = right, default: opposite of current. * NOTE: This only takes into account the state when the function is called. * Making a "opposite turn" inside a Timeline might not have the expected result. * @returns {Object} The turning tween. */ Character.prototype.moveTurn = function (direction) { // Turn by manipulating the scale. var newScale = (direction ? direction * Math.abs(this.scale.x) : -1 * this.scale.x); return new TweenMax(this.scale, 0.2, { x: newScale }); }; /** * Add a thought bubble to the agent. Must be called to use the "think" function. * NOTE: You can change the scale for the think function by setting the toScale property. * @param {number} x - The x position. * @param {number} y - The y position. * @param {number} representation - The representation of the guess. * @param {boolean} mirror - If the thought bubble should be to the right instead of left (default false). */ Character.prototype.addThought = function (x, y, representation, mirror) { this.thought = this.game.add.group(this); this.thought.x = x; this.thought.y = y; this.thought.visible = false; this.thought.toScale = 1; this.thought.bubble = this.thought.create(0, 0, 'objects', 'thought_bubble'); this.thought.bubble.scale.x = 1; this.thought.bubble.anchor.set(0.5); var options = { x: -60, y: -55, size: 100, disabled: true }; // Make sure that button background is correct according to method. if (this.game.state.getCurrentState().method === GLOBAL.METHOD.count || this.game.state.getCurrentState().method === GLOBAL.METHOD.incrementalSteps) { options.background = 'button'; } this.thought.guess = new NumberButton(this.game, 1, representation, options); this.thought.add(this.thought.guess); if (mirror) { this.mirrorThought(); } }; /** * Mirror the thought bubble 180 degrees horizontally. */ Character.prototype.mirrorThought = function () { this.thought.guess.x += (this.thought.guess.x > -60) ? -20 : 20; this.thought.bubble.scale.x *= -1; }; /** * Animation: Think about the guessed number! * NOTE: The addThought must have been called before this function. * @returns {Object} The animation timeline. */ Character.prototype.think = function () { if (typeof this.thought === 'undefined' || this.thought === null) { return; } var t = new TimelineMax(); t.addCallback(function () { this.thought.guess.visible = false; }, null, null, this); t.add(utils.fade(this.thought, true)); t.add(TweenMax.fromTo(this.thought.scale, 1.5, { x: 0, y: 0 }, { x: this.thought.toScale, y: this.thought.toScale, ease: Elastic.easeOut } ), 0); t.add(utils.fade(this.thought.guess, true, 1), 0.5); return t; }; },{"../global.js":8,"../objects/buttons/NumberButton.js":24,"../utils.js":48}],3:[function(require,module,exports){ var Agent = require('./Agent.js'); var LANG = require('../language.js'); module.exports = Hedgehog; Hedgehog.prototype = Object.create(Agent.prototype); Hedgehog.prototype.constructor = Hedgehog; Hedgehog.prototype.id = 'hedgehog'; // Reference for LANG files and asset files Hedgehog.prototype.agentName = LANG.TEXT.hedgehogName; /** * The hedgehog agent. * The asset files are loaded in the boot state using key: *.prototype.id. * @param {Object} game - A reference to the Phaser game. * @return Itself */ function Hedgehog (game) { this.coords = { arm: { left: { x: -100, y: -80 }, right: { x: 100, y: -80 } }, leg: { left: { x: -150, y: 300 }, right: { x: 150, y: 300 } }, eye: { left: { x: -53, y: -272 }, right: { x: 35, y: -272 }, depth: 20, maxMove: 7 }, mouth: { x: -6, y: -205 } }; Agent.call(this, game); // Call parent constructor. var leftEyeSocket = this.create(this.coords.eye.left.x + 1, this.coords.eye.left.y - 8, this.id, 'socket'); leftEyeSocket.anchor.set(0.5); this.bringToTop(this.leftEye); var rightEyeSocket = this.create(this.coords.eye.right.x - 1, this.coords.eye.right.y - 8, this.id, 'socket'); rightEyeSocket.anchor.set(0.5); rightEyeSocket.scale.set(-1, 1); this.bringToTop(this.rightEye); var nose = this.create(this.coords.mouth.x - 2, this.coords.mouth.y - 15, this.id, 'nose'); nose.anchor.set(0.5); var back = this.create(0, 0, this.id, 'back'); back.anchor.set(0.5); this.sendToBack(back); return this; } },{"../language.js":9,"./Agent.js":1}],4:[function(require,module,exports){ var Agent = require('./Agent.js'); var LANG = require('../language.js'); module.exports = Mouse; Mouse.prototype = Object.create(Agent.prototype); Mouse.prototype.constructor = Mouse; Mouse.prototype.id = 'mouse'; // Reference for LANG files and asset files Mouse.prototype.agentName = LANG.TEXT.mouseName; /** * The mouse agent. * The asset files are loaded in the boot state using key: *.prototype.id. * @param {Object} game - A reference to the Phaser game. * @return Itself */ function Mouse (game) { this.coords = { arm: { left: { x: -110, y: -40 }, right: { x: 110, y: -40 } }, leg: { left: { x: -150, y: 350 }, right: { x: 150, y: 350 } }, eye: { left: { x: -50, y: -240 }, right: { x: 50, y: -240 }, depth: 20, maxMove: 9 }, mouth: { x: 0, y: -150 } }; Agent.call(this, game); // Call parent constructor. var leftEyeSocket = this.create(this.coords.eye.left.x + 1, this.coords.eye.left.y - 8, this.id, 'socket'); leftEyeSocket.anchor.set(0.5); this.bringToTop(this.leftEye); var rightEyeSocket = this.create(this.coords.eye.right.x - 1, this.coords.eye.right.y - 8, this.id, 'socket'); rightEyeSocket.anchor.set(0.5); rightEyeSocket.scale.set(-1, 1); this.bringToTop(this.rightEye); var nose = this.create(this.coords.mouth.x - 1, this.coords.mouth.y - 17, this.id, 'nose'); nose.anchor.set(0.5); return this; } },{"../language.js":9,"./Agent.js":1}],5:[function(require,module,exports){ var Agent = require('./Agent.js'); var LANG = require('../language.js'); module.exports = Panda; Panda.prototype = Object.create(Agent.prototype); Panda.prototype.constructor = Panda; Panda.prototype.id = 'panda'; // Reference for LANG files and asset files Panda.prototype.agentName = LANG.TEXT.pandaName; /** * The panda agent. * The asset files are loaded in the boot state using key: *.prototype.id. * @param {Object} game - A reference to the Phaser game. * @return Itself */ function Panda (game) { this.coords = { arm: { left: { x: -150, y: -20 }, right: { x: 150, y: -20 } }, leg: { left: { x: -130, y: 320 }, right: { x: 130, y: 320 } }, eye: { left: { x: -65, y: -238 }, right: { x: 65, y: -238 }, depth: 20, maxMove: 9 }, mouth: { x: 0, y: -142 } }; Agent.call(this, game); // Call parent constructor. return this; } },{"../language.js":9,"./Agent.js":1}],6:[function(require,module,exports){ var GLOBAL = require('./global.js'); var EventSystem = require('./pubsub.js'); /** * Handles the communication with the backend. * The communication needs a Route object set, that object will tell where * to send the different get and post requests. * @global */ module.exports = { /** * @property {Object} _maxTries - Max tries to send requests. * @default * @private */ _maxTries: 10, /** * @property {Object} _rnd - A random data generator (we have no access to game object here). * @private */ _rnd: new Phaser.RandomDataGenerator(), /** * @property {Object} _previous - The previous scenario. * @private */ _previous: -1, /** * Basic ajax call. * Publishes connection event if ajax call fail. * @param {Object} settings - An object with settings to jQuery ajax call * @param {number} tries - Amount of times to resend if something goes wrong. * Default value is max tries. * NOTE: If server code is between 400 and 500 it will not retry. * @return {Array} A promise to the ajax request. * NOTE: This has a fail function set which will show connection lost. */ ajax: function (settings, tries) { if (isNaN(tries) || tries === null) { tries = this._maxTries; } tries--; var _this = this; return $.ajax(settings).fail(function (jqXHR) { if (jqXHR.status >= 400 && jqXHR.status < 500) { tries = 0; } if (tries > 0) { EventSystem.publish(GLOBAL.EVENT.connection, [false]); setTimeout(function () { _this.ajax(settings, tries); }, (_this._maxTries - tries) * 1000); } else { EventSystem.publish(GLOBAL.EVENT.connectionLost); } }); }, /** * GET request. * Publishes connection event when get is done. * NOTE: This request is sent synchronous. * @param {String} routeName - The name of the route function. * @param {*} parameters - optional parameters for the route action. * @return {Object} The object returned from the ajax request. **/ get: function (routeName, parameters) { var ret = null; if (typeof Routes !== 'undefined' && Routes[routeName]) { var settings = { url: Routes[routeName](parameters), async: false }; this.ajax(settings).done(function (data) { ret = data; EventSystem.publish(GLOBAL.EVENT.connection, [true]); }); } return ret; }, /** * POST data. * Publishes connection event when post is done. * @param {String} routeName - The name of the route function. * @param {Object} data - The data to send (will be transformed to JSON-format). */ post: function (routeName, data, callback) { /* We wrap the data in "magic" to make it easier to find at the server. */ var stringified = JSON.stringify({ magic: data }); if (typeof Routes !== 'undefined' && Routes[routeName]) { var settings = { url: Routes[routeName](), type: 'POST', dataType: 'json', contentType: 'application/json', data: stringified }; this.ajax(settings).done(function (data) { EventSystem.publish(GLOBAL.EVENT.connection, [true]); if (callback) { callback(data); } }); } else { /* This should only be used when in local mode. */ console.log('POST (' + routeName + '): ' + stringified); } }, /** * GET the data of the player. * @return {Object} An object with data about the player. */ getPlayer: function () { return this.get('current_api_players_path'); }, /** * GET the garden appearance. * @return {Object} An object with data about the garden. */ getGarden: function () { return this.get('current_api_gardens_path'); }, /** * GET the next game that should be played. * @return {Object} An object with data about the next game. */ getScenario: function () { var data = this.get('current_api_scenarios_path'); if (data) { // Setup subgame. First check if we should pick a random game. if (data.subgame === GLOBAL.STATE.random) { do { data.subgame = this._rnd.pick(GLOBAL.STATE.randomGames); } while (data.subgame === this._previous); } this._previous = data.subgame; // Representations are only one integer, but can include several representations. // Every position holds its own representation, see global.js for more info. var rep = []; while (data.representation >= 10) { rep.unshift(data.representation % 10); data.representation = Math.floor(data.representation/10); } rep.unshift(data.representation); data.representation = rep; // Add intro and outro for the game. data.mode.unshift(GLOBAL.MODE.intro); data.mode.push(GLOBAL.MODE.outro); } return data; }, /** * POST agent updates. * @param {Object} data - The agent updates. */ putAgent: function (data) { this.post('update_agent_api_players_path', data); }, /** * POST garden updates. * Publishes plantUpgrade event. * @param {Object} data - The garden updates. */ putUpgradePlant: function (data) { this.post('upgrade_field_api_gardens_path', data, function (data) { EventSystem.publish(GLOBAL.EVENT.plantUpgrade, [data]); }); }, /** * POST player session results. * @param {Object} data - The session results. */ putSession: function (data) { this.post('register_api_player_sessions_path', data); } }; },{"./global.js":8,"./pubsub.js":34}],7:[function(require,module,exports){ var GLOBAL = require('./global.js'); var Player = require('./player.js'); var Hedgehog = require('./agent/Hedgehog.js'); var Mouse = require('./agent/Mouse.js'); var Panda = require('./agent/Panda.js'); var BootState = require('./states/BootState.js'); var EntryState = require('./states/EntryState.js'); var AgentSetupState = require('./states/AgentSetupState.js'); var GardenState = require('./states/GardenState.js'); var BeachState = require('./states/BeachState.js'); var SharkGame = require('./states/subgames/SharkGame.js'); /*var LizardJungleGame = require('./states/subgames/LizardJungleGame.js'); var BirdheroGame = require('./states/subgames/BirdheroGame.js'); var BalloonGame = require('./states/subgames/BalloonGame.js');*/ var BeeFlightGame = require('./states/subgames/BeeFlightGame.js'); var ChooseScenarioState = require('./states/ChooseScenarioState.js'); require('./logger.js'); // Start logger require('./utils.js'); // Setup prototype functions. /** * This is the entrance point to the game. * This is where all the states/games are added. * BootState will run after this. */ window.onload = function () { // Only start game if the element to put it in exist. if (document.querySelector('#game')) { // If running locally we enter debug mode. if (window.location.hostname.toLowerCase() === 'localhost' || window.location.hostname === '127.0.0.1') { GLOBAL.debug = true; } // Create game object. var game = new Phaser.Game(1024, 768, Phaser.AUTO, 'game'); // Cache game object among GLOBALs, use this only if necessary. // TODO: This is not a pretty solution, but it becomes very complicated in utils otherwise. GLOBAL.game = game; /* Setup agent lookup globals */ GLOBAL.AGENT = { 0: Panda, 1: Hedgehog, 2: Mouse }; // Cache player object in the game object for easy access. game.player = new Player(game); // Setup game states. game.state.add('Boot', BootState); game.state.add(GLOBAL.STATE.entry, EntryState); game.state.add(GLOBAL.STATE.agentSetup, AgentSetupState); game.state.add(GLOBAL.STATE.garden, GardenState); game.state.add(GLOBAL.STATE.beach, BeachState); game.state.add(GLOBAL.STATE.sharkGame, SharkGame); /*game.state.add(GLOBAL.STATE.lizardGame, LizardJungleGame); game.state.add(GLOBAL.STATE.birdheroGame, BirdheroGame); game.state.add(GLOBAL.STATE.balloonGame, BalloonGame);*/ game.state.add(GLOBAL.STATE.beeGame, BeeFlightGame); game.state.add(GLOBAL.STATE.scenario, ChooseScenarioState); // Run the boot state. game.state.start('Boot'); } }; },{"./agent/Hedgehog.js":3,"./agent/Mouse.js":4,"./agent/Panda.js":5,"./global.js":8,"./logger.js":10,"./player.js":33,"./states/AgentSetupState.js":35,"./states/BeachState.js":36,"./states/BootState.js":37,"./states/ChooseScenarioState.js":38,"./states/EntryState.js":39,"./states/GardenState.js":40,"./states/subgames/BeeFlightGame.js":43,"./states/subgames/SharkGame.js":45,"./utils.js":48}],8:[function(require,module,exports){ /* Used for the publish-subscribe system */ exports.EVENT = { stateShutDown: 'stateShutDown', // [state] subgameStarted: 'subgameStarted', // [game type, session token] numbergameStarted: 'numbergameStarted', // [method, maxAmount, representation] modeChange: 'modeChange', // [new mode] tryNumber: 'tryNumber', // [guess, correct number] agentGuess: 'agentGuess', // [guess, correct number] numberPress: 'numberPress', // [number, representations] waterAdded: 'waterAdded', // [total amount, added amount] disabled: 'disabled', // [true/false] plantPress: 'plantPress', // [garden plant] waterPlant: 'waterPlant', // [garden plant] plantUpgrade: 'plantUpgrade', // [backend data] skippable: 'skippable', // [TimelineMax object] connection: 'connection', // [status] connectionLost: 'connectionLost' }; /* The different Phaser states, some are the subgames for scenarios */ exports.STATE = { entry: 'Entry', agentSetup: 'AgentSetup', garden: 'Garden', beach: 'Beach', 0: 'Lizard', lizardGame: 'Lizard', 1: 'Mountain', mountainGame: 'Mountain', 2: 'Birdhero', birdheroGame: 'Birdhero', 3: 'Balloon', balloonGame: 'Balloon', 4: 'BeeFlight', sharkGame: 'SharkGame', beeGame: 'BeeFlight', scenario: 'Scenario', random: 100, // Not an actual state. randomGames: [0, 2, 3, 4] // Not an actual state, it will randomly pick one in the array. }; exports.STATE_KEYS = null; // Used to clear a subgame, saved when subgame is booted. /* Method for scenario */ exports.METHOD = { count: 0, // All numbers displayed at the same time incrementalSteps: 1, // One number that you increment or decrement, ex: (- 1 +) addition: 2, // Start with one number and choose what to add subtraction: 3, // Start with one number and choose what to subtract additionSubtraction: 4 // Start with one number and choose what to add or subtract }; /* Number representation for scenario */ exports.NUMBER_REPRESENTATION = { none: 0, dots: 1, fingers: 2, strikes: 3, objects: 4, numbers: 5, dice: 6, mixed: 9, // Multiple representations will be formed as concatenations, such as: // fingers + dots = 21 // So if representations go above 10 there will be problems in Backend.js. yesno: 1000 // Special for yes/no: odd values = yes, even values = no }; exports.NUMBER_RANGE = { 0: 4, // Range 1-4 1: 9 // Range 1-9 }; /* The different modes of a subgame */ exports.MODE = { playerDo: 0, playerShow: 1, agentTry: 2, agentDo: 3, intro: 10, outro: 11 }; // Default button color. exports.BUTTON_COLOR = 0xc2a12d; // Font to use in the game. exports.FONT = 'Coming Soon'; },{}],9:[function(require,module,exports){ /** * This is the language variable for the game. * All text and speech files for the game should be here. * Text strings are in LANG.TEXT. * Speech sound files are in LANG.SPEECH. * For the agent, use LANG.SPEECH.AGENT. * * It was developed with switching languages in mind. * To do so use function LANG.change. * Swedish is the default language and should be used as a * template for other languages. * * NOTE: GLOBAL.FONT specifies which font that is used. * * *** A NOTE ABOUT AUDIO FILE SIZE *** * This project uses web audio, which in turn uses huge memory amounts. * This is a problem for our speech on devices with restricted memory. * I, Erik, have investigated how to lower this usage: * Has effect: * 1) Reducing the amount of channels, such as from stereo to mono. * 2) Removing unused speech. * 3) Never have any unused sound loaded in memory. * * Has NO effect: * 1) Reducing sample rate or bitrate (web audio decodes to 44100 32bit). * However, file size is reduced by this which gives faster loading times. * 2) Modifying format (same reason as previous). * However, some formats cannot be played on all devices, so backup is needed. * 3) Removing pauses (or at least has a very marginal effect). * * @global */ var LANG = {}; module.exports = LANG; /** * Change the language. * NOTE: A warning is set if text or speech are missing translations. * @param {Object} text - The text. * @param {Object} speech - The speech markers. */ LANG.change = function (text, speech, player) { function replacer (orig, plus, missing, prefix) { missing = missing || []; if (!prefix) { prefix = ''; } else { prefix += '/'; } for (var p in orig) { if (p === 'AGENT') { continue; } // AGENT is special case if (!plus.hasOwnProperty(p)) { missing.push(prefix + p); } else if (typeof orig[p] !== 'string') { replacer(orig[p], plus[p], missing, prefix + p); } else { orig[p] = plus[p]; } } return missing; } var m = replacer(LANG.TEXT, text); if (m.length > 0) { console.warn('TEXT is missing: ' + m); } m = replacer(LANG.SPEECH, speech); if (m.length > 0) { console.warn('SPEECH is missing: ' + m); } if (player && player.agent && player.agent.prototype.id) { LANG.setAgent(player.agent.prototype.id); } else { // Use panda as default agent. LANG.setAgent('panda'); } }; /** * Set the speech for the agent. * @param {Object} id - The id of the agent. */ LANG.setAgent = function (id) { LANG.SPEECH.AGENT = LANG.SPEECH[id]; }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Swedish language (default) */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ LANG.swedish = {}; LANG.swedish.text = { /* General */ ok: 'Ok', decoding: 'Snart klar...', // When decoding sound files connectionLost: 'Ingen anslutning', connectionLostMessage: 'Ajdå. Vi tappade anslutningen till servern.', /* Entry state */ title: 'Magical Garden', start: 'Starta!', continuePlaying: 'Fortsätt', changeAgent: 'Byt ut ', // Followed by agent name credits: 'Skapat av', anonymous: 'Anonym', logOut: 'Logga ut', /* Credits */ creditsMade: 'Detta spelet är skapat vid Lunds Universitet', creditsDeveloped: 'Idé och utformning', creditsProgramming: 'Programmering', creditsGraphics: 'Grafik', creditsVoices: 'Röster', creditsVoicePanda: 'Igis Gulz-Haake', creditsVoiceHedgehog: 'Agneta Gulz', creditsVoiceMouse: 'Sebastian Gulz-Haake', creditsVoiceWoodlouse: 'Igis Gulz-Haake', creditsVoiceLizard: 'Igis Gulz-Haake', creditsVoiceBumblebee: 'Agneta Gulz', creditsVoiceBird: 'Igis Gulz-Haake', creditsMusic: 'Musik', creditsSfx: 'Ljudeffekter', creditsThanks: 'Tack till', /* Garden state */ maxLevel: 'MAX!', /* Player setup state */ pickFriend: 'Vem vill du bli kompis med?', confirmFriend: 'Välj ', // Followed by agent name changeColor: 'Byt färg', /* Menu items */ menu: 'MENY', resume: 'Fortsätt', gotoGarden: 'Gå till trädgården', quit: 'Avsluta spelet', /* Agents and characters */ pandaName: 'Panders', hedgehogName: 'Igis', mouseName: 'Mille', woodlouseName: 'Grålle', lizardName: 'Kamilla', bumblebeeName: 'Humfrid', birdName: 'Fålia' }; LANG.swedish.speech = { /* Agent intro */ agentIntro: { speech: [ 'audio/agent/swedishIntro.m4a', 'audio/agent/swedishIntro.ogg', 'audio/agent/swedishIntro.mp3' ], markers: { pandaHello: [ 0.0, 1.7], pandaFunTogether: [ 2.8, 2.0], hedgehogHello: [ 5.7, 2.4], hedgehogFunTogether: [ 8.9, 3.0], mouseHello: [12.3, 1.7], mouseFunTogether: [14.4, 1.9] } }, /* Subgames */ birdhero: { speech: [ 'audio/subgames/birdhero/swedish.m4a', 'audio/subgames/birdhero/swedish.ogg', 'audio/subgames/birdhero/swedish.mp3' ], markers: { thisFloor: [ 0.2, 1.9], helpMeHome: [ 2.6, 2.0], dontLiveHere: [ 5.9, 1.7], notMyParent: [ 9.1, 2.3], higher: [13.0, 1.9], lower: [16.3, 1.8], thankYou: [19.7, 1.5], blownOut: [23.2, 7.8], countFeathers: [32.2, 3.3], pushButton: [37.0, 2.9], useMyself: [41.2, 2.5], howMuchHigher: [45.2, 2.0], howMuchLower: [48.3, 2.1], thinkItIs: [51.1, 2.8], higherOrLower: [55.6, 2.7] } }, balloongame: { speech: [ 'audio/subgames/balloongame/swedish.m4a', 'audio/subgames/balloongame/swedish.ogg', 'audio/subgames/balloongame/swedish.mp3' ], markers: { yippie1: [ 0.1, 1.3], yippie2: [ 2.2, 0.8], loveTreasures: [ 4.0, 1.6], helpToCave: [ 6.6, 4.4], lookAtMap: [ 12.0, 2.8], presetBalloons: [ 15.7, 3.4], guessBalloons: [ 20.4, 4.5], whatDoYouThink: [ 25.4, 0.6], canYouDrag: [ 27.1, 1.5], floor1: [ 29.6, 2.6], floor2: [ 33.1, 2.1], floor3: [ 36.3, 2.2], floor4: [ 39.7, 2.3], canYouDragRight:[ 43.3, 2.2], buttonSubtract: [ 46.9, 4.5], buttonAddSub: [ 53.0, 5.2], sameAsMap: [ 59.9, 3.0], whatButton: [ 64.2, 2.4], pushButton: [ 67.8, 5.7], pushAnchor: [ 74.8, 1.9], treasure1: [ 78.0, 1.6], treasure2: [ 80.2, 1.2], treasureBoot: [ 82.1, 2.9], newTreasure: [ 85.9, 0.7], helpMeGetThere: [ 87.7, 1.3], wrong1: [ 89.7, 1.4], wrong2: [ 92.0, 1.3], lower: [ 94.2, 1.7], higher: [ 96.9, 1.4], fullSack: [ 99.4, 4.6], thankYou: [104.7, 3.6] } }, sharkgame:{ speech: [ 'audio/subgames/sharkgame/swedish.mp3' ], markers:{ intro: [ 0.0, 12.5], shark: [ 12.5, 5.0], intro2: [ 23.0, 21.5], intro3: [ 45.0, 7.0], wrong: [ 53.0, 9.0], correct: [ 62.5, 9.0], agentIntro: [ 71.4, 8.0], watch: [ 80.0, 4.0], agentTry: [ 85.0, 5.0], try: [ 91.0, 5.0], guess: [ 97.0, 4.0], wrongGuess: [ 102.0, 4.0], win: [ 106.0, 11.0] } }, beeflight: { speech: [ 'audio/subgames/beeflight/swedish.m4a', 'audio/subgames/beeflight/swedish.ogg', 'audio/subgames/beeflight/swedish.mp3' ], markers: { slurp: [ 0.0, 2.0], okay: [ 2.5, 0.8], letsGo: [ 3.5, 1.2], order1: [ 5.5, 1.0], order2: [ 7.1, 1.1], order3: [ 8.7, 1.3], order4: [ 10.8, 1.2], order5: [ 12.9, 1.0], order6: [ 15.1, 1.0], order7: [ 17.2, 1.0], order8: [ 18.9, 1.5], order9: [ 21.1, 1.6], flower: [ 23.9, 1.3], number1: [ 25.9, 0.9], number2: [ 27.1, 0.9], number3: [ 28.7, 1.0], number4: [ 30.1, 1.0], number5: [ 31.6, 0.8], number6: [ 32.9, 0.6], number7: [ 34.1, 0.8], number8: [ 35.2, 1.1], number9: [ 36.7, 1.2], one: [ 38.6, 0.8], forward: [ 40.3, 0.8], backward: [ 42.2, 0.9], noNectar: [ 44.0, 5.4], tooFar: [ 50.4, 2.4], tooNear: [ 54.5, 4.2], wasBefore: [ 59.9, 3.6], nectar1: [ 64.6, 1.8], nectar2: [ 66.4, 2.0], goingBack: [ 69.5, 6.3], getMore: [ 76.5, 2.0], badSight: [ 79.8, 4.1], howToFind: [ 87.1, 3.3], showTheWay: [ 90.8, 6.3], decideHowFar: [ 97.7, 3.2], pushNumber: [102.3, 4.5], wrongPlace: [107.5, 5.6], notFarEnough: [114.4, 3.4], howMuchMore: [118.5, 2.3], goneTooFar: [122.1, 3.5], mustGoBack: [126.1, 4.7], thinkItIs: [132.3, 3.5], isItCorrect: [137.1, 1.2], useButtons: [139.6, 7.2], gettingHelp: [148.3, 6.7], youHelpLater: [156.2, 5.6], thatsAll: [164.3, 5.9], dancing: [171.2, 5.3] } }, lizard: { speech: [ 'audio/subgames/lizard/swedish.m4a', 'audio/subgames/lizard/swedish.ogg', 'audio/subgames/lizard/swedish.mp3' ], markers: { argh: [ 0.5, 1.5], arrg: [ 3.3, 0.9], miss: [ 5.3, 1.8], openMiss: [ 8.7, 1.5], treeTaste: [ 11.7, 3.4], higher: [ 16.6, 2.3], lower: [ 19.7, 2.9], tooHigh: [ 24.0, 6.5], tooLow: [ 32.2, 4.4], yummy: [ 38.2, 2.5], thankYou: [ 41.9, 2.4], almostFull: [ 46.0, 2.4], sleepyHungry: [ 49.8, 6.5], takeThatAnt: [ 57.6, 4.5], helpToAim: [ 63.5, 2.1], howHigh: [ 67.5, 3.3], chooseButton: [ 72.5, 3.6], imStuck: [ 77.4, 4.0], openHowHigher: [ 82.6, 4.1], openHowLower: [ 88.0, 6.8], thinkItIs: [ 96.2, 2.6], higherOrLower: [100.1, 5.3], helpingMeAim: [106.9, 6.3], fullAndSleepy: [114.5, 7.7], byeAndThanks: [122.6, 2.5], openHigher: [126.1, 3.2], openLower: [130.2, 3.0] } }, /* Agents */ panda: { speech: [ 'audio/agent/panda/swedish.m4a', 'audio/agent/panda/swedish.ogg', 'audio/agent/panda/swedish.mp3' ], markers: { ok1: [ 0.1, 0.7], ok2: [ 1.6, 0.4], hmm: [ 3.0, 1.0], isThisRight: [ 5.1, 1.3], itItThisOne: [ 7.5, 1.1], hasToBeThis: [ 9.4, 1.6], wrongShow: [ 12.1, 3.3], wasCorrect: [ 16.3, 1.6], tryAgain: [ 19.0, 2.2], wrong1: [ 22.6, 1.4], wrong2: [ 27.6, 1.5], higher: [ 25.0, 1.4], more: [155.9, 1.1], lower: [ 30.0, 2.1], fewer: [153.3, 1.5], myTurn1: [ 33.0, 2.2], myTurn2: [ 36.1, 1.3], willYouHelpMe: [ 38.5, 0.7], instructionGreen: [ 39.9, 3.0], instructionRed: [ 43.7, 3.1], letsGo: [105.8, 0.8], // Agent setup hello: [147.5, 1.7], // same as in intro speech file funTogether: [150.3, 1.9], // same as in intro speech file // Garden gardenIntro: [ 47.9, 6.6], gardenMyCan: [ 55.7, 6.5], gardenSign: [ 63.2, 2.0], gardenHaveWater: [ 66.1, 4.7], gardenPushField: [ 71.9, 2.4], gardenGrowing: [ 75.2, 1.7], gardenFullGrown: [ 78.2, 3.8], gardenWaterLeft: [ 83.3, 3.8], gardenEmptyCan: [ 88.2, 4.3], gardenWhereNow: [ 93.6, 2.2], gardenWaterFirst: [ 96.7, 7.9], gardenYoureBack: [107.7, 2.0], // Birdhero birdheroIntro: [140.1, 6.6], // Lizard lizardIntro1: [117.4, 4.5], lizardIntro2: [123.0, 4.0], // Bee beeIntro1: [128.1, 2.8], beeIntro2: [132.0, 2.8], beeIntro3: [135.7, 3.4], // Balloon balloonIntro: [110.4, 6.2] } }, hedgehog: { speech: [ 'audio/agent/hedgehog/swedish.m4a', 'audio/agent/hedgehog/swedish.ogg', 'audio/agent/hedgehog/swedish.mp3' ], markers: { ok1: [ 0.0, 0.6], ok2: [ 1.6, 0.6], hmm: [ 3.4, 1.0], isThisRight: [ 5.5, 1.5], itItThisOne: [ 8.1, 1.0], hasToBeThis: [ 10.0, 2.1], wrongShow: [ 13.1, 3.8], wasCorrect: [ 17.9, 1.9], tryAgain: [ 20.7, 2.4], wrong1: [ 23.7, 1.2], wrong2: [ 31.7, 1.6], higher: [ 25.8, 2.7], more: [ 29.3, 1.6], lower: [ 34.2, 3.0], fewer: [ 38.0, 1.9], myTurn1: [ 41.0, 3.1], myTurn2: [ 45.9, 1.6], willYouHelpMe: [ 48.6, 1.1], instructionGreen: [ 51.0, 4.2], instructionRed: [ 56.0, 4.4], letsGo: [ 69.0, 0.9], // Agent setup hello: [ 61.5, 2.3], // same as in intro speech file funTogether: [ 65.1, 2.9], // same as in intro speech file // Garden gardenIntro: [ 70.9, 9.5], gardenMyCan: [ 81.8, 7.5], gardenSign: [ 90.7, 2.4], gardenHaveWater: [ 94.7, 6.0], gardenPushField: [102.1, 3.1], gardenGrowing: [106.3, 1.5], gardenFullGrown: [109.1, 4.7], gardenWaterLeft: [115.1, 4.0], gardenEmptyCan: [120.4, 5.0], gardenWhereNow: [126.5, 2.2], gardenWaterFirst: [129.7,10.3], gardenYoureBack: [141.2, 2.1], // Birdhero birdheroIntro: [145.2,11.5], // Lizard lizardIntro1: [158.2, 5.4], lizardIntro2: [164.7, 5.3], // Bee beeIntro1: [172.0, 4.0], beeIntro2: [177.0, 3.2], beeIntro3: [181.4, 4.3], // Balloon balloonIntro: [187.7, 5.6] } }, mouse: { speech: [ 'audio/agent/mouse/swedish.m4a', 'audio/agent/mouse/swedish.ogg', 'audio/agent/mouse/swedish.mp3' ], markers: { ok1: [ 0.0, 0.5], ok2: [ 1.5, 0.5], hmm: [ 3.1, 1.6], isThisRight: [ 5.9, 1.2], itItThisOne: [ 8.5, 0.9], hasToBeThis: [ 10.6, 1.2], wrongShow: [ 13.3, 3.4], wasCorrect: [ 17.7, 1.6], tryAgain: [ 20.6, 2.1], wrong1: [ 24.2, 1.2], wrong2: [ 26.5, 1.4], higher: [ 28.9, 1.4], more: [ 31.1, 1.3], lower: [ 34.0, 2.2], fewer: [ 37.2, 1.3], myTurn1: [ 39.7, 2.1], myTurn2: [ 42.9, 1.0], willYouHelpMe: [ 45.3, 0.9], instructionGreen: [ 47.0, 3.1], instructionRed: [ 51.3, 3.0], letsGo: [ 60.2, 1.0], // Agent setup hello: [ 55.3, 1.6], // same as in intro speech file funTogether: [ 57.4, 2.0], // same as in intro speech file // Garden gardenIntro: [ 62.2, 6.0], gardenMyCan: [ 69.0, 3.1], gardenSign: [ 73.3, 1.6], gardenHaveWater: [ 76.1, 3.8], gardenPushField: [ 81.2, 2.0], gardenGrowing: [ 84.2, 1.2], gardenFullGrown: [ 86.6, 3.2], gardenWaterLeft: [ 91.0, 3.2], gardenEmptyCan: [ 95.2, 3.8], gardenWhereNow: [ 99.7, 1.6], gardenWaterFirst: [102.4, 7.5], gardenYoureBack: [111.0, 1.5], // Birdhero birdheroIntro: [113.6, 7.9], // Lizard lizardIntro1: [122.5, 4.4], lizardIntro2: [128.2, 3.9], // Bee beeIntro1: [133.0, 3.1], beeIntro2: [137.2, 2.6], beeIntro3: [140.7, 3.0], // Balloon balloonIntro: [144.9, 7.5] } } }; LANG.TEXT = LANG.swedish.text; LANG.SPEECH = LANG.swedish.speech; LANG.SPEECH.AGENT = LANG.SPEECH.panda; },{}],10:[function(require,module,exports){ var backend = require('./backend.js'); var GLOBAL = require('./global.js'); var EventSystem = require('./pubsub.js'); /** * Handles the logging of the game and sending to the backend. */ (function () { var session; var trial = {}; var wasCorrect = true; var time = 0; /** * Reset the current values of a session. */ function reset () { session = { modes: [], tries: 0, corrects: 0, finished: false, water: 0 }; time = Date.now(); } /** * Log when a subgame has started. * @param {string} type - The name of the subgame. * @param {number} token - The token recieved from backend (session id). */ function subgameStarted (type, token) { reset(); session.type = type; session.token = token; } /** * A subgame of type number game has started. * @param {number} method - Method used for subgame. * @param {number} maxAmount - The max number used in the subgame. * @param {number} representation - The representation of the numbers. */ function numbergameStarted (method, maxAmount, representation) { session.method = method; session.maxAmount = maxAmount; session.representation = representation; } /** * Game state has changed. Possibly from a subgame to garden. */ function stateChange () { // If we were in a subgame, then tries should be set. if (session.tries > 0) { backend.putSession(session); } reset(); } /** * The mode in a subgame has changed. * @param {number} mode - The new mode. */ function modeChange (mode) { if (mode === GLOBAL.MODE.outro) { // If we get the outro mode, then we know the player completed the subgame. session.finished = true; } else if (typeof mode !== 'undefined' && mode !== GLOBAL.MODE.intro) { // Create new mode item. session.modes.push({ type: mode, results: [] }); } } /** * A trial has been executed (someone has tried to answer a problem). * @param {number} guess - The players guess. * @param {number} correct - The actual correct value. * @param {number} pushed - The value that was pushed (used in mode addition, subtraction and add/sub). * @param {number} start - The value the trial started at (used in mode addition, subtraction and add/sub). */ function trialData (guess, correct, pushed, start) { var modeResults = session.modes[session.modes.length-1].results; if (modeResults.length <= 0 || wasCorrect) { modeResults.push({ target: correct, trials: [] }); } trial.try = guess; if (session.method >= GLOBAL.METHOD.addition) { trial.chosenValue = pushed; trial.startValue = start; } trial.time = Date.now() - time; // This is where trial data is saved. // It might however have data from other functions than this. modeResults[modeResults.length-1].trials.push(trial); session.tries++; if (guess === correct) { session.corrects++; wasCorrect = true; } else { wasCorrect = false; } trial = {}; // Reset trial } /** * An agent has guessed something. * @param {number} guess - The guess. */ function agentGuess (guess) { trial.agent = guess; } /** * A number button has been pressed. * Currently this only checks yesno pushes, others are logged in trialData. * @param {number} value - The guess. * @param {number} representations - The representations of the button. */ function numberPress (value, representations) { if (representations[0] === GLOBAL.NUMBER_REPRESENTATION.yesno) { // The button was correcting an agent. trial.corrected = (value % 2) === 0; // yes = 1, no = 0 } } /** * Add water to the session. */ function water () { session.water++; } /** * Set the start time for a session. */ function startTime () { time = Date.now(); } reset(); /* General */ EventSystem.subscribe(GLOBAL.EVENT.stateShutDown, function (/*state*/) { stateChange(); }, true); /* Session related */ EventSystem.subscribe(GLOBAL.EVENT.subgameStarted, function (type, token) { subgameStarted(type, token); }, true); EventSystem.subscribe(GLOBAL.EVENT.numbergameStarted, function (method, maxAmount, representation) { numbergameStarted(method, maxAmount, representation); }, true); EventSystem.subscribe(GLOBAL.EVENT.modeChange, function (mode) { modeChange(mode); }, true); EventSystem.subscribe(GLOBAL.EVENT.tryNumber, function (guess, correct, chosen, start) { trialData(guess, correct, chosen, start); }, true); EventSystem.subscribe(GLOBAL.EVENT.agentGuess, function (guess/*, correct*/) { agentGuess(guess); }, true); EventSystem.subscribe(GLOBAL.EVENT.waterAdded, function (/*current, diff*/) { water(); }, true); EventSystem.subscribe(GLOBAL.EVENT.numberPress, function (value, representations) { numberPress(value, representations); }, true); EventSystem.subscribe(GLOBAL.EVENT.disabled, function (value) { if (!value) { startTime(); } }, true); })(); },{"./backend.js":6,"./global.js":8,"./pubsub.js":34}],11:[function(require,module,exports){ var DraggableObject = require('./DraggableObject'); module.exports = Cookies; Cookies.prototype = Object.create(DraggableObject.prototype); Cookies.prototype.constructor = Cookies; /** * A draggable cookie piece in the shark game * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number for the button, is overwritten in objectPanel. * @param {Object} options - A list of options (in addition to GeneralButton): * {number} min: The minimum value of the button. * {number} max: The maximum value of the button. * {number} size: the small side of the button (the other depend on representation amount) (default 75). * {string} idName: the name of current object type * {number} id: id number for the current object * {boolean} vertical: stretch button vertically if many representations, otherwise horisontally (default true). * {string} spriteKey: Used for object representation only. The key to the sprite. * {string} spriteFrame: Used for object representation only. The framename in the sprite. NOTE: Used like this: spriteFrame + this.number * @returns {Object} Itself. */ function Cookies (game, number, options) { this.background = options.background.slice(0, 6) + number + options.background.slice(7); this.spriteKey = options.spriteKey; this.spriteFrame = options.spriteFrame; if (typeof this.background === 'undefined') { this.background = options.background.slice(0, 6) + number + options.background.slice(7); } options.background = this.background; options.id += 1; this.id = options.id; this.idName = options.idName; DraggableObject.call(this, game, options); // Parent constructor. this.vertical = options.vertical; if (typeof this.vertical === 'undefined' || this.vertical === null) { this.vertical = true; } this.setDirection(!this.vertical); this.min = options.min || null; this.max = options.max || null; this._number = 0; this.number = number; this._clicker = options.onClick; this.onClick = function () { if (this._clicker) { this._clicker(this.number); } }; return this; } Object.defineProperty(Cookies.prototype, 'number', { get: function () { return this._number; }, set: function (value) { /* Check boundaries */ if (this.min && value < this.min) { value = this.min; } if (this.max && value > this.max) { value = this.max; } if (value === this._number) { return; } this._number = value; this.updateGraphics(value); } }); Cookies.prototype.updateGraphics = function (num) { /* Remove old graphics. */ if (this.children.length > 1) { this.removeBetween(1, this.children.length-1, true); } /*Setting the sprite frame to the image correlating to the cookies number, 8 is the difference between the number and its index in the json file*/ if(this.idName !== 'finalDragObject') { this.bg.frame = num + 8; } this.setSize(); this.reset(); }; Cookies.prototype.calcOffset = function (offset) { var t = { x: 0, y: 0, o: this.size/offset }; if (this.background) { // Probably square looking button. t.x = t.o*2; t.y = t.o*2; } else if (this.direction) { /* Up/Down */ t.x = t.o*1.8; t.y = t.o*(this._number >= 0 ? 3.3 : 1); } else { /* Left/Right */ t.x = t.o*(this._number >= 0 ? 1 : 3.3); t.y = t.o*2; } t.o *= 4; return t; }; Cookies.prototype.setSize = function (size) { DraggableObject.prototype.setSize.call(this, size || this.size); return this; }; Cookies.prototype.setDirection = function (val) { this.direction = val; if (val) { this.bg.rotation = -Math.PI/2; this.bg.y += this.bg.width; this.bg.adjusted = this.bg.width; } else { this.bg.rotation = 0; this.bg.y -= this.bg.adjusted || 0; } if (this.number) { this.updateGraphics(this.number); } return this; }; },{"./DraggableObject":14}],12:[function(require,module,exports){ module.exports = Counter; /** * An easy-to-use counter with a max value. * NOTE: This is not a graphical counter, only a programmatic. * * @constructor * @param {integer} max - The max value for the counter. * @param {boolean} loop - If the counter should loop back to 0 when reaching max value (default is false). * @param {integer} start - The start value the first loop (default is 0). * @return {Counter} This object. */ function Counter (max, loop, start) { /** * @property {boolean} _loop - If the counter should loop. * @default false * @private */ this._loop = loop || false; /** * @property {number} _value - The value of the counter. * @default 0 * @private */ this._value = start || 0; /** * @property {number} max - The max value of the counter. */ this.max = max; /** * @property {function} onAdd - A function to run when adding water. */ this.onAdd = null; /** * @property {function} onMax - A function to run when water is at max. */ this.onMax = null; return this; } /** * @property {number} left - Value left until max. * @readonly */ Object.defineProperty(Counter.prototype, 'left', { get: function() { return this.max - this._value; } }); /** * @property {number} value - The value of the counter. * This will fire onAdd and onMax when applicable. */ Object.defineProperty(Counter.prototype, 'value', { get: function() { return this._value; }, set: function(value) { var diff = value - this._value; this._value = value; if (this.onAdd) { this.onAdd(this._value, diff, this.left); } if (this._value >= this.max) { if (this._loop) { this._value = 0; } if (this.onMax) { this.onMax(this._value); } } } }); /** Calls the onAdd function with current values. */ Counter.prototype.update = function () { if (this.onAdd) { this.onAdd(this._value, 0, this.left); } }; },{}],13:[function(require,module,exports){ module.exports = Cover; Cover.prototype = Object.create(Phaser.Sprite.prototype); Cover.prototype.constructor = Cover; /** * A cover over the entire game. Traps all input events. * @param {Object} game - A reference to the Phaser game. * @param {number} color - The color of the cover (default '#000000'); * @param {number} alpha - The alpha of the cover (default 1); * @return {Object} Itself. */ function Cover (game, color, alpha) { var bmd = game.add.bitmapData(game.world.width, game.world.height); bmd.ctx.fillStyle = color || '#000000'; bmd.ctx.fillRect(0, 0, game.world.width, game.world.height); Phaser.Sprite.call(this, game, 0, 0, bmd); // Parent constructor. this.alpha = (typeof alpha !== 'undefined') ? alpha : 1; this.inputEnabled = true; return this; } },{}],14:[function(require,module,exports){ var GLOBAL = require('../global.js'); module.exports = DraggableObject; DraggableObject.prototype = Object.create(Phaser.Group.prototype); DraggableObject.prototype.constructor = DraggableObject; DraggableObject.prototype.buttonColor = GLOBAL.BUTTON_COLOR; /** * Super class for all draggable objects * @param {Object} game - A reference to the Phaser game. * @param {Object} options - A list of options: * {number} x: the x position (default 0). * {number} y: the y position (default 0). * {number} size: the side of the button (default 75). * {number} startPosX: the x position defined in the subgame * {number} startPosY: the y position defined in the subgame * {string} idName: the name of current object type * {number} id: id number for the current object * {string} background: the frame of the background (default 'button'). NOTE: Needs to be in the 'objects' atlas. * {number} color: the color of the button (default 0xb2911d). * NOTE: You can also set the prototype property buttonColor. * {number} colorPressed: the color when the button is pressed (default darker color). * {function} onClick: a function to run when a button is clicked. * {boolean} disabled: true if the button should be disabled (default false). * {boolean} keepDown: true if the button should not auto raise when clicked (default false). * @return {Object} Itself. */ function DraggableObject (game, options) { Phaser.Group.call(this, game, null); options = options || {}; this.x = options.x || 0; this.y = options.y || 0; this.startPosX = options.startPosX; this.startPosY = options.startPosY; this.color = options.color || this.buttonColor; this.try = 0; this.idName = options.idName; if (options.colorPressed) { this.colorPressed = options.colorPressed; } else { var col = Phaser.Color.getRGB(this.color); col.red -= col.red < 40 ? col.red : 40; col.green -= col.green < 40 ? col.green : 40; col.blue -= col.blue < 40 ? col.blue : 40; this.colorPressed = Phaser.Color.getColor(col.red, col.green, col.blue); } this.onClick = options.onClick; this.disabled = options.disabled || false; this.keepDown = options.keepDown || false; this.background = options.background; var background = options.background; if (typeof background === 'undefined') { background = 'button'; } this.bg = this.create(0, 0, (background === null ? null : 'cookie'), background); this.bg.inputEnabled = true; this.bg.input.enableDrag(true,true); this.id = options.id; this.dropPlaceX = options.dropPlaceX; this.dropPlaceY = options.dropPlaceY; this.bg.events.onDragStop.add(stopDrag,this,options); //sets the object to the down state when clicked on this.bg.events.onInputDown.add(function () { if (this.disabled || this.bg.tint === this.colorPressed) { return; } this.bg.tint = this.colorPressed; }, this); this.reset(); this.setSize(options.size || 75); return this; } //Function triggered when dropping an object function stopDrag(options){ var x = this.game.input.x; var y = this.game.input.y; x = x-156; //conversion from input coordinate system to the games if (this.idName !== 'finalDragObject') { //Drop placement for the dragObjects, needed because finalDragObjects drop area is bigger //To Do: get the coordinates and size from the gol object directly if(x > this.dropPlaceX -10 && x < this.dropPlaceX+ 80 && y > this.dropPlaceY -10 && y < this.dropPlaceY + 80) { if (this.onClick) { this.onClick(); } //Placement algorithm for the visual feedback //If try is less than 0 place on top of the goal, if its over 0 place to the left of the goal //To do: get 113 from the white space calculation in objectPanel the variable fullSize /*If this is moved to a seperate function you could be able to use it in the agentTry mode instead of the visualAid sprite to place one of the cookies on its visual feedback position*/ if ( DraggableObject.try < 0) { options.x = this.dropPlaceX - (this.startPosX+ ((this.id-1) * 113)); options.y = this.dropPlaceY - this.startPosY; } else if(DraggableObject.try > 0){ options.x = this.dropPlaceX - ((this.startPosX+ ((this.id-1) * 113))+75); options.y = this.dropPlaceY - this.startPosY; } else{ options.x = 1; options.y = 1; } } else{ options.x = 1; options.y = 1; } } else{ if(x > this.dropPlaceX -30 && x < this.dropPlaceX+ 200 && y > this.dropPlaceY -10 && y < this.dropPlaceY + 200) { if (this.onClick) { this.onClick(); } } options.x = 1; options.y = 1; } this.reset(); } /** * Set the size of this button. * @param {Number} size - The new size. */ DraggableObject.prototype.setSize = function (size) { this.size = size; this.bg.width = size; this.bg.height = size; }; /** * Setting the try variable to the offset of the answer * @param num */ DraggableObject.prototype.setTry = function(num){ DraggableObject.try = num; }; /** * Reset the buttons to "up" state. */ DraggableObject.prototype.reset = function () { this.bg.tint = this.color; }; /** * Set the buttons to "down" state. * NOTE: This does not fire the click functions. */ DraggableObject.prototype.setDown = function () { this.bg.tint = this.colorPressed; }; /** * Highlight the object. * @param {Number} duration - How long to highlight the button. * @param {Number} from - The opacity to highlight from (will end at this as well) (default 1). * @returns {Object} The animation tweenmax. */ DraggableObject.prototype.highlight = function (duration, from) { from = typeof from === 'number' ? from : 1; return TweenMax.fromTo(this, 0.5, { alpha: from }, { alpha: 0 }).backForth(duration || 3); }; },{"../global.js":8}],15:[function(require,module,exports){ var GoalObject = require('./GoalObject'); module.exports = GoalCookie; GoalCookie.prototype = Object.create(GoalObject.prototype); GoalCookie.prototype.constructor = GoalCookie; /** * The goalCookie in shark game * @param {Object} game - A reference to the Phaser game. * @param {Object} options - A list of options: * {number} x: the x position (default 0). * {number} y: the y position (default 0). * {number} size: the side of the button (default 75). * {number} number: the number of the cookie * {number} min: The minimum value of the object. * {number} max: The maximum value of the object. * {string} background: the frame of the background (default 'button'). * @return {Object} Itself. */ function GoalCookie (game, number, options) { this.background = options.background.slice(0, 6) + number + '-mirror' + options.background.slice(7); this.spriteKey = options.spriteKey; this.spriteFrame = options.spriteFrame; if (typeof this.background === 'undefined') { this.background = 'Cookie6-mirror.png'; } GoalObject.call(this, game, options); // Parent constructor. this.vertical = options.vertical; if (typeof this.vertical === 'undefined' || this.vertical === null) { this.vertical = true; } this.setDirection(!this.vertical); this.min = options.min || null; this.max = options.max || null; this._number = 0; this.number = number; return this; } Object.defineProperty(GoalCookie.prototype, 'number', { get: function () { return this._number; }, set: function (value) { /* Check boundaries */ if (this.min && value < this.min) { value = this.min; } if (this.max && value > this.max) { value = this.max; } if (value === this._number) { return; } this._number = value; this.updateGraphics(value); } }); GoalCookie.prototype.updateGraphics = function (num) { /* Remove old graphics. */ if (this.children.length > 1) { this.removeBetween(1, this.children.length-1, true); } this.number = 0; //Setting the sprite frame to the image correlating to the goal cookies number. this.bg.frame = num-1; }; GoalCookie.prototype.calcOffset = function (offset) { var t = { x: 0, y: 0, o: this.size/offset }; if (this.background) { // Probably square looking button. t.x = t.o*2; t.y = t.o*2; } else if (this.direction) { /* Up/Down */ t.x = t.o*1.8; t.y = t.o*(this._number >= 0 ? 3.3 : 1); } else { /* Left/Right */ t.x = t.o*(this._number >= 0 ? 1 : 3.3); t.y = t.o*2; } t.o *= 4; return t; }; GoalCookie.prototype.setSize = function (size) { GoalObject.prototype.setSize.call(this, size || this.size); return this; }; GoalCookie.prototype.setDirection = function (val) { this.direction = val; if (val) { this.bg.rotation = -Math.PI / 2; this.bg.y += this.bg.width; this.bg.adjusted = this.bg.width; } else { this.bg.rotation = 0; this.bg.y -= this.bg.adjusted || 0; } if (this.number) { this.updateGraphics(this.number); } return this; }; },{"./GoalObject":16}],16:[function(require,module,exports){ var GLOBAL = require('../global.js'); module.exports = GoalObject; GoalObject.prototype = Object.create(Phaser.Group.prototype); GoalObject.prototype.constructor = GoalObject; GoalObject.prototype.buttonColor = GLOBAL.BUTTON_COLOR; /** * Super class for goalObjects on which to drop draggable objects * @param {Object} game - A reference to the Phaser game. * @param {Object} options - A list of options: * {number} x: the x position (default 0). * {number} y: the y position (default 0). * {number} size: the side of the button (default 75). * {string} background: the frame of the background (default 'button'). * @return {Object} Itself. */ function GoalObject (game, options) { Phaser.Group.call(this, game, null); // options = options || {}; this.x = options.dropPlaceX || 0; this.y = options.dropPlaceY || 0; this.color = options.color || this.buttonColor; var col = Phaser.Color.getRGB(this.color); col.red -= col.red < 40 ? col.red : 40; col.green -= col.green < 40 ? col.green : 40; col.blue -= col.blue < 40 ? col.blue : 40; this.disabled = options.disabled || false; var background = options.background; if (typeof background === 'undefined') { background = 'button'; } this.bg = this.create(0, 0, (background === null ? null : 'cookie'), background); this.setSize(options.size || 75); return this; } /** * Set the size of this object. * @param {Number} size - The new size. */ GoalObject.prototype.setSize = function (size) { this.size = size; this.bg.width = size; this.bg.height = size; }; /** * Highlight the objects. * @param {Number} duration - How long to highlight the button. * @param {Number} from - The opacity to highlight from (will end at this as well) (default 1). * @returns {Object} The animation tweenmax. */ GoalObject.prototype.highlight = function (duration, from) { from = typeof from === 'number' ? from : 1; return TweenMax.fromTo(this, 0.5, {alpha: from}, {alpha: 0}).backForth(duration || 3); }; },{"../global.js":8}],17:[function(require,module,exports){ var Cover = require('./Cover.js'); var Slider = require('./Slider.js'); var GeneralButton = require('./buttons/GeneralButton.js'); var SpriteButton = require('./buttons/SpriteButton.js'); var TextButton = require('./buttons/TextButton.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var EventSystem = require('../pubsub.js'); module.exports = Menu; Menu.prototype = Object.create(Phaser.Group.prototype); Menu.prototype.constructor = Menu; /** * The game's main menu. * @param {Object} game - A reference to the Phaser game. * @return {Object} Itself. */ function Menu (game) { Phaser.Group.call(this, game, null); // Parent constructor. var centerX = game.world.centerX; var centerY = game.world.centerY; /* Add menu button. */ var button = new GeneralButton(game, { x: 5, y: 5, size: 56, onClick: function () { showMenu(true); } }); this.add(button); var menuSplit = Math.ceil(LANG.TEXT.menu.length/2); var menuStyle = { font: '20pt ' + GLOBAL.FONT, stroke: '#000000', strokeThickness: 2, align: 'center' }; var menuText = game.add.text( button.x + button.width/2, button.y + button.height/2 - 7, LANG.TEXT.menu.substr(0, menuSplit), menuStyle, this ); menuText.anchor.set(0.5); menuText = game.add.text( button.x + button.width/2, button.y + button.height/2 + 17, LANG.TEXT.menu.substr(menuSplit), menuStyle, this ); menuText.anchor.set(0.5); /* For skipping timelines */ var skipper = null; var skipButton = new TextButton(game, '>>', { x: 145, y: 5, size: 56, fontSize: 30, doNotAdapt: true, onClick: function () { if (skipper) { skipper.totalProgress(1); } } }); skipButton.visible = false; this.add(skipButton); EventSystem.subscribe(GLOBAL.EVENT.skippable, function (timeline) { if (!skipper || skipper.getChildren().indexOf(timeline) < 0) { skipper = timeline; } skipButton.visible = !!timeline; }); /* Create the menu group. It will be shown when the button is clicked. */ var menuGroup = game.add.group(this); showMenu(false); /* Create a cover behind the menu. */ menuGroup.add(new Cover(game, '#056449', 0.7)); /* Create the background of the menu. */ var bmd = game.add.bitmapData(parseInt(game.world.width*0.4), parseInt(game.world.height*0.6)); bmd.ctx.fillStyle = '#b9d384'; bmd.ctx.roundRect(0, 0, bmd.width, bmd.height, 20).fill(); menuGroup.create(game.world.width*0.3, centerY*0.6, bmd).alpha = 0.7; /* Create the texts. */ var title = game.add.text(centerX, centerY*0.4, LANG.TEXT.title, { font: '50pt ' + GLOBAL.FONT, fill: '#ffff00', stroke: '#000000', strokeThickness: 5 }, menuGroup); title.anchor.set(0.5); var resume = new TextButton(game, LANG.TEXT.resume, { x: centerX, y: centerY*0.7, fontSize: 30, onClick: function () { showMenu(false); } }); resume.x -= resume.width/2; menuGroup.add(resume); /* Add volume control. */ var fgVolumeSlider = new Slider(game, centerX - bmd.width*0.2, centerY*1.05, bmd.width*0.5, 40, function (value) { game.sound.fgVolume = value; localStorage.fgVolume = value; if (value > 0) { fgMuteButton.sprite.frameName = 'speech'; fgMuteButton.muteValue = value; } else { fgMuteButton.sprite.frameName = 'speech_mute'; } }, game.sound.fgVolume ); menuGroup.add(fgVolumeSlider); var fgMuteButton = new SpriteButton(game, 'objects', game.sound.fgVolume > 0 ? 'speech' : 'speech_mute', { x: centerX - bmd.width*0.35, y: fgVolumeSlider.y - fgVolumeSlider.height*0.75, size: fgVolumeSlider.height*1.5, onClick: function () { if (this.sprite.frameName === 'speech_mute') { fgVolumeSlider.value = this.muteValue > 0.1 ? this.muteValue : 1; } else { fgVolumeSlider.value = 0; } } }); fgMuteButton.sprite.scale.set(0.6); fgMuteButton.muteValue = fgVolumeSlider.value; menuGroup.add(fgMuteButton); var bgVolumeSlider = new Slider(game, centerX - bmd.width*0.2, centerY*1.25, bmd.width*0.5, 40, function (value) { game.sound.bgVolume = value; localStorage.bgVolume = value; if (value > 0) { bgMuteButton.sprite.frameName = 'volume'; bgMuteButton.muteValue = value; } else { bgMuteButton.sprite.frameName = 'volume_mute'; } }, game.sound.bgVolume ); menuGroup.add(bgVolumeSlider); var bgMuteButton = new SpriteButton(game, 'objects', game.sound.bgVolume > 0 ? 'volume' : 'volume_mute', { x: centerX - bmd.width*0.35, y: bgVolumeSlider.y - bgVolumeSlider.height*0.75, size: bgVolumeSlider.height*1.5, onClick: function () { if (this.sprite.frameName === 'volume_mute') { bgVolumeSlider.value = this.muteValue > 0.1 ? this.muteValue : 1; } else { bgVolumeSlider.value = 0; } } }); bgMuteButton.sprite.scale.set(0.6); bgMuteButton.muteValue = bgVolumeSlider.value; menuGroup.add(bgMuteButton); var currentState = game.state.states[game.state.current]; if (currentState.menuBack) { var garden = game.add.text(centerX, centerY*1.5, currentState.menuBack.text, { font: '30pt ' + GLOBAL.FONT, fill: '#000000' }, menuGroup); garden.anchor.set(0.5); garden.inputEnabled = true; garden.events.onInputDown.add(function () { game.state.start(currentState.menuBack.state); }, this); } var quit = game.add.text(centerX, centerY*1.7, LANG.TEXT.quit, { font: '30pt ' + GLOBAL.FONT, fill: '#000000' }, menuGroup); quit.anchor.set(0.5); quit.inputEnabled = true; quit.events.onInputDown.add(function () { game.state.start(GLOBAL.STATE.entry); }, this); function showMenu (value) { menuGroup.visible = value; } return this; } },{"../global.js":8,"../language.js":9,"../pubsub.js":34,"./Cover.js":13,"./Slider.js":20,"./buttons/GeneralButton.js":23,"./buttons/SpriteButton.js":25,"./buttons/TextButton.js":26}],18:[function(require,module,exports){ var Cover = require('./Cover.js'); var TextButton = require('./buttons/TextButton.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); module.exports = Modal; Modal.prototype = Object.create(Phaser.Group.prototype); Modal.prototype.constructor = Modal; /** * A modal with a single ok button. * @param {Object} game - A reference to the Phaser game. * @param {string} text - The text in the modal. * @param {number} fontSize - The size of the text. (default is 50). * @param {function} callback - A callback when pushing ok (optional). */ function Modal (game, text, fontSize, callback) { Phaser.Group.call(this, game, null); // Parent constructor. var centerX = game.world.centerX; var centerY = game.world.centerY; /* Create a cover behind the modal, traps all mouse events. */ this.add(new Cover(game, '#056449', 0.7)); /* Create the modal background. */ var bmd = game.add.bitmapData(parseInt(game.world.width/3), parseInt(game.world.height/2)); bmd.ctx.fillStyle = '#b9d384'; bmd.ctx.roundRect(0, 0, bmd.width, bmd.height, 20).fill(); this.create(game.world.width/3, centerY * 0.67, bmd).alpha = 0.7; /* Add the text field. */ game.add.text(centerX, centerY, text, { font: (fontSize || 50) + 'pt ' + GLOBAL.FONT, fill: '#dd00dd', align: 'center', wordWrap: true, wordWrapWidth: bmd.width * 0.7 }, this).anchor.set(0.5); /* Add the ok button. */ var _this = this; this.add(new TextButton(game, LANG.TEXT.ok, { x: centerX - 55, y: centerY/0.75, size: 80, fontSize: 30, onClick: function () { _this.destroy(); if (callback) { callback(); } } })); } },{"../global.js":8,"../language.js":9,"./Cover.js":13,"./buttons/TextButton.js":26}],19:[function(require,module,exports){ var Cookies = require('./Cookies.js'); var GoalCookie = require('./GoalCookie.js'); module.exports = ObjectPanel; ObjectPanel.prototype = Object.create(Phaser.Group.prototype); ObjectPanel.prototype.constructor = ObjectPanel; /** * Create a panel filled with dradg and drop or goal objects. * See NumberButton and GeneralButton for more information. * @param {Object} game - A reference to the Phaser game. * @param {number} amount - The number of buttons (this will be overwritten in updateObject for goalCookie and ) * @param {Object} options - options for the panel: * {number} x - The x position (default is 0) * {number} y - The y position (default is 0) * (string) id and idName - identifier for what object it is (dragObject, goalObject or goalObject) is converted to idName in objectoptions * (number) id indentifies the specific object of the 4 cookies (1-4) * (number) dropPlaceX - the x drop position for the object, defined at creation in sharkGame * (number) dropPlaceY - the y drop position for the object, defined at creation in sharkGame * {number} size - The size of the panel (default is game width or height, depending on if vertical is set) * {number} min - The smallest number on the panel (default is 1) * {number} max - The biggest number on the panel (default is min + amount - 1) * {function} onClick - What should happen when clicking the button * {string} background - The sprite key for the button backgrounds * {number} maxButtonSize - The maximum size of the buttons (default is 75) * NOTE: The button size is always calculated to not overlap * @return {Object} Itself. */ function ObjectPanel (game, amount, options) { Phaser.Group.call(this, game, null); // Parent constructor. this.x = options.x || 0; this.y = options.y || 0; this.vertical = options.vertical || false; this.reversed = options.reversed || false; this.size = options.size || (this.vertical ? this.game.world.height : this.game.world.width); this.dropPlaceX = options.dropPlaceX; this.dropPlaceY = options.dropPlaceY; this.id = options.id; this.color = options.color; this.background = options.background; this.background = 'cookie4.png'; this.maxObjectSize = options.maxObjectSize || 75; this.onClick = options.onClick; options.min = options.min || 1; this.setRange(options.min, options.max || (options.min + amount - 1)); return this; } ObjectPanel.prototype._createObject = function () { this.removeAll(true); /* Calculate max object size. */ var objectSize = this.size/this.amount; if (objectSize > this.maxObjectSize) { objectSize = this.maxObjectSize; } /* These options will be used when creating the objects. */ var objectOptions = { min: this.min, max: this.max, size: objectSize, background: this.background, color: this.color, vertical: !this.vertical, onClick: this.onClick, dropPlaceX: this.dropPlaceX, dropPlaceY: this.dropPlaceY, id: 0, idName: this.id, startPosX: this.x, startPosY: this.y }; /* Set up the objects that should be in the panel. depending on the present object */ if(this.id === 'dragObject' ) { for (var i = this.min; i <= this.max; i++) { this.cookie = new Cookies(this.game, i, objectOptions); this.add(this.cookie); } } else if(this.id === 'goalObject') { this.goalCookie = new GoalCookie(this.game,6, objectOptions); this.add(this.goalCookie); } else{ this.add(this.finalDragObject = new Cookies(this.game,10, objectOptions)); } /* Reverse the order of the buttons if needed. */ if (this.reversed) { this.reverse(); } /* Calculate white space. */ var widthLeft = this.size - objectSize*this.amount; var paddingSize = widthLeft/this.amount; if (paddingSize > objectSize/2) { paddingSize = objectSize/2; } var margin = (this.size - this.amount*objectSize - (this.amount - 1)*paddingSize)/2; var fullSize = paddingSize + objectSize; /* Set up the x and y positions. */ var direction = this.vertical ? 'y' : 'x'; for (var j = 0; j < this.length; j++) { this.children[j][direction] = margin + fullSize*j; } }; //Update the numbers of each object, 3 randomized and the current correct number ObjectPanel.prototype._updateObjects = function (currentNumber) { var rand = Math.round(Math.random()*9); var correct = currentNumber; while(rand === correct){ rand = Math.round(Math.random()*9); } var randIndex = Math.floor(Math.random()*3); //a randomized index for the current number var i = 0; if(this.cookie) { //looping over the cookies for (var key in this.children) { this.children[key].min = this.min; this.children[key].max = 9; if (i === randIndex) { this.children[key].number = correct; } else { this.children[key].number = rand; } Cookies.prototype.updateGraphics.call(this.cookie, rand); //Updating the graphics correlating to the new number rand = Math.round(Math.random() * 9); //making sure that none of the cookies gets the same number while (this.children[0].number === rand || this.children[1].number === rand || this.children[2].number === rand || this.children[3].number === rand) { rand = Math.round(Math.random() * 9); } i++; } i = 0; } if(this.goalCookie) { //Setting the goalCookie number to the inverse of the current number GoalCookie.prototype.updateGraphics.call(this.goalCookie, 10-currentNumber); } }; /** * Set the range for the button panel. It will create or update the panel accordingly. * @param {Number} The minimum amount in the panel. * @param {Number} The maximum amount in the panel. */ ObjectPanel.prototype.setRange = function (min, max,currentNumber) { this.min = min; this.max = max; var oldAmount = this.amount || 0; this.amount = (this.max - this.min + 1); if (this.amount !== oldAmount || this.length <= 0) { this._createObject(); } else { this._updateObjects(currentNumber); } }; /** * Reset all objects to "up" state. */ ObjectPanel.prototype.reset = function () { for (var i = 0; i < this.length; i++) { this.children[i].reset(); } }; /** * Highlight all objects. * @param {Number} duration - How long to highlight the buttons. * @param {Number} from - The opacity to highlight from (will end at this as well) (default 1). * @returns {Object} The animation timeline. */ ObjectPanel.prototype.highlightObject = function (duration, from) { var t = new TimelineMax(); for (var i = 0; i < this.length; i++) { t.add(this.children[i].highlightObject(duration, from), 0); } return t; }; /** * Disable/Enable all object input. * @param {Boolean} disable - True is disabled, false is enabled */ ObjectPanel.prototype.disable = function (value) { for (var i = 0; i < this.length; i++) { this.children[i].disabled = value; } }; },{"./Cookies.js":11,"./GoalCookie.js":15}],20:[function(require,module,exports){ var GeneralButton = require('./buttons/GeneralButton.js'); module.exports = Slider; Slider.prototype = Object.create(Phaser.Group.prototype); Slider.prototype.constructor = Slider; /** * A slider (that is an interactive handle on a line). * NOTE: Uses GeneralButton.prototype.buttonColor for colors. * @param {Object} game - A reference to the Phaser game. * @param {number} x - the x position (default 0). * @param {number} y - the y position (default 0). * @param {number} width - the width (of the line) (default 300). * @param {number} height - the height (of the handle) (default 50). * @param {Function} onChange: function to run when handle changes (default null). * @param {number} initial: initial value of the slider (default 0). * @returns {Object} Itself. */ function Slider (game, x, y, width, height, onChange, initial) { Phaser.Group.call(this, game, null); // Parent constructor. this.x = x || 0; this.y = y || 0; this.onChange = onChange; height = height || 50; width = width || 300; initial = initial || 0; /* Add the line. */ var line = this.create(0, 0, 'objects', 'button'); line.tint = GeneralButton.prototype.buttonColor; line.anchor.set(0, 0.5); line.height = height/10; line.width = width; /* Add the handle. */ this.handle = this.create(0, 0, 'objects', 'button'); this.handle.tint = GeneralButton.prototype.buttonColor; this.handle.anchor.set(0.5); this.handle.width = height; this.handle.height = height; this.handle.max = line.width - this.handle.width; this.handle.x = this.handle.max * initial; /* Move objects so that handle is easy to use */ this.x += this.handle.width/2; line.x -= this.handle.width/2; /* Use a large input area, that can be pushed anywhere on the slider */ var trigger = this.create(line.x, line.y, game.add.bitmapData(line.width, this.handle.height)); trigger.anchor.set(0, 0.5); trigger.inputEnabled = true; trigger.events.onInputDown.add(function () { var _this = this; // _this is the whole slider this.handle.tint -= 0x1e1e1e; this.handle.update = function () { // this will be the handle in this scope. this.x = game.input.activePointer.x - _this.x; if (this.x < 0) { this.x = 0; } else if (this.x > this.max) { this.x = this.max; } _this.onChange(this.x / this.max); }; }, this); var click = game.add.audio('click'); trigger.events.onInputUp.add(function () { this.handle.update = function () {}; this.handle.tint += 0x1e1e1e; click.play(); }, this); } /** * @property {number} value - The value of the slider. */ Object.defineProperty(Slider.prototype, 'value', { get: function() { return this.handle.x / this.handle.max; }, set: function(value) { this.handle.x = this.handle.max * value; this.onChange(value); } }); },{"./buttons/GeneralButton.js":23}],21:[function(require,module,exports){ var EventSystem = require('../pubsub.js'); var GLOBAL = require('../global.js'); module.exports = WaterCan; WaterCan.prototype = Object.create(Phaser.Group.prototype); WaterCan.prototype.constructor = WaterCan; /** * The graphical representation of the watering can. * @param {Object} game - A reference to the Phaser game. * @param {number} x - X position (default is game.width - 150). * @param {number} y - Y position (default is 5). * @param {number} amount - amount of water in the can (default player amount). * @returns {Object} Itself. */ function WaterCan (game, x, y, amount) { Phaser.Group.call(this, game, null); // Parent constructor. this.x = x || game.width - 125; this.y = y || 5; this.amount = amount || this.game.player.water; var origin = 87; var waterStep = 54 / this.game.player.maxWater; /* Add water level */ var bmd = game.add.bitmapData(62, 1); bmd.ctx.fillStyle = '#0000ff'; bmd.ctx.fillRect(0, 0, bmd.width, bmd.height); var water = this.create(20, origin, bmd); water.height = waterStep*this.amount; water.y -= water.height; /* Add can */ this.can = this.create(0, 0, 'objects', 'watering_can'); this.can.tint = 0xbb3333; /* Keep track of when the player's water changes */ this._sub = EventSystem.subscribe(GLOBAL.EVENT.waterAdded, function (total) { var h = waterStep*total; TweenMax.to(water, 0.5, { height: h, y: origin - h }); }); return this; } /** Removes subscriptions in addition to Phaser.Group.destroy */ WaterCan.prototype.destroy = function (destroyChildren, soft) { EventSystem.unsubscribe(this._sub); // Otherwise possible memory leak. Phaser.Group.prototype.destroy.call(this, destroyChildren, soft); }; /** * Pour water from the can. * @param {number} duration - Duration to pour. * @returns {Object} The animation TweenMax. */ WaterCan.prototype.pour = function (duration) { var emitter = this.game.add.emitter(this.can.width, 5, 200); emitter.width = 5; emitter.makeParticles('objects', 'drop'); emitter.setScale(0.1, 0.3, 0.1, 0.3); emitter.setYSpeed(100, 150); emitter.setXSpeed(50, 100); emitter.setRotation(0, 0); this.can.addChild(emitter); return new TweenMax(emitter, duration, { onStart: function () { emitter.start(false, 500, 10, (duration-0.5)*50); }, onComplete: function () { emitter.destroy(); } }); }; },{"../global.js":8,"../pubsub.js":34}],22:[function(require,module,exports){ var GLOBAL = require('../../global.js'); var TextButton = require('./TextButton.js'); var NumberButton = require('./NumberButton.js'); module.exports = ButtonPanel; ButtonPanel.prototype = Object.create(Phaser.Group.prototype); ButtonPanel.prototype.constructor = ButtonPanel; /** * Create a panel filled with buttons. * See NumberButton and GeneralButton for more information. * @param {Object} game - A reference to the Phaser game. * @param {number} amount - The number of buttons (NOTE, this will be overwritten if you set option max) * @param {number|Array} representations - The representations to use on the buttons. * @param {Object} options - options for the panel: * {number} x - The x position (default is 0) * {number} y - The y position (default is 0) * {number} size - The size of the panel (default is game width or height, depending on if vertical is set) * {number} method - The method of the panel (default is GLOBAL.METHOD.count) * {boolean} vertical - If the panel should be vertical (default is false) * {boolean} reversed - If the panel should display the buttons in reverse (default is false) * {number} min - The smallest number on the panel (default is 1) * {number} max - The biggest number on the panel (default is min + amount - 1) * {function} onClick - What should happen when clicking the button * {string} background - The sprite key for the button backgrounds * {string} color - The color of the representation * {number} maxButtonSize - The maximum size of the buttons (default is 75) * NOTE: The button size is always calculated to not overlap * @return {Object} Itself. */ function ButtonPanel (game, amount, representations, options) { Phaser.Group.call(this, game, null); // Parent constructor. this.representations = representations; this.x = options.x || 0; this.y = options.y || 0; this.vertical = options.vertical || false; this.reversed = options.reversed || false; this.size = options.size || (this.vertical ? this.game.world.height : this.game.world.width); this.method = options.method || GLOBAL.METHOD.count; this.color = options.color; this.background = options.background; if (!this.background && (this.method === GLOBAL.METHOD.count || this.method === GLOBAL.METHOD.incrementalSteps)) { this.background = 'button'; } this.maxButtonSize = options.maxButtonSize || 75; this.onClick = options.onClick; /* Set range of the panel, which will create the buttons. */ options.min = options.min || 1; this.setRange(options.min, options.max || (options.min + amount - 1)); return this; } /** * Create the buttons. * @private */ ButtonPanel.prototype._createButtons = function () { this.removeAll(true); /* Calculate max button size. */ var buttonSize = this.size/this.amount; if (buttonSize > this.maxButtonSize) { buttonSize = this.maxButtonSize; } /* These options will be used when creating the buttons. */ var buttonOptions = { min: this.min, max: this.max, size: buttonSize, background: this.background, color: this.color, vertical: !this.vertical, onClick: this.onClick }; /* Set up the buttons that should be in the panel. */ if (this.method === GLOBAL.METHOD.incrementalSteps) { buttonOptions.doNotAdapt = true; // Create buttons first, then add them in their order (this is because we manipulate the buttonOptions later) var change = new NumberButton(this.game, 1, this.representations, buttonOptions); // Put the other buttons centered. buttonOptions[this.vertical ? 'x' : 'y'] = ((this.representations.length - 1) * buttonSize)/2; buttonOptions.onClick = function () { change.bg.events.onInputDown.dispatch(); }; var go = new NumberButton(this.game, 1, GLOBAL.NUMBER_REPRESENTATION.yesno, buttonOptions); buttonOptions.keepDown = false; buttonOptions.background = 'button_minus'; buttonOptions.onClick = function () { change.number--; }; var minus = new TextButton(this.game, '-', buttonOptions); buttonOptions.background = 'button_plus'; buttonOptions.onClick = function () { change.number++; }; var plus = new TextButton(this.game, '+', buttonOptions); if (this.vertical) { minus.bg.rotation = -Math.PI/2; minus.bg.y += minus.bg.width; minus._text.y -= 6; plus.bg.rotation = -Math.PI/2; plus.bg.y += plus.bg.width; plus._text.y += 5; } else { minus._text.x += 5; plus._text.x -= 4; } this.add(minus); this.add(change); this.add(plus); this.add(go); } else { for (var i = this.min; i <= this.max; i++) { this.add(new NumberButton(this.game, i, this.representations, buttonOptions)); } } /* Reverse the order of the buttons if needed. */ if (this.reversed) { this.reverse(); } /* Calculate white space. */ var widthLeft = this.size - buttonSize*this.amount; var paddingSize = widthLeft/this.amount; if (paddingSize > buttonSize/2) { paddingSize = buttonSize/2; } var margin = (this.size - this.amount*buttonSize - (this.amount - 1)*paddingSize)/2; var fullSize = paddingSize + buttonSize; /* Set up the x and y positions. */ var direction = this.vertical ? 'y' : 'x'; for (var j = 0; j < this.length; j++) { this.children[j][direction] = margin + fullSize*j; } }; /** * Update the values of the buttons. * @private */ ButtonPanel.prototype._updateButtons = function () { if (this.method === GLOBAL.METHOD.incrementalSteps) { var button = this.children[this.reversed ? 2 : 1]; button.min = this.min; button.max = this.max; } else { var val, dir; if (this.reversed) { val = this.max; dir = -1; } else { val = this.min; dir = 1; } for (var key in this.children) { this.children[key].min = this.min; this.children[key].max = this.max; this.children[key].number = val; val += dir; } } }; /** * Set the range for the button panel. It will create or update the panel accordingly. * @param {Number} The minimum amount in the panel. * @param {Number} The maximum amount in the panel. */ ButtonPanel.prototype.setRange = function (min, max) { this.min = min; this.max = max; var oldAmount = this.amount || 0; // incrementalSteps have these buttons: (-) (number) (+) (ok) this.amount = this.method === GLOBAL.METHOD.incrementalSteps ? 4 : (this.max - this.min + 1); if (this.amount !== oldAmount || this.length <= 0) { this._createButtons(); } else { this._updateButtons(); } }; /** * Reset all buttons to "up" state. */ ButtonPanel.prototype.reset = function () { for (var i = 0; i < this.length; i++) { this.children[i].reset(); } }; /** * Highlight all buttons. * @param {Number} duration - How long to highlight the buttons. * @param {Number} from - The opacity to highlight from (will end at this as well) (default 1). * @returns {Object} The animation timeline. */ ButtonPanel.prototype.highlight = function (duration, from) { var t = new TimelineMax(); for (var i = 0; i < this.length; i++) { t.add(this.children[i].highlight(duration, from), 0); } return t; }; /** * Disable/Enable all buttons. * @param {Boolean} disable - True is disabled, false is enabled */ ButtonPanel.prototype.disable = function (value) { for (var i = 0; i < this.length; i++) { this.children[i].disabled = value; } }; },{"../../global.js":8,"./NumberButton.js":24,"./TextButton.js":26}],23:[function(require,module,exports){ var GLOBAL = require('../../global.js'); module.exports = GeneralButton; GeneralButton.prototype = Object.create(Phaser.Group.prototype); GeneralButton.prototype.constructor = GeneralButton; GeneralButton.prototype.buttonColor = GLOBAL.BUTTON_COLOR; // TODO: Can we use this global directly instead? /** * A general button. * @param {Object} game - A reference to the Phaser game. * @param {Object} options - A list of options: * {number} x: the x position (default 0). * {number} y: the y position (default 0). * {number} size: the side of the button (default 75). * {string} background: the frame of the background (default 'button'). NOTE: Needs to be in the 'objects' atlas. * {number} color: the color of the button (default 0xb2911d). * NOTE: You can also set the prototype property buttonColor. * {number} colorPressed: the color when the button is pressed (default darker color). * {function} onClick: a function to run when a button is clicked. * {boolean} disabled: true if the button should be disabled (default false). * {boolean} keepDown: true if the button should not auto raise when clicked (default false). * @return {Object} Itself. */ function GeneralButton (game, options) { Phaser.Group.call(this, game, null); // Parent constructor. options = options || {}; this.x = options.x || 0; this.y = options.y || 0; this.color = options.color || this.buttonColor; if (options.colorPressed) { this.colorPressed = options.colorPressed; } else { var col = Phaser.Color.getRGB(this.color); col.red -= col.red < 40 ? col.red : 40; col.green -= col.green < 40 ? col.green : 40; col.blue -= col.blue < 40 ? col.blue : 40; this.colorPressed = Phaser.Color.getColor(col.red, col.green, col.blue); } this.onClick = options.onClick; this.disabled = options.disabled || false; this.keepDown = options.keepDown || false; var background = options.background; if (typeof background === 'undefined') { background = 'button'; } this.bg = this.create(0, 0, (background === null ? null : 'objects'), background); this.bg.inputEnabled = true; //this.bg.input.enableDrag(true,true); var click = game.add.audio('click'); this.bg.events.onInputDown.add(function () { if (this.disabled || this.bg.tint === this.colorPressed) { return; } this.bg.tint = this.colorPressed; click.play(); if (this.onClick) { this.onClick(); } }, this); this.bg.events.onInputUp.add(function () { if (!this.keepDown) { this.reset(); } }, this); this.reset(); this.setSize(options.size || 75); return this; } /** * Set the size of this object. * @param {Number} size - The new size. */ GeneralButton.prototype.setSize = function (size) { this.size = size; this.bg.width = size; this.bg.height = size; }; /** * Reset the buttons to "up" state. */ GeneralButton.prototype.reset = function () { this.bg.tint = this.color; }; /** * Set the buttons to "down" state. * NOTE: This does not fire the click functions. */ GeneralButton.prototype.setDown = function () { this.bg.tint = this.colorPressed; }; /** * Highlight the objects. * @param {Number} duration - How long to highlight the button. * @param {Number} from - The opacity to highlight from (will end at this as well) (default 1). * @returns {Object} The animation tweenmax. */ GeneralButton.prototype.highlight = function (duration, from) { from = typeof from === 'number' ? from : 1; return TweenMax.fromTo(this, 0.5, { alpha: from }, { alpha: 0 }).backForth(duration || 3); }; },{"../../global.js":8}],24:[function(require,module,exports){ var GeneralButton = require('./GeneralButton.js'); var DotsRepresentation = require('../representations/DotsRepresentation.js'); var FingerRepresentation = require('../representations/FingerRepresentation.js'); var StrikeRepresentation = require('../representations/StrikeRepresentation.js'); var NumberRepresentation = require('../representations/NumberRepresentation.js'); var DiceRepresentation = require('../representations/DiceRepresentation.js'); var YesnoRepresentation = require('../representations/YesnoRepresentation.js'); var GLOBAL = require('../../global.js'); var EventSystem = require('../../pubsub.js'); module.exports = NumberButton; NumberButton.prototype = Object.create(GeneralButton.prototype); NumberButton.prototype.constructor = NumberButton; /** * A button with number representations on it. * If you supply more than one representation the button will stretch. * Publishes numberPress event on click. * NOTE: This button will not go to "up" state after click unless you set keepDown option to false. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number for the button. * @param {number|Array} representations - The representations of the button (see GLOBAL.NUMBER_REPRESENTATION). * @param {Object} options - A list of options (in addition to GeneralButton): * {number} min: The minimum value of the button. * {number} max: The maximum value of the button. * {number} size: the small side of the button (the other depend on representation amount) (default 75). * {boolean} vertical: stretch button vertically if many representations, otherwise horisontally (default true). * {string} spriteKey: Used for object representation only. The key to the sprite. * {string} spriteFrame: Used for object representation only. The framename in the sprite. NOTE: Used like this: spriteFrame + this.number * @returns {Object} Itself. */ function NumberButton (game, number, representations, options) { /* The order here is a bit weird because GeneralButton calls setSize, which this class overshadows. */ if (typeof options.keepDown === 'undefined' || options.keepDown === null) { options.keepDown = true; } this.representations = representations; this.background = options.background; this.spriteKey = options.spriteKey; this.spriteFrame = options.spriteFrame; GeneralButton.call(this, game, options); // Parent constructor. this.vertical = options.vertical; if (typeof this.vertical === 'undefined' || this.vertical === null) { this.vertical = true; } this.setDirection(!this.vertical); this.min = options.min || null; this.max = options.max || null; this._number = 0; this.number = number; this._clicker = options.onClick; /* This will be called in the GeneralButton's onInputDown */ this.onClick = function () { EventSystem.publish(GLOBAL.EVENT.numberPress, [this.number, this.representations]); if (this._clicker) { this._clicker(this.number); } }; return this; } /** * @property {number|Array} representations - The representations on the button. */ Object.defineProperty(NumberButton.prototype, 'representations', { get: function () { return this._representations; }, set: function (value) { this._representations = Array.isArray(value) ? value : [value]; if (typeof this.number !== 'undefined' && this.number !== null) { this.updateGraphics(); } } }); /** * @property {number} number - The number on the button. Set according to representations. * NOTE: This can not be less or more than min or max. */ Object.defineProperty(NumberButton.prototype, 'number', { get: function () { return this._number; }, set: function (value) { /* Check boundaries */ if (this.min && value < this.min) { value = this.min; } if (this.max && value > this.max) { value = this.max; } if (value === this._number) { return; } this._number = value; this.updateGraphics(); } }); /** * Update the graphics of the button. */ NumberButton.prototype.updateGraphics = function () { /* Remove old graphics. */ if (this.children.length > 1) { this.removeBetween(1, this.children.length-1, true); } if (typeof this.background === 'undefined' && this.representations[0] !== GLOBAL.NUMBER_REPRESENTATION.yesno) { if (this._number > 0) { this.bg.frameName = 'button_plus'; } else if (this._number < 0) { this.bg.frameName = 'button_minus'; } else { this.bg.frameName = 'button_zero'; } this.setSize(); this.reset(); } /* Add new graphics. */ var x = 0; var y = 0; var offset = 0; var useNum = Math.abs(this._number); var rep; for (var i = 0; i < this.representations.length; i++) { if (this.vertical) { y = this.size * i; } else { x = this.size * i; } if (i > 0) { var bmd = this.vertical ? this.game.add.bitmapData(this.size - 10, 3) : this.game.add.bitmapData(3, this.size - 10); bmd.ctx.fillStyle = '#000000'; bmd.ctx.globalAlpha = 0.2; bmd.ctx.roundRect(0, 0, bmd.width, bmd.height, 2).fill(); if (this.vertical) { this.create(x + 5, y - 1, bmd); } else { this.create(x - 1, y + 5, bmd); } } rep = this.representations[i] === GLOBAL.NUMBER_REPRESENTATION.mixed ? this.game.rnd.pick([ GLOBAL.NUMBER_REPRESENTATION.dots, GLOBAL.NUMBER_REPRESENTATION.fingers, GLOBAL.NUMBER_REPRESENTATION.strikes, GLOBAL.NUMBER_REPRESENTATION.numbers, GLOBAL.NUMBER_REPRESENTATION.dice ]) : this.representations[i]; if (rep === GLOBAL.NUMBER_REPRESENTATION.dots) { offset = this.calcOffset(16); this.add(new DotsRepresentation(this.game, useNum, x+offset.x, y+offset.y, this.size-offset.o, this.color)); } else if (rep === GLOBAL.NUMBER_REPRESENTATION.fingers) { offset = this.calcOffset(24); this.add(new FingerRepresentation(this.game, useNum, x+offset.x, y+offset.y, this.size-offset.o, this.color)); } else if (rep === GLOBAL.NUMBER_REPRESENTATION.strikes) { offset = this.calcOffset(12); this.add(new StrikeRepresentation(this.game, useNum, x+offset.x, y+offset.y, this.size-offset.o, this.color, this.max - this.min + 1)); } else if (rep === GLOBAL.NUMBER_REPRESENTATION.objects) { var s = this.create(x, y, this.spriteKey, (this.spriteFrame ? this.spriteFrame + Math.abs(this._number) : null)); var scale = this.size/(s.width > s.height ? s.width : s.height)*0.8; s.scale.set(scale); s.x = (!this.direction ? (this._number > 0 ? this.size * 0.8 : this.size * 1.2) : this.size)/2 - s.width/2; s.y = (this.direction ? (this._number > 0 ? this.size * 1.2 : this.size * 0.8) : this.size)/2 - s.height/2; } else if (rep === GLOBAL.NUMBER_REPRESENTATION.numbers) { offset = this.calcOffset(24); this.add(new NumberRepresentation(this.game, this._number, x+offset.x - this.size/12, y+offset.y, this.size/2, this.color)); } else if (rep === GLOBAL.NUMBER_REPRESENTATION.dice) { offset = this.calcOffset(12); this.add(new DiceRepresentation(this.game, useNum, x+offset.x, y+offset.y, this.size-offset.o, this.color)); } else if (rep === GLOBAL.NUMBER_REPRESENTATION.yesno) { this._number = this._number % 2; offset = this.size*0.1; this.add(new YesnoRepresentation(this.game, this._number, x + offset, y + offset, this.size - offset*2)); } } }; /** * Calculate the different offsets for the button (needed due to arrow in button). * @param {Number} offset - Offset from button edge (used like: this.size/offset). * @returns {Object} Offsets on the form { o: offset, x: x, y: y }. */ NumberButton.prototype.calcOffset = function (offset) { var t = { x: 0, y: 0, o: this.size/offset }; if (this.background) { // Probably square looking button. t.x = t.o*2; t.y = t.o*2; } else if (this.direction) { /* Up/Down */ t.x = t.o*1.8; t.y = t.o*(this._number >= 0 ? 3.3 : 1); } else { /* Left/Right */ t.x = t.o*(this._number >= 0 ? 1 : 3.3); t.y = t.o*2; } t.o *= 4; return t; }; /** * Set the size of this button. * @param {Number} The new size. * @returns {Object} This button. */ NumberButton.prototype.setSize = function (size) { GeneralButton.prototype.setSize.call(this, size || this.size); // If the button should expand horizontally it will be rotated. // So we always want to change height, not width. this.bg.height *= this.representations.length; return this; }; /** * Set the direction of the background button (where the arrow should point). * @param {Boolean} val - True = up/down, false = left/right. * @returns {Object} This button. */ NumberButton.prototype.setDirection = function (val) { this.direction = val; if (val) { this.bg.rotation = -Math.PI/2; this.bg.y += this.bg.width; this.bg.adjusted = this.bg.width; } else { this.bg.rotation = 0; this.bg.y -= this.bg.adjusted || 0; } if (this.number) { this.updateGraphics(); } return this; }; },{"../../global.js":8,"../../pubsub.js":34,"../representations/DiceRepresentation.js":27,"../representations/DotsRepresentation.js":28,"../representations/FingerRepresentation.js":29,"../representations/NumberRepresentation.js":30,"../representations/StrikeRepresentation.js":31,"../representations/YesnoRepresentation.js":32,"./GeneralButton.js":23}],25:[function(require,module,exports){ var GeneralButton = require('./GeneralButton.js'); module.exports = SpriteButton; SpriteButton.prototype = Object.create(GeneralButton.prototype); SpriteButton.prototype.constructor = SpriteButton; /** * A button with a sprite on it. * @param {Object} game - A reference to the Phaser game. * @param {string} key - The sprite key. * @param {string} frame - The frame of the sprite (optional). * @param {Object} options - A list of options (see GeneralButton). * @return {Object} Itself. */ function SpriteButton (game, key, frame, options) { GeneralButton.call(this, game, options); // Parent constructor. var half = this.size/2; this.sprite = this.create(half, half, key, frame); this.sprite.anchor.set(0.5); this._scaleSprite(); return this; } /** * Scale the sprite according to the button size. * @private */ SpriteButton.prototype._scaleSprite = function () { var padded = this.size*0.9; this.sprite.scale.set(padded/(this.sprite.width > this.sprite.height ? this.sprite.width : this.sprite.height)); }; /** * Set the size of this button. * @param {Number} The new size. */ SpriteButton.prototype.setSize = function (size) { GeneralButton.prototype.setSize.call(this, size); if (this.sprite) { this._scaleSprite(); } }; },{"./GeneralButton.js":23}],26:[function(require,module,exports){ var GeneralButton = require('./GeneralButton.js'); var GLOBAL = require('../../global.js'); module.exports = TextButton; TextButton.prototype = Object.create(GeneralButton.prototype); TextButton.prototype.constructor = TextButton; /** * A button with text on it. * @param {Object} game - A reference to the Phaser game. * @param {string} text - The text for the button. * @param {Object} options - A list of options (in addition to GeneralButton): * {number} fontSize: The size of the font (default is options.size * 0.8). * {number} strokeThickness: The size of the stroke (default is 3). * {string} strokeColor: The color of stroke (if any) (default options.color). * {boolean} doNotAdapt: True if the size should not adapt to text size (default false). * @return {Object} Itself. */ function TextButton (game, text, options) { GeneralButton.call(this, game, options); // Parent constructor. this.doNotAdapt = options.doNotAdapt || false; var half = this.size/2; var fontSize = (options.fontSize || this.size*0.8); this._text = game.add.text(half, half, text, { font: fontSize + 'pt ' + GLOBAL.FONT, fill: this.color, stroke: options.strokeColor || this.color, strokeThickness: options.strokeThickness || 3 }, this); this._text.anchor.set(0.5, 0.45); /* Do this to adapt button size. */ this.text = this.text; if (options.onClick) { this._clicker = options.onClick; // This will be called in the GeneralButton's onInputDown this.onClick = function () { if (this._clicker) { this._clicker(this.text); } }; } return this; } /** * @property {string} text - The text on the button. */ Object.defineProperty(TextButton.prototype, 'text', { get: function() { return this._text.text; }, set: function(value) { this._text.text = value; if (!this.doNotAdapt) { this.adaptSize(); } } }); /** * Adapt the button background to the text size. */ TextButton.prototype.adaptSize = function () { this.bg.width = (this._text.width > this.size ? this._text.width : this.size) + 30; this.bg.height = (this._text.height > this.size ? this._text.height : this.size); this._text.x = this.bg.width/2; this._text.y = this.bg.height/2; }; },{"../../global.js":8,"./GeneralButton.js":23}],27:[function(require,module,exports){ module.exports = DiceRepresentation; DiceRepresentation.prototype = Object.create(Phaser.Sprite.prototype); DiceRepresentation.prototype.constructor = DiceRepresentation; /** * Dice representation of a number. * This is similar to DotsRepresentation, but has a pattern for the dot positions. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number to represent. * @param {number} x - X position. * @param {number} y - Y position. * @param {number} size - Width and height of the representation (default 100). * @param {string} color - The color of the representation (default '#000000'). * @return {Object} Itself. */ function DiceRepresentation (game, number, x, y, size, color) { size = size || 100; this.radius = parseInt(size/8); var top = this.radius+1; var bottom = size-this.radius-1; var left = top; var right = bottom; var middle = parseInt(size/2); /* * For more information about context: * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */ var bmd = game.add.bitmapData(size, size); var ctx = bmd.ctx; ctx.fillStyle = color || '#000000'; ctx.beginPath(); if (number === 1) { this.createDots(ctx, [[middle, middle]]); } else if (number === 2) { this.createDots(ctx, [[left, top], [right, bottom]]); } else if (number === 3) { this.createDots(ctx, [[left, top], [middle, middle], [right, bottom]]); } else if (number === 4) { this.createDots(ctx, [[left, top], [right, top], [left, bottom], [right, bottom]]); } else if (number === 5) { this.createDots(ctx, [[left, top], [right, top], [middle, middle], [left, bottom], [right, bottom]]); } else if (number === 6) { this.createDots(ctx, [[left, top], [right, top], [left, middle], [right, middle], [left, bottom], [right, bottom]]); } else if (number === 7) { this.createDots(ctx, [[left, top], [right, top], [left, middle], [middle, middle], [right, middle], [left, bottom], [right, bottom]]); } else if (number === 8) { this.createDots(ctx, [[left, top], [middle, top], [right, top], [left, middle], [right, middle], [left, bottom], [middle, bottom], [right, bottom]]); } else if (number === 9) { this.createDots(ctx, [[left, top], [middle, top], [right, top], [left, middle], [middle, middle], [right, middle], [left, bottom], [middle, bottom], [right, bottom]]); } ctx.closePath(); ctx.fill(); Phaser.Sprite.call(this, game, x, y, bmd); // Parent constructor. return this; } DiceRepresentation.prototype.createDots = function (ctx, dots) { ctx.arc(dots[0][0], dots[0][1], this.radius, 0, Math.PI2); for (var i = 1; i < dots.length; i++) { ctx.moveTo(dots[i][0], dots[i][1]); ctx.arc(dots[i][0], dots[i][1], this.radius, 0, Math.PI2); } }; },{}],28:[function(require,module,exports){ module.exports = DotsRepresentation; DotsRepresentation.prototype = Object.create(Phaser.Sprite.prototype); DotsRepresentation.prototype.constructor = DotsRepresentation; /** * Dots representation of a number. * This is similar to DiceRepresentation, but has a random dot position. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number to represent. * @param {number} xPos - X position. * @param {number} yPos - Y position. * @param {number} size - Width and height of the representation (default 100). * @param {string} color - The color of the representation (default '#000000'). * @return {Object} Itself. */ function DotsRepresentation (game, number, xPos, yPos, size, color) { size = size || 100; var radius = parseInt(size/9); var dotSize = radius*2 + 1; // diameter + offset var left = radius + 1; var right = size - radius - 1; var top = left; var bottom = right; /* * For more information about context: * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */ var bmd = game.add.bitmapData(size, size); var ctx = bmd.ctx; ctx.fillStyle = color || '#000000'; ctx.beginPath(); /* Fill up with dots. */ var dots = []; var x, y, t, i, overlap; while (dots.length < number) { /* The dots will be placed randomly. */ x = game.rnd.integerInRange(left, right); y = game.rnd.integerInRange(top, bottom); t = { x: x, y: y }; overlap = false; /* And then checked that they do not overlap other dots. */ for (i = 0; i < dots.length; i++) { if (game.physics.arcade.distanceBetween(t, dots[i]) < dotSize) { overlap = true; break; } } /* And added if they do not. */ if (!overlap) { dots.push(t); ctx.moveTo(x, y); ctx.arc(x, y, radius, 0, Math.PI2); } } ctx.closePath(); ctx.fill(); Phaser.Sprite.call(this, game, xPos, yPos, bmd); // Parent constructor. return this; } },{}],29:[function(require,module,exports){ module.exports = FingerRepresentation; FingerRepresentation.prototype = Object.create(Phaser.Sprite.prototype); FingerRepresentation.prototype.constructor = FingerRepresentation; /** * Finger representation of a number. * NOTE: Only available between numbers 1-9. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number to represent. * @param {number} xPos - X position. * @param {number} yPos - Y position. * @param {number} size - Width and height of the representation (default 100). * @param {string} color - The color of the representation (default '#000000'). * @return {Object} Itself. */ function FingerRepresentation (game, number, xPos, yPos, size, color) { size = size || 100; var half = size/2; var width = size/20; var middle = 11.2; /* * For more information about context: * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */ var bmd = game.add.bitmapData(size, size); var ctx = bmd.ctx; ctx.fillStyle = color || '#000000'; ctx.beginPath(); var x, y, height; if (number >= 1) { x = 0; y = half*0.8; height = half*0.7; ctx.moveTo(x, y); ctx.lineTo(width, y - width); ctx.lineTo(width*2.5, y + height); ctx.lineTo(width*1.5, y + height + width); ctx.lineTo(x, y); } if (number >= 2) { x = width*2.2; y = half*0.5; height = half*0.9; ctx.moveTo(x, y); ctx.lineTo(x + width, y - width); ctx.lineTo(x + width*2, y + height); ctx.lineTo(x + width, y + height + width); ctx.lineTo(x, y); } if (number >= 3) { x = width*4.4; y = half*0.3; height = half*1.1; ctx.moveTo(x, y); ctx.lineTo(x + width, y); ctx.lineTo(x + width, y + height); ctx.lineTo(x, y + height); ctx.lineTo(x, y); } if (number >= 4) { x = width*6.6; y = half*0.5; height = half; ctx.moveTo(x, y - width); ctx.lineTo(x + width, y); ctx.lineTo(x + width/2, y + height); ctx.lineTo(x - width/2, y + height - width); ctx.lineTo(x, y - width); } if (number >= 5) { x = width*8.6; y = half; height = half*0.7; ctx.moveTo(x, y - width); ctx.lineTo(x + width, y); ctx.lineTo(x, y + height); ctx.lineTo(x - width, y + height + width); ctx.lineTo(x, y - width); } if (number >= 6) { x = width*middle; y = half; height = half*0.7; ctx.moveTo(x, y); ctx.lineTo(x + width, y - width); ctx.lineTo(x + width*2, y + height + width); ctx.lineTo(x + width, y + height); ctx.lineTo(x, y); } if (number >= 7) { x = width*(middle+2); y = half*0.5; height = half; ctx.moveTo(x, y); ctx.lineTo(x + width, y - width); ctx.lineTo(x + width*1.5, y + height - width); ctx.lineTo(x + width/2, y + height); ctx.lineTo(x, y); } if (number >= 8) { x = width*(middle + 4.2); y = half*0.3; height = half*1.1; ctx.moveTo(x, y); ctx.lineTo(x + width, y); ctx.lineTo(x + width, y + height); ctx.lineTo(x, y + height); ctx.lineTo(x, y); } if (number >= 9) { x = width*(middle + 6.4); y = half*0.5; height = half*0.9; ctx.moveTo(x, y - width); ctx.lineTo(x + width, y); ctx.lineTo(x, y + height + width); ctx.lineTo(x - width, y + height); ctx.lineTo(x, y - width); } ctx.closePath(); ctx.fill(); Phaser.Sprite.call(this, game, xPos, yPos, bmd); // Parent constructor. return this; } },{}],30:[function(require,module,exports){ var GLOBAL = require('../../global.js'); module.exports = NumberRepresentation; NumberRepresentation.prototype = Object.create(Phaser.Text.prototype); NumberRepresentation.prototype.constructor = NumberRepresentation; /** * Number symbol representation of a number. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number to represent. * @param {number} x - X position. * @param {number} y - Y position. * @param {number} size - Font size of the representation (default 50). * @param {string} color - The color of the representation (default '#000000'). * @return {Object} Itself. */ function NumberRepresentation (game, number, x, y, size, color) { size = size || 50; color = color || '#000000'; Phaser.Text.call(this, game, x+size, y+size, number.toString(), { font: size + 'pt ' + GLOBAL.FONT, fill: color, stroke: color, strokeThickness: 3 }); // Parent constructor. this.anchor.set(0.5); //this.updatePosition(); return this; } NumberRepresentation.updatePosition = function(x1,y1) { this.x = x1; this.y = y1; }; },{"../../global.js":8}],31:[function(require,module,exports){ module.exports = StrikeRepresentation; StrikeRepresentation.prototype = Object.create(Phaser.Sprite.prototype); StrikeRepresentation.prototype.constructor = StrikeRepresentation; /** * Strike/Tick representation of a number. * @param {Object} game - A reference to the Phaser game. * @param {number} number - The number to represent. * @param {number} xPos - X position. * @param {number} yPos - Y position. * @param {number} size - Width and height of the representation (default 100). * @param {string} color - The color of the representation (default '#000000'). * @param {number} max - If you have a range of numbers, set this to the highest one, * that way the height of the individual strikes will be the same * (default argument number). * @return {Object} Itself. */ function StrikeRepresentation (game, number, xPos, yPos, size, color, max) { size = size || 100; max = max || number; max = Math.abs(max); if (max < number) { max = number; } var diagTop = 0.8; var diagBottom = 0.2; var width = size/10; var half = width/2; var padding = width*1.25; var offset = 2; var height = size/Math.ceil(max/5) - offset; var pos = (size - width - padding*2) / 3; /* * For more information about context: * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */ var bmd = new Phaser.BitmapData(game, '', size, size); var ctx = bmd.ctx; ctx.fillStyle = color || '#000000'; ctx.beginPath(); var x = padding; var y = offset/2; for (var i = 1; i <= number; i++) { if (i % 5 === 0 && i !== 0) { ctx.moveTo(0, y + height*diagTop - half ); ctx.lineTo(size - half, y + height*diagBottom ); ctx.lineTo(size, y + height*diagBottom + half); ctx.lineTo(half, y + height*diagTop ); ctx.lineTo(0, y + height*diagTop - half ); x = padding; y += height + offset; } else { ctx.fillRect(x, y, width, height); x += pos; } } ctx.closePath(); ctx.fill(); Phaser.Sprite.call(this, game, xPos, yPos, bmd); // Parent constructor. return this; } },{}],32:[function(require,module,exports){ module.exports = YesnoRepresentation; YesnoRepresentation.prototype = Object.create(Phaser.Sprite.prototype); YesnoRepresentation.prototype.constructor = YesnoRepresentation; /** * Yes - No representation. * @param {Object} game - A reference to the Phaser game. * @param {boolean} yes - True is yes, false is no. * @param {number} x - X position. * @param {number} y - Y position. * @param {number} size - Font size of the representation (default 50). * @return {Object} Itself. */ function YesnoRepresentation (game, yes, x, y, size) { size = size || 50; var typ = yes ? 'yes' : 'no'; Phaser.Sprite.call(this, game, x, y, 'objects', typ + 1); this.width = size; this.height = size; this.animations.add('cycle', [typ + 1, typ + 2, typ + 1, typ + 3, typ + 1], 5, true).play(); return this; } },{}],33:[function(require,module,exports){ //var backend = require('./backend.js'); var GLOBAL = require('./global.js'); var LANG = require('./language.js'); var EventSystem = require('./pubsub.js'); module.exports = Player; /** * Creates an instance of Player. * The player will load information about it from server upon instantiation. * * @constructor * @param {Object} game - A reference to the Phaser game. */ function Player (game) { this.game = game; /** * @property {number} _agent - A pointer to the agent type. * @private */ this._agent = null; /** * @property {number} _water - The amount of water the player has. * @private */ this._water = 0; /** * @property {number} name - The name of the player. */ this.name = LANG.TEXT.anonymous; /** * @property {number} tint - A tint for the agent. */ this.tint = 0xffffff; /* Load player data from server. */ /*var data = backend.getPlayer(); if (data) { this.name = data.name; this.agent = GLOBAL.AGENT[data.agent.type]; this.tint = data.agent.tint || this.tint; this._water = data.water || 0; // Do not use water since that fires an event. }*/ this.name= 'Erik Anderberg'; this._agent = GLOBAL.AGENT[1]; this.tint = this.tint; return this; } /** * @property {number} maxWater - The maximum amount of water the player can have. */ Player.prototype.maxWater = 6; /** * @property {number} water - The amount of water the player has. * Publishes waterAdded event when changed. */ Object.defineProperty(Player.prototype, 'water', { get: function() { return this._water; }, set: function(value) { if (value >= 0) { value = value > this.maxWater ? this.maxWater : value; var diff = value - this._water; this._water = value; EventSystem.publish(GLOBAL.EVENT.waterAdded, [this._water, diff]); } } }); /** * @property {Object} agent - Pointer to the agent constructor. * NOTE: Do not use this to create an agent, use createAgent. * NOTE: Updates the language object as well. */ Object.defineProperty(Player.prototype, 'agent', { get: function() { return this._agent; }, set: function(value) { this._agent = value; if (this._agent && this._agent.prototype.id) { LANG.setAgent(this._agent.prototype.id); } } }); /** * Creates an agent of the current type the player uses. * @returns {Object} An instance of the agent belonging to the player. */ Player.prototype.createAgent = function () { var agent = new this.agent(this.game); agent.tint = this.tint; return agent; }; },{"./global.js":8,"./language.js":9,"./pubsub.js":34}],34:[function(require,module,exports){ /** * A publish/subscribe style event system. * Subscribe to an event and it will run when someone publish it. * * There are two subscription types: regular and persistent. * The difference is that persistent will not be removed by * the clear function unless explicitly specified. * @global */ module.exports = { /** * Registered subscriptions. * @property {Object} _events * @private */ _events: {}, /** * Registered persistent subscriptions. * @property {Object} _persistent * @private */ _persistent: {}, /** * Push a subscription to a list. * @param {Object} to - The list to add to (use _events or _persistent). * @param {string} topic - The topic of the event. * @param {function} callback - The function to run when topic is published. * @private */ _pushEvent: function (to, topic, callback) { if (!to[topic]) { to[topic] = []; } to[topic].push(callback); }, /** * Publish an event. This will run all its subscriptions. * @param {string} topic - The topic of the event. * @param {Array} args - The arguments to supply to the subscriptions. */ publish: function (topic, args) { var subs = [].concat(this._events[topic], this._persistent[topic]); var len = subs.length; while (len--) { if (subs[len]) { subs[len].apply(this, args || []); } } }, /** * Subscribe to a certain event. * NOTE: scope will be lost. * @param {string} topic - The topic of the event. * @param {function} callback - The function to run when event is published. * @param {boolean} persistent - If the subscription should be added to the persistent list. * @return {Array} A handle to the subscription. */ subscribe: function (topic, callback, persistent) { this._pushEvent((persistent ? this._persistent : this._events), topic, callback); return [topic, callback]; // Array }, /** * Unsubscribe to a certain regular event. * @param {Array|string} handle - The array returned by the subscribe function or * the topic if handle is missing. * @param {function} callback - Supply this if you do not have an array handle. */ unsubscribe: function (handle, callback) { var subs = this._events[callback ? handle : handle[0]]; callback = callback || handle[1]; var len = subs ? subs.length : 0; while (len--) { if (subs[len] === callback) { subs.splice(len, 1); } } }, /** * Clear the event lists. * @param {boolean} persistent - True will delete all persistent events as well. */ clear: function (persistent) { this._events = {}; if (persistent) { this._persistent = {}; } } }; },{}],35:[function(require,module,exports){ var SuperState = require('./SuperState.js'); var backend = require('../backend.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var util = require('../utils.js'); var Hedgehog = require('../agent/Hedgehog.js'); var Mouse = require('../agent/Mouse.js'); var Panda = require('../agent/Panda.js'); var Menu = require('../objects/Menu.js'); var NumberButton = require('../objects/buttons/NumberButton.js'); var TextButton = require('../objects/buttons/TextButton.js'); module.exports = AgentSetupState; AgentSetupState.prototype = Object.create(SuperState.prototype); AgentSetupState.prototype.constructor = AgentSetupState; /** * The state for choosing agent. */ function AgentSetupState () {} /* Phaser state function */ AgentSetupState.prototype.preload = function() { this.load.audio('entryMusic', ['audio/music.m4a', 'audio/music.ogg', 'audio/music.mp3']); this.load.audio('chooseSpeech', LANG.SPEECH.agentIntro.speech); this.load.atlasJSONHash(Panda.prototype.id, 'img/agent/panda/atlas.png', 'img/agent/panda/atlas.json'); this.load.atlasJSONHash(Hedgehog.prototype.id, 'img/agent/hedgehog/atlas.png', 'img/agent/hedgehog/atlas.json'); this.load.atlasJSONHash(Mouse.prototype.id, 'img/agent/mouse/atlas.png', 'img/agent/mouse/atlas.json'); }; /* Phaser state function */ AgentSetupState.prototype.create = function () { var _this = this; var spacing = 450; var scale = { x: 0.3, y: 0.3 }; // Default scale var scaleActive = { x: 0.4, y: 0.4 }; // Scale when pushed var scalePicked = { x: 0.5, y: 0.5 }; // Scale when pushed the second time var slideTime = 1; var fontStyle = { font: '50pt ' + GLOBAL.FONT, fill: '#ffff00', stroke: '#000000', strokeThickness: 5 }; var waving; var speech = util.createAudioSheet.call(this, 'chooseSpeech', LANG.SPEECH.agentIntro.markers); function clickAgent () { if (a === this) { /* Agent was already active, go into coloring mode */ pickAgent(); } else { if (a) { cancelAgent(); TweenMax.to(a.scale, slideTime, scale); // Scale down the old agent } a = this; TweenMax.to(a.scale, slideTime, scaleActive); // Scale up the new agent // Move the agent group to get the sliding effect on all agents TweenMax.to(agents, slideTime, { x: -(agents.children.indexOf(a) * spacing), ease: Power2.easeOut, onStart: function () { speech.stop(); }, onComplete: function () { a.say(speech, a.id + 'Hello').play(a.id + 'Hello'); waving = a.wave(2, 1); } }); } } function fadeInterface (value) { confirm.text = LANG.TEXT.confirmFriend + a.agentName + '?'; util.fade(title, !value, value ? 0.2 : 0.5); util.fade(confirm, value, !value ? 0.2 : 0.5); util.fade(noToAgent, value); util.fade(yesToAgent, value); util.fade(color, value); } function pickAgent () { TweenMax.to(a.scale, 0.5, scalePicked); fadeInterface(true); } function cancelAgent () { TweenMax.to(a.scale, 0.5, scaleActive); fadeInterface(false); noToAgent.reset(); } function chooseAgent () { _this.input.disabled = true; if (waving) { waving.kill(); } fadeInterface(false); speech.stop(); var t = new TimelineMax(); t.addSound(speech, a, a.id + 'FunTogether'); t.addCallback(function () { a.fistPump(); backend.putAgent({ agent: { type: a.key, tint: a.tint } }); _this.game.player.agent = GLOBAL.AGENT[a.key]; _this.game.player.tint = a.tint; }, 0); t.addCallback(function () { _this.input.disabled = false; _this.state.start(GLOBAL.STATE.beach); }, '+=0.5'); } // Add music this.add.music('entryMusic', 0.3, true).play(); // Add background this.add.image(0, 0, 'entryBg'); var agents = this.add.group(); agents.x = spacing; var a; for (var key in GLOBAL.AGENT) { a = new GLOBAL.AGENT[key](this.game); this.add.text(0, -(a.body.height/2) - 50, a.agentName, fontStyle, a).anchor.set(0.5); a.x = this.world.centerX + spacing * key; a.y = this.world.centerY + 70; a.scale.x = scale.x; a.scale.y = scale.y; a.body.inputEnabled = true; a.body.events.onInputDown.add(clickAgent, a); a.key = key; agents.add(a); } a = null; var title = this.add.text(this.world.centerX, 75, LANG.TEXT.pickFriend, fontStyle); title.anchor.set(0.5); var confirm = this.add.text(this.world.centerX, 75, '', fontStyle); confirm.anchor.set(0.5); confirm.visible = false; var noToAgent = new NumberButton(this.game, 2, GLOBAL.NUMBER_REPRESENTATION.yesno, { x: this.world.centerX - 275, y: this.world.centerY*0.5, size: 75, onClick: cancelAgent }); noToAgent.visible = false; this.world.add(noToAgent); var yesToAgent = new NumberButton(this.game, 1, GLOBAL.NUMBER_REPRESENTATION.yesno, { x: this.world.centerX + 200, y: this.world.centerY*0.5, size: 75, onClick: chooseAgent }); yesToAgent.visible = false; this.world.add(yesToAgent); var color = new TextButton(this.game, LANG.TEXT.changeColor, { x: this.world.centerX, y: this.world.height - 75, fontSize: 30, onClick: function () { a.tint = _this.game.rnd.integerInRange(0x000000, 0xffffff); } }); color.x -= color.width/2; color.visible = false; this.world.add(color); this.world.add(new Menu(this.game)); /* When the state starts. */ this.startGame = function () { /* Choose the first agent if player does not have one */ var current = 0; if (this.game.player.agent) { for (var k in agents.children) { if (agents.children[k].id === this.game.player.agent.prototype.id) { agents.children[k].tint = this.game.player.tint; current = k; break; } } } agents.children[current].body.events.onInputDown.dispatch(); }; }; /* Phaser state function */ AgentSetupState.prototype.shutdown = function () { if (!this.game.player.agent || this.game.player.agent.prototype.id !== Panda.prototype.id) { this.cache.removeSound(Panda.prototype.id + 'Speech'); this.cache.removeImage(Panda.prototype.id); } if (!this.game.player.agent || this.game.player.agent.prototype.id !== Hedgehog.prototype.id) { this.cache.removeSound(Hedgehog.prototype.id + 'Speech'); this.cache.removeImage(Hedgehog.prototype.id); } if (!this.game.player.agent || this.game.player.agent.prototype.id !== Mouse.prototype.id) { this.cache.removeSound(Mouse.prototype.id + 'Speech'); this.cache.removeImage(Mouse.prototype.id); } SuperState.prototype.shutdown.call(this); }; },{"../agent/Hedgehog.js":3,"../agent/Mouse.js":4,"../agent/Panda.js":5,"../backend.js":6,"../global.js":8,"../language.js":9,"../objects/Menu.js":17,"../objects/buttons/NumberButton.js":24,"../objects/buttons/TextButton.js":26,"../utils.js":48,"./SuperState.js":41}],36:[function(require,module,exports){ var SuperState = require('./SuperState.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var Cover = require('../objects/Cover.js'); var Menu = require('../objects/Menu.js'); module.exports = BeachState; BeachState.prototype = Object.create(SuperState.prototype); BeachState.prototype.constructor = BeachState; /** * The beach of the game. * The base from where you go to the subgames * Basically the GardenState without the garden and backend */ function BeachState () {} /* Phaser state function */ BeachState.prototype.preload = function() { if (!this.cache._sounds[this.game.player.agent.prototype.id + 'Speech']) { this.load.audio(this.game.player.agent.prototype.id + 'Speech', LANG.SPEECH.AGENT.speech); } if (!this.cache._sounds.gardenMusic) { this.load.audio('gardenMusic', ['audio/garden/music.m4a', 'audio/garden/music.ogg', 'audio/garden/music.mp3']); } if (!this.cache._images.garden) { this.load.atlasJSONHash('garden', 'img/garden/atlas.png', 'img/garden/atlas.json'); } }; BeachState.prototype.create = function () { // Add music this.add.music('gardenMusic', 0.2, true).play(); // Add background this.add.sprite(0, 0, 'garden', 'bg'); // Add sign to go to next scenario //var sure = false; var sign = this.add.sprite(750, 100, 'garden', 'sign'); sign.inputEnabled = true; sign.events.onInputDown.add(function () { // This happens either on local machine or on "trial" version of the game. if (typeof Routes === 'undefined' || Routes === null) { this.game.state.start(GLOBAL.STATE.scenario, true, false); return; } var t = new TimelineMax(); t.addCallback(function () { disabler.visible = true; }); t.addCallback(function () { disabler.visible = false; }); }, this); var startPos = 200; var height = (this.world.height - startPos)/3; var agent = this.game.player.createAgent(); agent.scale.set(0.2); agent.x = -100; agent.y = startPos + height - agent.height/2; this.world.add(agent); /* Add disabler. */ var disabler = new Cover(this.game, '#ffffff', 0); this.world.add(disabler); /* Add the menu */ this.world.add(new Menu(this.game)); this.startGame = function () { var t = new TimelineMax().skippable(); t.add(agent.move({ x: this.world.centerX }, 3)); t.addLabel('sign'); t.add(agent.wave(1, 1)); t.addCallback(agent.eyesFollowObject, 'sign', [sign], agent); t.addSound(agent.speech, agent, 'gardenSign', 'sign'); t.addCallback(function () { agent.eyesStopFollow(); disabler.visible = false; }, null, null, this); }; }; },{"../global.js":8,"../language.js":9,"../objects/Cover.js":13,"../objects/Menu.js":17,"./SuperState.js":41}],37:[function(require,module,exports){ var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var EventSystem = require('../pubsub.js'); var Modal = require('../objects/Modal.js'); var Hedgehog = require('../agent/Hedgehog.js'); var Mouse = require('../agent/Mouse.js'); var Panda = require('../agent/Panda.js'); module.exports = BootState; /** * The boot state will load the first parts of the game and common game assets. * Add assets that will be used by many states. */ function BootState () {} /** * @property {boolean} _isLoaded - Used for loading all assets. See bootGame. * @default * @private */ BootState.prototype._fontLoaded = false; /* Phaser state function */ BootState.prototype.preload = function () { var _this = this; GLOBAL.STATE_KEYS = Object.keys(this); GLOBAL.STATE_KEYS.push('loaded'); /* Make sure tweens are stopped when pausing. */ this.game.onPause.add(function () { TweenMax.globalTimeScale(0); this.game.sound.pauseAll(); }, this); this.game.onResume.add(function () { TweenMax.globalTimeScale(1); this.game.sound.resumeAll(); }, this); /* Show loading progress accordingly */ this.load.onFileComplete.add(function (progress) { document.querySelector('.progress').innerHTML = progress + '%'; if (progress >= 100) { document.querySelector('.loading').style.display = 'none'; } else { document.querySelector('.loading').style.display = 'block'; } }); /* Respond to connection problems */ EventSystem.subscribe(GLOBAL.EVENT.connection, function (status) { if (status) { document.querySelector('.loading').style.display = 'none'; } else { document.querySelector('.progress').innerHTML = LANG.TEXT.connectionLost; document.querySelector('.loading').style.display = 'block'; } }, true); EventSystem.subscribe(GLOBAL.EVENT.connectionLost, function () { _this.game.world.add(new Modal(_this.game, LANG.TEXT.connectionLostMessage, 20, function () { document.querySelector('.loading').style.display = 'none'; _this.game.state.start(GLOBAL.STATE.entry); })); }, true); /* Make sure the game scales according to resolution */ this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; /* Setup sound manager */ // Array to hold music objects, needed to change bg-volume this.sound._music = []; /* Use stored volumes, if any. */ this.sound._fgVolume = 1; if (typeof localStorage.fgVolume !== 'undefined') { this.sound.fgVolume = localStorage.fgVolume; } this.sound._bgVolume = 1; if (typeof localStorage.bgVolume !== 'undefined') { this.sound.bgVolume = localStorage.bgVolume; } // Overshadow the original sound managers add function. // To save maxVolume for the sound and setup actual volume according to fg. this.sound.add = function (key, volume, loop, connect) { var sound = Phaser.SoundManager.prototype.add.call(this, key, volume, loop, connect); sound.maxVolume = sound.volume; sound.volume = sound.maxVolume * this.fgVolume; return sound; }; // Overshadow the original sound managers remove function. // To make sure that object is removed from music array. this.sound.remove = function (sound) { var success = Phaser.SoundManager.prototype.remove.call(this, sound); if (this._music.indexOf(sound) >= 0) { this._music.splice(this._music.indexOf(sound), 1); } return success; }; // Overshadow the original sound objects play function. // To set volume according to fg/bg. var soundFunction = Phaser.Sound.prototype.play; Phaser.Sound.prototype.play = function (marker, position, volume, loop, forceRestart) { var container = this.game.sound[this.game.sound._music.indexOf(this) >= 0 ? 'bgVolume' : 'fgVolume']; volume = (typeof volume !== 'number' ? this.maxVolume : volume) * container; return soundFunction.call(this, marker, position, volume, loop, forceRestart); }; /* Allow images to be served from external sites, e.g. amazon */ this.load.crossOrigin = 'anonymous'; /* Load the Google WebFont Loader script */ // The Google WebFont Loader will look for this specific object. window.WebFontConfig = { active: function () { _this._fontLoaded = true; }, google: { families: [GLOBAL.FONT] } }; this.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'); /* Agent related assets */ if (this.game.player.agent) { var name = this.game.player.agent.prototype.id; this.load.audio(name + 'Speech', LANG.SPEECH.AGENT.speech); if (name === Panda.prototype.id) { this.load.atlasJSONHash(name, 'img/agent/panda/atlas.png', 'img/agent/panda/atlas.json'); } else if (name === Hedgehog.prototype.id) { this.load.atlasJSONHash(name, 'img/agent/hedgehog/atlas.png', 'img/agent/hedgehog/atlas.json'); } else if (name === Mouse.prototype.id) { this.load.atlasJSONHash(name, 'img/agent/mouse/atlas.png', 'img/agent/mouse/atlas.json'); } } /* Common game assets */ this.load.audio('click', ['audio/click.m4a', 'audio/click.ogg', 'audio/click.mp3']); this.load.atlasJSONHash('objects', 'img/objects/objects.png', 'img/objects/objects.json'); this.load.atlasJSONHash('cookie', 'img/objects/cookies.png', 'img/objects/cookies.json'); /* All sounds are purged from cache when switching state (memory issues), set this to not delete a sound. */ this.sound._doNotDelete = ['click', Panda.prototype.id + 'Speech', Hedgehog.prototype.id + 'Speech', Mouse.prototype.id + 'Speech']; /* Load the entry state assets as well, no need to do two loaders. */ this.load.image('entryBg', 'img/jungle.png'); }; /* Phaser state function */ BootState.prototype.update = function () { /** * The next state will be called when everything has been loaded. * So we need to wait for the web font to set its loaded flag. */ if (this._fontLoaded) { if (typeof Routes === 'undefined' || Routes === null) { console.warn('You are missing a route to the server, no data will be fetched or sent.'); } if (GLOBAL.debug) { console.log('You are running in debug mode, sneaking into choose scenario state :)'); this.game.state.start(GLOBAL.STATE.scenario); } else { this.game.state.start(GLOBAL.STATE.entry); } } }; },{"../agent/Hedgehog.js":3,"../agent/Mouse.js":4,"../agent/Panda.js":5,"../global.js":8,"../language.js":9,"../objects/Modal.js":18,"../pubsub.js":34}],38:[function(require,module,exports){ var SuperState = require('./SuperState.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var Panda = require('../agent/Panda.js'); var Menu = require('../objects/Menu.js'); var NumberButton = require('../objects/buttons/NumberButton.js'); var TextButton = require('../objects/buttons/TextButton.js'); module.exports = ChooseScenarioState; ChooseScenarioState.prototype = Object.create(SuperState.prototype); ChooseScenarioState.prototype.constructor = ChooseScenarioState; /* The menu for choosing agent, */ function ChooseScenarioState () {} /* Phaser state function */ ChooseScenarioState.prototype.preload = function() { if (!this.game.player.agent) { console.log('Setting agent to: ' + Panda.prototype.id); this.game.player.agent = Panda; this.load.audio('pandaSpeech', LANG.SPEECH.AGENT.speech); this.load.atlasJSONHash('panda', 'img/agent/panda/atlas.png', 'img/agent/panda/atlas.json'); } }; /* Phaser state function */ ChooseScenarioState.prototype.create = function () { var _this = this; this.add.image(0, 0, 'entryBg'); var textOptions = { font: '20pt ' + GLOBAL.FONT, fill: '#ffffff', stroke: '#000000', strokeThickness: 4 }; var offset = 10; var i, t, key; /* Subgame selection */ var subgame = null; var gameClicker = function () { if (subgame !== this && subgame) { subgame.reset(); } subgame = this; }; this.add.text(75, 80, 'Subgame', textOptions); var games = [ ['Shark', GLOBAL.STATE.sharkGame], ['Bird Hero', GLOBAL.STATE.birdheroGame], ['Lizard', GLOBAL.STATE.lizardGame], ['Bee Flight', GLOBAL.STATE.beeGame] ]; var gameButtons = []; for (i = 0; i < games.length; i++) { t = new TextButton(this.game, games[i][0], { x: t ? t.x + t.width + offset : 50, y: 125, fontSize: 25, onClick: gameClicker, keepDown: true }); t.gameState = games[i][1]; this.world.add(t); gameButtons.push(t); } /* Range selection */ var range = null; var rangeClicker = function () { if (range !== this && range) { range.reset(); } range = this; }; this.add.text(75, 220, 'Number Range', textOptions); var rangeButtons = []; t = null; for (key in GLOBAL.NUMBER_RANGE) { t = new TextButton(this.game, '1 - ' + GLOBAL.NUMBER_RANGE[key], { x: t ? t.x + t.width + offset : 50, y: 265, fontSize: 33, onClick: rangeClicker, keepDown: true }); t.range = key; this.world.add(t); rangeButtons[key] = t; } /* Representation selection */ var representation = null; var representationClicker = function () { if (representation !== this && representation) { representation.reset(); } representation = this; }; this.add.text(75, 360, 'Number Representation', textOptions); var representationButtons = []; i = 0; for (key in GLOBAL.NUMBER_REPRESENTATION) { if (key === 'objects' || key === 'yesno') { continue; } representationButtons[GLOBAL.NUMBER_REPRESENTATION[key]] = new NumberButton(this.game, 4, GLOBAL.NUMBER_REPRESENTATION[key], { x: 50 + i*(75 + offset), y: 405, onClick: representationClicker }); this.world.add(representationButtons[representationButtons.length-1]); i++; } /* Method selection */ var method = null; var methodClicker = function () { if (method !== this && method) { method.reset(); } method = this; }; this.add.text(75, 500, 'Method', textOptions); var methods = [ ['Counting', GLOBAL.METHOD.count], ['Step-by-step', GLOBAL.METHOD.incrementalSteps], ['Addition', GLOBAL.METHOD.addition], ['Subtraction', GLOBAL.METHOD.subtraction], ['Add & Sub', GLOBAL.METHOD.additionSubtraction] ]; var methodButtons = []; t = null; for (i = 0; i < methods.length; i++) { t = new TextButton(this.game, methods[i][0], { x: t ? t.x + t.width + offset : 50, y: 545, fontSize: 20, onClick: methodClicker, keepDown: true }); t.method = methods[i][1]; this.world.add(t); methodButtons.push(t); } /* Start game (save current options) */ var startButton = new TextButton(this.game, 'Start scenario', { x: this.world.centerX - 150, y: 660, fontSize: 30, onClick: function () { if (!subgame || !subgame.gameState || !range || !range.range || !representation || !representation.representations || !method || (typeof method.method === 'undefined')) { return; } /* Persistent save for ease of use. */ localStorage.chooseSubgame = subgame.gameState; localStorage.chooseRange = range.range; localStorage.chooseRepresentation = representation.representations; localStorage.chooseMethod = method.method; _this.game.state.start(subgame.gameState, true, false, { method: method.method, representation: representation.representations, range: range.range, roundsPerMode: 3 }); } }); this.world.add(startButton); /* In case you want to check out garden instead. */ var gotoGarden = new TextButton(this.game, LANG.TEXT.gotoGarden, { x: 75, y: 5, size: 56, fontSize: 20, onClick: function () { _this.game.state.start(GLOBAL.STATE.beach); } }); this.world.add(gotoGarden); this.world.add(new Menu(this.game)); /* If we have been in this state before, we try to preset the correct buttons. */ switch (localStorage.chooseSubgame) { case GLOBAL.STATE.balloonGame: gameButtons[0].setDown(); subgame = gameButtons[0]; break; case GLOBAL.STATE.birdheroGame: gameButtons[1].setDown(); subgame = gameButtons[1]; break; case GLOBAL.STATE.lizardGame: gameButtons[2].setDown(); subgame = gameButtons[2]; break; case GLOBAL.STATE.beeGame: gameButtons[3].setDown(); subgame = gameButtons[3]; break; } if (localStorage.chooseRange) { rangeButtons[parseInt(localStorage.chooseRange)].setDown(); range = rangeButtons[parseInt(localStorage.chooseRange)]; } if (localStorage.chooseRepresentation) { representationButtons[parseInt(localStorage.chooseRepresentation)].setDown(); representation = representationButtons[parseInt(localStorage.chooseRepresentation)]; } if (localStorage.chooseMethod) { methodButtons[parseInt(localStorage.chooseMethod)].setDown(); method = methodButtons[parseInt(localStorage.chooseMethod)]; } }; },{"../agent/Panda.js":5,"../global.js":8,"../language.js":9,"../objects/Menu.js":17,"../objects/buttons/NumberButton.js":24,"../objects/buttons/TextButton.js":26,"./SuperState.js":41}],39:[function(require,module,exports){ var SuperState = require('./SuperState.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var util = require('../utils.js'); var Cover = require('../objects/Cover.js'); module.exports = EntryState; EntryState.prototype = Object.create(SuperState.prototype); EntryState.prototype.constructor = EntryState; /** * The first state of the game, where you start the game or do settings. */ function EntryState () {} /* Phaser state function */ EntryState.prototype.preload = function () { this.load.audio('entryMusic', ['audio/music.m4a', 'audio/music.ogg', 'audio/music.mp3']); }; /* Entry state assets are loaded in the boot section */ /* Phaser state function */ EntryState.prototype.create = function () { // Add music this.add.music('entryMusic', 0.7, true).play(); // Add background this.add.image(0, 0, 'entryBg'); // Add headlines var title = this.add.text(this.world.centerX, this.world.centerY/2, LANG.TEXT.title, { font: '50pt ' + GLOBAL.FONT, fill: '#ffff00', stroke: '#000000', strokeThickness: 5 }); title.anchor.set(0.5); var start = this.add.text(this.world.centerX, this.world.centerY, LANG.TEXT.continuePlaying, { font: '50pt ' + GLOBAL.FONT, fill: '#dd00dd' }); start.anchor.set(0.5); start.inputEnabled = true; var changeAgent = this.add.text(this.world.centerX, this.world.centerY*1.4, '', { font: '35pt ' + GLOBAL.FONT, fill: '#000000' }); changeAgent.anchor.set(0.5); changeAgent.inputEnabled = true; if (this.game.player.agent) { // Player has played before, we go to garden directly and show the agent change option. start.events.onInputDown.add(function () { this.state.start(GLOBAL.STATE.beach); }, this); changeAgent.text = LANG.TEXT.changeAgent + this.game.player.agent.prototype.agentName; changeAgent.events.onInputDown.add(function () { this.state.start(GLOBAL.STATE.agentSetup); }, this); } else { // Player has not played before, go to setup. start.text = LANG.TEXT.start; start.events.onInputDown.add(function () { this.state.start(GLOBAL.STATE.agentSetup); }, this); } /* Log out player. */ var log = this.add.text(20, this.world.height, LANG.TEXT.logOut + '\n' + this.game.player.name, { font: '25pt ' + GLOBAL.FONT, fill: '#000000' }); log.anchor.set(0, 1); log.inputEnabled = true; log.events.onInputDown.add(function () { window.location = window.location.origin; }); /* Credits related objects: */ var credits = this.add.text(this.world.width - 20, this.world.height, LANG.TEXT.credits, { font: '25pt ' + GLOBAL.FONT, fill: '#000000' }); credits.anchor.set(1); credits.inputEnabled = true; credits.events.onInputDown.add(function () { util.fade(credits, false, 0.3); util.fade(start, false, 0.3); util.fade(changeAgent, false, 0.3); util.fade(allCredits, true); rolling.restart(); cover.visible = true; TweenMax.to(cover, 0.5, { alpha: 0.7 }); }, this); var cover = new Cover(this.game, '#000000', 0); cover.visible = false; cover.inputEnabled = true; cover.events.onInputDown.add(function () { util.fade(credits, true); util.fade(start, true); util.fade(changeAgent, true); util.fade(allCredits, false, 0.3); rolling.pause(); TweenMax.to(cover, 0.3, { alpha: 0, onComplete: function () { cover.visible = false; } }); }, this); this.world.add(cover); var allCredits = this.add.text(this.world.centerX, this.world.height, LANG.TEXT.creditsMade + '\n\n\n' + LANG.TEXT.creditsDeveloped + ':\nErik Anderberg\t \tAgneta Gulz\nMagnus Haake\t \tLayla Husain\n\n' + LANG.TEXT.creditsProgramming + ':\nErik Anderberg\t \tMarcus Malmberg\nHenrik Söllvander\n\n' + LANG.TEXT.creditsGraphics + ':\nSebastian Gulz Haake\nErik Anderberg\n\n' + LANG.TEXT.creditsVoices + ':\n' + LANG.TEXT.pandaName + '\t-\t' + LANG.TEXT.creditsVoicePanda + '\n' + LANG.TEXT.hedgehogName + '\t-\t' + LANG.TEXT.creditsVoiceHedgehog + '\n' + LANG.TEXT.mouseName + '\t-\t' + LANG.TEXT.creditsVoiceMouse + '\n' + LANG.TEXT.woodlouseName + '\t-\t' + LANG.TEXT.creditsVoiceWoodlouse + '\n' + LANG.TEXT.lizardName + '\t-\t' + LANG.TEXT.creditsVoiceLizard + '\n' + LANG.TEXT.bumblebeeName + '\t-\t' + LANG.TEXT.creditsVoiceBumblebee + '\n' + LANG.TEXT.birdName + '\t-\t' + LANG.TEXT.creditsVoiceBird + '\n\n' + LANG.TEXT.creditsMusic + ':\nTorbjörn Gulz\n\n' + LANG.TEXT.creditsSfx + ':\nAnton Axelsson\nhttp://soundbible.com\nhttp://freesfx.co.uk\n\n' + LANG.TEXT.creditsThanks + ':\nSanne Bengtsson\t \tMaja Håkansson\nLisa Lindberg\t \tBjörn Norrliden\nBrunnsparksskolan', { font: '15pt ' + GLOBAL.FONT, fill: '#ffffff', align: 'center' }); allCredits.anchor.set(0.5, 0); allCredits.visible = false; var rolling = TweenMax.fromTo(allCredits, 30, { y: this.world.height }, { y: -allCredits.height, ease: Power0.easeInOut, repeat: -1, paused: true }); }; },{"../global.js":8,"../language.js":9,"../objects/Cover.js":13,"../utils.js":48,"./SuperState.js":41}],40:[function(require,module,exports){ var SuperState = require('./SuperState.js'); var backend = require('../backend.js'); var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var EventSystem = require('../pubsub.js'); var util = require('../utils.js'); var Counter = require('../objects/Counter.js'); var Cover = require('../objects/Cover.js'); var Menu = require('../objects/Menu.js'); var WaterCan = require('../objects/WaterCan.js'); var SpriteButton = require('../objects/buttons/SpriteButton.js'); module.exports = GardenState; GardenState.prototype = Object.create(SuperState.prototype); GardenState.prototype.constructor = GardenState; /** * The garden of the game. * This is where the player uses the water from the sessions. */ function GardenState () {} /* Phaser state function */ GardenState.prototype.preload = function() { if (!this.cache._sounds[this.game.player.agent.prototype.id + 'Speech']) { this.load.audio(this.game.player.agent.prototype.id + 'Speech', LANG.SPEECH.AGENT.speech); } if (!this.cache._sounds.gardenMusic) { this.load.audio('gardenMusic', ['audio/garden/music.m4a', 'audio/garden/music.ogg', 'audio/garden/music.mp3']); } if (!this.cache._images.garden) { this.load.atlasJSONHash('garden', 'img/garden/atlas.png', 'img/garden/atlas.json'); } //this.gardenData = backend.getGarden() || { fields: [] }; }; /* Phaser state function */ GardenState.prototype.create = function () { // Add music this.add.music('gardenMusic', 0.2, true).play(); // Add background this.add.sprite(0, 0, 'garden', 'bg'); // Add sign to go to next scenario //var sure = false; var sign = this.add.sprite(750, 100, 'garden', 'sign'); sign.inputEnabled = true; sign.events.onInputDown.add(function () { // This happens either on local machine or on "trial" version of the game. if (typeof Routes === 'undefined' || Routes === null) { this.game.state.start(GLOBAL.STATE.scenario, true, false); return; } var t = new TimelineMax(); t.addCallback(function () { disabler.visible = true; });/* if (this.game.player.water > this.game.player.maxWater - 3 && !sure) { t.addSound(agent.speech, agent, 'gardenWaterFirst'); sure = true; var sub = EventSystem.subscribe(GLOBAL.EVENT.waterPlant, function () { sure = false; EventSystem.unsubscribe(sub); }); } else {*/ var scen = backend.getScenario(); if (scen) { t.addSound(agent.speech, agent, 'letsGo'); t.addCallback(function () { this.game.state.start(GLOBAL.STATE[scen.subgame], true, false, scen); }, null, null, this); } //} t.addCallback(function () { disabler.visible = false; }); }, this); /* Setup the garden fields */ var rows = 3; var columns = 8; var startPos = 200; var width = this.world.width/columns; var height = (this.world.height - startPos)/rows; var type, level, water, i; var fields = this.gardenData.fields; for (var row = 0; row < rows; row++) { for (var column = 0; column < columns; column++) { type = this.rnd.integerInRange(1, 9); level = 0; water = 0; for (i = 0; i < fields.length; i++) { if (fields[i].x === column && fields[i].y === row) { /*jshint camelcase:false */ type = fields[i].content_type || type; /*jshint camelcase:true */ level = fields[i].level || level; break; } } this.world.add(new GardenPlant(this.game, column, row, column*width, startPos+row*height, width, height, type, level, water)); } } /* Add the garden agent */ var agent = this.game.player.createAgent(); agent.scale.set(0.2); agent.x = -100; agent.y = startPos + height - agent.height/2; this.world.add(agent); var currentMove = null; /* Add the water can */ this.world.add(new WaterCan(this.game)); var firstWatering = true; /* Add disabler. */ var disabler = new Cover(this.game, '#ffffff', 0); this.world.add(disabler); /* Add the menu */ this.world.add(new Menu(this.game)); /* Move agent when we push a plant. */ var _this = this; EventSystem.subscribe(GLOBAL.EVENT.plantPress, function (plant) { var y = plant.y + plant.plantHeight - agent.height/2; var x = plant.x; // If this is changed: update the side variable in the waterPlant subscription. var side = -plant.width * 0.3; if (agent.x > x) { x += plant.width; side *= -1; } if (agent.x === x && agent.y === y ) { return; } if (currentMove) { currentMove.kill(); } currentMove = new TimelineMax(); var distance = agent.x - x; if (agent.y !== y) { if (agent.y % (plant.plantHeight - agent.height/2) < 10) { distance = 0; currentMove.add(agent.move({ x: x }, Math.abs((agent.x - x)/width))); } currentMove.add(agent.move({ y: y }, Math.abs((agent.y - y)/height))); } if (agent.x !== x + side || agent.y !== y) { currentMove.add(agent.move({ x: x + side }, Math.abs((distance + side)/width))); } currentMove.addSound(agent.speech, agent, 'ok' + _this.game.rnd.integerInRange(1, 2), 0); }); /* Water plant when we push it. */ EventSystem.subscribe(GLOBAL.EVENT.waterPlant, function (plant) { var t; if (_this.game.player.water > 0) { var side = ((plant.x + plant.width/3) <= agent.x) ? -1 : 1; t = agent.water(2, side); t.addCallback(function () { _this.game.player.water--; plant.water.value++; agent.say(agent.speech, 'gardenGrowing').play('gardenGrowing'); }, 'watering'); if (plant.water.left === 1 && plant.level.left === 1) { t.addSound(agent.speech, agent, 'gardenFullGrown'); } if (firstWatering && _this.game.player.water > 1) { firstWatering = false; t.addSound(agent.speech, agent, 'gardenWaterLeft'); } } else { t = new TimelineMax(); t.addSound(agent.speech, agent, 'gardenEmptyCan'); } t.addCallback(function () { disabler.visible = true; }, 0); // at start t.addCallback(function () { plant.waterButton.reset(); disabler.visible = false; }); // at end if (currentMove && currentMove.progress() < 1) { currentMove.add(t); } }); /* Check that backend accepts plant upgrade */ EventSystem.subscribe(GLOBAL.EVENT.plantUpgrade, function (data) { /*jshint camelcase:false */ if (data.remaining_water !== _this.game.player.water) { _this.game.player.water = data.remaining_water; } /*jshint camelcase:true */ }); /* When the state starts. */ this.startGame = function () { var t = new TimelineMax().skippable(); t.add(agent.move({ x: this.world.centerX }, 3)); if (this.game.player.water > 0) { if (this.gardenData.fields.length > 0) { t.addSound(agent.speech, agent, 'gardenWhereNow'); } else { t.addSound(agent.speech, agent, 'gardenHaveWater'); t.addSound(agent.speech, agent, 'gardenPushField', '+=0.5'); } } else { if (this.gardenData.fields.length > 0) { t.addSound(agent.speech, agent, 'gardenYoureBack'); } else { var w = new WaterCan(this.game); w.visible = false; this.world.add(w); t.addSound(agent.speech, agent, 'gardenIntro'); t.addLabel('myCan', '+=0.5'); t.addCallback(function () { w.x = agent.x - w.width/4; // Since we scale to 0.5 w.y = agent.y; w.scale.set(0); w.visible = true; agent.eyesFollowObject(w); }); t.add(new TweenMax(w.scale, 1, { x: 0.5, y: 0.5, ease: Elastic.easeOut }), 'myCan'); t.addSound(agent.speech, agent, 'gardenMyCan', 'myCan'); t.add(new TweenMax(w.scale, 1, { x: 0, y: 0, ease: Elastic.easeOut, onComplete: w.destroy, onCompleteScope: w })); } t.addLabel('sign'); t.add(agent.wave(1, 1)); t.addCallback(agent.eyesFollowObject, 'sign', [sign], agent); t.addSound(agent.speech, agent, 'gardenSign', 'sign'); } t.addCallback(function () { agent.eyesStopFollow(); disabler.visible = false; }, null, null, this); }; }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Garden objects */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ /** * A garden plant/field. * It will level up depending on how much you water it. * @param {number} column - The column position of the plant (for server). * @param {number} row - The row position of the plant (for server). * @param {number} x - X position. * @param {number} y - Y position. * @param {number} width - The width. * @param {number} height - The height. * @param {number} type - The type of plant. * @param {number} level - The level of the plant. * @param {number} water - The amount of water the plant has. */ GardenPlant.prototype = Object.create(Phaser.Group.prototype); GardenPlant.prototype.constructor = GardenPlant; function GardenPlant (game, column, row, x, y, width, height, type, level, water) { Phaser.Group.call(this, game, null); // Parent constructor. var _this = this; var maxLevel = 5; this.column = column; this.row = row; this.x = x; this.y = y; this.plantHeight = height; /* The pushable area of the field */ var bmd = game.add.bitmapData(width, height); bmd.ctx.globalAlpha = 0; bmd.ctx.fillRect(0, 0, bmd.width, bmd.height); var trigger = this.create(0, 0, bmd); trigger.inputEnabled = true; trigger.events.onInputDown.add(this.down, this); if (level !== maxLevel) { var hl = game.add.bitmapData(width - 6, height * 0.6); hl.ctx.fillStyle = '#6b3e09'; hl.ctx.globalAlpha = 0.2; hl.ctx.roundRect(0, 0, hl.width, hl.height, 10).fill(); this.highlight = this.create(3, height * 0.4, hl); } this.type = type; var plant = null; this.water = new Counter(1, true, water); this.level = new Counter(maxLevel, false, level); this.level.onAdd = function (current, diff) { if (current <= 0) { if (plant) { plant.destroy(); } return; } var newPlant = _this.create(width/2, height/2, 'garden', 'plant' + _this.type + '-' + current); newPlant.anchor.set(0.5); newPlant.scale.set(0.5); // TODO: We should not scale this, use better graphics. if (diff > 0) { // Plant has leveled up by watering. newPlant.alpha = 0; /* Check that backend accepts plant upgrade */ var ev = EventSystem.subscribe(GLOBAL.EVENT.plantUpgrade, function (data) { if (!data.success && data.field.x === _this.column && data.field.y === _this.row) { _this.level.value = data.field.level; } EventSystem.unsubscribe(ev); }); /* Upgrade plant animation, ending with sending to backend. */ TweenMax.to(newPlant, 2, { alpha: 1, onComplete: function () { _this.water.update(); if (plant) { plant.destroy(); } plant = newPlant; /*jshint camelcase:false */ backend.putUpgradePlant({ field: { x: column, y: row, level: this.value, content_type: type }}); /*jshint camelcase:true */ } }); } else { // Could be: Setup of plant from constructor // Could be: Backend says that water is missing if (plant) { plant.destroy(); } plant = newPlant; } }; this.level.update(); return this; } /** * When pushing on a garden plant. * Publishes plantPress event. * Publishes waterPlant when waterButton is pushed. */ GardenPlant.prototype.down = function () { var _this = this; // Events do not have access to this /* If this plant is active, it means that it is already showing only publish plantPress */ if (this.active) { EventSystem.publish(GLOBAL.EVENT.plantPress, [this]); return; } /* The interface for the plant is set up when needed. */ if (!this.infoGroup) { var height = 100; this.infoGroup = this.game.add.group(this); this.infoGroup.x = 0; this.infoGroup.y = -height; this.infoGroup.visible = false; var bmd = this.game.add.bitmapData(this.width, height); bmd.ctx.fillStyle = '#ffffff'; bmd.ctx.globalAlpha = 0.5; bmd.ctx.fillRect(0, 0, bmd.width, bmd.height); this.game.add.sprite(0, 0, bmd, null, this.infoGroup).inputEnabled = true; /* The button to push when adding water. */ this.waterButton = new SpriteButton(this.game, 'objects', 'watering_can', { x: this.width/2 - (height - 20)/2, y: 10, size: height - 20, keepDown: true, onClick: function () { /* Water is added to the plant when animation runs. */ EventSystem.publish(GLOBAL.EVENT.waterPlant, [_this]); } }); this.waterButton.sprite.tint = 0xbb3333; this.infoGroup.add(this.waterButton); /* Water management */ var maxLevel = function () { _this.waterButton.destroy(); _this.highlight.destroy(); _this.game.add.text(_this.width/2, height/2, LANG.TEXT.maxLevel, { font: '40pt ' + GLOBAL.FONT, fill: '#5555ff' }, _this.infoGroup).anchor.set(0.5); }; /* Check if this plant can be upgraded more. */ if (this.level.left > 0) { this.water.onMax = function () { _this.level.value++; if (_this.level.value === _this.level.max) { _this.water.onMax = null; maxLevel(); } }; this.water.update(); } else { maxLevel(); } } util.fade(this.infoGroup, true, 0.2); /* Publish plantPress to hide other possible active plant interfaces. */ EventSystem.publish(GLOBAL.EVENT.plantPress, [this]); /* Subscribe to plantPress to hide this plant interface when applicable. */ this.active = EventSystem.subscribe(GLOBAL.EVENT.plantPress, function () { _this.waterButton.reset(); _this.hide(); }); }; /** * Hide the plant interface */ GardenPlant.prototype.hide = function () { EventSystem.unsubscribe(this.active); this.active = null; util.fade(this.infoGroup, false, 0.2); }; },{"../backend.js":6,"../global.js":8,"../language.js":9,"../objects/Counter.js":12,"../objects/Cover.js":13,"../objects/Menu.js":17,"../objects/WaterCan.js":21,"../objects/buttons/SpriteButton.js":25,"../pubsub.js":34,"../utils.js":48,"./SuperState.js":41}],41:[function(require,module,exports){ var GLOBAL = require('../global.js'); var LANG = require('../language.js'); var EventSystem = require('../pubsub.js'); var GeneralButton = require('../objects/buttons/GeneralButton.js'); var DraggableObjects = require('../objects/DraggableObject'); module.exports = SuperState; /** * The boot state will load the first parts of the game and common game assets. * Add assets that will be used by many states. * NOTE: Do not overshadow the update function! Use 'run' instead. */ function SuperState () {} /** * Update will trigger after create. But sounds might not be decoded yet, so we wait for that. * NOTE: Do not overshadow the update function! Use 'run' instead. */ SuperState.prototype.update = function () { this.state.onUpdateCallback = function () {}; var keys = [], key; for (var i = 0; i < this.sound._sounds.length; i++) { key = this.sound._sounds[i].key; if (keys.indexOf(key) < 0 && this.cache._sounds[key]) { this.sound.decode(key); // Make sure that decoding has begun. keys.push(key); } } document.querySelector('.loading').style.display = 'block'; document.querySelector('.progress').innerHTML = LANG.TEXT.decoding; this.sound.setDecodedCallback(keys, this._soundsDecoded, this); }; /** This function runs when all sounds have been decoded. */ SuperState.prototype._soundsDecoded = function () { document.querySelector('.loading').style.display = 'none'; if (this.startGame) { this.startGame(); } this.state.onUpdateCallback = this.run; }; /** * Overshadow this function for use of the update loop. * This will be set when all sounds have been decoded. */ SuperState.prototype.run = function () {}; /** * Utility function: Call this upon state shutdown. * Publishes stateShutDown event. */ SuperState.prototype.shutdown = function () { TweenMax.killAll(); EventSystem.publish(GLOBAL.EVENT.stateShutDown, this); EventSystem.clear(); GeneralButton.prototype.buttonColor = GLOBAL.BUTTON_COLOR; DraggableObjects.prototype.buttonColor = GLOBAL.BUTTON_COLOR; // Purge sound var key = this.sound._sounds.length; while (key--) { this.sound._sounds[key].destroy(true); } // Purge sound from cache as well for (key in this.cache._sounds) { if (this.sound._doNotDelete.indexOf(key) < 0) { this.cache.removeSound(key); } } // Purge all "this" variables. for (key in this) { if (GLOBAL.STATE_KEYS.indexOf(key) < 0) { if (this[key] && this[key].destroy) { try { this[key].destroy(true); } catch (e) { // Don't care about errors here. // console.log(e); } } delete this[key]; } } this.world.removeAll(true); }; },{"../global.js":8,"../language.js":9,"../objects/DraggableObject":14,"../objects/buttons/GeneralButton.js":23,"../pubsub.js":34}],42:[function(require,module,exports){ var Character = require('../../agent/Character.js'); module.exports = BeeFlightBee; /* Humfrid, the bee you are helping. */ BeeFlightBee.prototype = Object.create(Character.prototype); BeeFlightBee.prototype.constructor = BeeFlightBee; function BeeFlightBee (game, x, y) { Character.call(this, game); // Parent constructor. this.turn = true; this.x = x || 0; this.y = y || 0; this.body = this.create(0, 0, 'bee', 'body'); this.body.anchor.set(0.5); this.mouth = this.create(50, 35, 'bee', 'mouth_happy'); this.mouth.anchor.set(0.5); this.wings = this.create(-25, -43, 'bee', 'wings1'); this.wings.anchor.set(0.5); this.talk = TweenMax.to(this.mouth, 0.2, { frame: this.mouth.frame+1, roundProps: 'frame', ease: Power0.easeInOut, repeat: -1, yoyo: true, paused: true }); this._flap = TweenMax.to(this.wings, 0.1, { frame: this.wings.frame+1, roundProps: 'frame', ease: Power0.easeInOut, repeat: -1, yoyo: true, paused: true }); this.wings.frameName = 'wings0'; } BeeFlightBee.prototype.flap = function (on) { if (on) { if (this._flap.paused()) { this.wings.frameName = 'wings1'; this._flap.restart(0); } } else { this._flap.pause(0); this.wings.frameName = 'wings0'; } }; },{"../../agent/Character.js":2}],43:[function(require,module,exports){ var BeeFlightBee = require('./BeeFlightBee.js'); var NumberGame = require('./NumberGame.js'); var GLOBAL = require('../../global.js'); var LANG = require('../../language.js'); var util = require('../../utils.js'); module.exports = BeeFlightGame; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Bee Flight game /* Methods: All /* Representations: All, except "none". /* Range: 1--4, 1--9 /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ BeeFlightGame.prototype = Object.create(NumberGame.prototype); BeeFlightGame.prototype.constructor = BeeFlightGame; function BeeFlightGame () { NumberGame.call(this); // Call parent constructor. } BeeFlightGame.prototype.pos = { flowers: { start: 325, stopOffset: 0 }, home: { x: 110, y: 700 }, bee: { x: 120, y: 300, homeScale: 0.3, airScale: 0.8, flowerScale: 0.6 }, agent: { start: { x: 1200, y: 400 }, stop: { x: 777, y: 360 }, scale: 0.35 } }; BeeFlightGame.prototype.buttonColor = 0xface3d; /* Phaser state function */ BeeFlightGame.prototype.preload = function () { this.load.audio('beeSpeech', LANG.SPEECH.beeflight.speech); // speech sheet this.load.audio('beeMusic', ['audio/subgames/beeflight/music.m4a', 'audio/subgames/beeflight/music.ogg', 'audio/subgames/beeflight/music.mp3']); this.load.atlasJSONHash('bee', 'img/subgames/beeflight/atlas.png', 'img/subgames/beeflight/atlas.json'); }; /* Phaser state function */ BeeFlightGame.prototype.create = function () { // Setup additional game objects on top of NumberGame.init this.setupButtons({ buttons: { x: 150, y: 25, size: this.world.width - 300 }, yesnos: { x: 150, y: 25, size: this.world.width - 300 } }); // Add music, sounds and speech this.speech = util.createAudioSheet('beeSpeech', LANG.SPEECH.beeflight.markers); this.add.music('beeMusic', 0.1, true).play(); // Add background this.add.sprite(0, 0, 'bee', 'bg', this.gameGroup); var cloud1 = this.gameGroup.create(-1000, 10, 'objects', 'cloud2'); var cloud2 = this.gameGroup.create(-1000, 150, 'objects', 'cloud1'); TweenMax.fromTo(cloud1, 380, { x: -cloud1.width }, { x: this.world.width, repeat: -1 }); TweenMax.fromTo(cloud2, 290, { x: -cloud2.width }, { x: this.world.width, repeat: -1 }); var home = this.add.sprite(this.pos.home.x, this.pos.home.y, 'bee', 'home', this.gameGroup); home.anchor.set(0.5, 1); this.agent.thought.y += 100; this.gameGroup.bringToTop(this.agent); // Setup flowers var size = this.world.width - this.pos.flowers.stopOffset - this.pos.flowers.start; var width = size / this.amount; var yPos = 550; this.flowers = []; var i, v, c; for (i = 0; i < this.amount; i++) { this.flowers.push(this.add.sprite(this.pos.flowers.start + width*i, yPos, 'bee', 'flower', this.gameGroup)); this.flowers[i].anchor.set(0.5, 0); // Calculate tint v = this.rnd.integerInRange(150, 230); c = this.rnd.integerInRange(1, 3); this.flowers[i].tint = Phaser.Color.getColor(c === 1 ? v : 255, c === 2 ? v : 255, c === 3 ? v : 255); } // Setup bee this.bee = new BeeFlightBee(this.game, this.pos.home.x, this.pos.home.y); this.bee.scale.set(this.pos.bee.homeScale); if (this.method === GLOBAL.METHOD.additionSubtraction) { this.bee.addThought(170, -75, this.representation[0], true); this.bee.thought.toScale = 0.7; } this.gameGroup.add(this.bee); // Add Timeline/Tween functions var _this = this; this.bee.moveTo = { home: function (duration) { var t = new TimelineMax(); t.addCallback(_this.bee.flap, null, [true], _this.bee); t.add(_this.bee.move(_this.pos.home, duration || 5, _this.pos.bee.homeScale)); t.addCallback(_this.bee.flap, null, [false], _this.bee); return t; }, start: function () { var t = new TimelineMax(); t.addCallback(_this.bee.flap, null, [true], _this.bee); t.add(_this.bee.move(_this.pos.bee, 2, _this.pos.bee.airScale)); return t; }, flower: function (target, direct) { var t = new TimelineMax(); t.addCallback(_this.bee.flap, null, [true], _this.bee); if (_this.bee.y > 300) { t.add(_this.bee.move({ y: _this.pos.bee.y }, 1)); } var flow = _this.flowers[target - 1]; if (this.atValue !== target) { if (direct) { t.add(_this.bee.move({ x: flow.x }, 2)); } else { var dir = target < _this.atValue ? -1 : 1; var i = _this.atValue + dir; while (i !== target + dir) { t.add(_this.bee.move({ x: _this.flowers[i - 1].x }, 1)); t.addSound(_this.speech, _this.bee, 'number' + i, '-=0.5'); i += dir; } } } t.add(_this.bee.move({ y: flow.y }, 0.75, _this.pos.bee.flowerScale)); t.addCallback(_this.bee.flap, null, [false], _this.bee); return t; } }; }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Instruction functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ BeeFlightGame.prototype.instructionCount = function () { var t = new TimelineMax(); t.addSound(this.speech, this.bee, 'showTheWay'); t.addSound(this.speech, this.bee, 'decideHowFar', '+=0.8'); t.add(this.pointAtFlowers(this.currentNumber)); t.addLabel('useButtons'); t.addLabel('flashButtons', '+=0.5'); t.addSound(this.speech, this.bee, 'pushNumber', 'useButtons'); t.add(util.fade(this.buttons, true), 'useButtons'); t.addCallback(this.buttons.highlight, 'flashButtons', [1], this.buttons); return t; }; BeeFlightGame.prototype.instructionSteps = BeeFlightGame.prototype.instructionCount; BeeFlightGame.prototype.instructionAdd = function () { var t = new TimelineMax(); t.addSound(this.speech, this.bee, 'wrongPlace'); t.addSound(this.speech, this.bee, 'notFarEnough', '+=0.8'); t.addSound(this.speech, this.bee, 'howMuchMore'); // t.add(this.pointAtFlowers(this.currentNumber)); t.addLabel('useButtons', '+=0.3'); t.addLabel('flashButtons', '+=0.8'); t.addSound(this.speech, this.bee, 'pushNumber', 'useButtons'); t.add(util.fade(this.buttons, true), 'useButtons'); t.addCallback(this.buttons.highlight, 'flashButtons', [1], this.buttons); return t; }; BeeFlightGame.prototype.instructionSubtract = function () { var t = new TimelineMax(); t.addSound(this.speech, this.bee, 'goneTooFar'); t.addSound(this.speech, this.bee, 'mustGoBack'); // t.add(this.pointAtFlowers(this.currentNumber)); t.addLabel('useButtons', '+=0.3'); t.addLabel('flashButtons', '+=0.8'); t.addSound(this.speech, this.bee, 'pushNumber', 'useButtons'); t.add(util.fade(this.buttons, true), 'useButtons'); t.addCallback(this.buttons.highlight, 'flashButtons', [1], this.buttons); return t; }; BeeFlightGame.prototype.instructionAddSubtract = function () { var t = new TimelineMax(); t.addLabel('useButtons'); t.addLabel('flashButtons', '+=0.5'); t.addSound(this.speech, this.bee, 'useButtons', 'useButtons'); t.add(util.fade(this.buttons, true), 'useButtons'); t.addCallback(this.buttons.highlight, 'flashButtons', [1], this.buttons); return t; }; BeeFlightGame.prototype.pointAtFlowers = function (number) { var startY = this.pos.bee.y; var arrow = this.gameGroup.create(this.flowers[0].x, startY, 'objects', 'arrow'); arrow.tint = 0xf0f000; arrow.anchor.set(0, 0.5); arrow.rotation = -Math.PI/2; arrow.visible = false; var t = new TimelineMax(); t.addCallback(function () { arrow.visible = true; }); t.addCallback(function () {}, '+=0.5'); for (var i = 0; i < number; i++) { if (i !== 0) { t.add(new TweenMax(arrow, 0.75, { x: this.flowers[i].x, y: startY }), '+=0.3'); } t.add(new TweenMax(arrow, 1, { y: this.flowers[i].y })); } t.addCallback(function () { arrow.destroy(); }, '+=0.5'); return t; }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Start round functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ BeeFlightGame.prototype.newFlower = function (silent) { var t = new TimelineMax(); t.addCallback(this.openFlower, null, [this.currentNumber], this); this.doStartFunction(t, silent); return t; }; BeeFlightGame.prototype.openFlower = function (number) { this.flowers[number - 1].frameName = 'flower' + number; }; BeeFlightGame.prototype.startStop = function () { // Do nothing }; BeeFlightGame.prototype.startBelow = function (t, silent) { t.add(this.runNumber(this.rnd.integerInRange(1, this.currentNumber - 1), true)); if (!silent) { t.addSound(this.speech, this.bee, this.rnd.pick(['notFarEnough', 'howMuchMore'])); } }; BeeFlightGame.prototype.startAbove = function (t, silent) { t.add(this.runNumber(this.rnd.integerInRange(this.currentNumber + 1, this.amount), true)); if (!silent) { t.addSound(this.speech, this.bee, this.rnd.pick(['goneTooFar', 'mustGoBack'])); } }; BeeFlightGame.prototype.startThink = function (t) { var addTo = this.rnd.integerInRange(1, this.amount); t.addCallback(function () { this.addToNumber = addTo; this.bee.thought.guess.number = this.addToNumber; }, null, null, this); t.addSound(this.speech, this.bee, 'thinkItIs'); t.addLabel('number', '+=0.3'); t.add(this.bee.think()); t.addSound(this.speech, this.bee, 'number' + addTo, 'number'); }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Number chosen and return functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ BeeFlightGame.prototype.runNumber = function (number, simulate) { var current = this.currentNumber-1; var sum = number + this.addToNumber; var result = simulate ? sum - this.currentNumber : this.tryNumber(number, this.addToNumber); this.disable(true); this.agent.eyesFollowObject(this.bee); if (this.bee.thought) { this.bee.thought.visible = false; } var t = new TimelineMax(); if (GLOBAL.debug) { t.skippable(); } if (!simulate) { if (number !== 0) { var moving = Math.abs(number); if (this.isRelative) { t.addSound(this.speech, this.bee, moving === 1 ? 'one' : 'number' + moving); t.addSound(this.speech, this.bee, number > 0 ? 'forward' : 'backward'); } else { t.addSound(this.speech, this.bee, 'order' + moving); t.addSound(this.speech, this.bee, 'flower'); } t.addCallback(function () {}, '+=0.5'); // Pause until next sound. } t.addSound(this.speech, this.bee, 'letsGo'); } t.add(this.bee.moveTo.flower(sum)); /* Correct :) */ if (!result) { t.addCallback(function () { this.hideButtons(); this.flowers[current].frameName = 'flower'; this.agent.setHappy(); }, null, null, this); t.addSound(this.speech, this.bee, this.rnd.pick(['slurp', 'nectar1', 'nectar2'])); t.addLabel('goingHome', '+=0.5'); if (this._totalCorrect === 1) { // Only say "going back" first time. t.addSound(this.speech, this.bee, 'goingBack', 'goingHome'); t.add(this.bee.moveTo.home(), 'goingHome'); } else { t.add(this.bee.moveTo.home(2), 'goingHome'); } t.add(this.bee.moveTo.start()); this.atValue = 0; /* Incorrect :( */ } else { t.addCallback(this.agent.setSad, null, null, this.agent); this.doReturnFunction(t, sum, result, simulate); } t.addCallback(this.agent.setNeutral, null, null, this.agent); t.addCallback(this.updateRelative, null, null, this); return t; }; BeeFlightGame.prototype.returnToStart = function (t) { this.atValue = 0; t.addSound(this.speech, this.bee, 'noNectar'); t.add(this.bee.moveTo.start()); t.add(this.bee.moveTurn(1)); }; BeeFlightGame.prototype.returnNone = function (t, number, notUsed, silent) { this.atValue = number; if (!silent) { t.addSound(this.speech, this.bee, 'noNectar'); } }; BeeFlightGame.prototype.returnToPreviousIfHigher = function (t, number, diff, silent) { if (diff > 0) { t.addSound(this.speech, this.bee, 'tooFar'); t.addSound(this.speech, this.bee, 'wasBefore'); t.add(this.bee.moveTo.flower(this.atValue, true)); } else { this.returnNone(t, number, diff, silent); } }; BeeFlightGame.prototype.returnToPreviousIfLower = function (t, number, diff, silent) { if (diff < 0) { t.addSound(this.speech, this.bee, 'tooNear'); t.addSound(this.speech, this.bee, 'wasBefore'); t.add(this.bee.moveTo.flower(this.atValue, true)); } else { this.returnNone(t, number, diff, silent); } }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Overshadowing Subgame mode functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ BeeFlightGame.prototype.modeIntro = function () { var t = new TimelineMax().skippable(); t.addSound(this.speech, this.bee, 'badSight'); t.addLabel('gotoStart', '+=0.5'); t.add(this.bee.moveTo.start(), 'gotoStart'); t.addSound(this.speech, this.bee, 'howToFind', 'gotoStart'); t.addCallback(this.nextRound, null, null, this); }; BeeFlightGame.prototype.modePlayerDo = function (intro, tries) { if (tries > 0) { this.showNumbers(); } else { // if intro or first try var t = new TimelineMax(); if (intro) { t.skippable(); if (this.instructions) { t.add(this.newFlower(true)); t.addCallback(this.updateButtons, null, null, this); t.add(this.doInstructions()); } else { t.add(this.newFlower()); } } else { t.addSound(this.speech, this.bee, 'getMore'); t.add(this.newFlower()); } t.addCallback(this.showNumbers, null, null, this); } }; BeeFlightGame.prototype.modePlayerShow = function (intro, tries) { if (tries > 0) { this.showNumbers(); } else { // if intro or first try var t = new TimelineMax(); if (intro) { t.skippable(); t.add(this.agent.moveTo.start()); t.addSound(this.agent.speech, this.agent, 'beeIntro1'); t.addLabel('agentIntro', '+=0.5'); t.add(this.agent.wave(3, 1), 'agentIntro'); t.addSound(this.agent.speech, this.agent, 'beeIntro2', 'agentIntro'); t.addCallback(this.agent.eyesFollowObject, 'agentIntro', [this.bee], this.agent); t.addSound(this.speech, this.bee, 'gettingHelp', '+=0.2'); t.addSound(this.agent.speech, this.agent, 'beeIntro3', '+=0.2'); t.addSound(this.speech, this.bee, 'youHelpLater', '+=0.2'); } t.add(this.newFlower()); t.addCallback(this.showNumbers, null, null, this); } }; BeeFlightGame.prototype.modeAgentTry = function (intro, tries) { var t = new TimelineMax(); if (tries > 0) { t.addSound(this.agent.speech, this.agent, 'tryAgain'); } else { // if intro or first try if (intro) { t.skippable(); t.add(this.agent.moveTo.start()); // Agent should be here already. t.addSound(this.agent.speech, this.agent, 'myTurn' + this.rnd.integerInRange(1, 2)); } t.add(this.newFlower()); } t.add(this.agentGuess(), '+=0.3'); if (intro && this.instructionsAgent) { t.add(this.instructionYesNo(), '+=0.5'); } t.addCallback(this.showYesnos, null, null, this); }; BeeFlightGame.prototype.modeOutro = function () { this.agent.thought.visible = false; var t = new TimelineMax().skippable(); t.addLabel('water1', '+=1.0'); t.addLabel('water2', '+=2.5'); t.addLabel('water3', '+=4'); t.addSound(this.speech, this.bee, 'thatsAll', 0); t.addCallback(this.agent.setHappy, 'water1', null, this.agent); t.add(this.agent.fistPump(), 'water1'); var i, number, flower, opened = []; for (i = 1; i <= 3; i++) { do { number = this.rnd.integerInRange(1, this.amount); console.log(number, opened); } while (opened.indexOf(number) >= 0); opened.push(number); flower = this.flowers[number - 1]; t.addCallback(this.openFlower, 'water' + i, [number], this); t.add(this.addWater(flower.x, flower.y + 10), 'water' + i); } t.addLabel('letsDance'); t.add(this.bee.moveTo.home(), 'letsDance'); t.addSound(this.speech, this.bee, 'dancing', 'letsDance'); t.addCallback(this.nextRound, null, null, this); }; },{"../../global.js":8,"../../language.js":9,"../../utils.js":48,"./BeeFlightBee.js":42,"./NumberGame.js":44}],44:[function(require,module,exports){ var Subgame = require('./Subgame.js'); var GLOBAL = require('../../global.js'); var EventSystem = require('../../pubsub.js'); var util = require('../../utils.js'); var ButtonPanel = require('../../objects/buttons/ButtonPanel.js'); var GeneralButton = require('../../objects/buttons/GeneralButton.js'); var TextButton = require('../../objects/buttons/TextButton.js'); var DraggableObject = require('../../objects/DraggableObject.js'); var ObjectPanel = require('../../objects/ObjectPanel'); module.exports = NumberGame; /** * A superclass for games where you need to guess the correct number. * This class will set the .doInstructions, .doStartFunction and .doReturnFunction. * They will map to the functions that you should setup (see _setupFunctions). * See BeeFlightGame for inspiration of how you can use this class. * * * SETUP THESE IN THE SUBCLASS: * "this" object should have a property used when setting agent start position: * this.pos: { agent: { start: { x, y }, scale: z } } }. * * NEVER DO ANY LOGICAL CHANGES IN THE INSTRUCTIONS! * instructionCount: Method count. * instructionSteps: Method incremental-steps. * instructionAdd: Method addition. * instructionSubtract: Method subtraction. * instructionAddSubtract: Method addition subtraction. * * startStop: When round start without automatic "guessing". Used in count and incremental-steps method. * startBelow: When round start by guessing lower than target. Used in addition method. * startAbove: When round start by guessing higher than target. Used in subtraction method. * startThink: When round start by guessing something. Used in add/subt method. * * runNumber: The function to run when a number has been chosen. * * returnToStart: When returning to the start position on incorrect answer. * returnNone: When the game stays at the incorrect answer position. * returnToPreviousIfHigher: When returning to previous value if the incorrect answer was too high. * returnToPreviousIfLower: When returning to previous value if the incorrect answer was too low. * * * VARIABLES THE SUBCLASS CAN USE: * Number amount: this.amount * Representation: this.representation * The method: this.method * The number to answer: this.currentNumber (updates automatically) * * FUNCTIONS THE SUBCLASS CAN USE: * Try a number: this.tryNumber(number) - when testing a guess against this.currentNumber * * * Typical game flow: * // the first mode, this.modeIntro, will be called automatically when assets are loaded and decoded. * this.nextRound(); // start next round (will automatically start next mode) * this.disable(false); // make it possible to interact with anything * this.tryNumber(x); // try a number against the current one * this.nextRound(); // do this regardless if right or wrong, * // it takes care of mode switching and function calls for you * // Repeat last two functions until game is over. */ NumberGame.prototype = Object.create(Subgame.prototype); NumberGame.prototype.constructor = NumberGame; function NumberGame () { Subgame.call(this); // Call parent constructor. } /* * Phaser state function. * Publishes subgameStarted event. */ NumberGame.prototype.init = function (options) { Subgame.prototype.init.call(this, options); GeneralButton.prototype.buttonColor = this.buttonColor || GLOBAL.BUTTON_COLOR; DraggableObject.prototype.objectColor = this.objectColor || GLOBAL.BUTTON_COLOR; /* Public variables */ //No need for different methods in MI, the methods system should be removed in the future at the moment set to one staticly this.method = GLOBAL.METHOD.addition; this.representation = options.representation; this.amount = 4; //Always wants 4 cookies in teh sharkGame /* The current number to answer */ this.currentNumber = null; /* Stores the offset of the last try, can be used to judge last try */ /* Ex: -1 means that last try was one less than currentNumber */ this.lastTry = 0; /* This should be used to save the current position. */ this.atValue = 0; /* This is used to add to the number of the button pushes. */ /* This should be modified only when isRelative is set to true. */ this.addToNumber = 0; // Setup gameplay differently depending on situation. this.isRelative = false; this._setupFunctions(); /* Numbers for randomisation. */ this._weighted = this.amount > 4 && this.method === GLOBAL.METHOD.count; this._numberMin = 1; this._numberMax = 9; if (this.method === GLOBAL.METHOD.addition) { this._numberMin++; } if (this.method === GLOBAL.METHOD.subtraction) { this._numberMax--; } // Agent is added to the game in the superclass, but we set it up here. this.agent.x = this.pos.agent.start.x; this.agent.y = this.pos.agent.start.y; this.agent.scale.set(this.pos.agent.scale); this.agent.visible = true; this.agent.addThought(this.representation[0], this.pos.agent.mirror || false); this.saidAgentWrong = false; var _this = this; this.agent.moveTo = { start: function () { if (_this.agent.x === _this.pos.agent.stop.x && _this.agent.y === _this.pos.agent.stop.y) { return new TweenMax(_this.agent); } return _this.agent.move({ x: _this.pos.agent.stop.x, y: _this.pos.agent.stop.y }, 3); } }; // Setup help button with correct instruction functions. this.helpButton = new TextButton(this.game, '?', { x: 75, y: 5, size: 56, fontSize: 30, color: GLOBAL.BUTTON_COLOR, doNotAdapt: true, onClick: function () { _this.disable(true); var t; if (_this.currentMode === GLOBAL.MODE.agentTry && !_this.saidAgentWrong) { t = _this.instructionYesNo(); } else { t = _this.doInstructions(); } t.addCallback(_this.disable, null, [false], true); t.skippable(); } }); this.helpButton.visible = false; this.hudGroup.add(this.helpButton); }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Private functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ /** * Setup start and return functions. * Will map to the functions the subclass should overshadow (see bottom of this class). * The .doStartFunction is an easy way to call the appropriate start function. * The .doReturnFunction is an wasy way to call the appropriate return function when answer is incorrect. */ NumberGame.prototype._setupFunctions = function () { if (this.method === GLOBAL.METHOD.count) { this.doInstructions = this.instructionCount; this.doStartFunction = this.startStop; this.doReturnFunction = this.returnToStart; } else if (this.method === GLOBAL.METHOD.incrementalSteps) { this.doInstructions = this.instructionSteps; this.doStartFunction = this.startStop; this.doReturnFunction = this.returnNone; } else if (this.method === GLOBAL.METHOD.addition) { this.doInstructions = this.instructionAdd; this.doStartFunction = this.startBelow; this.doReturnFunction = this.returnToPreviousIfHigher; this.isRelative = true; } else if (this.method === GLOBAL.METHOD.subtraction) { this.doInstructions = this.instructionSubtract; this.doStartFunction = this.startAbove; this.doReturnFunction = this.returnToPreviousIfLower; this.isRelative = true; } else { this.doInstructions = this.instructionAddSubtract; this.doStartFunction = this.startThink; this.doReturnFunction = this.returnNone; this.isRelative = true; } }; /** Change this.currentNumber to a new one (resets the tries). */ // TODO: Should we allow the same number again? NumberGame.prototype._nextNumber = function () { // Weighted randomisation if applicable if (this._weighted && this.rnd.frac() < 0.2) { this.currentNumber = this.rnd.integerInRange(5, this._numberMax); } else { this.currentNumber = this.rnd.integerInRange(this._numberMin, this._numberMax); } }; NumberGame.prototype._getRange = function () { if (this.method === GLOBAL.METHOD.addition) { return { min: 1, max: this.amount - this.addToNumber }; } else if (this.method === GLOBAL.METHOD.subtraction) { return { min: 1 - this.addToNumber, max: -1 }; } else if (this.method === GLOBAL.METHOD.additionSubtraction) { return { min: 1 - this.addToNumber, max: this.amount - this.addToNumber }; } else { return { min: 1, max: this.amount }; } }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Public functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ /** * Try a number against this.currentNumber. * The offset of the last try is stored in this.lastTry. * Publishes tryNumber event. * @param {number} The number to try. * @param {number} The offset to the number (example if you start at 2). * @return {boolean} The offset of the last try (0 is correct, -x is too low, +x is too high). */ NumberGame.prototype.tryNumber = function (number, offset) { var sum = number + (offset || 0); this.lastTry = sum - this.currentNumber; EventSystem.publish(GLOBAL.EVENT.tryNumber, [sum, this.currentNumber, number, offset]); DraggableObject.prototype.setTry.call(this, this.lastTry); //Send the last try offset to draggable object for the visual feedback this._currentTries++; this._totalTries++; if (!this.lastTry) { this._counter.value++; // This will trigger next mode if we loop. this._nextNumber(); this._totalCorrect++; this._currentTries = 0; } return this.lastTry; }; /** Have the agent guess a number. */ NumberGame.prototype.agentGuess = function () { var t = new TimelineMax(); t.addCallback(function () { this.agent.guessNumber(this.currentNumber - (this.isRelative ? this.addToNumber : 0), this._numberMin, this._numberMax); }, 0, null, this); t.add(this.agent.think()); return t; }; /** * Setup HUD buttons. * @param {Object} options - The options for the buttons * Supply like this: { buttons: {...}, yesnos: {...} }. * NOTE: .method and .onClick will be set in this function. */ NumberGame.prototype.setupButtons = function (options) { var _this = this; if (options.buttons) { options.buttons.method = this.method; options.buttons.onClick = function (number) { _this.pushNumber(number); }; this.buttons = new ButtonPanel(this.game, this.amount, this.representation, options.buttons); this.buttons.visible = false; this.hudGroup.add(this.buttons); } if (options.yesnos) { options.yesnos.onClick = function (value) { _this.pushYesNo(value); }; this.yesnos = new ButtonPanel(this.game, 2, GLOBAL.NUMBER_REPRESENTATION.yesno, options.yesnos); this.yesnos.visible = false; this.hudGroup.add(this.yesnos); } }; /** * Setup drag and goal objects. * created in the same way as the buttons */ NumberGame.prototype.setUpDragObject = function(options){ var _this = this; if(options.dragObject){ options.dragObject.onClick = function (number) {_this.pushNumber(number);}; this.dragObject = new ObjectPanel(this.game,this.amount, options.dragObject); this.dragObject.visible = false; this.hudGroup.add(this.dragObject); } if(options.goalObject){ this.goalObject = new ObjectPanel(this.game,this.amount, options.goalObject); this.goalObject.visible = false; this.hudGroup.add(this.goalObject); } if(options.finalDragObject){ options.finalDragObject.onClick = function(){_this.moveObject();}; this.finalDragObject = new ObjectPanel(this.game, this.amount, options.finalDragObject); this.finalDragObject.visible = false; this.hudGroup.add(this.finalDragObject); } }; /* Function to trigger when a button or object in the number panel is pushed/dropped. * if you want to trigger nextRound call it from within run Number*/ NumberGame.prototype.pushNumber = function (number) { this.saidAgentWrong = false; return this.runNumber(number); }; /* Function triggered when a finalDragObject is drooped on the correct position*/ NumberGame.prototype.moveObject = function(){ this.hideWinObject(); return this.win().addCallback(this.nextRound, null, null, this); }; /* Function to trigger when a button in the yes-no panel is pushed. */ NumberGame.prototype.pushYesNo = function (value) { if (!value) { this.saidAgentWrong = true; if (this.speech) { this.agent.say(this.agent.speech, 'wrongShow').play('wrongShow'); } this.showNumbers(); } else { this.yesButton = true; this.pushNumber(this.agent.lastGuess); } }; /*Shows the drag object on win hides the goalObject*/ NumberGame.prototype.showWinObject = function(){ this.disable(false); if(this.finalDragObject) { util.fade(this.finalDragObject, true); } if (this.dragObject) { util.fade(this.dragObject, false); } if (this.goalObject) { util.fade(this.goalObject, false); } }; // Hides the finalDragObject NumberGame.prototype.hideWinObject = function(){ this.disable(false); if(this.finalDragObject) { util.fade(this.finalDragObject, false); } }; // Shows teh goalObject NumberGame.prototype.showGoalObject = function(){ if(this.goalObject){ if(this.isRelative){ this.updateObjects(); } util.fade(this.goalObject, true).eventCallback('onComplete', this.disable, false, this); } }; /* Show the number panel, hide the yes/no panel and enable input. */ NumberGame.prototype.showNumbers = function () { this.disable(true); if (this.buttons) { this.buttons.reset(); if (this.isRelative) { this.updateButtons(); } util.fade(this.buttons, true).eventCallback('onComplete', this.disable, false, this); } if(this.dragObject){ this.dragObject.reset(); if(this.isRelative){ this.updateObjects(); } util.fade(this.dragObject, true).eventCallback('onComplete', this.disable, false, this); } if(this.goalObject){ if(this.isRelative){ this.updateObjects(); } util.fade(this.goalObject, true).eventCallback('onComplete', this.disable, false, this); } if (this.yesnos) { util.fade(this.yesnos, false); } if (this.agent.visible) { util.fade(this.agent.thought, false); this.agent.eyesFollowPointer(); } }; /* Show the yes/no panel, hide the number panel and enable input. */ NumberGame.prototype.showYesnos = function () { this.disable(true); if (this.buttons) { util.fade(this.buttons, false); } if (this.yesnos) { this.yesnos.reset(); util.fade(this.yesnos, true).eventCallback('onComplete', this.disable, false, this); } if (this.agent.visible) { this.agent.eyesFollowPointer(); } }; /* Hide the number and yes/no panel. */ NumberGame.prototype.hideButtons = function () { this.disable(true); if (this.buttons) { util.fade(this.buttons, false); } if (this.yesnos) { util.fade(this.yesnos, false); } if (this.dragObject) { util.fade(this.dragObject, false); } if(this.goalObject){ util.fade(this.goalObject, false); } if (this.agent.visible) { this.agent.eyesStopFollow(); } }; /* Update the values of the button panel. */ NumberGame.prototype.updateButtons = function () { if (this.buttons) { var range = this._getRange(); this.buttons.setRange(range.min, range.max); } }; NumberGame.prototype.updateObjects = function(){ var range = this._getRange(); if(this.dragObject ){ range = this._getRange(); this.dragObject.setRange(range.min, range.max,this.currentNumber); } if(this.goalObject){ range = this._getRange(); this.goalObject.setRange(range.min,range.max, this.currentNumber); } }; /* Update the relative value. */ NumberGame.prototype.updateRelative = function () { if (this.isRelative) { this.addToNumber = this.atValue; } }; /*set relative true*/ NumberGame.prototype.setRelative = function (correct){ if (correct === true){ this.isRelative = true; } else { this.isRelative = false; } }; /*Set relative false*/ NumberGame.prototype.setRelativefalse = function (){ this.isRelative = true; }; /* Instructions for the yes - no panel */ NumberGame.prototype.instructionYesNo = function () { var t = new TimelineMax(); t.addSound(this.agent.speech, this.agent, 'willYouHelpMe'); t.add(util.fade(this.yesnos, true), 0); t.addLabel('green', '+=0.7'); t.addSound(this.agent.speech, this.agent, 'instructionGreen', 'green'); t.add(this.yesnos.children[0].highlight(3), 'green'); t.addLabel('red'); t.addSound(this.agent.speech, this.agent, 'instructionRed', 'red'); t.add(this.yesnos.children[1].highlight(3), 'red'); return t; }; /* Start the game. */ NumberGame.prototype.startGame = function () { this._nextNumber(); this.helpButton.visible = true; Subgame.prototype.startGame.call(this); EventSystem.publish(GLOBAL.EVENT.numbergameStarted, [this.method, this.amount, this.representation]); }; /* The following functions should be overshadowed in the game object. */ NumberGame.prototype.pos = { agent: { start: { x: 0, y: 0 }, scale: 1 } }; NumberGame.prototype.instructionCount = function () {}; NumberGame.prototype.instructionSteps = function () {}; NumberGame.prototype.instructionAdd = function () {}; NumberGame.prototype.instructionSubtract = function () {}; NumberGame.prototype.instructionAddSubtract = function () {}; NumberGame.prototype.startStop = function () {}; NumberGame.prototype.startBelow = function () {}; NumberGame.prototype.startAbove = function () {}; NumberGame.prototype.startThink = function () {}; NumberGame.prototype.returnToStart = function () {}; NumberGame.prototype.returnNone = function () {}; NumberGame.prototype.returnToPreviousIfHigher = function () {}; NumberGame.prototype.returnToPreviousIfLower = function () {}; },{"../../global.js":8,"../../objects/DraggableObject.js":14,"../../objects/ObjectPanel":19,"../../objects/buttons/ButtonPanel.js":22,"../../objects/buttons/GeneralButton.js":23,"../../objects/buttons/TextButton.js":26,"../../pubsub.js":34,"../../utils.js":48,"./Subgame.js":47}],45:[function(require,module,exports){ var NumberGame = require('./NumberGame.js'); var SharkGameApe = require('./SharkGameApe.js'); var GLOBAL = require('../../global.js'); var LANG = require('../../language.js'); var util = require('../../utils.js'); module.exports = SharkGame; SharkGame.prototype = Object.create(NumberGame.prototype); SharkGame.prototype.constructor = SharkGame; function SharkGame () { NumberGame.call(this); // Call parent constructor. } SharkGame.prototype.pos = { home: { x: 110, y: 700 }, ape: { x: 120, y: 300, homeScale: 0.8 }, agent: { start: { x: 1200, y: 400 }, stop: { x: 777, y: 360 }, scale: 0.35 } }; /* Phaser state function */ SharkGame.prototype.preload = function () { this.load.audio('apeSpeech', LANG.SPEECH.sharkgame.speech); this.load.audio('beeMusic', ['audio/subgames/beeflight/music.m4a', 'audio/subgames/beeflight/music.ogg', 'audio/subgames/beeflight/music.mp3']); this.load.atlasJSONHash('ape', 'img/subgames/beeflight/atlas.png', 'img/subgames/beeflight/atlas.json'); this.load.atlasJSONHash('shark', 'img/subgames/sharkgame/atlas.png', 'img/subgames/sharkgame/atlas.json'); this.load.atlasJSONHash('apa', 'img/subgames/sharkgame/apa.png', 'img/subgames/sharkgame/apa.json'); this.load.atlasJSONHash('numbers', 'img/objects/numbers.png', 'img/objects/numbers.json'); }; SharkGame.prototype.buttonColor = 0xface3d; SharkGame.prototype.create = function () { // Setup additional game objects on top of NumberGame.init this.setupButtons({ yesnos: { x: 150, y: 25, size: this.world.width - 300 } }); this.dropPlaceX = 200; this.dropPlaceY = 200; this.setUpDragObject({ dragObject:{ x: 100, y: 670, size: this.world.width - 300, dropPlaceX: this.dropPlaceX, dropPlaceY: this.dropPlaceY, id: 'dragObject' }, goalObject:{ x: this.dropPlaceX, y: this.dropPlaceY, size: this.world.width - 300, id: 'goalObject' }, finalDragObject:{ x: this.dropPlaceX, y: this.dropPlaceY, size: this.world.width - 300, dropPlaceX: -100, dropPlaceY: 450, id: 'finalDragObject' } }); this.add.sprite(0, 0, 'shark', 'island.png', this.gameGroup); //Sprites for the equation var cloud1 = this.gameGroup.create(-1000, 10, 'objects', 'cloud2'); var cloud2 = this.gameGroup.create(-1000, 150, 'objects', 'cloud1'); this.number1 = this.gameGroup.create(50, 200, 'numbers', '1.png'); this.plus = this.gameGroup.create(120, 180, 'numbers', '+.png'); this.number2 = this.gameGroup.create(150, 200, 'numbers', '1.png'); this.equal = this.gameGroup.create(200, 200, 'numbers', '=.png'); this.answer = this.gameGroup.create(250, 200, 'numbers', '10.png'); this.number1.visible = false; this.plus.visible = false; this.number2.visible = false; this.equal.visible = false; this.answer.visible = false; TweenMax.fromTo(cloud1, 380, { x: -cloud1.width }, { x: this.world.width, repeat: -1 }); TweenMax.fromTo(cloud2, 290, { x: -cloud2.width }, { x: this.world.width, repeat: -1 }); //To Do: Make the shark a real goal object var shark = this.add.sprite(this.pos.home.x, this.pos.home.y, 'shark', 'Shark_angry.png', this.gameGroup); shark.anchor.set(0.5, 1); this.agent.thought.y += 100; this.gameGroup.bringToTop(this.agent); this.aGuess = true; this.speech = util.createAudioSheet('apeSpeech', LANG.SPEECH.sharkgame.markers); this.visualAid = this.gameGroup.create(355, 200, 'cookie', 'cookie1.png'); this.visualAid.width = 75; this.visualAid.height = 75; this.visualAid.visible = false; this.visualAid.tint = 0xCC7A00; // Setup ape this.ape = new SharkGameApe(this.game, 450, 500); this.ape.scale.set(this.pos.ape.homeScale); if (this.method === GLOBAL.METHOD.additionSubtraction) { this.ape.addThought(170, -75, this.representation[0], true); this.ape.thought.toScale = 0.7; } this.gameGroup.add(this.ape); this.add.music('apeMusic', 0.1, true).play(); }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Number chosen and return functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ SharkGame.prototype.runNumber = function (number, simulate) { var sum = number + this.addToNumber; var result = simulate ? sum - this.currentNumber : this.tryNumber(number, this.addToNumber); var correct = false; this.disable(true); this.visualAid.visible = false; var t = new TimelineMax(); if (GLOBAL.debug) { t.skippable(); } /* Correct :) */ if (!result) { correct = true; t.addCallback(function () { this.showWinObject(); }, null, null, this); //Setting the sprites correlating to the equation var goalNumber = (10 - number); this.number1.frameName = number +'.png'; this.number2.frameName = goalNumber +'.png'; this.number1.visible = true; this.plus.visible = true; this.number2.visible = true; this.equal.visible = true; this.answer.visible = true; this.atValue = 0; this.aGuess = true; this.setRelative(correct); /* Incorrect :( */ } else { correct = false; t.addSound(this.speech, this.ape, 'wrong'); //If the current mode is agentTry the drag objects and the visualAid sprite should be shown when you are wrong /*To Do: instead of using the visualAid sprite use the DraggableObjects visual feedback algorithm before showNumbers see DragableObjects stopDrag function for more info*/ if(this.currentMode === GLOBAL.MODE.agentTry){ this.visualAid.frame = this.agent.lastGuess + 8; if(this.lastTry !== 0 && this.yesButton === true) { this.showNumbers(); if (this.lastTry > 0) { this.visualAid.x = 280; } else if (this.lastTry < 0) { this.visualAid.x = 355; } this.visualAid.visible = true; } } this.aGuess = false; this.setRelative(correct); this.nextRound(); } t.addCallback(this.updateRelative, null, null, this); return t; }; //Triggerd when the complete cookie is fed to the shark SharkGame.prototype.win = function(){ var t = new TimelineMax(); this.number1.visible = false; this.plus.visible = false; this.number2.visible = false; this.equal.visible = false; this.answer.visible = false; //If the last correct choice the final wining sound will be played otherwise the correct cookie sound will be played if(this._totalCorrect !== 9) { t.skippable(); t.addSound(this.speech, this.ape, 'correct'); } else{ t.skippable(); t.addSound(this.speech, this.ape, 'win'); } return t; }; //The intro dialouge is played SharkGame.prototype.modeIntro = function () { var t = new TimelineMax().skippable(); t.addSound(this.speech, this.ape, 'intro'); t.addSound(this.speech, this.ape, 'shark'); t.addSound(this.speech, this.ape, 'intro2'); t.addSound(this.speech, this.ape, 'intro3'); t.addCallback(this.nextRound, null, null, this); }; SharkGame.prototype.modePlayerDo = function (intro, tries) { if (tries > 0) { this.showNumbers(); } else { // if intro or first try var t = new TimelineMax(); t.addCallback(this.showNumbers, null, null, this); } }; SharkGame.prototype.modePlayerShow = function (intro, tries) { if (tries > 0) { this.showNumbers(); } else { // if intro or first try var t = new TimelineMax(); if (intro) { t.skippable(); t.add(this.agent.moveTo.start()); t.addSound(this.speech, this.agent, 'agentIntro'); t.addSound(this.speech, this.ape, 'watch'); } t.addCallback(this.showNumbers, null, null, this); } }; SharkGame.prototype.modeAgentTry = function (intro, tries) { var t = new TimelineMax(); // if intro or first try if (intro) { t.skippable(); t.addSound(this.speech, this.agent,'agentTry'); t.addSound(this.speech, this.ape,'try'); } this.yesButton = false; t.addCallback(this.showGoalObject, null, null, this); if(this.aGuess === true) { t.add(this.agentGuess(), '+=0.3'); t.addCallback(this.showYesnos, null, null, this); } }; },{"../../global.js":8,"../../language.js":9,"../../utils.js":48,"./NumberGame.js":44,"./SharkGameApe.js":46}],46:[function(require,module,exports){ var Character = require('../../agent/Character.js'); module.exports = SharkGameApe; /* Humfrid, the bee you are helping. */ SharkGameApe.prototype = Object.create(Character.prototype); SharkGameApe.prototype.constructor = SharkGameApe; function SharkGameApe (game, x, y) { Character.call(this, game); // Parent constructor. this.turn = true; this.x = x || 0; this.y = y || 0; this.body = this.create(0, 90, 'apa', 'Chimp_empty_cup.png'); this.body.anchor.set(0.5); this.mouth = this.create(0, 0, 'apa', 'Chimp_sadTalking.png'); this.mouth.anchor.set(0.5); //this.wings = this.create(-25, -43, 'bee', 'wings1'); //this.wings.anchor.set(0.5); this.talk = TweenMax.to(this.mouth, 0.2, { frame: this.mouth.frame+1, roundProps: 'frame', ease: Power0.easeInOut, repeat: -1, yoyo: true, paused: true }); } /* SharkGameApe.prototype.flap = function (on) { if (on) { if (this._flap.paused()) { this.wings.frameName = 'wings1'; this._flap.restart(0); } } else { this._flap.pause(0); this.wings.frameName = 'wings0'; } };*/ },{"../../agent/Character.js":2}],47:[function(require,module,exports){ var SuperState = require('../SuperState.js'); var GLOBAL = require('../../global.js'); var LANG = require('../../language.js'); var EventSystem = require('../../pubsub.js'); var Counter = require('../../objects/Counter.js'); var Cover = require('../../objects/Cover.js'); var Menu = require('../../objects/Menu.js'); module.exports = Subgame; /** * Superclass for all games. * Holds shared logic for mode and round handling. Also some graphic setups. * Also see subclass NumberGame. * * SETUP THESE IN THE SUBCLASS: * They are called with two parameters (ifFirstTime, triesSoFar). * modeIntro: Introduce the game, call nextRound to start next mode. * modePlayerDo: Player only * modePlayerShow: Player is showing the TA * modeAgentTry: TA is guessing and the player is helping out * modeAgentDo: TA only * modeOutro: The game is finished, celebrate! * * VARIABLES THE SUBCLASS CAN USE: * Add game objects to: this.gameGroup * Add buttons and HUD to: this.hudGroup * Use agent with: this.agent (default visibility = false) * * FUNCTIONS THE SUBCLASS CAN USE: * Disable/Enable input: this.disable(true/false) - default = true = disabled (publishes disabled event) * Run next round: this.nextRound() - will change mode automatically when needed * Add water to the can: this.addWater(fromX, fromY) - Adds a water drop to the can */ Subgame.prototype = Object.create(SuperState.prototype); Subgame.prototype.constructor = Subgame; function Subgame () {} /* * Phaser state function. */ Subgame.prototype.init = function (options) { /* "Private" variables */ var _this = this; // Event subscriptions does not have access to this this._token = options.token || Date.now(); this._modes = options.mode || [ GLOBAL.MODE.intro, GLOBAL.MODE.playerDo, GLOBAL.MODE.playerShow, GLOBAL.MODE.agentTry, // GLOBAL.MODE.agentDo, GLOBAL.MODE.outro ]; this._mode = null; this._pendingMode = null; this._first = true; /* Keep track of how many rounds that have been played */ this._counter = new Counter(options.roundsPerMode || 3, true); /* When enough rounds have been played, trigger a mode change */ this._counter.onMax = function () { _this._nextMode(); }; this._currentTries = 0; this._totalTries = 0; this._totalCorrect = 0; // Instruction options this.instructions = typeof options.instructions !== 'undefined' ? options.instructions : true; this.instructionsAgent = typeof options.instructionsAgent !== 'undefined' ? options.instructionsAgent : true; /* Public variables */ this.currentMode = null; // The current mode running /* Setup game objects */ this.gameGroup = this.add.group(); this.agent = this.game.player.createAgent(); this.agent.visible = false; this.gameGroup.add(this.agent); this.hudGroup = this.add.group(); var disabler = new Cover(this.game, '#ffffff', 0); this.world.add(disabler); this.disable = function (value) { if (disabler.visible !== value) { EventSystem.publish(GLOBAL.EVENT.disabled, [value]); } disabler.visible = value; }; /* Setup menu objects */ this._menuGroup = this.add.group(); this._menuGroup.visible = false; //this._waterCan = new WaterCan(this.game); //this._menuGroup.add(this._waterCan); this.menuBack = { state: GLOBAL.STATE.garden, text: LANG.TEXT.gotoGarden }; this._menuGroup.add(new Menu(this.game)); /* For cleanup when shutting down state */ this._origAudio = Object.keys(this.game.cache._sounds); this._origImages = Object.keys(this.game.cache._images); }; /* Phaser state function */ Subgame.prototype.shutdown = function () { var key; for (key in this.game.cache._sounds) { if (this._origAudio.indexOf(key) < 0) { this.game.cache.removeSound(key); } } for (key in this.game.cache._images) { if (this._origImages.indexOf(key) < 0) { this.game.cache.removeImage(key); } } SuperState.prototype.shutdown.call(this); }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Private functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ /** Change to the next mode in the queue. */ Subgame.prototype._nextMode = function () { var newMode = this._modes.shift(); this._decideMode(newMode); this._pendingMode = newMode; this._first = true; }; /** * Translate from integer to mode function * @param {number} */ Subgame.prototype._decideMode = function (mode) { if (mode === GLOBAL.MODE.intro) { this._mode = this.modeIntro; } else if (mode === GLOBAL.MODE.playerDo) { this._mode = this.modePlayerDo; } else if (mode === GLOBAL.MODE.playerShow) { this._mode = this.modePlayerShow; } else if (mode === GLOBAL.MODE.agentTry) { this._mode = this.modeAgentTry; } else if (mode === GLOBAL.MODE.agentDo) { this._mode = this.modeAgentDo; } else if (mode === GLOBAL.MODE.outro) { this._mode = this.modeOutro; } else { this._mode = this.endGame; } }; /** Skip the current mode. */ Subgame.prototype._skipMode = function () { this._nextMode(); this.nextRound(); }; /*MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/ /* Public functions */ /*WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW*/ /** * Calls the current mode function. It will be called with two parameters: * 1) If it is the first time on this mode. * 2) How many tries that have been made on the current number. * Publishes modeChange event (first time a mode runs). */ Subgame.prototype.nextRound = function () { // Special case: intro and outro only have one round if ((this.currentMode === GLOBAL.MODE.intro || this.currentMode === GLOBAL.MODE.outro) && this.currentMode === this._pendingMode) { this._nextMode(); } // Publish event when it it is the first time it runs if (this._first) { EventSystem.publish(GLOBAL.EVENT.modeChange, [this._pendingMode]); } // Run mode and update properties this.currentMode = this._pendingMode; this._mode(this._first, this._currentTries); this._first = false; }; /** * Adds water to the water can. * Water will only be added in modes playerShow, agentTry and agentDo. * @param {number} The x position where the drop will begin. * @param {number} The y position where the drop will begin. * @param {boolean} Override mode restrictions and force drop to be added. * @return {Object} The drop animation from x, y to water can. */ /*Subgame.prototype.addWater = function (x, y) { var drop = this.add.sprite(x, y, 'objects', 'drop', this._menuGroup); drop.anchor.set(0.5); drop.scale.set(0.7, 0); // Show drop return new TimelineMax().to(drop.scale, 1.5, { y: 0.7, ease:Elastic.easeOut }) // Move drop .to(drop, 1.5, { x: this._waterCan.x + 50, y: this._waterCan.y + 30, ease:Power2.easeOut }) // Hide drop and add water .to(drop, 0.5, { height: 0, onStart: function () { this.game.player.water++; }, onStartScope: this, onComplete: function () { drop.destroy(); } }); }; */ /** * Start the game! * Publishes subgameStarted event. */ Subgame.prototype.startGame = function () { /* Send event that subgame is started. */ EventSystem.publish(GLOBAL.EVENT.subgameStarted, [this.game.state.current, this._token]); this._menuGroup.visible = true; this._nextMode(); this.nextRound(); }; /** End the game. */ Subgame.prototype.endGame = function () { this.state.start(GLOBAL.STATE.beach); }; /* The following functions should be overshadowed in the game object. */ Subgame.prototype.modeIntro = Subgame.prototype._skipMode; Subgame.prototype.modePlayerDo = Subgame.prototype._skipMode; Subgame.prototype.modePlayerShow = Subgame.prototype._skipMode; Subgame.prototype.modeAgentTry = Subgame.prototype._skipMode; Subgame.prototype.modeAgentDo = Subgame.prototype._skipMode; Subgame.prototype.modeOutro = Subgame.prototype._skipMode; },{"../../global.js":8,"../../language.js":9,"../../objects/Counter.js":12,"../../objects/Cover.js":13,"../../objects/Menu.js":17,"../../pubsub.js":34,"../SuperState.js":41}],48:[function(require,module,exports){ var GLOBAL = require('./global.js'); var EventSystem = require('./pubsub.js'); /** * Fade in or out an object. * NOTE: The returned tween has both an onStart and onComplete function. * @param {Object} what - The object to fade, needs to have an alpha property. * @param {boolean} typ - Fade in = true, out = false, toggle = undefined (default: toggle). * @param {number} duration - Fade duration in seconds (default: 0.5). * NOTE: The tween will have 0 duration if state is correct. * @param {number} to - The alpha to fade to (only used when fading in) (default: 1). * NOTE: You can fade to a lower alpha using fade in. * @return {Object} The animation TweenMax. */ exports.fade = function (what, typ, duration, to) { duration = duration || 0.5; return TweenMax.to(what, duration, { onStart: function () { /* If this object is fading, stop it! */ if (what.isFading) { what.isFading.kill(); } /* No specified type: Toggle the current one. */ if (typeof typ === 'undefined' || typ === null) { typ = !what.visible || what.alpha === 0; } /* Not visible? Set alpha to 0 and make it visible if it should be. */ if (!what.visible) { what.alpha = 0; if (typ) { what.visible = true; } } /* If we are fading in, fade to the specified alpha, otherwise 0. */ to = typ > 0 ? (to || 1) : 0; if (what.alpha !== to) { this.updateTo({ alpha: to }); } else { /* We are already at correct state, cut the duration. */ this.duration(0); } what.isFading = this; }, onComplete: function () { if (!typ) { what.visible = false; } delete what.isFading; } }); }; /** * Easily tween an objects tint. It tweens from the current tint value. * @param {Object} what - The object to fade, needs to have an alpha property. * @param {number} toColor - The color to fade to. * @param {number} duration - Tween duration in seconds (default: 1). * @return {Object} The animation TweenMax. */ exports.tweenTint = function (what, toColor, duration) { duration = duration || 1; var color = Phaser.Color.getRGB(what.tint); var endColor = Phaser.Color.getRGB(toColor); return TweenMax.to(color, duration, { r: endColor.r, g: endColor.g, b: endColor.b, onUpdate: function () { what.tint = Phaser.Color.getColor(color.r, color.g, color.b); } }); }; /** * Easily create an audio sheet. * @param {string} key - The key of the audio object. * @param {Object} markers - The Markers of the audio object. * @return {Object} The audio object. */ exports.createAudioSheet = function (key, markers) { var a = GLOBAL.game.add.audio(key); for (var marker in markers) { a.addMarker(marker, markers[marker][0], markers[marker][1]); } return a; }; /** * Creates a new Sound object as background music * * @method Phaser.GameObjectFactory#music * @param {string} key - The Game.cache key of the sound that this object will use. * @param {number} [volume=1] - The volume at which the sound will be played. * @param {boolean} [loop=false] - Whether or not the sound will loop. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio. * @return {Phaser.Sound} The newly created text object. */ Phaser.GameObjectFactory.prototype.music = function (key, volume, loop, connect) { var music = this.game.sound.add(key, volume, loop, connect); music.volume = music.maxVolume * this.game.sound.bgVolume; this.game.sound._music.push(music); return music; }; /** * @name Phaser.SoundManager#fgVolume * @property {number} fgVolume - Gets or sets the foreground volume of the SoundManager, a value between 0 and 1. */ Object.defineProperty(Phaser.SoundManager.prototype, 'fgVolume', { get: function () { return this._fgVolume; }, set: function (value) { this._fgVolume = value; for (var i = 0; i < this._sounds.length; i++) { if (this._music.indexOf(this._sounds[i]) < 0) { this._sounds[i].volume = this._sounds[i].maxVolume * value; } } } }); /** * @name Phaser.SoundManager#bgVolume * @property {number} bgVolume - Gets or sets the background volume of the SoundManager, a value between 0 and 1. */ Object.defineProperty(Phaser.SoundManager.prototype, 'bgVolume', { get: function () { return this._bgVolume; }, set: function (value) { this._bgVolume = value; for (var i = 0; i < this._sounds.length; i++) { if (this._music.indexOf(this._sounds[i]) >= 0) { this._sounds[i].volume = this._sounds[i].maxVolume * value; } } } }); /** * Randomize array element order in-place. * Using Fisher-Yates shuffle algorithm. * @param {Array} The array to shuffle. (Use .splice(0) if you need to copy an array.) * @returns {Array} The input array in shuffled order. */ Phaser.RandomDataGenerator.prototype.shuffle = function (array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }; /** * A function to easily add sound to a tween timeline. * @param {string|Object} what - The name of the sound file, or the sound object, to play. * @param {Object} who - If someone should say it (object must have "say" function) (optional). * @param {string} marker - For playing a specific marker in a sound file (optional). * @param {number} position - The position to put the sound (default is '+=0'). * @return {Object} The TimelineMax object. */ TimelineMax.prototype.addSound = function (what, who, marker, position) { var a = (who && who.say) ? who.say(what, marker) : ((typeof what === 'string') ? GLOBAL.game.add.audio(what) : what); if (typeof position === 'undefined' || position === null) { position = '+=0'; } var end; if (marker) { this.addCallback(function () { a.play(marker); }, position); end = a.markers[marker].duration; } else { this.addCallback(function () { a.play(); }, position); end = GLOBAL.game.cache.getSound(a.key).data.duration; } if (isNaN(position)) { // The position might be a label. Try to get its position. var label = this.getLabelTime(position); if (label >= 0) { // Label present, add to its time. end = label + end; } else { // Relative position. var time = parseFloat(position.substr(0, 1) + position.substr(2)) + end; end = (time < 0 ? '-=' : '+=') + Math.abs(time); } } else { end += position; } this.addCallback(function () { a.stop(); }, end); return this; }; /** * Skip a timeline. * Publishes skippable event. * NOTE: You can not skip part of a timeline. * NOTE: See menu object for more information about skipping. * @returns: 'this' TimelineMax object, enables chaining. */ TimelineMax.prototype.skippable = function () { this.addCallback(function () { EventSystem.publish(GLOBAL.EVENT.skippable, [this]); this.addCallback(function () { EventSystem.publish(GLOBAL.EVENT.skippable); }); }, 0, null, this); return this; }; /** * When you want a yoyo animation to go back to the beginning. * @param {number} total - The total duration for the animation. * @param {number} each - The duration of one direction (half of the loop from start back to start). * @return {number} The amount of times to repeat the animation */ TweenMax.prototype.calcYoyo = function (total, each) { var times = parseInt(total / each); return times + (times % 2 === 0 ? 1 : 0); // Odd number will make the animation return to origin. }; /** * Make an animation loop from start back to the origin. * @param {number} total - The total duration of the animation. * NOTE: This is not exact time, depending on how well animation duration and total match. * @return {Object} The TweenMax object. */ TweenMax.prototype.backForth = function (total) { this.yoyo(true); this.repeat(this.calcYoyo(total, this.duration())); return this; }; /** * Adds a rounded rectangle to the built-in rendering context. * @param {number} x - The x position * @param {number} y - The y position * @param {number} w - The width * @param {number} h - The height * @param {number} r - The radius * @return {Object} The CanvasRenderingContext2D object */ CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { if (w < 2 * r) { r = w / 2; } if (h < 2 * r) { r = h / 2; } this.beginPath(); this.moveTo(x+r, y); this.arcTo(x+w, y, x+w, y+h, r); this.arcTo(x+w, y+h, x, y+h, r); this.arcTo(x, y+h, x, y, r); this.arcTo(x, y, x+w, y, r); this.closePath(); return this; }; /** * @property {number} PI2 - Math.PI * 2. */ Math.PI2 = Math.PI*2; },{"./global.js":8,"./pubsub.js":34}]},{},[7]) //# sourceMappingURL=game.js.map
(function (ninja) { var ut = ninja.unitTests = { runSynchronousTests: function () { document.getElementById("busyblock").className = "busy"; var div = document.createElement("div"); div.setAttribute("class", "unittests"); div.setAttribute("id", "unittests"); var testResults = ""; var passCount = 0; var testCount = 0; for (var test in ut.synchronousTests) { var exceptionMsg = ""; var resultBool = false; try { resultBool = ut.synchronousTests[test](); } catch (ex) { exceptionMsg = ex.toString(); resultBool = false; } if (resultBool == true) { var passFailStr = "pass"; passCount++; } else { var passFailStr = "<b>FAIL " + exceptionMsg + "</b>"; } testCount++; testResults += test + ": " + passFailStr + "<br/>"; } testResults += passCount + " of " + testCount + " synchronous tests passed"; if (passCount < testCount) { testResults += "<b>" + (testCount - passCount) + " unit test(s) failed</b>"; } div.innerHTML = "<h3>Unit Tests</h3><div id=\"unittestresults\">" + testResults + "<br/><br/></div>"; document.body.appendChild(div); document.getElementById("busyblock").className = ""; }, runAsynchronousTests: function () { var div = document.createElement("div"); div.setAttribute("class", "unittests"); div.setAttribute("id", "asyncunittests"); div.innerHTML = "<h3>Async Unit Tests</h3><div id=\"asyncunittestresults\"></div><br/><br/><br/><br/>"; document.body.appendChild(div); // run the asynchronous tests one after another so we don't crash the browser ninja.foreachSerialized(ninja.unitTests.asynchronousTests, function (name, cb) { document.getElementById("busyblock").className = "busy"; ninja.unitTests.asynchronousTests[name](cb); }, function () { document.getElementById("asyncunittestresults").innerHTML += "running of asynchronous unit tests complete!<br/>"; document.getElementById("busyblock").className = ""; }); }, synchronousTests: { //ninja.publicKey tests testIsPublicKeyHexFormat: function () { var key = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var bool = ninja.publicKey.isPublicKeyHexFormat(key); if (bool != true) { return false; } return true; }, testGetHexFromByteArray: function () { var bytes = [4, 120, 152, 47, 64, 250, 12, 11, 122, 85, 113, 117, 131, 175, 201, 154, 78, 223, 211, 1, 162, 114, 157, 197, 155, 11, 142, 185, 225, 134, 146, 188, 181, 33, 240, 84, 250, 217, 130, 175, 76, 193, 147, 58, 253, 31, 27, 86, 62, 167, 121, 166, 170, 108, 206, 54, 163, 11, 148, 125, 214, 83, 230, 62, 68]; var key = ninja.publicKey.getHexFromByteArray(bytes); if (key != "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44") { return false; } return true; }, testHexToBytes: function () { var key = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var bytes = Crypto.util.hexToBytes(key); if (bytes.toString() != "4,120,152,47,64,250,12,11,122,85,113,117,131,175,201,154,78,223,211,1,162,114,157,197,155,11,142,185,225,134,146,188,181,33,240,84,250,217,130,175,76,193,147,58,253,31,27,86,62,167,121,166,170,108,206,54,163,11,148,125,214,83,230,62,68") { return false; } return true; }, testGetBitcoinAddressFromByteArray: function () { var bytes = [4, 120, 152, 47, 64, 250, 12, 11, 122, 85, 113, 117, 131, 175, 201, 154, 78, 223, 211, 1, 162, 114, 157, 197, 155, 11, 142, 185, 225, 134, 146, 188, 181, 33, 240, 84, 250, 217, 130, 175, 76, 193, 147, 58, 253, 31, 27, 86, 62, 167, 121, 166, 170, 108, 206, 54, 163, 11, 148, 125, 214, 83, 230, 62, 68]; var address = ninja.publicKey.getBitcoinAddressFromByteArray(bytes); if (address != "1Cnz9ULjzBPYhDw1J8bpczDWCEXnC9HuU1") { return false; } return true; }, testGetByteArrayFromAdding: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "0419153E53FECAD7FF07FEC26F7DDEB1EDD66957711AA4554B8475F10AFBBCD81C0159DC0099AD54F733812892EB9A11A8C816A201B3BAF0D97117EBA2033C9AB2"; var bytes = ninja.publicKey.getByteArrayFromAdding(key1, key2); if (bytes.toString() != "4,151,19,227,152,54,37,184,255,4,83,115,216,102,189,76,82,170,57,4,196,253,2,41,74,6,226,33,167,199,250,74,235,223,128,233,99,150,147,92,57,39,208,84,196,71,68,248,166,106,138,95,172,253,224,70,187,65,62,92,81,38,253,79,0") { return false; } return true; }, testGetByteArrayFromAddingCompressed: function () { var key1 = "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5"; var key2 = "0219153E53FECAD7FF07FEC26F7DDEB1EDD66957711AA4554B8475F10AFBBCD81C"; var bytes = ninja.publicKey.getByteArrayFromAdding(key1, key2); var hex = ninja.publicKey.getHexFromByteArray(bytes); if (hex != "029713E3983625B8FF045373D866BD4C52AA3904C4FD02294A06E221A7C7FA4AEB") { return false; } return true; }, testGetByteArrayFromAddingUncompressedAndCompressed: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "0219153E53FECAD7FF07FEC26F7DDEB1EDD66957711AA4554B8475F10AFBBCD81C"; var bytes = ninja.publicKey.getByteArrayFromAdding(key1, key2); if (bytes.toString() != "4,151,19,227,152,54,37,184,255,4,83,115,216,102,189,76,82,170,57,4,196,253,2,41,74,6,226,33,167,199,250,74,235,223,128,233,99,150,147,92,57,39,208,84,196,71,68,248,166,106,138,95,172,253,224,70,187,65,62,92,81,38,253,79,0") { return false; } return true; }, testGetByteArrayFromAddingShouldReturnNullWhenSameKey1: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var bytes = ninja.publicKey.getByteArrayFromAdding(key1, key2); if (bytes != null) { return false; } return true; }, testGetByteArrayFromAddingShouldReturnNullWhenSameKey2: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5"; var bytes = ninja.publicKey.getByteArrayFromAdding(key1, key2); if (bytes != null) { return false; } return true; }, testGetByteArrayFromMultiplying: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "SQE6yipP5oW8RBaStWoB47xsRQ8pat"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(key1, new Bitcoin.ECKey(key2)); if (bytes.toString() != "4,102,230,163,180,107,9,21,17,48,35,245,227,110,199,119,144,57,41,112,64,245,182,40,224,41,230,41,5,26,206,138,57,115,35,54,105,7,180,5,106,217,57,229,127,174,145,215,79,121,163,191,211,143,215,50,48,156,211,178,72,226,68,150,52") { return false; } return true; }, testGetByteArrayFromMultiplyingCompressedOutputsUncompressed: function () { var key1 = "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5"; var key2 = "SQE6yipP5oW8RBaStWoB47xsRQ8pat"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(key1, new Bitcoin.ECKey(key2)); if (bytes.toString() != "4,102,230,163,180,107,9,21,17,48,35,245,227,110,199,119,144,57,41,112,64,245,182,40,224,41,230,41,5,26,206,138,57,115,35,54,105,7,180,5,106,217,57,229,127,174,145,215,79,121,163,191,211,143,215,50,48,156,211,178,72,226,68,150,52") { return false; } return true; }, testGetByteArrayFromMultiplyingCompressedOutputsCompressed: function () { var key1 = "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5"; var key2 = "L1n4cgNZAo2KwdUc15zzstvo1dcxpBw26NkrLqfDZtU9AEbPkLWu"; var ecKey = new Bitcoin.ECKey(key2); var bytes = ninja.publicKey.getByteArrayFromMultiplying(key1, ecKey); if (bytes.toString() != "2,102,230,163,180,107,9,21,17,48,35,245,227,110,199,119,144,57,41,112,64,245,182,40,224,41,230,41,5,26,206,138,57") { return false; } return true; }, testGetByteArrayFromMultiplyingShouldReturnNullWhenSameKey1: function () { var key1 = "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44"; var key2 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(key1, new Bitcoin.ECKey(key2)); if (bytes != null) { return false; } return true; }, testGetByteArrayFromMultiplyingShouldReturnNullWhenSameKey2: function () { var key1 = "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5"; var key2 = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(key1, new Bitcoin.ECKey(key2)); if (bytes != null) { return false; } return true; }, // confirms multiplication is working and BigInteger was created correctly (Pub Key B vs Priv Key A) testGetPubHexFromMultiplyingPrivAPubB: function () { var keyPub = "04F04BF260DCCC46061B5868F60FE962C77B5379698658C98A93C3129F5F98938020F36EBBDE6F1BEAF98E5BD0E425747E68B0F2FB7A2A59EDE93F43C0D78156FF"; var keyPriv = "B1202A137E917536B3B4C5010C3FF5DDD4784917B3EEF21D3A3BF21B2E03310C"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(keyPub, new Bitcoin.ECKey(keyPriv)); var pubHex = ninja.publicKey.getHexFromByteArray(bytes); if (pubHex != "04C6732006AF4AE571C7758DF7A7FB9E3689DFCF8B53D8724D3A15517D8AB1B4DBBE0CB8BB1C4525F8A3001771FC7E801D3C5986A555E2E9441F1AD6D181356076") { return false; } return true; }, // confirms multiplication is working and BigInteger was created correctly (Pub Key A vs Priv Key B) testGetPubHexFromMultiplyingPrivBPubA: function () { var keyPub = "0429BF26C0AF7D31D608474CEBD49DA6E7C541B8FAD95404B897643476CE621CFD05E24F7AE8DE8033AADE5857DB837E0B704A31FDDFE574F6ECA879643A0D3709"; var keyPriv = "7DE52819F1553C2BFEDE6A2628B6FDDF03C2A07EB21CF77ACA6C2C3D252E1FD9"; var bytes = ninja.publicKey.getByteArrayFromMultiplying(keyPub, new Bitcoin.ECKey(keyPriv)); var pubHex = ninja.publicKey.getHexFromByteArray(bytes); if (pubHex != "04C6732006AF4AE571C7758DF7A7FB9E3689DFCF8B53D8724D3A15517D8AB1B4DBBE0CB8BB1C4525F8A3001771FC7E801D3C5986A555E2E9441F1AD6D181356076") { return false; } return true; }, // Private Key tests testBadKeyIsNotWif: function () { return !(Bitcoin.ECKey.isWalletImportFormat("bad key")); }, testBadKeyIsNotWifCompressed: function () { return !(Bitcoin.ECKey.isCompressedWalletImportFormat("bad key")); }, testBadKeyIsNotHex: function () { return !(Bitcoin.ECKey.isHexFormat("bad key")); }, testBadKeyIsNotBase64: function () { return !(Bitcoin.ECKey.isBase64Format("bad key")); }, testBadKeyIsNotMini: function () { return !(Bitcoin.ECKey.isMiniFormat("bad key")); }, testBadKeyReturnsNullPrivFromECKey: function () { var key = "bad key"; var ecKey = new Bitcoin.ECKey(key); if (ecKey.priv != null) { return false; } return true; }, testGetBitcoinPrivateKeyByteArray: function () { var key = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var bytes = [41, 38, 101, 195, 135, 36, 24, 173, 241, 218, 127, 250, 58, 100, 111, 47, 6, 2, 36, 109, 166, 9, 138, 145, 210, 41, 195, 33, 80, 242, 113, 139]; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinPrivateKeyByteArray().toString() != bytes.toString()) { return false; } return true; }, testECKeyDecodeWalletImportFormat: function () { var key = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var bytes1 = [41, 38, 101, 195, 135, 36, 24, 173, 241, 218, 127, 250, 58, 100, 111, 47, 6, 2, 36, 109, 166, 9, 138, 145, 210, 41, 195, 33, 80, 242, 113, 139]; var bytes2 = Bitcoin.ECKey.decodeWalletImportFormat(key); if (bytes1.toString() != bytes2.toString()) { return false; } return true; }, testECKeyDecodeCompressedWalletImportFormat: function () { var key = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var bytes1 = [41, 38, 101, 195, 135, 36, 24, 173, 241, 218, 127, 250, 58, 100, 111, 47, 6, 2, 36, 109, 166, 9, 138, 145, 210, 41, 195, 33, 80, 242, 113, 139]; var bytes2 = Bitcoin.ECKey.decodeCompressedWalletImportFormat(key); if (bytes1.toString() != bytes2.toString()) { return false; } return true; }, testWifToPubKeyHex: function () { var key = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getPubKeyHex() != "0478982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB521F054FAD982AF4CC1933AFD1F1B563EA779A6AA6CCE36A30B947DD653E63E44" || btcKey.getPubPoint().compressed != false) { return false; } return true; }, testWifToPubKeyHexCompressed: function () { var key = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var btcKey = new Bitcoin.ECKey(key); btcKey.setCompressed(true); if (btcKey.getPubKeyHex() != "0278982F40FA0C0B7A55717583AFC99A4EDFD301A2729DC59B0B8EB9E18692BCB5" || btcKey.getPubPoint().compressed != true) { return false; } return true; }, testBase64ToECKey: function () { var key = "KSZlw4ckGK3x2n/6OmRvLwYCJG2mCYqR0inDIVDycYs="; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinBase64Format() != "KSZlw4ckGK3x2n/6OmRvLwYCJG2mCYqR0inDIVDycYs=") { return false; } return true; }, testHexToECKey: function () { var key = "292665C3872418ADF1DA7FFA3A646F2F0602246DA6098A91D229C32150F2718B"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinHexFormat() != "292665C3872418ADF1DA7FFA3A646F2F0602246DA6098A91D229C32150F2718B") { return false; } return true; }, testCompressedWifToECKey: function () { var key = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinWalletImportFormat() != "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S" || btcKey.getPubPoint().compressed != true) { return false; } return true; }, testWifToECKey: function () { var key = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinWalletImportFormat() != "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb") { return false; } return true; }, testBrainToECKey: function () { var key = "bitaddress.org unit test"; var bytes = Crypto.SHA256(key, { asBytes: true }); var btcKey = new Bitcoin.ECKey(bytes); if (btcKey.getBitcoinWalletImportFormat() != "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb") { return false; } return true; }, testMini30CharsToECKey: function () { var key = "SQE6yipP5oW8RBaStWoB47xsRQ8pat"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinWalletImportFormat() != "5JrBLQseeZdYw4jWEAHmNxGMr5fxh9NJU3fUwnv4khfKcg2rJVh") { return false; } return true; }, testGetECKeyFromAdding: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "SQE6yipP5oW8RBaStWoB47xsRQ8pat"; var ecKey = ninja.privateKey.getECKeyFromAdding(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "5KAJTSqSjpsZ11KyEE3qu5PrJVjR4ZCbNxK3Nb1F637oe41m1c2") { return false; } return true; }, testGetECKeyFromAddingCompressed: function () { var key1 = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var key2 = "L1n4cgNZAo2KwdUc15zzstvo1dcxpBw26NkrLqfDZtU9AEbPkLWu"; var ecKey = ninja.privateKey.getECKeyFromAdding(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "L3A43j2pc2J8F2SjBNbYprPrcDpDCh8Aju8dUH65BEM2r7RFSLv4") { return false; } return true; }, testGetECKeyFromAddingUncompressedAndCompressed: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "L1n4cgNZAo2KwdUc15zzstvo1dcxpBw26NkrLqfDZtU9AEbPkLWu"; var ecKey = ninja.privateKey.getECKeyFromAdding(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "5KAJTSqSjpsZ11KyEE3qu5PrJVjR4ZCbNxK3Nb1F637oe41m1c2") { return false; } return true; }, testGetECKeyFromAddingShouldReturnNullWhenSameKey1: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var ecKey = ninja.privateKey.getECKeyFromAdding(key1, key2); if (ecKey != null) { return false; } return true; }, testGetECKeyFromAddingShouldReturnNullWhenSameKey2: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var ecKey = ninja.privateKey.getECKeyFromAdding(key1, key2); if (ecKey != null) { return false; } return true; }, testGetECKeyFromMultiplying: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "SQE6yipP5oW8RBaStWoB47xsRQ8pat"; var ecKey = ninja.privateKey.getECKeyFromMultiplying(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "5KetpZ5mCGagCeJnMmvo18n4iVrtPSqrpnW5RP92Gv2BQy7GPCk") { return false; } return true; }, testGetECKeyFromMultiplyingCompressed: function () { var key1 = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var key2 = "L1n4cgNZAo2KwdUc15zzstvo1dcxpBw26NkrLqfDZtU9AEbPkLWu"; var ecKey = ninja.privateKey.getECKeyFromMultiplying(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "L5LFitc24jme2PfVChJS3bKuQAPBp54euuqLWciQdF2CxnaU3M8t") { return false; } return true; }, testGetECKeyFromMultiplyingUncompressedAndCompressed: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "L1n4cgNZAo2KwdUc15zzstvo1dcxpBw26NkrLqfDZtU9AEbPkLWu"; var ecKey = ninja.privateKey.getECKeyFromMultiplying(key1, key2); if (ecKey.getBitcoinWalletImportFormat() != "5KetpZ5mCGagCeJnMmvo18n4iVrtPSqrpnW5RP92Gv2BQy7GPCk") { return false; } return true; }, testGetECKeyFromMultiplyingShouldReturnNullWhenSameKey1: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var ecKey = ninja.privateKey.getECKeyFromMultiplying(key1, key2); if (ecKey != null) { return false; } return true; }, testGetECKeyFromMultiplyingShouldReturnNullWhenSameKey2: function () { var key1 = "5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb"; var key2 = "KxbhchnQquYQ2dfSxz7rrEaQTCukF4uCV57TkamyTbLzjFWcdi3S"; var ecKey = ninja.privateKey.getECKeyFromMultiplying(key1, key2); if (ecKey != null) { return false; } return true; }, testGetECKeyFromBase6Key: function () { var baseKey = "100531114202410255230521444145414341221420541210522412225005202300434134213212540304311321323051431"; var hexKey = "292665C3872418ADF1DA7FFA3A646F2F0602246DA6098A91D229C32150F2718B"; var ecKey = new Bitcoin.ECKey(baseKey); if (ecKey.getBitcoinHexFormat() != hexKey) { return false; } return true; }, // EllipticCurve tests testDecodePointEqualsDecodeFrom: function () { var key = "04F04BF260DCCC46061B5868F60FE962C77B5379698658C98A93C3129F5F98938020F36EBBDE6F1BEAF98E5BD0E425747E68B0F2FB7A2A59EDE93F43C0D78156FF"; var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); var ecPoint1 = EllipticCurve.PointFp.decodeFrom(ecparams.getCurve(), Crypto.util.hexToBytes(key)); var ecPoint2 = ecparams.getCurve().decodePointHex(key); if (!ecPoint1.equals(ecPoint2)) { return false; } return true; }, testDecodePointHexForCompressedPublicKey: function () { var key = "03F04BF260DCCC46061B5868F60FE962C77B5379698658C98A93C3129F5F989380"; var pubHexUncompressed = ninja.publicKey.getDecompressedPubKeyHex(key); if (pubHexUncompressed != "04F04BF260DCCC46061B5868F60FE962C77B5379698658C98A93C3129F5F98938020F36EBBDE6F1BEAF98E5BD0E425747E68B0F2FB7A2A59EDE93F43C0D78156FF") { return false; } return true; }, // old bugs testBugWithLeadingZeroBytePublicKey: function () { var key = "5Je7CkWTzgdo1RpwjYhwnVKxQXt8EPRq17WZFtWcq5umQdsDtTP"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinAddress() != "1M6dsMZUjFxjdwsyVk8nJytWcfr9tfUa9E") { return false; } return true; }, testBugWithLeadingZeroBytePrivateKey: function () { var key = "0004d30da67214fa65a41a6493576944c7ea86713b14db437446c7a8df8e13da"; var btcKey = new Bitcoin.ECKey(key); if (btcKey.getBitcoinAddress() != "1NAjZjF81YGfiJ3rTKc7jf1nmZ26KN7Gkn") { return false; } return true; }, // test split wallet testSplitAndCombinePrivateKey2of2: function () { // lowercase hex key var key = "0004d30da67214fa65a41a6493576944c7ea86713b14db437446c7a8df8e13da"; //5HpJ4bpHFEMWYwCidjtZHwM2rsMh4PRfmZKV8Y21i7msiUkQKUW var numshares = 2; var threshold = 2; secrets.setRNG(); secrets.init(7); var shares = ninja.wallets.splitwallet.getFormattedShares(key, numshares, threshold); var combined = ninja.wallets.splitwallet.combineFormattedShares(shares); var btcKey = new Bitcoin.ECKey(combined); if (btcKey.getBitcoinHexFormat() != key.toUpperCase()) { return false; } return true; }, // Example use case #1: // Division of 3 shares: // 1 share in a safety deposit box ("Box") // 1 share at Home // 1 share at Work // Threshold of 2 can be redeemed in these permutations // Home + Box // Work + Box // Home + Work testSplitAndCombinePrivateKey2of3: function () { // lowercase hex key var key = "0004d30da67214fa65a41a6493576944c7ea86713b14db437446c7a8df8e13da"; //5HpJ4bpHFEMWYwCidjtZHwM2rsMh4PRfmZKV8Y21i7msiUkQKUW var numshares = 3; var threshold = 2; secrets.setRNG(); secrets.init(7); var shares = ninja.wallets.splitwallet.getFormattedShares(key, numshares, threshold); shares.shift(); var combined = ninja.wallets.splitwallet.combineFormattedShares(shares); var btcKey = new Bitcoin.ECKey(combined); if (btcKey.getBitcoinHexFormat() != key.toUpperCase()) { return false; } return true; }, testSplitAndCombinePrivateKey2of4: function () { // uppercase hex key var key = "292665C3872418ADF1DA7FFA3A646F2F0602246DA6098A91D229C32150F2718B"; //5J8QhiQtAiozKwyk3GCycAscg1tNaYhNdiiLey8vaDK8Bzm4znb var numshares = 4; var threshold = 2; secrets.setRNG(); secrets.init(7); var shares = ninja.wallets.splitwallet.getFormattedShares(key, numshares, threshold); shares.shift(); shares.shift(); var combined = ninja.wallets.splitwallet.combineFormattedShares(shares); var btcKey = new Bitcoin.ECKey(combined); if (btcKey.getBitcoinHexFormat() != key) { return false; } return true; }, // Example use case #2: // Division of 13 shares: // 4 shares in a safety deposit box ("Box") // 3 shares with good friend Angie // 3 shares with good friend Fred // 3 shares with Self at home or office // Threshold of 7 can be redeemed in these permutations // Self + Box (no trust to spend your coins but your friends are backing up your shares) // Angie + Box (Angie will send btc to executor of your will) // Fred + Box (if Angie hasn't already then Fred will send btc to executor of your will) // Angie + Fred + Self (bank fire/theft then you with both your friends can spend the coins) testSplitAndCombinePrivateKey7of13: function () { var key = "0004d30da67214fa65a41a6493576944c7ea86713b14db437446c7a8df8e13da"; var numshares = 12; var threshold = 7; secrets.setRNG(); secrets.init(7); var shares = ninja.wallets.splitwallet.getFormattedShares(key, numshares, threshold); var combined = ninja.wallets.splitwallet.combineFormattedShares(shares); var btcKey = new Bitcoin.ECKey(combined); if (btcKey.getBitcoinHexFormat() != key.toUpperCase()) { return false; } return true; }, testCombinePrivateKeyFromXofYShares: function () { var key = "5K9nHKqbwc1xXpa6wV5p3AaCnubvxQDBukKaFkq7ThAkxgMTMEh"; // these are 4 of 6 shares var shares = ["3XxjMASmrkk6eXMM9kAJA7qiqViNVBfiwA1GQDLvg4PVScL", "3Y2DkcPuNX8VKZwpnDdxw55wJtcnCvv2nALqe8nBLViHvck", "3Y6qv7kyGwgRBKVHVbUNtzmLYAZWQtTPztPwR8wc7uf4MXR", "3YD4TowZn6jw5ss8U89vrcPHonFW4vSs9VKq8MupV5kevG4"] secrets.setRNG(); secrets.init(7); var combined = ninja.wallets.splitwallet.combineFormattedShares(shares); var btcKey = new Bitcoin.ECKey(combined); if (btcKey.getBitcoinWalletImportFormat() != key) { return false; } return true; } }, asynchronousTests: { //https://en.bitcoin.it/wiki/BIP_0038 testBip38: function (done) { var tests = [ //No compression, no EC multiply ["6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg", "TestingOneTwoThree", "5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR"], ["6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq", "Satoshi", "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5"], //Compression, no EC multiply ["6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo", "TestingOneTwoThree", "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP"], ["6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7", "Satoshi", "KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7"], //EC multiply, no compression, no lot/sequence numbers ["6PfQu77ygVyJLZjfvMLyhLMQbYnu5uguoJJ4kMCLqWwPEdfpwANVS76gTX", "TestingOneTwoThree", "5K4caxezwjGCGfnoPTZ8tMcJBLB7Jvyjv4xxeacadhq8nLisLR2"], ["6PfLGnQs6VZnrNpmVKfjotbnQuaJK4KZoPFrAjx1JMJUa1Ft8gnf5WxfKd", "Satoshi", "5KJ51SgxWaAYR13zd9ReMhJpwrcX47xTJh2D3fGPG9CM8vkv5sH"], //EC multiply, no compression, lot/sequence numbers ["6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j", "MOLON LABE", "5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8"], ["6PgGWtx25kUg8QWvwuJAgorN6k9FbE25rv5dMRwu5SKMnfpfVe5mar2ngH", Crypto.charenc.UTF8.bytesToString([206, 156, 206, 159, 206, 155, 206, 169, 206, 157, 32, 206, 155, 206, 145, 206, 146, 206, 149])/*UTF-8 characters, encoded in source so they don't get corrupted*/, "5KMKKuUmAkiNbA3DazMQiLfDq47qs8MAEThm4yL8R2PhV1ov33D"]]; // running each test uses a lot of memory, which isn't freed // immediately, so give the VM a little time to reclaim memory function waitThenCall(callback) { return function () { setTimeout(callback, 10000); } } var decryptTest = function (test, i, onComplete) { ninja.privateKey.BIP38EncryptedKeyToByteArrayAsync(test[0], test[1], function (privBytes) { if (privBytes.constructor == Error) { document.getElementById("asyncunittestresults").innerHTML += "fail testDecryptBip38 #" + i + ", error: " + privBytes.message + "<br/>"; } else { var btcKey = new Bitcoin.ECKey(privBytes); var wif = !test[2].substr(0, 1).match(/[LK]/) ? btcKey.setCompressed(false).getBitcoinWalletImportFormat() : btcKey.setCompressed(true).getBitcoinWalletImportFormat(); if (wif != test[2]) { document.getElementById("asyncunittestresults").innerHTML += "fail testDecryptBip38 #" + i + "<br/>"; } else { document.getElementById("asyncunittestresults").innerHTML += "pass testDecryptBip38 #" + i + "<br/>"; } } onComplete(); }); }; var encryptTest = function (test, compressed, i, onComplete) { ninja.privateKey.BIP38PrivateKeyToEncryptedKeyAsync(test[2], test[1], compressed, function (encryptedKey) { if (encryptedKey === test[0]) { document.getElementById("asyncunittestresults").innerHTML += "pass testBip38Encrypt #" + i + "<br/>"; } else { document.getElementById("asyncunittestresults").innerHTML += "fail testBip38Encrypt #" + i + "<br/>"; document.getElementById("asyncunittestresults").innerHTML += "expected " + test[0] + "<br/>received " + encryptedKey + "<br/>"; } onComplete(); }); }; // test randomly generated encryption-decryption cycle var cycleTest = function (i, compress, onComplete) { // create new private key var privKey = (new Bitcoin.ECKey(false)).getBitcoinWalletImportFormat(); // encrypt private key ninja.privateKey.BIP38PrivateKeyToEncryptedKeyAsync(privKey, 'testing', compress, function (encryptedKey) { // decrypt encryptedKey ninja.privateKey.BIP38EncryptedKeyToByteArrayAsync(encryptedKey, 'testing', function (decryptedBytes) { var decryptedKey = (new Bitcoin.ECKey(decryptedBytes)).getBitcoinWalletImportFormat(); if (decryptedKey === privKey) { document.getElementById("asyncunittestresults").innerHTML += "pass cycleBip38 test #" + i + "<br/>"; } else { document.getElementById("asyncunittestresults").innerHTML += "fail cycleBip38 test #" + i + " " + privKey + "<br/>"; document.getElementById("asyncunittestresults").innerHTML += "encrypted key: " + encryptedKey + "<br/>decrypted key: " + decryptedKey; } onComplete(); }); }); }; // intermediate test - create some encrypted keys from an intermediate // then decrypt them to check that the private keys are recoverable var intermediateTest = function (i, onComplete) { var pass = Math.random().toString(36).substr(2); ninja.privateKey.BIP38GenerateIntermediatePointAsync(pass, null, null, function (intermediatePoint) { ninja.privateKey.BIP38GenerateECAddressAsync(intermediatePoint, false, function (address, encryptedKey) { ninja.privateKey.BIP38EncryptedKeyToByteArrayAsync(encryptedKey, pass, function (privBytes) { if (privBytes.constructor == Error) { document.getElementById("asyncunittestresults").innerHTML += "fail testBip38Intermediate #" + i + ", error: " + privBytes.message + "<br/>"; } else { var btcKey = new Bitcoin.ECKey(privBytes); var btcAddress = btcKey.getBitcoinAddress(); if (address !== btcKey.getBitcoinAddress()) { document.getElementById("asyncunittestresults").innerHTML += "fail testBip38Intermediate #" + i + "<br/>"; } else { document.getElementById("asyncunittestresults").innerHTML += "pass testBip38Intermediate #" + i + "<br/>"; } } onComplete(); }); }); }); } document.getElementById("asyncunittestresults").innerHTML += "running " + tests.length + " tests named testDecryptBip38<br/>"; document.getElementById("asyncunittestresults").innerHTML += "running 4 tests named testBip38Encrypt<br/>"; document.getElementById("asyncunittestresults").innerHTML += "running 2 tests named cycleBip38<br/>"; document.getElementById("asyncunittestresults").innerHTML += "running 5 tests named testBip38Intermediate<br/>"; ninja.runSerialized([ function (cb) { ninja.forSerialized(0, tests.length, function (i, callback) { decryptTest(tests[i], i, waitThenCall(callback)); }, waitThenCall(cb)); }, function (cb) { ninja.forSerialized(0, 4, function (i, callback) { // only first 4 test vectors are not EC-multiply, // compression param false for i = 1,2 and true for i = 3,4 encryptTest(tests[i], i >= 2, i, waitThenCall(callback)); }, waitThenCall(cb)); }, function (cb) { ninja.forSerialized(0, 2, function (i, callback) { cycleTest(i, i % 2 ? true : false, waitThenCall(callback)); }, waitThenCall(cb)); }, function (cb) { ninja.forSerialized(0, 5, function (i, callback) { intermediateTest(i, waitThenCall(callback)); }, cb); } ], done); } } }; })(ninja);
import { coreInit } from 'isolated-core' coreInit({ scriptURL: 'error.js', run: () => { throw new Error('this core crashes!') }, })
/* * Copyright 2014 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** * @constructor * @extends {WebInspector.Object} * @implements {WebInspector.TargetManager.Observer} */ WebInspector.TracingManager = function() { WebInspector.Object.call(this); this._active = false; this._eventBufferSize = 0; this._eventsRetrieved = 0; WebInspector.targetManager.observeTargets(this); } WebInspector.TracingManager.Events = { "RetrieveEventsProgress": "RetrieveEventsProgress", "BufferUsage": "BufferUsage", "TracingStarted": "TracingStarted", "EventsCollected": "EventsCollected", "TracingStopped": "TracingStopped", "TracingComplete": "TracingComplete" } /** @typedef {!{ cat: string, pid: number, tid: number, ts: number, ph: string, name: string, args: !Object, dur: number, id: number, s: string }} */ WebInspector.TracingManager.EventPayload; WebInspector.TracingManager.TransferMode = { ReportEvents: "ReportEvents", ReturnAsStream: "ReturnAsStream" }; WebInspector.TracingManager.prototype = { /** * @override * @param {!WebInspector.Target} target */ targetAdded: function(target) { if (this._target) return; this._target = target; target.registerTracingDispatcher(new WebInspector.TracingDispatcher(this)); }, /** * @override * @param {!WebInspector.Target} target */ targetRemoved: function(target) { if (this._target !== target) return; delete this._target; }, /** * @return {?WebInspector.Target} */ target: function() { return this._target; }, /** * @param {number=} usage * @param {number=} eventCount * @param {number=} percentFull */ _bufferUsage: function(usage, eventCount, percentFull) { this._eventBufferSize = eventCount; this.dispatchEventToListeners(WebInspector.TracingManager.Events.BufferUsage, usage || percentFull); }, /** * @param {!Array.<!WebInspector.TracingManager.EventPayload>} events */ _eventsCollected: function(events) { this.dispatchEventToListeners(WebInspector.TracingManager.Events.EventsCollected, events); this._eventsRetrieved += events.length; if (!this._eventBufferSize) return; if (this._eventsRetrieved > this._eventBufferSize) this._eventsRetrieved = this._eventBufferSize; this.dispatchEventToListeners(WebInspector.TracingManager.Events.RetrieveEventsProgress, this._eventsRetrieved / this._eventBufferSize); }, _tracingComplete: function() { this._eventBufferSize = 0; this._eventsRetrieved = 0; <<<<<<< HEAD this.dispatchEventToListeners(WebInspector.TracingManager.Events.TracingComplete); ======= this._activeClient.tracingComplete(); this._activeClient = null; this._finishing = false; >>>>>>> 793500c01f8bb29015a736c79cc8d3e4322558bd }, /** * @param {string} categoryFilter * @param {string} options * @param {function(?string)=} callback */ start: function(categoryFilter, options, callback) { <<<<<<< HEAD if (this._active) return; WebInspector.targetManager.suspendAllTargets(); var bufferUsageReportingIntervalMs = 500; TracingAgent.start(categoryFilter, options, bufferUsageReportingIntervalMs, callback); this._active = true; this.dispatchEventToListeners(WebInspector.TracingManager.Events.TracingStarted); ======= if (this._activeClient) throw new Error("Tracing is already started"); var bufferUsageReportingIntervalMs = 500; this._activeClient = client; this._target.tracingAgent().start(categoryFilter, options, bufferUsageReportingIntervalMs, WebInspector.TracingManager.TransferMode.ReportEvents, callback); this._activeClient.tracingStarted(); >>>>>>> 793500c01f8bb29015a736c79cc8d3e4322558bd }, stop: function() { <<<<<<< HEAD if (!this._active) return; TracingAgent.end(this._onStop.bind(this)); WebInspector.targetManager.resumeAllTargets(); }, _onStop: function() { if (!this._active) return; this.dispatchEventToListeners(WebInspector.TracingManager.Events.TracingStopped); this._active = false; }, __proto__: WebInspector.Object.prototype ======= if (!this._activeClient) throw new Error("Tracing is not started"); if (this._finishing) throw new Error("Tracing is already being stopped"); this._finishing = true; this._target.tracingAgent().end(); } >>>>>>> 793500c01f8bb29015a736c79cc8d3e4322558bd } /** * @constructor * @implements {TracingAgent.Dispatcher} * @param {!WebInspector.TracingManager} tracingManager */ WebInspector.TracingDispatcher = function(tracingManager) { this._tracingManager = tracingManager; } WebInspector.TracingDispatcher.prototype = { /** * @override * @param {number=} usage * @param {number=} eventCount * @param {number=} percentFull */ bufferUsage: function(usage, eventCount, percentFull) { this._tracingManager._bufferUsage(usage, eventCount, percentFull); }, /** * @override * @param {!Array.<!WebInspector.TracingManager.EventPayload>} data */ dataCollected: function(data) { this._tracingManager._eventsCollected(data); }, /** * @override */ tracingComplete: function() { this._tracingManager._tracingComplete(); } }
var express = require('express') var request = require('request') var pcl = require('pretty-console.log') pcl.enable() // getApiUserId > postApiHora var globalUser = '' // getMembresias var membership = '' // getHorarios var schedule = '' // respuesta a peticion HTTP var globalStatus = '' // getApiHoraUserId var globalHorasId = '' // var globalCont = '' var router = express.Router() // controllers //var stock = require('../controllers/stock') //var scheduling = require('../controllers/scheduling') // auth middleware var isAuthenticated = function (req, res, next) { // if user is authenticated in the session, call the next() to call the next request handler // Passport adds this method to request object. A middleware is allowed to add properties to // request and response objects if (req.isAuthenticated()) return next(); // if the user is not authenticated then redirect him to the login page res.redirect('/'); } // Admin middleware var isAdmin = function (req, res, next) { if (role == 'admin') return next() // if the user is not authenticated then redirect him to the login page res.redirect('/index-loggedin') } // (1) // GET index usuarios var getApiUsers = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/usuarios/' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body); users = JSON.parse(body); console.log('Listado de usuarios obtenido con éxito!'); //pcl(users); } else { console.log('[getApiUsers] Lo sentimos no hemos podido responder tu solicitud. Inténtelo más tarde.') } }) } // (2) // GET usuario por ID // TODO SIEMPRE OBTENER EL ID DEL QLO var getApiUserId = function (req, res, name, next) { var nombre = name uriCall = 'http://api.fernandopiza.xyz/usuario/' + nombre //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body); usuario_id = JSON.parse(body); console.log('Datos de usuarios obtenidos con éxito! Usuario '+ usuario_id.id); globalUser = usuario_id.id //pcl('globalUser: ' + globalUser) } else { console.log('[getApiUserId] Error ('+ response.statusCode +') No se ha podido obtener el usuario ' + nombre) } }) } // (2.1) // GET usuario por ID // TODO var getApiHoraUserId = function (req, res, name, next) { uriCall = 'http://api.fernandopiza.xyz/hora_usuario/' + name + '/usuario' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { horasId = JSON.parse(body); console.log('[getApiHoraUserId] Datos de horas de usuario obtenidas con éxito!: ' + name); globalHorasId = horasId //console.log(body); } else { console.log('[getApiHoraUserId] Error ('+ response.statusCode +') No se ha podido obtener las horas de usuario: ' + name) } }) } // (3) // POST apiUser var postApiUser = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/usuarios' request( { method: 'post', uri: uriCall, form: { usuario: { nombre: req.body.username, correo: req.body.email, numero: req.body.phone, direccion: req.body.address } } }, function (error, response, body, user) { //console.log(body); if(!error && response.statusCode == 201){ //console.log(body); user = JSON.parse(body); console.log('Usuario creado con éxito. ' + user.nombre); } else { console.log(' [postApiUser] Lo sentimos, el usuario no ha sido registrado. Vuelva a intentarlo más tarde.') console.log(body + 'error: ' + response.statusCode) } } ) return req.body } // (4) // GET FLORES var getFlores = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/flores/' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { menu = JSON.parse(body); console.log('Variedades de flores obtenidas con éxito!'); //pcl(menu); } else { console.log(' [getFlores] Lo sentimos. Error ('+ response.statusCode +') No se ha podido solicitar el stock.'); } }) } // (5) // GET index hora_usuarios var getHorasIndex = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/hora_usuarios' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body); indexHoras = JSON.parse(body); console.log('Horas de usuario obtenidas con éxito!') //pcl(indexHoras) } else { console.log('[getHorasIndex] Error ('+ response.statusCode +') No se ha podido solicitar las horas de usuario.') //console.log(body) } }) } // (6) TODO - agragar comentario en modelo api // POST apiHora - ISSUE usuario_id var postHora = function (req, res, globalUser, next) { uriCall = 'http://api.fernandopiza.xyz/hora_usuarios/' //console.log(uriCall); //console.log(req.body); request( { method: 'post', uri: uriCall, form: { hora_usuario: { nombre: req.body.nombre, tipo_atencion: req.body.tipo_atencion, fecha: req.body.fecha, hora_medica_id: req.body.hora_medica_id, usuario_id: globalUser, membresia_id: req.body.membresia_id, comentarios: req.body.comentarios } } }, function (error, response, body) { if(!error && response.statusCode == 201){ hora = JSON.parse(body); //console.log('Hora registrada con éxito!'); globalStatus = 'Hora registrada con éxito! Lo esperamos el día ' + req.body.fecha + '!' pcl(globalStatus); } else { console.log('[postApiHora] Lo sentimos, no hemos podido crear su hora. Vuelva a intentarlo más tarde.') //console.log(body + 'error:' + response.statusCode) globalStatus = 'Lo sentimos, no hemos podido crear su hora. Vuelva a intentarlo más tarde.' pcl(globalStatus); } }) } //CALL scheduling // (7) var getMembresias = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/membresias' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body); membresias = JSON.parse(body); console.log(' [membresias] Membresias de usuario obtenidas con éxito!') //pcl(membresias) membership = membresias } else { console.log('[membresias] Error ('+ response.statusCode +') No se ha podido solicitar las horas de usuario.') //console.log(body) } }) } // (8) var getHorarios = function (req, res, next) { uriCall = 'http://api.fernandopiza.xyz/horas' //console.log(uriCall); request( { method: 'get', uri: uriCall }, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body); horas = JSON.parse(body); console.log('Horarios de atención obtenidas con éxito!') //pcl(horas) schedule = horas } else { console.log('[horariosIndex] Error ('+ response.statusCode +') No se ha podido solicitar las horas de usuario.') //console.log(body) } }) } //end CALL scheduling // MAIN module.exports = function(passport){ router.get('/index-loggedin', isAuthenticated, function(req, res){ var name = req.user.username //console.log('req.user.username: ' + req.user.username); var body = getApiUserId(req, res, name) getApiHoraUserId(req, res, name) getApiUsers() getFlores() getHorarios() getMembresias() getHorasIndex() res.render('index-loggedin', {title:'ACCI', usuario: req.user.username, estado: globalStatus}) }) ////////////////////// USERS //////////////////////////////// router.get('/user', isAuthenticated, isAdmin, function(req, res) { res.render('ficha', {title: 'ACCI'}) }) // postApiUser router.post('/user', isAuthenticated, isAdmin, function(req, res, next){ var name = req.user.username //var body = getApiUserId(req, res, name) var body2 = postApiUser(req, res) //console.log(body2); res.render('profile', {title: 'ACCI'}) }) router.get('/validate', isAuthenticated, isAdmin, function(req, res) { res.render('fichaValidada', {title: 'ACCI'}) }) ////////////////////// STOCK //////////////////////////////// //get stock router.get('/stock', isAuthenticated, function(req, res){ res.render('stock', {title:'ACCI'}) }); router.get('/editStock', isAuthenticated, function(req, res){ res.render('editStock', {title:'ACCI'}) }); ////////////////////// AGENDAMIENTOS ////////////////////// //// GET router.get('/scheduling', isAuthenticated, function(req, res){ var name = req.user.username if (globalCont == true) { globalCont = false console.log(globalCont); } else { globalStatus = '' console.log(globalCont); } getApiHoraUserId(req, res, name) res.render('scheduling', {title: 'ACCI', estado: globalStatus, horasUser: globalHorasId}) }) //// POST router.post('/scheduling', isAuthenticated, function(req, res){ var name = req.user.username getApiHoraUserId(req, res, name) var body = postHora(req, res, globalUser) globalCont = true //console.log('hora' + status); //console.log(body); pcl('post ' + globalStatus) res.render('index-loggedin', {title: 'ACCI', estado: globalUser, estado: globalStatus}) }) //// PUT router.put('/scheduling', isAuthenticated, function(req, res){ //var body = putHora(req, res) res.send('put scheduling', {title: 'ACCI', estado: body}) }) //// DELETE router.delete('/scheduling', isAuthenticated, function(req, res){ //var body = deleteHora(req, res) res.send('delete scheduling', {title: 'ACCI', estado: body}) }) router.get('/history', isAdmin, isAuthenticated, function(req, res){ res.render('history', {title: 'ACCI'}) }) ////////////////////// DECLARACIONES ////////////////////// //get declaraciones router.get('/declaraciones', isAuthenticated, function(req, res){ res.render('declaraciones', {title:'ACCI'}); }); ////////////////////// GALERIA ////////////////////// // get galeria router.get('/galeria', isAuthenticated, function(req, res){ res.render('galeria', {title:'ACCI'}); }); ////////////////////// FICHA DE SOCIO ////////////////////// //get profile router.get('/profile', isAuthenticated, function(req, res){ res.render('profile', {title:'ACCI', usuario: req.user.username, rut: req.user.rut, name: req.user.name, age: req.user.age, phone: req.user.phone, email: req.user.email, address: req.user.address, region: req.user.region, comuna: req.user.comuna, sick: req.user.sick, operaciones: req.user.operaciones, alergias: req.user.alergias, medicamentos: req.user.medicamentos, declaracion: req.user.declaracion, sender: req.user.sender, dosis: req.user.dosis, product: req.user.product, diary: req.user.diary, week: req.user.week, month: req.user.month, other: req.user.other, sign: req.user.sign }); }); //end get profile return router; }
"use strict"; /** * @license * * Copyright 2011 Google Inc. * * 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. */ /** * @fileoverview Map Label. * * @author Luke Mahe (lukem@google.com), * Chris Broadfoot (cbro@google.com) */ /** * Creates a new Map Label * @constructor * @extends google.maps.OverlayView * @param {Object.<string, *>=} opt_options Optional properties to set. */ function MapLabel(opt_options) { this.set('fontFamily', 'sans-serif'); this.set('fontSize', 12); this.set('fontColor', '#000000'); this.set('strokeWeight', 4); this.set('strokeColor', '#ffffff'); this.set('align', 'center'); this.set('zIndex', 1e3); this.setValues(opt_options); } MapLabel.prototype = new google.maps.OverlayView; window['MapLabel'] = MapLabel; /** @inheritDoc */ MapLabel.prototype.changed = function(prop) { switch (prop) { case 'fontFamily': case 'fontSize': case 'fontColor': case 'strokeWeight': case 'strokeColor': case 'align': case 'text': return this.drawCanvas_(); case 'maxZoom': case 'minZoom': case 'position': return this.draw(); } }; /** * Draws the label to the canvas 2d context. * @private */ MapLabel.prototype.drawCanvas_ = function() { var canvas = this.canvas_; if (!canvas) return; var style = canvas.style; style.zIndex = /** @type number */(this.get('zIndex')); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = this.get('strokeColor'); ctx.fillStyle = this.get('fontColor'); ctx.font = this.get('fontSize') + 'px ' + this.get('fontFamily'); var strokeWeight = Number(this.get('strokeWeight')); var text = this.get('text'); if (text) { if (strokeWeight) { ctx.lineWidth = strokeWeight; ctx.strokeText(text, strokeWeight, strokeWeight); } ctx.fillText(text, strokeWeight, strokeWeight); var textMeasure = ctx.measureText(text); var textWidth = textMeasure.width + strokeWeight; style.marginLeft = this.getMarginLeft_(textWidth) + 'px'; // Bring actual text top in line with desired latitude. // Cheaper than calculating height of text. style.marginTop = '-0.4em'; } }; /** * @inheritDoc */ MapLabel.prototype.onAdd = function() { var canvas = this.canvas_ = document.createElement('canvas'); var style = canvas.style; style.position = 'absolute'; var ctx = canvas.getContext('2d'); ctx.lineJoin = 'round'; ctx.textBaseline = 'top'; this.drawCanvas_(); var panes = this.getPanes(); if (panes) { panes.mapPane.appendChild(canvas); } }; MapLabel.prototype['onAdd'] = MapLabel.prototype.onAdd; /** * Gets the appropriate margin-left for the canvas. * @private * @param {number} textWidth the width of the text, in pixels. * @return {number} the margin-left, in pixels. */ MapLabel.prototype.getMarginLeft_ = function(textWidth) { switch (this.get('align')) { case 'left': return 0; case 'right': return -textWidth; } return textWidth / -2; }; /** * @inheritDoc */ MapLabel.prototype.draw = function() { var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } var latLng = /** @type {google.maps.LatLng} */ (this.get('position')); if (!latLng) { return; } var pos = projection.fromLatLngToDivPixel(latLng); var style = this.canvas_.style; style['top'] = pos.y + 'px'; style['left'] = pos.x + 'px'; style['visibility'] = this.getVisible_(); }; MapLabel.prototype['draw'] = MapLabel.prototype.draw; /** * Get the visibility of the label. * @private * @return {string} blank string if visible, 'hidden' if invisible. */ MapLabel.prototype.getVisible_ = function() { var minZoom = /** @type number */(this.get('minZoom')); var maxZoom = /** @type number */(this.get('maxZoom')); if (minZoom === undefined && maxZoom === undefined) { return ''; } var map = this.getMap(); if (!map) { return ''; } var mapZoom = map.getZoom(); if (mapZoom < minZoom || mapZoom > maxZoom) { return 'hidden'; } return ''; }; /** * @inheritDoc */ MapLabel.prototype.onRemove = function() { var canvas = this.canvas_; if (canvas && canvas.parentNode) { canvas.parentNode.removeChild(canvas); } }; MapLabel.prototype['onRemove'] = MapLabel.prototype.onRemove;
/* @flow */ import type { Dimension } from './type'; /** * Utility object to help debug node optimizations during measurement */ export const DebugDimension: Dimension<void> = { name: 'debug', displayName: 'debugging', units: '-', startMeasuring: (): void => { process.stdout.write('[[[ START measuring --'); }, stopMeasuring: (): number => { process.stdout.write('-- STOP measuring ]]]\n'); return 0; } };
// Data model declaration for Encapsule Project's // Software Circuit Description Language (SCDL). module.exports = { // Software Circuit Description Language (SCDL) onm data model declaration object. dataModelDeclaration: require('./dist/data-model/scdl'), // SCDL data model declaration sub-objects for testing, and for building derived // data model declarations that leverage SCDL object declarations. dataModelDeclarationObjects: { SemanticBindings: require('./dist/data-model/scdl-semantic-bindings'), Catalogue: require('./dist/data-model/scdl-catalogue'), Specification: require('./dist/data-model/scdl-specification'), System: require('./dist/data-model/scdl-system'), Socket: require('./dist/data-model/scdl-socket'), Contract: require('./dist/data-model/scdl-contract'), Machine: require('./dist/data-model/scdl-machine'), Pins: require('./dist/data-model/scdl-pins'), Type: require('./dist/data-model/scdl-type') }, // A simple helper API over the generic onm API's that simplify client code // SCDL model CRUD operations. crudAPI: { // SCDL API SCDLStore: require('./dist/crud-api/scdl-store-api'), SCDLStoreSelector: require('./dist/crud-api/scdl-store-selector-api'), // SCDL API implementation objects. SCDLCatalogue: require('./dist/crud-api/scdl-catalogue-api'), SCDLType: require('./dist/crud-api/scdl-type-api'), SCDLSystem: require('./dist/crud-api/scdl-system-api'), SCDLInputPin: require('./dist/crud-api/scdl-system-pin-api').SCDLInputPin, SCDLOutputPin: require('./dist/crud-api/scdl-system-pin-api').SCDLOutputPin, SCDLSubsystem: require('./dist/crud-api/scdl-system-subsystem-api'), SCDLInputPinInstance: require('./dist/crud-api/scdl-system-subsystem-pin-api').SCDLInputPinInstance, SCDLOutputPinInstance: require('./dist/crud-api/scdl-system-subsystem-pin-api').SCDLOutputPinInstance, SCDLSubnode: require('./dist/crud-api/scdl-system-subnode-api') }, intrinsics: { createIntrinsicSCDLStore: require('./src/intrinsics/intrinsic-scdl-store-factory'), properties: { typeModels: require('./src/intrinsics/intrinsic-scdl-type-properties') } } };
version https://git-lfs.github.com/spec/v1 oid sha256:49c65d50cd18866af7daf18a4996ce70df052249a6550c945c72ddf7691942e5 size 369852
System.register(["github:aurelia/templating-resources@0.9.2/index"], function($__export) { return { setters: [function(m) { for (var p in m) $__export(p, m[p]); }], execute: function() {} }; });
'use strict'; var parse = require('css-parse'); var fs = require('fs'); var Q = require('q'); module.exports = function() { return function(path) { var deferred = Q.defer(); if (!path.match(/.css$/)) { deferred.resolve({}); return deferred.promise; } fs.readFile(path, { encoding: 'utf-8' }, function(err, data) { if (err) { deferred.reject(new Error('Failed to read CSS file data')); } var parsedData = parse(data).stylesheet; var rules = parsedData.rules.length; var selectors = function() { var totalSelectors = 0, l = rules; for (var i = 0; i < l; i++) { var rule = parsedData.rules[i]; if (rule.type === 'rule') { totalSelectors += parsedData.rules[i].selectors.length; } } return totalSelectors; }; deferred.resolve({ rules: rules, totalSelectors: selectors(), averageSelectors: +(selectors() / rules).toFixed(1) }); }); return deferred.promise; }; };
var colors = require('colors'); var ep = module.exports = {}; function log(type, msg) { if (type) { type = '\n[' + type.toLocaleUpperCase() + '][ALPACA-SM]'; } process.stdout.write(type + msg + '\n'); } ep.error = function(err) { if (!(err instanceof Error)) { err = new Error(err.message || err); } log('error', err.message.red); process.exit(1); } ep.warning = function(msg) { log('waring', msg.yellow); } ep.info = function(msg) { log('', msg.green); } ep.debug = function(msg){ log('debug',msg.blue); }
export default { "ajs.datepicker.localisations.day-names.sunday": "Domingo", "ajs.datepicker.localisations.day-names.monday": "Luns", "ajs.datepicker.localisations.day-names.tuesday": "Martes", "ajs.datepicker.localisations.day-names.wednesday": "M&eacute;rcores", "ajs.datepicker.localisations.day-names.thursday": "Xoves", "ajs.datepicker.localisations.day-names.friday": "Venres", "ajs.datepicker.localisations.day-names.saturday": "S&aacute;bado", "ajs.datepicker.localisations.day-names-min.sunday": "Dom", "ajs.datepicker.localisations.day-names-min.monday": "Lun", "ajs.datepicker.localisations.day-names-min.tuesday": "Mar", "ajs.datepicker.localisations.day-names-min.wednesday": "M&eacute;r", "ajs.datepicker.localisations.day-names-min.thursday": "Xov", "ajs.datepicker.localisations.day-names-min.friday": "Ven", "ajs.datepicker.localisations.day-names-min.saturday": "S&aacute;b", "ajs.datepicker.localisations.first-day": 1, "ajs.datepicker.localisations.is-RTL": false, "ajs.datepicker.localisations.month-names.january": "Xaneiro", "ajs.datepicker.localisations.month-names.february": "Febreiro", "ajs.datepicker.localisations.month-names.march": "Marzo", "ajs.datepicker.localisations.month-names.april": "Abril", "ajs.datepicker.localisations.month-names.may": "Maio", "ajs.datepicker.localisations.month-names.june": "Xuño", "ajs.datepicker.localisations.month-names.july": "Xullo", "ajs.datepicker.localisations.month-names.august": "Agosto", "ajs.datepicker.localisations.month-names.september": "Setembro", "ajs.datepicker.localisations.month-names.october": "Outubro", "ajs.datepicker.localisations.month-names.november": "Novembro", "ajs.datepicker.localisations.month-names.december": "Decembro", "ajs.datepicker.localisations.show-month-after-year": false, "ajs.datepicker.localisations.year-suffix": null }
/** * Socket.io configuration */ 'use strict'; // dependencies var config = require('./environment'); // exports module.exports.init = _init; // private functions /** * socket.io (v1.x.x) is powered by debug. * In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope. * ex: DEBUG: "http*,socket.io:socket" * * We can authenticate socket.io users and access their token through socket.handshake.decoded_token * You will need to send the token in `client/components/socket/socket.service.js` * @param socketio socket.io module instance * @private */ function _init(socketio) { // Require authentication here: socketio.use(require('socketio-jwt').authorize({ secret: config.secrets.session, handshake: true })); socketio.on('connection', function (socket) { socket.address = socket.handshake.address + ":" + config.port; socket.connectedAt = new Date(); // Call _onDisconnect. socket.on('disconnect', function () { _onDisconnect(socket); //socket.on('user:off'); console.info('[%s] DISCONNECTED', socket.address); }); // Call _onConnect. _onConnect(socket, socketio); console.info('[%s] CONNECTED', socket.address); }); } /** * When the user disconnects.. perform this */ function _onDisconnect(socket) { } /** * When the user connects.. perform this */ function _onConnect(socket, io) { // When the client emits 'info', this listens and executes socket.on('info', function (data) { console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2)); }); // Insert sockets below require('../api/message/message.socket').register(socket, io); require('../api/user/user.socket').register(socket, io); }
const autoprefixer = require('autoprefixer'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const getClientEnvironment = require('./env'); const paths = require('./paths'); // Webpack uses `publicPath` to determine where the app is being served from. // In development, we always serve from the root. This makes config easier. const publicPath = '/'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. const publicUrl = ''; // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // This is the development configuration. // It is focused on developer experience and fast rebuilds. // The production configuration is different and lives in a separate file. module.exports = { // You may want 'eval' instead if you prefer to see the compiled output in DevTools. // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. devtool: 'cheap-module-source-map', // These are the "entry points" to our application. // This means they will be the "root" imports that are included in JS bundle. // The first two entry points enable "hot" CSS and auto-refreshes for JS. entry: [ // Include an alternative client for WebpackDevServer. A client's job is to // connect to WebpackDevServer by a socket and get notified about changes. // When you save a file, the client will either apply hot updates (in case // of CSS changes), or refresh the page (in case of JS changes). When you // make a syntax error, this client will display a syntax error overlay. // Note: instead of the default WebpackDevServer client, we use a custom one // to bring better experience for Create React App users. You can replace // the line below with these two lines if you prefer the stock client: // require.resolve('webpack-dev-server/client') + '?/', // require.resolve('webpack/hot/dev-server'), require.resolve('react-dev-utils/webpackHotDevClient'), // We ship a few polyfills by default: require.resolve('./polyfills'), // Finally, this is your app's code: paths.appIndexJs // We include the app code last so that if there is a runtime error during // initialization, it doesn't blow up the WebpackDevServer client, and // changing JS code would still trigger a refresh. ], output: { // Next line is not used in dev but WebpackDevServer crashes without it: path: paths.appBuild, // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // This does not produce a real file. It's just the virtual path that is // served by WebpackDevServer in development. This is the JS bundle // containing code from all our entry points, and the Webpack runtime. filename: 'static/js/bundle.js', // This is the URL that app is served from. We use "/" in development. publicPath }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We read `NODE_PATH` environment variable in `paths.js` and pass paths here. // We use `fallback` instead of `root` because we want `node_modules` to "win" // if there any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 fallback: paths.nodePaths, // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 extensions: ['.js', '.json', '.jsx', ''], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web' } }, module: { // First, run the linter. // It's important to do this before Babel processes the JS. preLoaders: [ { test: /\.(js|jsx)$/, loader: 'eslint', include: paths.appSrc, } ], loaders: [ // Default loader: load all assets that are not handled // by other loaders with the url loader. // Note: This list needs to be updated with every change of extensions // the other loaders match. // E.g., when adding a loader for a new supported file extension, // we need to add the supported extension to this loader too. // Add one new line in `exclude` for each loader. // // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `build` folder. // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { exclude: [ /\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/, /\.woff$/, /\.woff2$/, /\.(ttf|svg|eot)$/ ], loader: 'url', query: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }, // Process JS with Babel. { test: /\.(js|jsx)$/, include: paths.appSrc, loader: 'babel', query: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true } }, // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader turns CSS into JS modules that inject <style> tags. // In production, we use a plugin to extract that CSS to a file, but // in development "style" loader enables hot editing of CSS. { test: /\.css$/, loader: 'style!css?importLoaders=1!postcss' }, // JSON is not enabled by default in Webpack but both Node and Browserify // allow it implicitly so we also enable it. { test: /\.json$/, loader: 'json' }, // "file" loader for svg { test: /\.svg$/, loader: 'file', query: { name: 'static/media/[name].[hash:8].[ext]' } }, // "file" loader for fonts { test: /\.woff$/, loader: 'file', query: { name: 'fonts/[name].[hash].[ext]' } }, { test: /\.woff2$/, loader: 'file', query: { name: 'fonts/[name].[hash].[ext]' } }, { test: /\.(ttf|eot)$/, loader: 'file', query: { name: 'fonts/[name].[hash].[ext]' } }, // Truffle solidity loader to watch for changes in Solitiy files and hot // reload contracts with webpack. // // CURRENTLY REMOVED DUE TO INCOMPATIBILITY WITH TRUFFLE 3 // Compile and migrate contracts manually. // /* { test: /\.sol$/, loader: 'truffle-solidity?network_id=123' } */ ] }, // We use PostCSS for autoprefixing only. postcss() { return [ autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ] }), ]; }, plugins: [ // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In development, this will be an empty string. new InterpolateHtmlPlugin({ PUBLIC_URL: publicUrl }), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`. new webpack.DefinePlugin(env), // This is necessary to emit hot updates (currently CSS only): new webpack.HotModuleReplacementPlugin(), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // If you require a missing module and then `npm install` it, you still have // to restart the development server for Webpack to discover it. This plugin // makes the discovery automatic so you don't have to restart. // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } };
/* Terminal Kit Copyright (c) 2009 - 2021 Cédric Ronvel The MIT License (MIT) 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. */ "use strict" ; const Text = require( './Text.js' ) ; const spChars = require( '../spChars.js' ) ; function AnimatedText( options ) { // Clone options if necessary options = ! options ? {} : options.internal ? options : Object.create( options ) ; options.internal = true ; options.attr = options.attr || {} ; if ( Array.isArray( options.animation ) ) { this.animation = options.animation ; } else if ( typeof options.animation === 'string' ) { this.animation = spChars.animation[ options.animation ] || spChars.animation.lineSpinner ; if ( options.contentHasMarkup !== false ) { options.contentHasMarkup = true ; } } else { this.animation = spChars.animation.lineSpinner ; } this.animation = this.animation.map( e => Array.isArray( e ) ? e : [ e ] ) ; this.isAnimated = false ; this.frameDuration = options.frameDuration || 150 ; this.animationSpeed = options.animationSpeed || 1 ; this.frame = options.frame || 0 ; this.autoUpdateTimer = null ; this.autoUpdate = this.autoUpdate.bind( this ) ; options.content = this.animation[ this.frame ] ; Text.call( this , options ) ; if ( this.elementType === 'AnimatedText' && ! options.noDraw ) { this.draw() ; this.animate() ; } } module.exports = AnimatedText ; AnimatedText.prototype = Object.create( Text.prototype ) ; AnimatedText.prototype.constructor = AnimatedText ; AnimatedText.prototype.elementType = 'AnimatedText' ; AnimatedText.prototype.inlineCursorRestoreAfterDraw = true ; AnimatedText.prototype.animate = function( animationSpeed = 1 ) { this.isAnimated = !! animationSpeed ; this.animationSpeed = + animationSpeed || 0 ; if ( ! this.isAnimated ) { if ( this.autoUpdateTimer ) { clearTimeout( this.autoUpdateTimer ) ; } this.autoUpdateTimer = null ; return ; } if ( ! this.autoUpdateTimer ) { this.autoUpdateTimer = setTimeout( () => this.autoUpdate() , this.frameDuration / this.animationSpeed ) ; } } ; AnimatedText.prototype.autoUpdate = function() { this.frame = ( this.frame + 1 ) % this.animation.length ; this.content = this.animation[ this.frame ] ; this.draw() ; this.autoUpdateTimer = setTimeout( () => this.autoUpdate() , this.frameDuration / this.animationSpeed ) ; } ;
import Ember from 'ember'; import mapBboxRoute from 'mobility-playground/mixins/map-bbox-route'; import setLoading from 'mobility-playground/mixins/set-loading'; export default Ember.Route.extend(mapBboxRoute, setLoading, { queryParams: { onestop_id: { // replace: true, refreshModel: true }, bbox: { replace: true, refreshModel: true }, pin: { replace: true, } }, setupController: function (controller, model) { if (controller.get('bbox') !== null){ var coordinateArray = []; var bboxString = controller.get('bbox'); var tempArray = []; var boundsArray = []; coordinateArray = bboxString.split(','); for (var i = 0; i < coordinateArray.length; i++){ tempArray.push(parseFloat(coordinateArray[i])); } var arrayOne = []; var arrayTwo = []; arrayOne.push(tempArray[1]); arrayOne.push(tempArray[0]); arrayTwo.push(tempArray[3]); arrayTwo.push(tempArray[2]); boundsArray.push(arrayOne); boundsArray.push(arrayTwo); controller.set('leafletBounds', boundsArray); } controller.set('leafletBbox', controller.get('bbox')); this._super(controller, model); }, model: function(params){ this.store.unloadAll('data/transitland/operator'); this.store.unloadAll('data/transitland/stop'); this.store.unloadAll('data/transitland/route'); this.store.unloadAll('data/transitland/route_stop_pattern'); params.total=true; params.pin=null; return this.store.query('data/transitland/operator', params); }, actions:{ } });
import gulp from 'gulp'; import path from 'path'; import del from 'del'; import zip from 'gulp-zip'; import electronBuilder from 'electron-builder'; import config from '../../src/electron/package.json'; const compress = (src, name, dest = './build') => () => { gulp.src(src) .pipe(zip(name)) .pipe(gulp.dest(dest)); }; gulp.task('compress:app', compress('./build/app/**', 'app.zip') ); gulp.task('compress:electron:osx', () => { del([`./build/${config.productName}.dmg`]).then(paths => { console.warn('paths', paths); const builder = electronBuilder.init(); builder.build({ appPath: path.resolve(`./build/executables/${config.productName}-darwin-x64/${config.productName}.app`), platform: 'osx', out: path.resolve('./build'), config: './src/electron/resources/config.json' }, function (err) { if (err) console.error(err); }); }); }); gulp.task('compress:win32-ia32', compress(`./build/executables/${config.productName}-win32-ia32/**`, 'win32-ia32.zip') ); gulp.task('compress:win32-x64', compress(`./build/executables/${config.productName}-win32-x64/**`, 'win32-x64.zip') ); gulp.task('compress:linux-ia32', compress(`./build/executables/${config.productName}-linux-ia32/**`, 'linux-ia32.zip') ); gulp.task('compress:linux-x64', compress(`./build/executables/${config.productName}-linux-x64/**`, 'linux-x64.zip') ); gulp.task('compress:electron', [ 'compress:electron:osx', 'compress:win32-ia32', 'compress:win32-x64', 'compress:linux-ia32', 'compress:linux-x64' ] );
var gulp = require('gulp'); gulp.task('clean', function() { var del = require('del'); var pathsHelper = require('../helpers/paths.helper'); return del([ // delete tmp folder pathsHelper.tmp, pathsHelper.build, `${pathsHelper.public}/assets/`, pathsHelper.craft.templates ]); });
import React from 'react' import test from 'tape' import { shallow } from 'enzyme' import Select from './' test('<Select />', t => { const wrapper = shallow( <Select> <Select.Option value="1">One</Select.Option> <Select.Option value="2">Two</Select.Option> </Select>) t.ok(wrapper.contains("One")) t.end() })
var App = App || {}; (function() { "use strict"; App.Views.EditorView = Backbone.View.extend({ el: "#content-info", template: Handlebars.compile($("#editor-template").html()), events: { "click input[type=button]": "saveInfo" }, saveInfo: function() { var notesEl = this.$("#notes"); var sourcesEl = this.$("#sources"); var notesVal = notesEl.val(); var sourcesVal = sourcesEl.val(); var attributes = { notes: notesVal, sources: sourcesVal }; var ajaxOptions = { success: function() { alert("Success"); }, error: function() { alert("Error"); } }; this.model.save(attributes, ajaxOptions); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); })();
import React, { Component } from 'react'; import $ from "jquery"; import DiceExp from "../../services/DiceExp"; import QTipService from "../QTipService"; import ReactDOM from 'react-dom'; import RollableData from "./RollableData"; import RollableTableData from "./RollableTableData"; import TableRollParseService from "./TableRollParseService"; import { throttle } from 'lodash'; /** * regex to catch normal values from cells */ const cellRegex = /^\s*[0-9]+\s*$/i; /** * regex to catch range values from cells */ const cellRangeRegex = /^\s*[0-9]+\s*[-–]\s*[0-9]+\s*$/i; /** * regex to catch value or more like: * 16+ * 16 or more * 16 or higher */ const cellValueOrMoreRegex = /^[0-9]+(( or more)|( or higher)|(\+))$/i; /** * regex to catch value or lower like: 2 or lower */ const cellValueOrLowerRegex = /^[0-9]+ or lower$/i; /** * class that add the rolled border left for the first column */ const ROLLED_LEFT_CLASS_NAME = "BH-Table-roll-cell-left"; /** * class that add the rolled border right for the other but applied on the previous sibling column */ const ROLLED_RIGHT_CLASS_NAME = "BH-Table-roll-cell-right"; /** * attr name of pre calculated cell value min */ const MIN_ATTR = "bh-roll-min"; /** * attr name of pre calculated cell value max */ const MAX_ATTR = "bh-roll-max"; /** * Inits the table rendering the clickable div, only for top left cells that are dice expressions. * @param {HTMLElement} table table element */ const initTable = function (table: HTMLElement, index: number) { const rollableTable = TableRollParseService.parse(table, index); if (!rollableTable) return; rollableTable.rolables.forEach(rollable => { ReactDOM.render(<ClickableRoller data={rollable} />, rollable.renderTarget); }); }; /** * Make a roll and show the result. */ const throttledRoll = throttle((data: RollableData, rollEl: HTMLElement) => { const jqRollEl = $(rollEl); const table = jqRollEl.closest("table"); const rows = $(table).find("tbody tr"); // remove the classes that indicates a roll result of all cells const cells = rows.find("td"); cells.removeClass(ROLLED_LEFT_CLASS_NAME); cells.removeClass(ROLLED_RIGHT_CLASS_NAME); let found = false; // makes a roll and shows the tooltip const rolled = DiceExp.calcValue(data.diceValue); QTipService.animateIntoQTip(jqRollEl, rolled + ""); // tries to find the cell with the rolled vavlue and show in it the result rows.each((index, row: HTMLElement) => { if (found) return; data.valuedColumns.forEach(columnIndex => { if (found) return; found = checkCell(row, columnIndex, rolled); }); }); }, 500); /** * Checks if a cell is the corresponding result of rolled value. * @param {HTMLElement} row row element * @param {number} columnIndex index of the cell column to check * @param {number} rolled the dice rolled value */ const checkCell = function (row: HTMLElement, columnIndex: number, rolled: number): boolean { const jqRow = $(row); const jqCell = jqRow.find(`td:nth-child(${columnIndex + 1})`); // if the cell does not have pre calculated values calculates it if (jqCell.attr(MIN_ATTR) === undefined) { processCell(jqCell); } // if the cell still does not have it is not a value cell if (jqCell.attr(MIN_ATTR) === undefined) return false; const min = jqCell.attr(MIN_ATTR); const max = jqCell.attr(MAX_ATTR); if (rolled < min || rolled > max) return false; // if the rolled value it is in the range adds the classes with border change to show the result // for the first column add as a left border // for the others adds as a right border of the previous sibling const className = columnIndex === 0 ? ROLLED_LEFT_CLASS_NAME : ROLLED_RIGHT_CLASS_NAME; const jqCellToApply = columnIndex === 0 ? jqCell : jqRow.find(`td:nth-child(${columnIndex})`); jqCellToApply.addClass(className); return true; }; /** * Calcs min and max values of a cell and add then as attributes. * @param {*} jqCell jquery object with a cell */ const processCell = function (jqCell) { // if it is not a value cell just returns let text: string = jqCell.text(); text = text ? text.trim() : text; if (!text) return; const value: string = (text) => text === "00" ? "100" : text; // adds the value attributes for each type of value cell // normal: 22 // range: 3-7 // value or more: 16+, 16 or more, 16 or higher // value or lower: 2 or lower if (cellRegex.test(text)) { jqCell.attr(MIN_ATTR, value(text)); jqCell.attr(MAX_ATTR, value(text)); } else if (cellRangeRegex.test(text)) { const rangeValues = text.split(/[-–]/); jqCell.attr(MIN_ATTR, value(rangeValues[0])); jqCell.attr(MAX_ATTR, value(rangeValues[1])); } else if (cellValueOrMoreRegex.test(text)) { jqCell.attr(MIN_ATTR, value(text.split(/[ +]/)[0])); jqCell.attr(MAX_ATTR, "9999999999999"); } else if (cellValueOrLowerRegex.test(text)) { jqCell.attr(MIN_ATTR, "1"); jqCell.attr(MAX_ATTR, value(text.split(" ")[0])); } }; /** * Shows a tooltip with the reolled result. * @param {*} target jquery object with the target to show the tooltip * @param {*} targetId id of the target to sohw the tooltip * @param {*} rolled rolled dice value */ const showQtip = function (target, targetId: string, rolled: number) { const qtipOptions = { content: "" + rolled, show: { event: "none", effect: true, ready: true }, hide: { event: "unfocus", effect: true }, position: { my: "bottom center", at: "top center" }, style: { classes: "qtip-light BH-Table-roll-tip" } }; const qtipOptionsString = JSON.stringify(qtipOptions); // adds a script to run on the ddb page that adds the tooltip target.find("script").replaceWith(`<script>jQuery("#${targetId}").qtip(${qtipOptionsString})</script>`); }; class TableRollService { static init() { $("body.body-forum, body.body-user, body.body-devtracker").find("table.compendium-left-aligned-table:not(.mceLayout)").addClass("mceLayout"); $("table:not(.bh-processed)").each((index, table) => initTable(table, index)); } } class ClickableRoller extends Component { roll = () => { throttledRoll(this.props.data, this.rollEl); } render() { return ( <span className="BH-Table-roll-dice" title="Click to Roll" onClick={this.roll} ref={(el) => { this.rollEl = el; }}> {this.props.data.text} <script /> </span > ); } } export default TableRollService;
define(/** @lends BaseModel */function() { 'use strict'; /** * @constructor * @param {Object} data Initial data to populate the model */ function BaseModel(json) { if (json) { this._fromJSON(json); } } /** @lends BaseModel.prototype */ BaseModel.prototype = { constructor: BaseModel, /** * Merges properties from a POJO into the model * @param {Object} json raw data */ _fromJSON: function(json) { var key; for (key in json) { if (json.hasOwnProperty(key)) { this[key] = json[key]; } } }, /** * Returns an object hash of the model properties * @return {Object} */ toJSON: function() { var hash = {}; var key; for (key in this) { if (this.hasOwnProperty(key) && typeof this[key] !== 'function') { hash[key] = this[key]; } } return hash; } }; return BaseModel; });
import configureStore from 'redux-mock-store'; import WsClient from 'ui-common/WsClient'; import wsAPI from 'ui-common/store/wsAPI'; import { AKTUALNI_ROK } from '../../constants'; import ucastniciTestData from '../../entities/ucastnici/ucastniciTestData'; import { POZNAMKA_ADD, POZNAMKA_DELETE, POZNAMKA_MODIFY, addPoznamka, deletePoznamka, modifyPoznamka, } from './PoznamkyActions'; const unsuccessfulResponse = { code: 'unfulfilled request', status: 'A strange error occurred.', }; const mockWsClient = new WsClient(); const middlewares = [wsAPI.withExtraArgument(mockWsClient)]; const mockStore = configureStore(middlewares); it('addPoznamka() should dispatch two successful actions', async () => { const poznamka = { datum: '2019-04-06T08:12:45.455Z', text: "it's a kind of magic" }; const response = { code: 'ok', response: { poznamky: [poznamka], }, status: 'uloženo v pořádku', requestId: '0.9310306652587377', }; mockWsClient.sendRequest = async () => response; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); await store.dispatch(addPoznamka({ id: '7a09b1fd371dec1e99b7e142', poznamka })); const request = { id: '7a09b1fd371dec1e99b7e142', poznamka, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_ADD}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_ADD}_SUCCESS`, request, response: { code: 'ok', status: 'uloženo v pořádku', poznamky: [poznamka], }, title: 'přidávání poznámky', receivedAt: expect.any(Number), }); }); it('addPoznamka() should dispatch two unsuccessful actions', async () => { mockWsClient.sendRequest = async () => unsuccessfulResponse; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); const poznamka = { datum: '2019-04-06T08:12:45.455Z', text: "it's a kind of magic" }; await store.dispatch( addPoznamka({ id: '7a09b1fd371dec1e99b7e142', poznamka: { ...poznamka, datum: new Date(poznamka.datum) }, }) ); const request = { id: '7a09b1fd371dec1e99b7e142', poznamka, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_ADD}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_ADD}_ERROR`, request, response: { code: 'unfulfilled request', status: 'A strange error occurred.', }, title: 'přidávání poznámky', receivedAt: expect.any(Number), }); }); it('deletePoznamka() should dispatch two successful actions', async () => { const response = { code: 'ok', response: { poznamky: [], }, status: 'uloženo v pořádku', requestId: '0.9310306652587377', }; mockWsClient.sendRequest = async () => response; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); await store.dispatch(deletePoznamka({ id: '7a09b1fd371dec1e99b7e142', index: 0 })); const request = { id: '7a09b1fd371dec1e99b7e142', index: 0, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_DELETE}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_DELETE}_SUCCESS`, request, response: { code: 'ok', status: 'uloženo v pořádku', poznamky: [], }, title: 'mazání poznámky', receivedAt: expect.any(Number), }); }); it('deletePoznamka() should dispatch two unsuccessful actions', async () => { mockWsClient.sendRequest = async () => unsuccessfulResponse; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); await store.dispatch(deletePoznamka({ id: '7a09b1fd371dec1e99b7e142', index: 0 })); const request = { id: '7a09b1fd371dec1e99b7e142', index: 0, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_DELETE}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_DELETE}_ERROR`, request, response: { code: 'unfulfilled request', status: 'A strange error occurred.', }, title: 'mazání poznámky', receivedAt: expect.any(Number), }); }); it('modifyPoznamka() should dispatch two successful actions', async () => { const poznamka = { datum: '2019-04-06T08:12:45.455Z', text: "it's a kind of magic" }; const response = { code: 'ok', response: { poznamky: [poznamka], }, status: 'uloženo v pořádku', requestId: '0.9310306652587377', }; mockWsClient.sendRequest = async () => response; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); await store.dispatch(modifyPoznamka({ id: '7a09b1fd371dec1e99b7e142', index: 0, poznamka })); const request = { id: '7a09b1fd371dec1e99b7e142', index: 0, poznamka, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_MODIFY}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_MODIFY}_SUCCESS`, request, response: { code: 'ok', status: 'uloženo v pořádku', poznamky: [poznamka], }, title: 'ukládání poznámky', receivedAt: expect.any(Number), }); }); it('modifyPoznamka() should dispatch two unsuccessful actions', async () => { mockWsClient.sendRequest = async () => unsuccessfulResponse; const store = mockStore({ ...ucastniciTestData, auth: { token: '===token===' } }); const poznamka = { datum: '2019-04-06T08:12:45.455Z', text: "it's a kind of magic" }; await store.dispatch( modifyPoznamka({ id: '7a09b1fd371dec1e99b7e142', index: 0, poznamka: { ...poznamka, datum: new Date(poznamka.datum) }, }) ); const request = { id: '7a09b1fd371dec1e99b7e142', index: 0, poznamka, rok: AKTUALNI_ROK }; const actions = store.getActions(); expect(actions[0]).toEqual({ type: `${POZNAMKA_MODIFY}_REQUEST`, request, receivedAt: expect.any(Number), }); expect(actions[1]).toEqual({ type: `${POZNAMKA_MODIFY}_ERROR`, request, response: { code: 'unfulfilled request', status: 'A strange error occurred.', }, title: 'ukládání poznámky', receivedAt: expect.any(Number), }); });
import React from "react" import { css, Styled } from "theme-ui" import Header from "./header" export default ({ children, ...props }) => ( <Styled.root> <Header {...props} /> <div> <div css={css({ maxWidth: `container`, mx: `auto`, px: 3, py: 4, })} > {children} </div> </div> </Styled.root> )
/** * A class for managing any sort of interaction functions, like collision * detection. * */ var Interaction = function(){ }; /** * Takes two parameters, representing boxes. Two functions are expected; * getSize : which returns an object with two properties, height and width. * getPosition : which returns an object with two properties, x and y. * * Returns true if there is an overlapping of the boxes. * * @param a * @param b * @returns boolean : * */ Interaction.prototype.collision = function(a, b){ if ((a.getPosition().x - b.getSize().width) < b.getPosition().x) { if (b.getPosition().x < (a.getPosition().x + a.getSize().width)) { if ((b.getPosition().y + b.getSize().height) > a.getPosition().y) { if (b.getPosition().y < (a.getPosition().y + a.getSize().height)) { return true; } } } } return false; }; module.exports = Interaction;
var namespace_snowflake_1_1_emulator_1_1_input_1_1_input_manager = [ [ "IInputDevice", "interface_snowflake_1_1_emulator_1_1_input_1_1_input_manager_1_1_i_input_device.html", "interface_snowflake_1_1_emulator_1_1_input_1_1_input_manager_1_1_i_input_device" ], [ "IInputManager", "interface_snowflake_1_1_emulator_1_1_input_1_1_input_manager_1_1_i_input_manager.html", "interface_snowflake_1_1_emulator_1_1_input_1_1_input_manager_1_1_i_input_manager" ] ];
'use strict'; const setLinzNamespace = require('./set-linz-namespace'); /** * Set req.linz.record. * @returns {Void} Calls the next middleware. */ const setRecord = () => (req, res, next) => { setLinzNamespace()(req, res, (namespaceErr) => { if (namespaceErr) { return next(namespaceErr); } if (!req.linz.model) { return next(new Error('Missing Linz model form')); } req.linz.model.getObject(req.params.id, (err, doc) => { if (err || !doc) { return next(err); } req.linz.record = doc; return next(); }); }); }; module.exports = setRecord;
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. * File Name : computed_member_expression.js * Created at : 2019-03-19 * Updated at : 2020-09-09 * Author : jeefo * Purpose : * Description : * Reference : .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/ // ignore:start "use strict"; /* globals*/ /* exported*/ // ignore:end const {expression} = require("../enums/states_enum"); const {MEMBER_EXPRESSION} = require("../enums/precedence_enum"); const { is_open_square_bracket: is_open_sqr, get_last_non_comment_node, } = require("../../helpers"); module.exports = { id : "Computed member expression", type : "Member expression", precedence : MEMBER_EXPRESSION, is (token, parser) { if (parser.current_state === expression && is_open_sqr(parser)) { const last = get_last_non_comment_node(parser); return last && [ "Call expression", "Member expression", "Primary expression" ].includes(last.type); } }, initialize (node, token, parser) { const object = get_last_non_comment_node(parser, true); parser.change_state("computed_member_access"); const member = parser.generate_next_node(); node.object = object; node.member = member; node.start = object.start; node.end = member.end; parser.current_state = expression; }, };
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var concatCss = require('gulp-concat-css'); var minifyCss = require('gulp-minify-css'); var browserSync = require('browser-sync').create(); gulp.task('sass', function () { gulp.src('./sass/**/*.scss') .pipe(sass.sync().on('error', sass.logError)) .pipe(concatCss("./css/app.css")) .pipe(minifyCss("./css/app.css")) .pipe(gulp.dest('.')) .pipe(browserSync.reload({ stream: true })) }); gulp.task('browserSync', function() { browserSync.init({ server: { baseDir: './' }, }) }) gulp.task('watch', ['browserSync', 'sass'], function () { gulp.watch('./sass/**/*.scss', ['sass']); });
import React from 'react'; import _ from 'lodash'; import Webiny from 'webiny'; class Auth { constructor() { this.loginRoute = 'Login'; this.forbiddenRoute = 'Forbidden'; this.routerEvent = null; } init() { Webiny.Router.addRoute(new Webiny.Route(this.loginRoute, '/login', this.renderLogin(), 'Login').setLayout('empty')); Webiny.Router.addRoute(new Webiny.Route(this.forbiddenRoute, '/forbidden', this.renderForbidden(), 'Forbidden')); Webiny.Router.onBeforeStart(routerEvent => { Webiny.Http.addRequestInterceptor(http => { http.addHeader('X-Webiny-Authorization', Webiny.Cookies.get(this.getCookieName())); }); // Watch if we got a forbidden request - then log out Webiny.Http.addResponseInterceptor(this.getResponseInterceptor()); return this.checkUser(routerEvent); }); Webiny.Router.onRouteWillChange(this.checkUser.bind(this)); } getResponseInterceptor() { return response => { if (response.getStatus() === 403) { this.onForbidden(response); } }; } /** * Check if user is authenticated and authorized to visit requested route. * This method is the main "entry point" into the verification process. * * @param routerEvent * @returns {*} */ checkUser(routerEvent) { this.routerEvent = routerEvent; if (Webiny.Model.get('User')) { return this.checkRouteRole(routerEvent); } const token = Webiny.Cookies.get(this.getCookieName()); // Check if token exists on client side if (!token) { return this.onNoToken(routerEvent); } // Try fetching user data return this.getUser().then(() => this.checkRouteRole(routerEvent)); } checkRouteRole(routerEvent) { if (Webiny.Config.Js.CheckUserRoles && _.has(routerEvent.route, 'role')) { return new Promise((resolve) => { const user = Webiny.Model.get('User'); if (user && _.isArray(routerEvent.route.role) && this.hasRole(routerEvent.route.role)) { return resolve(routerEvent); } if (user && _.isFunction(routerEvent.route.role)) { return Promise.resolve(routerEvent.route.role(routerEvent.route)).then(allowed => { if (!allowed) { routerEvent.stop(); routerEvent.goToRoute(this.forbiddenRoute); } resolve(routerEvent); }); } routerEvent.stop(); routerEvent.goToRoute(this.forbiddenRoute); resolve(routerEvent); }); } return Promise.resolve(routerEvent); } /** * This method checks if current target route is already a login route and redirects (or not) properly. * * @param routerEvent * @returns {*} */ goToLogin(routerEvent) { const isLoginRoute = _.get(routerEvent.route, 'name') === this.loginRoute; if (!isLoginRoute) { Webiny.LocalStorage.set('loginRedirect', window.location.href); routerEvent.stop(); routerEvent.goToRoute(this.loginRoute); } return routerEvent; } onNoToken(routerEvent) { return this.goToLogin(routerEvent); } /** * Use the given user data to check if the user is authorized to be in this app. * This logic is completely specific to your application. Implement this as you see fit. * * This method is used by `verifyUser` and Login forms to check authorization of logged in user. * * @param user * @returns {boolean} */ isAuthorized(user) { if (!!_.find(user.roles, {slug: 'administrator'})) { return true; } return !!_.find(user.roleGroups, rg => !!_.find(rg.roles, {slug: 'administrator'})); } getUserFields() { return '*,roles.slug,roleGroups[id,name,roles.slug],gravatar'; } /** * Fetch user profile and verify the returned data. * * @returns Promise */ getUser() { return this.getApiEndpoint().get('/me', {_fields: this.getUserFields()}).then(apiResponse => { return Promise.resolve(this.verifyUser(apiResponse)).then(() => apiResponse); }); } /** * Get cookie name * @returns {string} */ getCookieName() { return 'webiny-token'; } getApiEndpoint() { if (!this.authApi) { this.authApi = new Webiny.Api.Endpoint('/entities/webiny/users') } return this.authApi; } refresh() { return this.getUser(); } logout(redirect = true) { let logout = Promise.resolve().then(() => { Webiny.Model.set('User', null); Webiny.Cookies.remove(this.getCookieName()); }); if (redirect) { logout = logout.then(() => Webiny.Router.goToRoute(this.loginRoute)); } return logout; } /** * This method determines if the given response from the API is valid user data. * It also executes `isAuthorized` to see if given user is allowed to be in this app. * * This method can be overridden to suit your app's needs. * It is up to the developer to handle both `verified` and `unverified` cases as he sees fit. * * @param apiResponse * @returns {*} */ verifyUser(apiResponse) { const data = apiResponse.getData(); if (apiResponse.isError() || !this.isAuthorized(data)) { // We need to stop router event to prevent him from rendering the route he initially intended this.routerEvent && this.routerEvent.stop(); return this.logout(); } Webiny.Model.set('User', data); } /** * Check if current user has any of the requested roles (checks both roles and roleGroups) * @param role */ hasRole(role) { if (_.isString(role)) { role = [role]; } const user = Webiny.Model.get('User'); // First check user roles let hasRole = _.find(user.roles, r => role.indexOf(r.slug) > -1); if (!hasRole) { // Check user role groups _.each(user.roleGroups, group => { hasRole = _.find(group.roles, r => role.indexOf(r.slug) > -1); if (hasRole) { return false; } }); } return hasRole; } /** * Triggered when user is not authorized to perform the HTTP request. */ onForbidden(httpResponse) { // Implement whatever logic you see fit } renderLogin() { return null; } renderForbidden() { return null; } } export default Auth;
const capitalize = (name) => name.charAt(0).toUpperCase() + name.slice(1); module.exports = { capitalize, };
import { assert } from 'chai' import * as jsdocx from '../dist/jsdocx' describe('#Table', () => { describe('#src', () => { it('should be equal to "w:tbl"', () => { let t = new jsdocx.Table() assert.equal(t.hasOwnProperty('src'), true) assert.deepEqual(t.src, { 'w:tbl': {} }) }) }) describe('#contentHook', () => { it('should exist after creation', () => { let t = new jsdocx.Table() assert.equal(t.hasOwnProperty('contentHook'), true) assert.equal(t.contentHook, '["w:tbl"]') }) }) describe('#addFormat', () => { it('should add a valid format', () => { let t = new jsdocx.Table() let f = t.addFormat() assert.equal(f instanceof jsdocx.TableFormat, true) }) }) describe('#toJson', () => { it('should insert contents inside "w:tbl" tag', () => { let t = new jsdocx.Table() let m = new jsdocx.Element({ a: 2 }) t.contents.push(m) assert.deepEqual(t.toJson(), { 'w:tbl': { '#': [{ 'a': 2 }] } }) }) }) describe('#toXml', () => { it('should render simple subtree correctly', () => { let t = new jsdocx.Table() t.addGrid().addColumn() assert.equal(t.toXml(), '<w:tbl><w:tblGrid><w:gridCol></w:gridCol></w:tblGrid></w:tbl>') }) it('should render with format', () => { let t = new jsdocx.Table() t.addGrid() // Format will be injected before any other content. t.addFormat() assert.equal(t.toXml(), '<w:tbl><w:tblPr></w:tblPr><w:tblGrid></w:tblGrid></w:tbl>') }) it('should render rows correctly', () => { let t = new jsdocx.Table() t.addRow().addCell() t.addRow() assert.equal(t.toXml(), '<w:tbl><w:tr><w:tc></w:tc></w:tr><w:tr></w:tr></w:tbl>') }) it('should render cell with format correctly', () => { let t = new jsdocx.Table() t.addRow().addCell().addFormat() assert.equal(t.toXml(), '<w:tbl><w:tr><w:tc><w:tcPr></w:tcPr></w:tc></w:tr></w:tbl>') }) it('should render cell width correctly', () => { let fmt = new jsdocx.Table().addRow().addCell().addFormat() fmt.setWidth('33.3%', 'pct') assert.equal(fmt.toXml(), '<w:tcPr><w:tcW w:type="pct" w:w="33.3%"/></w:tcPr>') }) it('should render cell horizontal span correctly', () => { let fmt = new jsdocx.Table().addRow().addCell().addFormat() fmt.setHSpan(3) assert.equal(fmt.toXml(), '<w:tcPr><w:gridSpan w:val="3"/></w:tcPr>') }) it('should render cell vertical alignment correctly', () => { let fmt = new jsdocx.Table().addRow().addCell().addFormat() fmt.setVAlign('bottom') assert.equal(fmt.toXml(), '<w:tcPr><w:vAlign w:val="bottom"/></w:tcPr>') }) }) })
import React from 'react' import Navbar from "./Navbar" import Welcome from "./Welcome" class App extends React.Component { render() { return ( <div class="container"> <Navbar/> <div> {this.props.children || <Welcome/>} </div> </div> ) } } export default App
(function(){ "use strict"; angular.module("app"). service("partidasService", ["apiService", partidasService]); function partidasService(apiService) { return { get: get }; function get() { return apiService.get("partidas"); } } })();
import React from 'react'; import PropTypes from 'prop-types'; import { Form, Input, Select, Button, InputNumber } from 'antd'; import { inject, observer } from 'mobx-react'; import { withRouter} from 'react-router-dom'; @inject('store') @observer class ProductForm extends React.Component { handleSubmit = (e) => { e.preventDefault(); const { store, productId } = this.props; this.props.form.validateFields((err, values) => { if (!err) { store.update(productId, values); this.props.history.push('/'); } }); } render () { const { getFieldDecorator } = this.props.form; const readOnly = this.props.readOnly; const { store } = this.props; const submitBtn = readOnly ? null : (<Button type="primary" htmlType="submit">Submit</Button>); const form = <Form onSubmit={this.handleSubmit}> <Form.Item label="Name" labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} > {getFieldDecorator('name', { initialValue: store.product.name, rules: [{ required: !readOnly, message: 'Please input a valid product name!' }], })( <Input placeholder="Name" disabled={readOnly} /> )} </Form.Item> <Form.Item label="Price" labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} > {getFieldDecorator('price', { initialValue: store.product.price, rules: [{ required: !readOnly, message: 'Please input a valid Price!' }], })( <InputNumber placeholder="0" min={0} disabled={readOnly} /> )} </Form.Item> <Form.Item label="Currency" labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} > {getFieldDecorator('currency', { initialValue: store.product.currency, rules: [{ required: !readOnly, message: 'Please select a currency!' }], })( <Select placeholder="Currency" disabled={readOnly} > <Select.Option value="USD">USD</Select.Option> <Select.Option value="EUR">EUR</Select.Option> <Select.Option value="BGN">BGN</Select.Option> </Select> )} </Form.Item> <Button type="primary" onClick={() => this.props.history.push('/')}>Back</Button> {submitBtn} </Form> return form; } } export default withRouter(Form.create()(ProductForm)); ProductForm.PropTypes = { form: PropTypes.object, store: PropTypes.object, readOnly: PropTypes.bool, productId: PropTypes.number, }
module.exports = require('./lib/sqlite3-webapi-kit');
/** * Stripe Recipient Model * * <%= whatIsThis %>. * * Refer to Stripe Documentation https://stripe.com/docs/api#recipients */ module.exports = { autoPK: false, attributes: { id: { type: 'string', //"rp_3Uh38RCOt3igvD" primaryKey: true, unique: true }, object: { type: 'string' //"recipient" }, created: { type: 'datetime' //1392367798 }, livemode: { type: 'boolean' //false }, type: { type: 'string' //"individual" }, description: { type: 'string' //"Added through Widget" }, email: { type: 'email' //"michael@widget" }, name: { type: 'string' //"Mike" }, verified: { type: 'boolean' //false }, metadata: { type: 'json' //{} }, active_account: { type: 'string' //null }, cards: { type: 'json' // {} }, default_card: { model: 'Card' //null }, migrated_to: { type: 'string' //null }, //Added to Model and doesn't exists in Stripe lastStripeEvent: { type: 'datetime' } }, beforeValidate: function (values, cb){ if(values.created){ values.created = new Date(values.created * 1000); } cb(); }, // Stripe Webhook recipient.created stripeRecipientCreated: function (recipient, cb) { Recipient.findOrCreate(recipient.id, recipient) .exec(function (err, foundRecipient){ if (err) return cb(err); if (foundRecipient.lastStripeEvent > recipient.lastStripeEvent) return cb(null, foundRecipient); if (foundRecipient.lastStripeEvent == recipient.lastStripeEvent) return Recipient.afterStripeRecipientCreated(foundRecipient, function(err, recipient){ return cb(err, recipient)}); Recipient.update(foundRecipient.id, recipient) .exec(function(err, updatedRecipients){ if (err) return cb(err); if (!updatedRecipients) return cb(null, null); Recipient.afterStripeRecipientCreated(updatedRecipients[0], function(err, recipient){ cb(err, recipient); }); }); }); }, afterStripeRecipientCreated: function (recipient, next){ //Do somethings after recipient created next(null, recipient); }, // Stripe Webhook recipient.updated stripeRecipientUpdated: function (recipient, cb) { Recipient.findOrCreate(recipient.id, recipient) .exec(function (err, foundRecipient){ if (err) return cb(err); if (foundRecipient.lastStripeEvent >= recipient.lastStripeEvent) return cb(null, foundRecipient); if (foundRecipient.lastStripeEvent == recipient.lastStripeEvent) return Recipient.afterStripeRecipientUpdated(foundRecipient, function(err, recipient){ return cb(err, recipient)}); Recipient.update(foundRecipient.id, recipient) .exec(function(err, updatedRecipients){ if (err) return cb(err); if (!updatedRecipients) return cb(null, null); Recipient.afterStripeRecipientUpdated(updatedRecipients[0], function(err, recipient){ cb(err, recipient); }); }); }); }, afterStripeRecipientUpdated: function (recipient, next){ //Do somethings after recipient updated next(null, recipient); }, // Stripe Webhook recipient.deleted stripeRecipientDeleted: function (recipient, cb) { Recipient.destroy(recipient.id) .exec(function (err, destroyedRecipients){ if (err) return cb(err); if (!destroyedRecipients) return cb(null, null); Recipient.afterStripeRecipientDeleted(destroyedRecipients[0], function(err, recipient){ cb(err, recipient); }); }); }, afterStripeRecipientDeleted: function (recipient, next){ //Do somethings after recipient deleted next(null, recipient); } }
window.addEvent('domready',function(){ var tree = new Mif.Tree({ initialize: function(){ this.initExpandTo(); }, container: $('tree_container'),// tree container forest: true }); var jsonChildren=[ { "name": "nodeA" }, { "name": "nodeB", "children": [ { "name": "nodeB.1" }, { "name": "nodeB.2", "expandTo": true, "children":[ { "name": "nodeB.2.1" } ] }, { "name": "nodeB.3" } ] }, { "name": "nodeC" } ]; var json=[ { "name": "root", "children": [ { "name": "node1" }, { "name": "node2", "open": true, "children":[ { "name": "node2.1" }, { "name": "node2.2", "expandTo": true, "children": [ { "name": "node2.2.1" }, { "name": "node2.2.2" }, { "name": "node2.2.3", "loaderOptions": {"json": jsonChildren}, "loadable": true } ] } ] }, { "name": "node4" }, { "name": "node3" } ] } ]; // load tree from json. tree.load(json); });
define([ '../../data/level-1-zones', '../../data/level-2-zones', '../../data/level-3-zones' ], function module(zones1, zones2, zones3) { var zones = []; zonesToList(1, '', zones, [zones1, zones2, zones3]); function zonesToList(level, append, zonesList, zonesArray) { var zones = zonesArray.shift(); if (typeof zones === 'undefined') return for (var i in zones) { var name = zones[i][1] + append; zonesList.push({ name: name, level: level }); var nextZones = pluckOutZones(zonesArray[0], zones[i][0]); zonesArray[0] = nextZones[0]; nextZones = nextZones[1]; var nextArray = [nextZones].concat(zonesArray.slice(1)); zonesToList(level + 1, ', ' + name, zonesList, nextArray); } } function pluckOutZones(zones, id) { var pluckedOut = []; var keptIn = []; for(var i in zones) { if (zones[i][2] === id) pluckedOut.push(zones[i]); else keptIn.push(zones[i]); } return [keptIn, pluckedOut]; } return zones; } );
'use strict'; const {tmpdir} = require('os'); const {join} = require('path'); const fs = require('fs'); const {reRequire} = require('mock-require'); const { readFileSync, unlinkSync, existsSync, } = fs; const test = require('supertape'); const {pack} = require('..'); test('jaguar: pack: no args', (t) => { t.throws(pack, /from should be a string!/, 'should throw when no args'); t.end(); }); test('jaguar: pack: to', (t) => { const fn = () => pack('hello'); t.throws(fn, /to should be string or object!/, 'should throw when no to'); t.end(); }); test('jaguar: pack: files', (t) => { const fn = () => pack('hello', 'world'); t.throws(fn, /files should be an array!/, 'should throw when no files'); t.end(); }); test('jaguar: pack: error: empty file list', (t) => { const packer = pack('hello', 'world', []); packer.on('error', (e) => { t.equal(e.message, 'Nothing to pack!', 'should emit error when file list is empty'); t.end(); }); }); test('jaguar: pack: error: read', (t) => { const expect = 'ENOENT: no such file or directory, lstat \'hello/world\''; const packer = pack('hello', 'hello.tar.gz', [ 'world', ]); packer.on('error', (e) => { t.equal(e.message, expect, 'should emit error when file not found'); t.end(); }); packer.on('end', () => { t.fail('should not emit end event when error'); }); }); test('jaguar: pack: error: write', (t) => { const expect = 'EACCES: permission denied, open \'/hello.tar.gz\''; const from = join(__dirname, 'fixture'); const packer = pack(from, '/hello.tar.gz', [ 'jaguar.txt', ]); packer.on('error', (e) => { t.equal(e.message, expect, 'should emit error when file not found'); t.end(); }); }); test('jaguar: pack', (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const fixture = join(__dirname, 'fixture'); const packer = pack(fixture, to, [ 'jaguar.txt', ]); packer.on('end', () => { const fileTo = readFileSync(to); unlinkSync(to); t.ok(fileTo.length, 'should pack file'); t.end(); }); }); test('jaguar: pack: abort', (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const fixture = join(__dirname, 'fixture'); const packer = pack(fixture, to, [ 'jaguar.txt', ]); packer.abort(); packer.on('end', () => { t.notOk(existsSync(to), 'should not create archive'); t.end(); }); }); test('jaguar: pack: abort', (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const fixture = join(__dirname, 'fixture'); const packer = pack(fixture, to, [ 'jaguar.txt', ]); packer.abort(); packer.on('end', () => { t.notOk(existsSync(to), 'should not create archive'); t.end(); }); }); test('jaguar: pack: abort: fast', (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const fixture = join(__dirname, 'fixture'); const packer = pack(fixture, to, [ 'jaguar.txt', ]); packer.abort(); packer.on('end', () => { t.notOk(existsSync(to), 'should not create archive'); t.end(); }); }); test('jaguar: pack: abort: unlink', (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const dir = join(__dirname, 'fixture'); const packer = pack(dir, to, [ 'jaguar.txt', ]); const {unlink} = fs.promises; fs.promises.unlink = async () => {}; packer.on('start', () => { packer.abort(); }); packer.on('end', () => { fs.promises.unlink = unlink; t.pass('should emit end'); t.end(); }); }); test('jaguar: pack: unlink', async (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const dir = join(__dirname, 'fixture'); const {unlink} = fs.promises; fs.promises.unlink = async () => {}; const {pack} = reRequire('..'); const packer = pack(dir, to, [ 'jaguar.txt', ]); packer.once('end', () => { fs.promises.unlink = unlink; t.pass('should emit end'); t.end(); }); await packer._unlink(to); }); test('jaguar: pack: unlink: error', async (t) => { const to = join(tmpdir(), `${Math.random()}.tar.gz`); const dir = join(__dirname, '..'); const {unlink} = fs.promises; fs.promises.unlink = async () => { throw Error('Can not remove'); }; const {pack} = reRequire('..'); const packer = pack(dir, to, [ '.git', ]); packer.on('error', (e) => { fs.promises.unlink = unlink; t.ok(e.message, 'Can not remove', 'should emit error'); t.end(); }); await packer._unlink(to); });
import { strictEqual } from "node:assert"; import dateFormat from "../lib/dateformat.js"; describe("Mask: 'mm'", function () { it("should format '2014-11-17' as '11'", function (done) { var date = new Date("2014-11-17"); var d = dateFormat(date, "mm"); strictEqual(d, "11"); done(); }); it("should format '1992-02-11' as '02'", function (done) { var date = new Date("1992-02-11"); var d = dateFormat(date, "mm"); strictEqual(d, "02"); done(); }); it("should format '2077-01-25' as '01'", function (done) { var date = new Date("2077-01-25"); var d = dateFormat(date, "mm"); strictEqual(d, "01"); done(); }); });
console.log('module 2');
import { connect } from 'react-redux'; import WeatherList from '../components/WeatherList'; function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps)(WeatherList);
var currentURL; $(document).ready(function () { rebuildSelectList(); $("#go").on("click", function () { updateListing($("#urlBox").val()); }); $("#urlBox").keypress(function (e) { if (e.which == 13) { updateListing($("#urlBox").val()); } }); $("#dir").on("click", ".listItem", function (e) { updateListing($("#urlBox").val(), $(this).attr('data-dir')); }); $("#select").on("click", ".listItem", function (e) { updateListing($(this).attr('data-dir')); }); $("#back").on("click", function () { var a = currentURL.split("/"); a.splice(-2,2); var b = a.join("/"); updateListing(b); }); $("#dir").on("click", "#dir>li>.listbtn", function (e) { var target = this; $.ajax('/insert?url=' + currentURL + $(this).siblings(".listItem").attr('data-dir'), { complete: function (httpobject, status) { $(target).addClass("checked disabled").text("✓"); rebuildSelectList(); } }); }); $("#select").on("click", "#select>li>.listbtn", function (e) { var target = this; $.ajax('/remove?url=' + $(this).siblings(".listItem").attr('data-dir'), { complete: function (httpobject, status) { $("#dirr>li>.listbtn").text("+"); updateListing($("#urlBox").val()); rebuildSelectList(); } }); }); }); /* * Moves the selected item out of the current container and * updates the overall listing. */ /*function moveSelection(item, location, isSelected) { $(item).parent().remove(); $("#" + location).append($(item).parent()); getSelected(function (data) { rebuildDirectoryList(data); rebuildSelectList(data); }); $("#" + location + ">li>.listbtn").text((isSelected ? "+" : "-")); updateListing($("#urlBox").val()); } */ function updateListing(domain, subdir) { // Domain is not optional if (!domain || domain == "") { alert("Please enter a url!"); return; } // Optional subdirectory not given if (!subdir) { subdir = ""; } // Remove trailing / from domain if (domain[domain.length - 1] == "/") { domain = domain.substring(0, domain.length - 1); } // Remove preceeding / from subdirectory if (subdir.length > 0 && subdir[0] == "/") { subdir = subdir.substring(1); } // Recombine domain/subdirectory currentURL = domain + "/" + subdir; $("#urlBox").val(currentURL); // Update urlbox with the new path getSelected(function (data) { rebuildDirectoryList(data); }); } function rebuildDirectoryList(monitored) { //console.log("List of monitored objects passed into rebuildDirectoryList: "); //console.log(monitored); // Rebuild directory listing with new path var uniqueQuery = '/getlist?url=' + currentURL; $.getJSON(uniqueQuery, function (data) { if (!data || data[0] == "") { $("#messageBox, #dir").empty(); $("#messageBox").append("<div class='alert alert-danger'>" + currentURL + " has no sub-directory(s) or its not a valid Subversion URL!</div>"); return; } $("#messageBox, #dir").empty(); // Add items to the directory listing only if they are NOT in the monitored list for (var i = 0; i < data.length; i++) { var url = currentURL + data[i]; var button; if ($.inArray(url, monitored) == -1) { button = "<button type='button' id='dir" + i + "' class='listbtn btn btn-xs btn-default'>+</button>"; } else { button = "<button type='button' id='dir" + i + "' class='listbtn checked disabled btn btn-xs btn-default'>✓</button>"; } $('#dir').append("<li>"+button+"<a " + "class='listItem' data-dir='" + data[i] + "' href='#'> " + data[i] + "</a></li>"); } }); } function rebuildSelectList(){ $("#select").empty(); getSelected(function (data){ if (!data || data == "") { console.log("no data");} for (var i in data) { $("#select").append("<li><button type='button' class='listbtn btn btn-xs btn-default'>-</button><a class='listItem' data-dir='" + data[i] + "' href='#'> " + data[i] + "</a></li>");} }) } /* * Returns a "Set" with a list of all items currently * being monitored by the server. */ function getSelected(callback) { $.getJSON('/dbjson', function (db) { var temp = []; if (db != null && db.Paths.length > 0) { var data = db.Paths; for (var i = 0; i < data.length; i++) { temp[i] = data[i].dir; } } callback(temp); }); }
(function() { /* Letter placement function */ function addLetterToPage (letter) { letter = letter.toUpperCase() // Update title tag var title = document.head.getElementsByTagName('title')[0] title.innerHTML = title.innerHTML + ' ' + letter // Update h1 tag var h1 = document.getElementsByTagName('h1')[0] h1.innerHTML = h1.innerHTML + ' ' + letter // Update meta tags var metaTagsToIgnore = ['viewport', 'twitter:card', 'twitter:site', 'twitter:creator', 'og:type', 'og:url', 'article:published_time', 'article:modified_time'] , metaTags = document.head.getElementsByTagName('meta') for (var i = 0; i < metaTags.length; i++) { var metaTag = metaTags[i] , name = metaTag.getAttribute('name') , itemprop = metaTag.getAttribute('itemprop') , property = metaTag.getAttribute('property') if (metaTag.getAttribute('http-equiv')) continue if (metaTagsToIgnore.indexOf(name) > -1) continue if (metaTagsToIgnore.indexOf(property) > -1) continue if ((name && name.indexOf('image') > -1) || (itemprop && itemprop.indexOf('image') > -1) || (property && property.indexOf('image') > -1)) { metaTag.setAttribute('content', metaTag.getAttribute('content') + '+' + letter) } else { metaTag.setAttribute('content', metaTag.getAttribute('content') + ' ' + letter) } } // Update table and image document.getElementById('table-' + letter).innerHTML = 'Yes' var img = document.getElementById('image') img.setAttribute('src', img.getAttribute('src') + '+' + letter) } /* AJAX request function */ function fetchAndPlaceLetter (url) { var xmlhttp = new XMLHttpRequest() xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4 if (xmlhttp.status == 200) { var res = JSON.parse(xmlhttp.responseText) if (res && res.letter) return addLetterToPage(res.letter) return console.warn('No letter returned with 200 response', res) } if (xmlhttp.status == 400) return console.warn('Problem with request to ' + url) console.warn('Non-200 response for ' + url) } } xmlhttp.open('GET', url, true) xmlhttp.send() } /* E */ addLetterToPage('E') /* F */ fetchAndPlaceLetter('/data/F') /* G */ fetchAndPlaceLetter('https://api.anymod.com/v0/letter/G') })();
RocketChat.sendMessage = function(user, message, room, upsert = false) { if (!user || !message || !room._id) { return false; } if (message.ts == null) { message.ts = new Date(); } message.u = _.pick(user, ['_id', 'username', 'name']); if (!Match.test(message.msg, String)) { message.msg = ''; } message.rid = room._id; if (!room.usernames || room.usernames.length === 0) { const updated_room = RocketChat.models.Rooms.findOneById(room._id); if (updated_room != null) { room = updated_room; } else { room.usernames = []; } } if (message.parseUrls !== false) { const urls = message.msg.match(/([A-Za-z]{3,9}):\/\/([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((\/[-\+=!:~%\/\.@\,\w]*)?\??([-\+=&!:;%@\/\.\,\w]+)?(?:#([^\s\)]+))?)?/g); if (urls) { message.urls = urls.map(function(url) { return { url }; }); } } message = RocketChat.callbacks.run('beforeSaveMessage', message); // Avoid saving sandstormSessionId to the database let sandstormSessionId = null; if (message.sandstormSessionId) { sandstormSessionId = message.sandstormSessionId; delete message.sandstormSessionId; } if (message._id && upsert) { const _id = message._id; delete message._id; RocketChat.models.Messages.upsert({ _id, 'u._id': message.u._id }, message); message._id = _id; } else { message._id = RocketChat.models.Messages.insert(message); } /* Defer other updates as their return is not interesting to the user */ Meteor.defer(() => { // Execute all callbacks message.sandstormSessionId = sandstormSessionId; return RocketChat.callbacks.run('afterSaveMessage', message, room); }); return message; };
define(['mac/resources/open_wctb'], function(open_wctb) { return open_wctb; });
// Sport.js // // @description :: The sport service allows you to // simplify basic functionalities concerning // the sport var CurrentSport = require('./sports/' + sails.config.FriendsBet.currentSport); if(!CurrentSport) { throw new Error( 'This sport (' + sails.config.currentSport + ') isn\'t implemented for the moment' ); } // Check if this score is possible // // @param score integer // @return boolean isScorePossible module.exports.checkTeamScore = function (score) { return CurrentSport.checkTeamScore(score); };
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import Field from './Field' export default class Message extends PureComponent { static propTypes = { name: PropTypes.string, type: PropTypes.string, label: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, PropTypes.func, ]), } static defaultProps = { name: 'message', type: 'textarea', } render() { return ( <Field {...this.props} /> ) } }
(function(){ "use strict"; var http = require('http'), fs = require('fs'), formidable = require('formidable'), util = require('util'), path = require('path'), mime = require('mime'); var port = 3030; http.createServer(function(request, response){ "use strict"; if(request.url === '/'){ fs.readdir('files', function(error, files){ var allFiles = '<div>'; for(var i = 0; i < files.length; i += 1){ allFiles += '<a href="/files/download/' + files[i] + '">' + files[i] + '</a><br/>'; } allFiles += '</div>'; fs.readFile('views/home-view.html', function(error, data) { response.writeHead(200); response.write(data + allFiles); response.end(); }); }); } if(request.url === '/files/upload'){ if(request.method.toLowerCase() === 'post'){ var form = new formidable.IncomingForm(); form.uploadDir = 'files'; form.keepExtensions = true; form.parse(request, function(err, fields, files) { response.writeHead(200, {'content-type': 'text/plain'}); response.end(util.inspect({files: files.upload.path})); }); } else { fs.readFile('views/login-view.html', function (error, data) { response.writeHead(200, {'content-type': 'text/html'}); response.write(data); response.end(); }); } } if(request.url.indexOf('/files/download') !== -1){ var filePath = __dirname +'/' + 'files/' + request.url.split('/')[3]; var filename = path.basename(filePath); var mimeType = mime.lookup(filePath); response.setHeader('Content-disposition', 'attachment; filename=' + filename); response.setHeader('Content-type', mimeType); var fileStream = fs.createReadStream(filePath); fileStream.pipe(response); } }).listen(port); console.log('Server running on port ' + port); }());
/** * Module dependencies. */ var express = require('express'); var compression = require('compression'); var logger = require('morgan'); var pkg = require('./package.json'); var readFile = require('fs').readFileSync; var entry = readFile('./index.html', 'utf-8'); /** * Expose `server`. */ module.exports = server; /** * Creates a server instance. * * I've wrapped the server in a function to easily * create new instances from an external CLI etc. * * @param {Object} opts * @return {Application} app * @api public */ function server(opts){ opts = opts || {}; // Environment. var app = express(); app.set('name', pkg.name); app.set('version', pkg.version); // Middle-ware. if ('test' != opts.env) app.use(logger()); app.use(compression()); app.use(express.static('./build')); app.use('/humans.txt', function(req, res){ res.sendfile('./humans.txt'); }); // Leave routing etc. to the client. // Meaning that routes that don't get a static hit, will be // dynamically routed to the `index.html` file. app.use(function(req, res){ var html = entry.replace('{{name}}', app.get('name')); res.type('html'); res.end(html); }); return app; } /** * Start a server automatically if there's no parent process. */ if (!module.parent){ var port = process.env.PORT || 3000; var app = server({ env: process.env.NODE_ENV || 'development', }); app.listen(port); console.log('Listening on port %s', port); }
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); /** * Thrown when a version check on an object that uses optimistic locking through a version field fails. */ var OptimisticLockVersionMismatchError = /** @class */ (function (_super) { __extends(OptimisticLockVersionMismatchError, _super); function OptimisticLockVersionMismatchError(entity, expectedVersion, actualVersion) { var _this = _super.call(this) || this; _this.name = "OptimisticLockVersionMismatchError"; Object.setPrototypeOf(_this, OptimisticLockVersionMismatchError.prototype); _this.message = "The optimistic lock on entity " + entity + " failed, version " + expectedVersion + " was expected, but is actually " + actualVersion + "."; return _this; } return OptimisticLockVersionMismatchError; }(Error)); exports.OptimisticLockVersionMismatchError = OptimisticLockVersionMismatchError; //# sourceMappingURL=OptimisticLockVersionMismatchError.js.map
"use strict"; var $ = require("jquery"); var hogan = require("hogan.js"); var tmplSrc = require("raw!./conduct-add-inject-form.html"); var resultTmplSrc = require("raw!./conduct-add-inject-search-result.html"); var resultTmpl = hogan.compile(resultTmplSrc); var task = require("../task"); var service = require("myclinic-service-api"); var mConsts = require("myclinic-consts"); exports.create = function(at){ var dom = $(tmplSrc); var ctx = { iyakuhincode: undefined }; bindSearch(dom, at); bindSearchResultSelect(dom, at, ctx); bindEnter(dom, ctx); bindCancel(dom); return dom; }; var drugNameSelector = "> form[mc-name=main-form] [mc-name=name]"; var drugUnitSelector = "> form[mc-name=main-form] [mc-name=unit]"; var amountInputSelector = "> form[mc-name=main-form] input[mc-name=amount]"; var kindInputSelector = "> form[mc-name=main-form] input[type=radio][name=kind]"; var searchFormSelector = "> form[mc-name=search-form]"; var searchTextSelector = "> form[mc-name=search-form] input[mc-name=searchText]"; var searchResultSelector = "> form[mc-name=search-form] select"; var enterSelector = "> form[mc-name=main-form] .workarea-commandbox [mc-name=enter]"; var cancelSelector = "> form[mc-name=main-form] .workarea-commandbox [mc-name=cancel]"; var listOfConductKinds = [mConsts.ConductKindHikaChuusha, mConsts.ConductKindJoumyakuChuusha, mConsts.ConductKindOtherChuusha, mConsts.ConductKindGazou]; function getSearchResultDom(dom){ return dom.find(searchResultSelector); } function getSearchText(dom){ return dom.find(searchTextSelector).val(); } function getAmount(dom){ return dom.find(amountInputSelector).val(); } function getKind(dom){ return dom.find(kindInputSelector).filter(function(){ return $(this).is(":checked"); }).val(); } function updateDrugName(dom, name){ dom.find(drugNameSelector).text(name); } function updateDrugUnit(dom, unit){ dom.find(drugUnitSelector).text(unit); } function updateSearchResult(dom, resultList){ getSearchResultDom(dom).html(resultTmpl.render({ list: resultList })); } function setDrug(dom, master, ctx){ ctx.iyakuhincode = master.iyakuhincode; updateDrugName(dom, master.name); updateDrugUnit(dom, master.unit); } function bindSearch(dom, at){ dom.on("submit", searchFormSelector, function(event){ event.preventDefault(); var text = getSearchText(dom).trim(); if( text === "" ){ return; } var searchResult; task.run([ function(done){ service.searchIyakuhinMaster(text, at, function(err, result){ if( err ){ done(err); return; } searchResult = result; done(); }) } ], function(err){ if( err ){ alert(err); return; } updateSearchResult(dom, searchResult); }) }); } function bindSearchResultSelect(dom, at, ctx){ dom.on("change", searchResultSelector, function(event){ var iyakuhincode = dom.find(searchResultSelector + " option:selected").val(); var master; task.run([ function(done){ service.resolveIyakuhinMasterAt(iyakuhincode, at, function(err, result){ if( err ){ done(err); return; } master = result; done(); }); } ], function(err){ if( err ){ alert(err); return; } setDrug(dom, master, ctx); }) }); } function bindEnter(dom, ctx){ dom.on("click", enterSelector, function(event){ event.preventDefault(); var iyakuhincode = ctx.iyakuhincode; if( !iyakuhincode ){ alert("薬剤が指定されていません。"); return; } iyakuhincode = +iyakuhincode; var amount = +getAmount(dom); var kind = +getKind(dom); if( !(amount > 0) ){ alert("用量が不適切です。"); return; } if( listOfConductKinds.indexOf(kind) < 0 ){ alert("invalid conduct kind: " + kind); return; } dom.trigger("enter", [iyakuhincode, amount, kind]); }); } function bindCancel(dom){ dom.on("click", cancelSelector, function(event){ event.preventDefault(); dom.trigger("cancel"); }); }
/* * ns-props * https://github.com/fatfisz/ns-props * * Copyright (c) 2015 FatFisz * Licensed under the MIT license. */ 'use strict'; var should = require('should'); var nsProps = require('../lib'); describe('get method', function () { it('simple prop', function () { var testObject = { prop: 'test', anotherProp: 'another test', }; should(nsProps.get(testObject, 'prop')).be.equal('test'); should(nsProps.get(testObject, 'anotherProp')).be.equal('another test'); }); it('namespaced prop', function () { var testObject = { namespace: { prop: 'test', }, anotherNamespace: { anotherProp: 'another test', }, }; should(nsProps.get(testObject, 'namespace.prop')).be.equal('test'); should(nsProps.get(testObject, 'anotherNamespace.anotherProp')).be.equal('another test'); }); it('very namespaced prop', function () { var testObject = { ns1: { ns2: { ns3: { ns4: { ns5: { prop: 'test', }, }, }, }, }, }; should(nsProps.get(testObject, 'ns1.ns2.ns3.ns4.ns5.prop')).be.equal('test'); }); }); describe('has method', function () { it('simple prop', function () { var testObject = { prop: 'test', }; should(nsProps.has(testObject, 'prop')).be.true(); should(nsProps.has(testObject, 'noSuchProp')).be.false(); }); it('namespaced prop', function () { var testObject = { namespace: { prop: 'test', }, }; should(nsProps.has(testObject, 'namespace.prop')).be.true(); should(nsProps.has(testObject, 'noSuchNamespace')).be.false(); should(nsProps.has(testObject, 'namespace.noSuchProp')).be.false(); }); it('very namespaced prop', function () { var testObject = { ns1: { ns2: { ns3: { ns4: { ns5: { prop: 'test', }, }, }, }, }, }; should(nsProps.has(testObject, 'ns1')).be.true(); should(nsProps.has(testObject, 'ns1.ns2')).be.true(); should(nsProps.has(testObject, 'ns1.ns2.ns3')).be.true(); should(nsProps.has(testObject, 'ns1.ns2.ns3.ns4')).be.true(); should(nsProps.has(testObject, 'ns1.ns2.ns3.ns4.ns5')).be.true(); should(nsProps.has(testObject, 'ns1.ns2.ns3.ns4.ns5.prop')).be.true(); }); }); describe('set method', function () { it('simple prop', function () { var testObject = {}; nsProps.set(testObject, 'prop', 'test'); nsProps.set(testObject, 'anotherProp', 'another test'); should(testObject.prop).be.equal('test'); should(testObject.anotherProp).be.equal('another test'); }); it('namespaced prop', function () { var testObject = {}; nsProps.set(testObject, 'namespace.prop', 'test'); nsProps.set(testObject, 'anotherNamespace.anotherProp', 'another test'); should(testObject.namespace.prop).be.equal('test'); should(testObject.anotherNamespace.anotherProp).be.equal('another test'); }); it('very namespaced prop', function () { var testObject = {}; nsProps.set(testObject, 'ns1.ns2.ns3.ns4.ns5.prop', 'test'); should(testObject.ns1.ns2.ns3.ns4.ns5.prop).be.equal('test'); }); }); describe('README example', function () { it('should work', function () { var obj = {}; nsProps.has(obj, 'ns.prop'); // false nsProps.set(obj, 'ns.prop', 'value'); // obj is { ns: { prop: 'value' } } nsProps.has(obj, 'ns.prop'); // true nsProps.get(obj, 'ns.prop'); // 'value' obj.ns.prop; // the same as above, 'value' should.throws(function () { nsProps.get(obj, 'hello'); // throws an error, no such property }, function (err) { should(err.message).be.equal('Namespaced property "hello" does not exist'); return true; }); should.throws(function () { nsProps.set(obj, 'ns.prop.another', 42); // throws an error, obj.ns.prop can't be a namespace }, function (err) { should(err.message).be.equal('"ns.prop" is already a non-namespace'); return true; }); }); });
/******************************************************************************** This file contains the Card object and related information. This file should contain no code that directly interacts with the UI, that code belongs to the Table class. ********************************************************************************/ /********************************************************************** * Enumerations **********************************************************************/ /********************************************************************** * An enumeration for playing card suit. **/ var eSuit = { SPADES : {short: "spade", value: 0}, HEARTS : {short: "heart", value: 1}, CLUBS : {short: "clubs", value: 2}, DIAMONDS : {short: "diamo", value: 3} }; /********************************************************************** * An enumeration for playing card ranks/values. **/ var eRank = { TWO : 2, THREE : 3, FOUR : 4, FIVE : 5, SIX : 6, SEVEN : 7, EIGHT : 8, NINE : 9, TEN : 10, JACK : 11, QUEEN : 12, KING : 13, ACE : 14 }; /******************************************************************************** * Playing Card Object and Elements ********************************************************************************/ /********************************************************************** * (Object) A standard playing card, with a suit and rank. **/ function Card(suit, rank) { this.suit = suit; this.rank = rank; }
/* ======================================================================== * DOM-based Routing * Based on http://goo.gl/EUTi53 by Paul Irish * Modified by Stamat <stamatmail@gmail.com> * * Only fires on body classes that match. If a body class contains a dash, * replace the dash with an underscore when adding it to the object below. * * .noConflict() * The routing is enclosed within an anonymous function so that you can * always reference jQuery with $, even when in .noConflict() mode. * ======================================================================== */ (function($) { // Use this variable to set up the common and page specific functions. If you // rename this variable, you will also need to rename the namespace below. var boilerwise = { // All pages init: function() { // JavaScript to be fired on all pages }, finalize: function(a, b, c) { // JavaScript to be fired on all pages, after page specific JS after everything else was executed }, // Home page 'home': function() { // JavaScript to be fired on the home page }, // About us page, note the change from about-us to about_us. 'about_us': function() { // JavaScript to be fired on the about us page } }; // The routing fires all common scripts, followed by the page specific scripts. // Add additional events for more control over timing e.g. a finalize event var UTIL = {}; UTIL.namespace = boilerwise; // Parses arguments in body's attribute data-args that are passed to the functions // Arguments are coma sepparated like in array without the need to begin and end with [] UTIL.argsParse = function(args) { if (!args || args.replace(/^\s\s*/, '').replace(/\s\s*$/, '') === '') { return []; } if (!args.match(/^\[/gmi)) { args = '[' + args; } if (!args.match(/$\]/gmi)) { args = args + ']'; } args = '{ "arr": ' + args + '}'; try { args = JSON.parse(args); } catch(e) { if (window.console && window.console.error) { console.error(e); } return []; } return args.arr; }; UTIL.fire = function(func, args) { var namespace = UTIL.namespace; if (func !== '' && namespace[func] && typeof namespace[func] === 'function') { namespace[func].apply(null, args); } }; UTIL.loadEvents= function() { var body = document.body; var args = UTIL.argsParse($(body).data('args')); // Fire common init JS UTIL.fire('init', args); // Fire page-specific init JS, and then finalize JS $.each(body.className.split(/\s+/), function(i, classnm) { //todo: get data args UTIL.fire(classnm.replace(/-/g, '_'), args); }); // Fire common finalize JS UTIL.fire('finalize', args); }; // Load Events $(document).ready(UTIL.loadEvents); })(jQuery); // Fully reference jQuery after this point.
var Module = require('../../../').Module, inherits = require('util').inherits; function TopNav() { this.baseSelector = 'ul.top-nav'; this._content = { 'links': { selector: 'li' } }; } inherits(TopNav, Module); module.exports = TopNav;
var expect = require('chai').expect; var helpers = require('../lib/helpers.js'); describe('Polyglot', function() { describe('#stripLang', function() { it('should add filepaths for matching translated files', function() { var filePaths = [ 'es/post/blog-post/index.html', 'fr/index.html', 'post/blog-post/index.html' ]; var languages = ['es', 'fr', 'en']; var expected = [ 'post/blog-post/index.html', 'index.html', 'post/blog-post/index.html' ]; var results = []; for (var i=0; i<filePaths.length; i++) { results.push(helpers.stripLang(filePaths[i], languages[i])); } expect(results).to.deep.equal(expected); }); }); describe('#permalinkAwareUrl', function() { it('should clean filepaths if permalinks are enabled', function() { var filePaths = [ 'post/blog-post/index.html', '/', 'post/blog-post/index.html', '/' ]; var permalinksEnabled = [true, true, false, true]; var expected = [ 'post/blog-post', '/', 'post/blog-post/index.html', '/' ]; var results = []; for (var i=0; i<filePaths.length; i++) { results.push(helpers.permalinkAwarePath(filePaths[i], permalinksEnabled[i])); } expect(results).to.deep.equal(expected); }); }); });
/* App Module */ var webPastCrew = angular.module("webPastCrew", ["ngRoute"]); webPastCrew.config(['$routeProvider', function($routeProvider){ $routeProvider.when('/home', { templateUrl : 'partials/home.html', controller : HomeController }); $routeProvider.when('/christian', { templateUrl : 'partials/christian.html', controller : ChristianController }); $routeProvider.when('/shannon', { templateUrl : 'partials/shannon.html', controller : ShannonController }); $routeProvider.when('/calender', { templateUrl : 'partials/calender.html', controller : calenderController }); $routeProvider.when('/contactus', { templateUrl : 'partials/contactus.html', controller : contactusController }); $routeProvider.otherwise({ redirectTo : '/home' }); }]); function HomeController($scope){ } function ChristianController($scope){ } function ShannonController($scope){ } function calenderController($scope){ } function contactusController(scope){ }