code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/* * Copyright 2019 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { redirect } from 'redux-first-router'; import { fetchDataAction, fetchSuccessAction, bulkFetchDataAction, createFetchPredicate, } from 'controllers/fetch'; import { showFilterOnLaunchesAction } from 'controllers/project'; import { activeFilterSelector } from 'controllers/filter'; import { activeProjectSelector } from 'controllers/user'; import { put, select, all, takeEvery, take, call } from 'redux-saga/effects'; import { testItemIdsArraySelector, launchIdSelector, pagePropertiesSelector, payloadSelector, TEST_ITEM_PAGE, pathnameChangedSelector, PROJECT_LOG_PAGE, filterIdSelector, pageSelector, testItemIdsSelector, } from 'controllers/pages'; import { PAGE_KEY } from 'controllers/pagination'; import { URLS } from 'common/urls'; import { fetch } from 'common/utils/fetch'; import { createNamespacedQuery } from 'common/utils/routingUtils'; import { LEVEL_NOT_FOUND } from 'common/constants/launchLevels'; import { FILTER_TITLES } from 'common/constants/reservedFilterTitles'; import { showScreenLockAction, hideScreenLockAction } from 'controllers/screenLock'; import { showNotification, showDefaultErrorNotification, NOTIFICATION_TYPES, } from 'controllers/notification'; import { getStorageItem, setStorageItem } from 'common/utils/storageUtils'; import { ALL } from 'common/constants/reservedFilterIds'; import { setLevelAction, setPageLoadingAction, setDefaultItemStatisticsAction, } from './actionCreators'; import { FETCH_TEST_ITEMS, NAMESPACE, PARENT_ITEMS_NAMESPACE, FILTERED_ITEM_STATISTICS_NAMESPACE, RESTORE_PATH, FETCH_TEST_ITEMS_LOG_PAGE, DELETE_TEST_ITEMS, CURRENT_ITEM_LEVEL, PROVIDER_TYPE_LAUNCH, PROVIDER_TYPE_FILTER, PROVIDER_TYPE_MODIFIERS_ID_MAP, } from './constants'; import { LEVELS } from './levels'; import { namespaceSelector, parentItemSelector, queryParametersSelector, isLostLaunchSelector, createParentItemsSelector, itemsSelector, logPageOffsetSelector, levelSelector, isTestItemsListSelector, isFilterParamsExistsSelector, launchSelector, } from './selectors'; import { calculateLevel } from './utils'; function* fetchFilteredItemStatistics(project, params) { yield put( fetchDataAction(FILTERED_ITEM_STATISTICS_NAMESPACE)(URLS.testItemStatistics(project), { params, }), ); yield take(createFetchPredicate(FILTERED_ITEM_STATISTICS_NAMESPACE)); } function* updateLaunchId(launchId) { const page = yield select(pageSelector); const payload = yield select(payloadSelector); const query = yield select(pagePropertiesSelector); const testItemIdsArray = yield select(testItemIdsArraySelector); yield put({ type: page || TEST_ITEM_PAGE, payload: { ...payload, testItemIds: [launchId, ...testItemIdsArray.slice(1)].join('/'), }, meta: { query }, }); } function* restorePath() { const parentItem = yield select(parentItemSelector); if (!parentItem) { return; } yield call(updateLaunchId, parentItem.launchId); } export function* fetchParentItems() { const itemIds = yield select(testItemIdsArraySelector); const project = yield select(activeProjectSelector); const urls = itemIds.map((id, i) => i === 0 ? URLS.launch(project, id) : URLS.testItem(project, id), ); yield put(bulkFetchDataAction(PARENT_ITEMS_NAMESPACE, true)(urls)); yield take(createFetchPredicate(PARENT_ITEMS_NAMESPACE)); } function* fetchTestItems({ payload = {} }) { const { offset = 0, params: payloadParams = {} } = payload; const filterId = yield select(filterIdSelector); const isPathNameChanged = yield select(pathnameChangedSelector); const isTestItemsList = yield select(isTestItemsListSelector); if (isPathNameChanged && !offset) { yield put(setPageLoadingAction(true)); yield put(setDefaultItemStatisticsAction()); if (!isTestItemsList) { yield call(fetchParentItems); } } const itemIdsArray = yield select(testItemIdsArraySelector); let launchId = yield select(launchIdSelector); if (isNaN(Number(launchId))) { const launch = yield select(launchSelector); launchId = launch && launch.id; itemIdsArray[0] = launch && launch.id; } const itemIds = offset ? itemIdsArray.slice(0, itemIdsArray.length - offset) : itemIdsArray; const isLostLaunch = yield select(isLostLaunchSelector); let parentId; if (isLostLaunch) { let parentItem; try { parentItem = yield select(createParentItemsSelector(offset)); } catch (e) {} // eslint-disable-line no-empty launchId = parentItem ? parentItem.launchId : launchId; } if (!isTestItemsList && !launchId) { return; } if (itemIds.length > 1) { parentId = itemIds[itemIds.length - 1]; } const project = yield select(activeProjectSelector); const namespace = yield select(namespaceSelector, offset); const query = yield select(queryParametersSelector, namespace); const pageQuery = yield select(pagePropertiesSelector); const activeFilter = yield select(activeFilterSelector); const uniqueIdFilterKey = 'filter.eq.uniqueId'; const noChildFilter = 'filter.eq.hasChildren' in query; const underPathItemsIds = itemIds.filter((item) => item !== launchId); const params = isTestItemsList ? { ...{ ...query, ...payloadParams }, } : { 'filter.eq.parentId': !noChildFilter ? parentId : undefined, 'filter.level.path': !parentId && !noChildFilter ? 1 : undefined, 'filter.under.path': noChildFilter && underPathItemsIds.length > 0 ? underPathItemsIds.join('.') : undefined, [uniqueIdFilterKey]: pageQuery[uniqueIdFilterKey], ...{ ...query, ...payloadParams }, }; if (!query.providerType) { const [providerType, id] = isTestItemsList ? [PROVIDER_TYPE_FILTER, filterId] : [PROVIDER_TYPE_LAUNCH, launchId]; const providerTypeModifierId = PROVIDER_TYPE_MODIFIERS_ID_MAP[providerType]; params.providerType = providerType; params[providerTypeModifierId] = id; } const isFilterNotReserved = !FILTER_TITLES[filterId]; if ((isTestItemsList || isFilterNotReserved) && !activeFilter) { try { const filter = yield call(fetch, URLS.filter(project, filterId)); if (filter) { yield put(showFilterOnLaunchesAction(filter)); } } catch { const testItemIds = yield select(testItemIdsSelector); const link = { type: TEST_ITEM_PAGE, payload: { filterId: ALL, projectId: project, testItemIds, }, meta: { query: pageQuery, }, }; yield put(redirect(link)); } } yield put( fetchDataAction(NAMESPACE)(URLS.testItemsWithProviderType(project), { params, }), ); const dataPayload = yield take(createFetchPredicate(NAMESPACE)); let level; if (dataPayload.error) { level = LEVEL_NOT_FOUND; } else { const previousLevel = yield select(levelSelector); const currentItemLevel = getStorageItem(CURRENT_ITEM_LEVEL); level = calculateLevel( dataPayload.payload.content, previousLevel, currentItemLevel, isTestItemsList, ); } if (LEVELS[level]) { yield put(fetchSuccessAction(LEVELS[level].namespace, dataPayload.payload)); } yield put(setLevelAction(level)); yield call(setStorageItem, CURRENT_ITEM_LEVEL, level); const isFilterParamsExists = yield select(isFilterParamsExistsSelector); if (!isTestItemsList && isFilterParamsExists) { yield call(fetchFilteredItemStatistics, project, params); } yield put(setPageLoadingAction(false)); } function* watchRestorePath() { yield takeEvery(RESTORE_PATH, restorePath); } function* watchFetchTestItems() { yield takeEvery(FETCH_TEST_ITEMS, fetchTestItems); } function* calculateStepPagination({ next = false, offset = 1 }) { const namespace = yield select(namespaceSelector, offset); const namespaceQuery = yield select(queryParametersSelector, namespace); let page = parseInt(namespaceQuery[PAGE_KEY], 10) - 1; if (next) { page = parseInt(namespaceQuery[PAGE_KEY], 10) + 1; } return { [PAGE_KEY]: page, }; } export function* fetchTestItemsFromLogPage({ payload = {} }) { const { next = false } = payload; const offset = yield select(logPageOffsetSelector); const stepParams = yield call(calculateStepPagination, { next, offset }); yield call(fetchTestItems, { payload: { offset, params: stepParams } }); const testItems = yield select(itemsSelector); const projectId = yield select(activeProjectSelector); const testItem = next ? testItems[0] : testItems[testItems.length - 1]; const { launchId, path } = testItem; const testItemIds = [launchId, ...path.split('.')].join('/'); const filterId = yield select(filterIdSelector); const namespace = yield select(namespaceSelector, offset); const namespaceQuery = yield select(queryParametersSelector, namespace); const params = { ...namespaceQuery, ...stepParams, }; const query = createNamespacedQuery(params, namespace); const link = { type: PROJECT_LOG_PAGE, payload: { filterId, projectId, testItemIds, }, query, }; yield put(redirect(link)); } function* watchTestItemsFromLogPage() { yield takeEvery(FETCH_TEST_ITEMS_LOG_PAGE, fetchTestItemsFromLogPage); } function* deleteTestItems({ payload: { items, callback } }) { const ids = items.map((item) => item.id).join(','); const projectId = yield select(activeProjectSelector); yield put(showScreenLockAction()); try { yield call(fetch, URLS.testItems(projectId, ids), { method: 'delete', }); yield put(hideScreenLockAction()); yield call(callback); yield put( showNotification({ messageId: items.length === 1 ? 'deleteTestItemSuccess' : 'deleteTestItemMultipleSuccess', type: NOTIFICATION_TYPES.SUCCESS, }), ); } catch (error) { yield put(hideScreenLockAction()); yield put(showDefaultErrorNotification(error)); } } function* watchDeleteTestItems() { yield takeEvery(DELETE_TEST_ITEMS, deleteTestItems); } export function* testItemsSagas() { yield all([ watchFetchTestItems(), watchRestorePath(), watchTestItemsFromLogPage(), watchDeleteTestItems(), ]); }
reportportal/service-ui
app/src/controllers/testItem/sagas.js
JavaScript
apache-2.0
10,865
var CU = require('../compilerUtils'), U = require('../../../utils'), CONST = require('../../../common/constants'), _ = require('../../../lib/alloy/underscore')._; exports.parse = function(node, state) { return require('./base').parse(node, state, parse); }; function parse(node, state, args) { var code = ''; // make symbol a local variable if necessary if (state.local) { args.symbol = CU.generateUniqueId(); } // Generate runtime code code += (state.local ? 'var ' : '') + args.symbol + " = " code += CU.generateStyleParams( state.styles, args.classes, args.id, CU.getNodeFullname(node), _.defaults(state.extraStyle || {}, args.createArgs || {}), _.extend(state, { isListItem: true }) ) + ';'; // Update the parsing state return { parent: { node: node, symbol: args.symbol }, local: state.local || false, model: state.model || undefined, condition: state.condition || undefined, styles: state.styles, code: code } };
jppope/alloy
Alloy/commands/compile/parsers/Ti.UI.ListItem.js
JavaScript
apache-2.0
972
const fs = require('fs'), nock = require('nock'), sinon = require('sinon'), request = require('postman-request'), COLLECTION = { id: 'C1', name: 'Collection', item: [{ id: 'ID1', name: 'R1', request: 'https://postman-echo.com/get' }] }, VARIABLE = { id: 'E1', name: 'Environment', values: [{ key: 'foo', value: 'bar' }] }; describe('newman.run postmanApiKey', function () { before(function () { nock('https://api.getpostman.com') .persist() .get(/^\/collections/) .reply(200, COLLECTION); nock('https://api.getpostman.com') .persist() .get(/^\/environments/) .reply(200, VARIABLE); nock('https://example.com') .persist() .get('/collection.json') .reply(200, COLLECTION); }); after(function () { nock.restore(); }); beforeEach(function () { sinon.spy(request, 'get'); }); afterEach(function () { request.get.restore(); }); it('should fetch collection via UID', function (done) { newman.run({ collection: '1234-588025f9-2497-46f7-b849-47f58b865807', postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.calledOnce(request.get); let requestArg = request.get.firstCall.args[0]; expect(requestArg).to.be.an('object').and.include.keys(['url', 'json', 'headers']); expect(requestArg.url) .to.equal('https://api.getpostman.com/collections/1234-588025f9-2497-46f7-b849-47f58b865807'); expect(requestArg.headers).to.be.an('object') .that.has.property('X-Api-Key', '12345678'); expect(summary).to.be.an('object') .that.has.property('collection').to.be.an('object') .and.include({ id: 'C1', name: 'Collection' }); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); it('should fetch environment via UID', function (done) { newman.run({ collection: 'test/fixtures/run/single-get-request.json', environment: '1234-931c1484-fd1e-4ceb-81d0-2aa102ca8b5f', postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.calledOnce(request.get); let requestArg = request.get.firstCall.args[0]; expect(requestArg).to.be.an('object').and.include.keys(['url', 'json', 'headers']); expect(requestArg.url) .to.equal('https://api.getpostman.com/environments/1234-931c1484-fd1e-4ceb-81d0-2aa102ca8b5f'); expect(requestArg.headers).to.be.an('object') .that.has.property('X-Api-Key', '12345678'); expect(summary).to.be.an('object') .that.has.property('environment').to.be.an('object') .and.include({ id: 'E1', name: 'Environment' }); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); it('should fetch all resources via UID', function (done) { newman.run({ collection: '1234-588025f9-2497-46f7-b849-47f58b865807', environment: '1234-931c1484-fd1e-4ceb-81d0-2aa102ca8b5f', postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.calledTwice(request.get); expect(summary).to.be.an('object').and.include.keys(['collection', 'environment', 'globals', 'run']); expect(summary.collection).to.include({ id: 'C1', name: 'Collection' }); expect(summary.environment).to.include({ id: 'E1', name: 'Environment' }); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); it('should end with an error if UID is passed without postmanApiKey and no such file exists', function (done) { newman.run({ collection: '1234-588025f9-2497-46f7-b849-47f58b865807' }, function (err) { expect(err).to.be.ok.that.match(/no such file or directory/); sinon.assert.notCalled(request.get); done(); }); }); it('should not pass API Key header for Postman API URLs', function (done) { newman.run({ collection: 'https://api.getpostman.com/collections?apikey=12345678', postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.calledOnce(request.get); let requestArg = request.get.firstCall.args[0]; expect(requestArg).to.be.an('object').and.include.keys(['url', 'json', 'headers']); expect(requestArg.url).to.equal('https://api.getpostman.com/collections?apikey=12345678'); expect(requestArg.headers).to.not.have.property('X-Api-Key'); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); it('should not pass API Key header for non Postman API URLs', function (done) { newman.run({ collection: 'https://example.com/collection.json', postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.calledOnce(request.get); let requestArg = request.get.firstCall.args[0]; expect(requestArg).to.be.an('object').and.include.keys(['url', 'json', 'headers']); expect(requestArg.url).to.equal('https://example.com/collection.json'); expect(requestArg.headers).to.not.have.property('X-Api-Key'); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); describe('read file', function () { const UID = '1234-96771253-046f-4ad7-81f9-a2d3c433492b'; beforeEach(function (done) { fs.stat(UID, function (err) { if (err) { return fs.writeFile(UID, JSON.stringify(COLLECTION), done); } done(); }); }); afterEach(function (done) { fs.stat(UID, function (err) { if (err) { return done(); } fs.unlink(UID, done); }); }); it('should fetch from file having UID name', function (done) { newman.run({ collection: UID, postmanApiKey: '12345678' }, function (err, summary) { expect(err).to.be.null; sinon.assert.notCalled(request.get); expect(summary).to.be.an('object') .that.has.property('collection').to.be.an('object') .and.include({ id: 'C1', name: 'Collection' }); expect(summary.run.failures).to.be.empty; expect(summary.run.executions, 'should have 1 execution').to.have.lengthOf(1); done(); }); }); }); });
postmanlabs/newman
test/library/postman-api-key.test.js
JavaScript
apache-2.0
7,684
/** * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { "use strict"; angular .module('designatedashboard.resources.os-designate-floatingip.details') .controller('designatedashboard.resources.os-designate-floatingip.details.overviewController', controller); controller.$inject = [ 'designatedashboard.resources.os-designate-floatingip.resourceType', 'horizon.framework.conf.resource-type-registry.service', '$scope' ]; function controller( resourceTypeCode, registry, $scope ) { var ctrl = this; ctrl.item; ctrl.resourceType = registry.getResourceType(resourceTypeCode); $scope.context.loadPromise.then(onGetResponse); function onGetResponse(response) { ctrl.item = response.data; } } })();
openstack/designate-dashboard
designatedashboard/static/designatedashboard/resources/os-designate-floatingip/details/overview.controller.js
JavaScript
apache-2.0
1,362
var slug = require('slug') , FeedParser = require('feedparser') , Parse = require("parse").Parse , MongoClient = require('mongodb').MongoClient , assert = require('assert') , request = require('request') , _ = require('underscore'); var req = request('https://yts.to/rss') , feedparser = new FeedParser() , parsedMovies = [] , PARSE_APP_KEY = process.env.PARSE_APP_KEY || "" , PARSE_JAVASCRIPT_KEY = process.env.PARSE_JAVASCRIPT_KEY || ""; var Movie = (function () { function Movie(item) { this.title = item.title; this.link = item.link; this.pub_date = item.pubDate; this.hash = slug(item.title, "_"); } return Movie; })(); function filterMovies(db, movies, callback){ var slugs = _.pluck(movies, "hash"); var collection = db.collection('movies'); // Find already inserted movies collection.find({"hash": {$in:slugs}}).toArray(function(err, alreadyInsertedMovies) { assert.equal(err, null); // take the ones that are not included var alreadyInsertedSlugs = _.pluck(alreadyInsertedMovies, "hash"); var filteredMovies = _.reject(movies, function(movie){ return _.contains(alreadyInsertedSlugs, movie.hash); }); callback(filteredMovies); }); } function insertMovies(db, movies, callback){ movies = movies || []; if(!movies.length){ return callback(movies); } var collection = db.collection('movies'); // Insert filtered movies collection.insert(movies, function(err, result) { assert.equal(err, null); console.log("Inserted "+ movies.length +" documents into the movies collection"); callback(movies); }); } function sendPushNotifications(movies){ console.log("new movies:"); console.log(movies); if(!movies.length){ return; } if(PARSE_APP_KEY != "" && PARSE_JAVASCRIPT_KEY != ""){ Parse.initialize(PARSE_APP_KEY, PARSE_JAVASCRIPT_KEY); Parse.Push.send({ channels: [""], // Set the broadcast channel data: { alert: "New movies uploaded: \n\n" + _.pluck(movies, "title").join("\n") } }, { success: function () { // Push was successful }, error: function (error) { // Handle error } }); } } req.on('error', function (error) { // handle any request errors }); req.on('response', function (res) { var stream = this; if (res.statusCode != 200) return this.emit('error', new Error('Bad status code')); stream.pipe(feedparser); }); feedparser.on('error', function(error) { // always handle errors console.log(error); }); feedparser.on('readable', function() { var stream = this , meta = this.meta // **NOTE** the "meta" is always available in the context of the feedparser instance , item; while (item = stream.read()) { parsedMovies.push(new Movie(item)); } }); feedparser.on('end', function(){ // This is where the action is! if(parsedMovies.length){ // Connection URL var url = 'mongodb://localhost:27017/yts'; // Use connect method to connect to the Server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server"); filterMovies(db, parsedMovies, function(filteredMovies){ insertMovies(db, filteredMovies, function(insertedMovies){ db.close(); sendPushNotifications(insertedMovies); }); }); }); } });
gbaldera/yts-movies-checker
movies_checker.js
JavaScript
apache-2.0
3,724
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // the package file to use uglify: { main: { files: { 'dist/afe.min.js': [ 'src/js/afe.js', 'src/js/afe.core.js', 'src/js/afe.form.js', 'src/js/afeCheckbox.js', 'src/js/afeRadiobox.js', 'src/js/afe.finish.js' ] } }, uncompress: { files: { 'dist/afe.js': [ 'src/js/afe.js', 'src/js/afe.core.js', 'src/js/afe.form.js', 'src/js/afeCheckbox.js', 'src/js/afeRadiobox.js', 'src/js/afe.finish.js' ] }, options: { compress: false, beautify: true } } }, less: { main: { options: { compress: true, cleancss: true }, src: [ "src/less/css.less" ], dest: "dist/afe.min.css" } }, watch: { css: { files: ['src/less/**'], tasks: ['default:less', 'copy'] }, js: { files: ['src/js/**'], tasks: ['default:uglify', 'copy'] } }, copy: { main: { files: [ {expand: true, cwd: 'dist', src: '*.js', dest: 'example/js/'}, {expand: true, cwd: 'dist', src: '*.css', dest: 'example/css/'}, {expand: true, cwd: 'bower_components/jquery/dist', src: 'jquery.min.js', dest: 'example/js/'}, {expand: true, cwd: 'bower_components/jquery/dist', src: 'jquery.min.map', dest: 'example/js/'} ] } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['uglify:main', 'uglify:uncompress', 'less', 'copy']); };
efureev/ajax-form-elements
Gruntfile.js
JavaScript
apache-2.0
1,694
/*jshint multistr: true */ /*jshint evil: true */ angular.module('slicebox.directives', []) .directive('sbxChip', function() { return { restrict: 'E', transclude: true, template: '<span class="sbx-chip {{chipClass}}" ng-transclude></span>', scope: { chipClass: '@' } }; }) .directive('sbxButton', function($q, $timeout) { return { restrict: 'E', template: '<md-button type="{{buttonType}}" ng-class="buttonClass" ng-click="buttonClicked()" ng-disabled="buttonDisabled || disabled">' + '<div layout="row" layout-wrap layout-align="center center">' + '{{buttonTitle}}&nbsp;<md-progress-circular md-mode="indeterminate" md-diameter="25" ng-if="disabled && showSpinner" />' + '</div>' + '</md-button>', scope: { action: '&', buttonType: '@', buttonTitle: '@', buttonDisabled: '=', buttonClass: '@' }, link: function($scope, $element, $attrs) { if (angular.isUndefined($attrs.buttonType)) { $scope.buttonType = 'button'; } var spinnerTimeoutPromise; $scope.buttonClicked = function() { $scope.showSpinner = false; $scope.disabled = true; spinnerTimeoutPromise = $timeout(function() { $scope.showSpinner = true; }, 700); var action = $scope.action(); $q.when(action).finally(function() { $scope.disabled = false; $timeout.cancel(spinnerTimeoutPromise); spinnerTimeoutPromise = null; }); }; } }; }) .directive('sbxDicomHexValue', function() { return { require: 'ngModel', restrict: 'A', link: function($scope, $element, $attrs, ngModel) { var parse = function(value) { if (angular.isUndefined(value)) { return value; } var hexValue = '0x' + value.trim(); var intValue = parseInt(hexValue); if (!isNaN(intValue)) { ngModel.$setValidity('sbxDicomHexValue', true); return intValue; } ngModel.$setValidity('sbxDicomHexValue', false); return undefined; }; var format = function(value) { if (angular.isUndefined(value) || value === 0) { return ''; } var returnValue = value.toString(16); while (returnValue.length < 8) { returnValue = '0' + returnValue; } return returnValue; }; ngModel.$parsers.push(parse); ngModel.$formatters.push(format); } }; }) .directive('tagPathForm', function($http) { return { restrict: 'E', templateUrl: '/assets/partials/directives/tagPathForm.html', scope: { tagPath: '=' }, link: function($scope, $element, $attrs) { var tagRegEx = /^\(?[0-9]{4},?[0-9]{4}\)?$/; var replaceRegEx = /\(|\)|,/g; var allItemIndices = ["*","1", "2", "3", "4", "5", "6", "7", "8", "9"]; var noNested = $attrs.hasOwnProperty('noNested'); var noWildcards = $attrs.hasOwnProperty('noWildcards'); var emptyPath = { tag: null, name: null }; $scope.uiState = { itemIndices: noWildcards ? allItemIndices.splice(0, 1) : allItemIndices, sequences: [], tag: null, noNested: noNested, noWildcards: noWildcards }; $scope.tagPath = emptyPath; updateTagPath(); // scope functions $scope.addSequence = function() { $scope.uiState.sequences.push({ item: null }); }; $scope.getMatchingTagKeywords = function(text) { return $http.get('/api/dicom/dictionary/keywords/nonsequence?filter=' + text).then(function (response) { return response.data.keywords; }); }; $scope.getMatchingSequenceKeywords = function(text) { return $http.get('/api/dicom/dictionary/keywords/sequence?filter=' + text).then(function (response) { return response.data.keywords; }); }; $scope.sequenceKeywordSelected = function(keyword, index) { var s = $scope.uiState.sequences[index]; s.tag = null; if (keyword && keyword.length > 0) { s.name = keyword; } else { s.name = null; } updateTagPath(); }; $scope.sequenceTagChanged = function(text, index) { var s = $scope.uiState.sequences[index]; s.name = null; if (text.match(tagRegEx)) { s.tag = text.replace(replaceRegEx, ''); } else { s.tag = null; } updateTagPath(); }; $scope.sequenceItemChanged = function() { updateTagPath(); }; $scope.tagKeywordSelected = function(keyword) { if (keyword && keyword.length > 0) { $scope.uiState.tag = {tag: null, name: keyword}; } else { $scope.uiState.tag = null; } updateTagPath(); }; $scope.tagTagChanged = function(text) { if (text.match(tagRegEx)) { $scope.uiState.tag = { tag: text.replace(replaceRegEx, ''), name: null }; } else { $scope.uiState.tag = null; } updateTagPath(); }; function parsePath(p, seqs, isNested) { var name = p.name; var tag = p.tag ? parseInt(p.tag, 16) : null; if (isNaN(tag)) { tag = null; } if (isNested) { return { tag: tag, name: name, item: p.item, previous: addItem(seqs.slice(0, -1)) }; } return { tag: tag, name: name, previous: addItem(seqs) }; } function addItem(seqs) { if (seqs.length === 0) { return null; } var s = seqs[seqs.length - 1]; if (!(s.tag || s.name) || !s.item) { return addItem(seqs.slice(0, -1)); } return parsePath(s, seqs, true); } function updateTagPath() { if ($scope.uiState.tag) { $scope.tagPath = parsePath($scope.uiState.tag, $scope.uiState.sequences, false); } else { $scope.tagPath = addItem($scope.uiState.sequences); } } } }; }) .directive('anonymizationProfileForm', function($http) { return { restrict: 'E', templateUrl: '/assets/partials/directives/anonymizationProfileForm.html', scope: { selectedOptions: '=options' }, link: function ($scope) { $scope.selectedOptions = $scope.selectedOptions || []; $scope.uiState = { options: null }; $http.get('/api/anonymization/options').then(function(response) { $scope.uiState.options = $scope.uiState.options || response.data; }); } }; }) /* * In order for selection check boxes and object actions to work, all objects in the * list must have an id property. */ .directive('sbxGrid', function($filter, $q, $timeout) { return { restrict: 'E', templateUrl: '/assets/partials/directives/sbxGrid.html', transclude: true, scope: { loadPage: '&', converter: '&', pageSize: '=', pageSizes: '=', objectSelectedCallback: '&objectSelected', objectActions: '=', sorting: '=', filter: '=', callbacks: '=', rowCSSClassesCallback: '&rowCssClasses', rowObjectActionsCallback: '&rowObjectActions', emptyMessage: '@', refreshButton: '=', gridState: '=' }, controller: function($scope, $element, $attrs) { $scope.columnDefinitions = []; this.addColumn = function(columnDefinition) { $scope.columnDefinitions.push(columnDefinition); }; }, link: function($scope, $element, $attrs) { // Initialization $scope.cssClasses = { empty: {}, pointerCursor: { cursor: 'pointer' }, rowSelected: { 'row-selected': true } }; if ($scope.gridState && !angular.equals($scope.gridState, {})) { $scope.uiState = angular.copy($scope.gridState); $scope.objectList = $scope.gridState.objectList; } else { $scope.uiState = { currentPage: 0, morePageExist: false, currentPageSize: pageSizeAsNumber(), selectedObject: null, orderByProperty: null, orderByDirection: null, objectActionSelection: [], selectAllChecked: false, emptyMessage: 'Empty', filter: '' }; } $scope.$on('$destroy', function () { if ($scope.gridState) { angular.copy($scope.uiState, $scope.gridState); $scope.gridState.objectList = $scope.objectList; } }); if (angular.isDefined($attrs.callbacks)) { $scope.callbacks = { reset: reset, reloadPage: loadPageData, selectedActionObjects: selectedActionObjects, clearSelection: clearSelection, clearActionSelection: clearActionSelection, selectObject: selectObject }; } if (angular.isDefined($attrs.emptyMessage)) { $scope.uiState.emptyMessage = $scope.emptyMessage; } $scope.$watchCollection('columnDefinitions', function () { doOnColumnsChanged(); }); $scope.$watchCollection('uiState.objectActionSelection', function () { updateSelectAllObjectActionChecked(); }); $scope.$watch('uiState.currentPageSize', function (newValue, oldValue) { if (newValue !== oldValue) { loadPageData(); } }); loadPageData(); // Scope functions $scope.tableBodyStyle = function() { if (selectionEnabled()) { return $scope.cssClasses.pointerCursor; } return $scope.cssClasses.empty; }; $scope.columnHeaderOrderByStyle = function(columnDefinition) { var orderByStyle = $scope.cssClasses.empty; if ($scope.sortingEnabled()) { orderByStyle = $scope.cssClasses.pointerCursor; } return orderByStyle; }; $scope.rowCSSClasses = function(rowObject) { var rowObjectSelected = $scope.uiState.selectedObject && rowObject.id === $scope.uiState.selectedObject.id; if (angular.isDefined($attrs.rowCssClasses)) { return $scope.rowCSSClassesCallback({rowObject: rowObject, selected: rowObjectSelected}); } if (selectionEnabled() && rowObjectSelected) { return $scope.cssClasses.rowSelected; } return $scope.cssClasses.empty; }; $scope.rowHasActions = function(rowObject) { if (angular.isUndefined($attrs.rowObjectActions)) { return true; } return $scope.rowObjectActionsCallback({rowObject: rowObject}).length > 0; }; $scope.loadNextPage = function() { if ($scope.objectList.length < $scope.uiState.currentPageSize) { return; } $scope.uiState.currentPage += 1; loadPageData(); }; $scope.loadPreviousPage = function() { if ($scope.uiState.currentPage === 0) { return; } $scope.uiState.currentPage -= 1; loadPageData(); }; $scope.rowClicked = function(rowObject) { if ($scope.uiState.selectedObject === rowObject) { selectObject(null); } else { selectObject(rowObject); } }; $scope.sortingEnabled = function() { var sortingEnabled = $scope.sorting; if (angular.isUndefined(sortingEnabled)) { sortingEnabled = true; } return sortingEnabled; }; $scope.filterEnabled = function() { return $scope.filter; }; $scope.filterChanged = function() { loadPageData(); }; $scope.refreshButtonEnabled = function() { return $scope.refreshButton; }; $scope.columnClicked = function(columnDefinition) { if (!$scope.sortingEnabled()) { return; } if ($scope.uiState.orderByProperty === columnDefinition.property) { if ($scope.uiState.orderByDirection === 'ASCENDING') { $scope.uiState.orderByDirection = 'DESCENDING'; } else { $scope.uiState.orderByDirection = 'ASCENDING'; } } else { $scope.uiState.orderByProperty = columnDefinition.property; $scope.uiState.orderByDirection = 'ASCENDING'; } loadPageData(); }; $scope.selectAllChanged = function() { for (var i = 0; i < $scope.uiState.objectActionSelection.length; i++) { $scope.uiState.objectActionSelection[i] = $scope.uiState.selectAllChecked; } }; $scope.objectActionsEnabled = function() { for (var i = 0; i < $scope.uiState.objectActionSelection.length; i++) { if ($scope.uiState.objectActionSelection[i] === true) { return true; } } return false; }; $scope.objectActionEnabled = function(objectAction) { if (!$scope.objectActionsEnabled()) { return false; } if (angular.isDefined(objectAction.requiredSelectionCount)) { return (objectAction.requiredSelectionCount === selectedActionObjects().length); } return true; }; $scope.objectActionSelected = function(objectAction) { performObjectAction(objectAction); }; $scope.refresh = function() { loadPageData(); }; // Private functions function doOnColumnsChanged() { calculateFilteredCellValues(); // Need to reset page data to trigger rerendering of rows var savedObjectList = $scope.objectList; $scope.objectList = null; $timeout(function() { if ($scope.objectList === null) { $scope.objectList = savedObjectList; } }); } function loadPageData() { if ($scope.uiState.currentPageSize <= 0) { return $q.when([]); } var selectedObjectsBeforeLoadPage = selectedActionObjects(); var deferred = $q.defer(); var startIndex = $scope.uiState.currentPage * $scope.uiState.currentPageSize; // Load one more object than pageSize to be able to check if more data is available var count = $scope.uiState.currentPageSize + 1; var loadPageFunctionParameters = { startIndex: startIndex, count: count, orderByProperty: $scope.uiState.orderByProperty, orderByDirection: $scope.uiState.orderByDirection }; if ($scope.uiState.filter && $scope.uiState.filter.length > 0) { loadPageFunctionParameters.filter = $scope.uiState.filter; } var loadPageResponse = ($scope.loadPage || angular.noop)(loadPageFunctionParameters); $q.when(loadPageResponse).then(function(response) { if (angular.isArray(response)) { handleLoadedPageData(response, selectedObjectsBeforeLoadPage); deferred.resolve(); } else if (response) { // Assume response is a http response and extract data handleLoadedPageData(response.data, selectedObjectsBeforeLoadPage); deferred.resolve(); } else { deferred.reject("Page data load error: empty response."); } }); return deferred.promise; } function pageSizeAsNumber() { var pageSizeNumber = null; if (angular.isDefined($scope.pageSize)) { pageSizeNumber = parseInt($scope.pageSize); } else { pageSizeNumber = 0; } return pageSizeNumber; } function handleLoadedPageData(pageData, selectedObjectsBeforeLoadPage) { $scope.objectList = convertPageData(pageData); if ($scope.objectList.length > $scope.uiState.currentPageSize) { // Remove the extra object from the end of the list $scope.objectList.splice(-1, 1); $scope.uiState.morePagesExists = true; } else { $scope.uiState.morePagesExists = false; } validateAndUpdateSelectedObject(); validateAndUpdateObjectActionSelection(selectedObjectsBeforeLoadPage); if ($scope.objectList.length === 0) { // Avoid empty pages $scope.loadPreviousPage(); } calculateFilteredCellValues(); } function convertPageData(pageData) { var result = null; if (angular.isDefined($attrs.converter)) { result = $scope.converter({pageData: pageData}); if (!angular.isArray(result)) { throwError('PageDataError', 'Converter must return an array'); } } else if (angular.isArray(pageData)) { result = pageData; } else { throwError('PageDataError', 'Unknown format for page data. Consider setting a converter.\n' + angular.toJson(pageData)); } return result; } function calculateFilteredCellValues() { $scope.filteredCellValues = []; if (!$scope.objectList || $scope.objectList.length === 0) { return; } angular.forEach($scope.objectList, function(rowObject) { $scope.filteredCellValues.push({}); }); angular.forEach($scope.columnDefinitions, function(columnDefinition) { calculateFilteredCellValuesForColumn(columnDefinition); }); } function calculateFilteredCellValuesForColumn(columnDefinition) { angular.forEach($scope.objectList, function(rowObject, index) { $scope.filteredCellValues[index][columnDefinition.property] = calculateFilteredCellValueForRowObjectAndColumn(rowObject, columnDefinition); }); } function calculateFilteredCellValueForRowObjectAndColumn(rowObject, columnDefinition) { var cellValue = rowObject[columnDefinition.property]; if (columnDefinition.property && columnDefinition.property.indexOf('[') !== -1) { cellValue = eval('rowObject.' + columnDefinition.property); } var filter = columnDefinition.filter; if (!filter) { return cellValue; } if (!angular.isString(filter)) { throwError('TypeError', 'Invalid filter value, must be a string: ' + angular.toJson(filter)); return cellValue; } var filterSeparatorIndex = filter.indexOf(':'); var filterName = filter; var filterParams = null; if (filterSeparatorIndex != -1) { filterName = filter.substring(0, filterSeparatorIndex).trim(); filterParams = filter.substring(filterSeparatorIndex + 1).trim(); } if (filterParams) { return $filter(filterName)(cellValue, filterParams); } else { return $filter(filterName)(cellValue); } } function validateAndUpdateSelectedObject() { if (!$scope.uiState.selectedObject) { return; } var newSelectedObject = findObjectInArray($scope.uiState.selectedObject, $scope.objectList); if (newSelectedObject) { $scope.uiState.selectedObject = newSelectedObject; } else { selectObject(null); } } function validateAndUpdateObjectActionSelection(selectedObjectsBeforeLoadPage) { $scope.uiState.objectActionSelection = new Array($scope.objectList.length); if (selectedObjectsBeforeLoadPage.length === 0) { return; } angular.forEach(selectedObjectsBeforeLoadPage, function(selectedObjectBeforeLoadPage) { var newSelectedObject = findObjectInArray(selectedObjectBeforeLoadPage, $scope.objectList); if (newSelectedObject) { var index = $scope.objectList.indexOf(newSelectedObject); if (index >= 0) { $scope.uiState.objectActionSelection[index] = true; } } }); } function updateSelectAllObjectActionChecked() { var allSelected = ($scope.uiState.objectActionSelection.length > 0); for (var i = 0; i < $scope.uiState.objectActionSelection.length; i++) { if (!$scope.uiState.objectActionSelection[i]) { allSelected = false; } } $scope.uiState.selectAllChecked = allSelected; } function selectionEnabled() { return angular.isDefined($attrs.objectSelected); } function selectObject(object) { if ($scope.uiState.selectedObject === object) { return; } $scope.objectSelectedCallback({object: object}); $scope.uiState.selectedObject = object; } function selectedActionObjects() { var selectedObjects = []; for (var i = 0; i < $scope.uiState.objectActionSelection.length; i++) { if ($scope.uiState.objectActionSelection[i]) { if ($scope.objectList && $scope.objectList.length > i) { selectedObjects.push($scope.objectList[i]); } } } return selectedObjects; } function typeOfObject(object) { if (angular.isDate(object)) { return 'date'; } if (angular.isNumber(object)) { return 'number'; } if (angular.isArray(object)) { return 'array'; } if (angular.isString(object)) { return 'text'; } if (angular.isObject(object)) { return 'object'; } } function findObjectInArray(object, objectsArray) { for (i = 0, length = objectsArray.length; i < length; i++) { var eachObject = objectsArray[i]; if (eachObject === object) { return eachObject; } if (angular.isDefined(eachObject.id) && angular.isDefined(object.id) && eachObject.id === object.id) { return eachObject; } } return null; } function findObjectByPropertyInArray(objectPropertyName, objectPropertyValue, objectsArray) { for (i = 0, length = objectsArray.length; i < length; i++) { var eachObject = objectsArray[i]; if (angular.isDefined(eachObject[objectPropertyName]) && eachObject[objectPropertyName] === objectPropertyValue) { return eachObject; } } return null; } function throwError(name, message) { throw { name: name, message: message }; } function reset() { $scope.uiState.currentPage = 0; return loadPageData(); } function clearSelection() { $scope.uiState.selectedObject = null; } function clearActionSelection() { $scope.uiState.objectActionSelection = []; } function performObjectAction(objectAction) { if (!$scope.objectActionEnabled(objectAction)) { $event.stopPropagation(); return; } if (angular.isFunction(objectAction.action)) { var objectActionResult = objectAction.action(selectedActionObjects()); $q.when(objectActionResult).finally(function() { loadPageData(); }); } else { throwError('TypeError', 'An object action must define an action function: ' + angular.toJson(objectAction)); } } } }; }) .directive('sbxGridColumn', function() { return { require: '^sbxGrid', restrict: 'E', transclude: true, scope: { property: '@', type: '=', title: '@', filter: '@' }, controller: function($scope, $element, $attrs) { this.setRenderer = function(rendererTranscludeFn, rendererScope) { $scope.rendererTranscludeFn = rendererTranscludeFn; $scope.rendererScope = rendererScope; }; }, link: function($scope, $element, $attrs, sbxGridController, $transclude) { // Initialization $transclude(function(rendererElement) { $element.append(rendererElement); }); var columnDefinition = { property: $scope.property, title: $scope.title, type: $scope.type, filter: $scope.filter, rendererTranscludeFn: $scope.rendererTranscludeFn, rendererScope: $scope.rendererScope }; sbxGridController.addColumn(columnDefinition); } }; }) .directive('sbxGridCell', function() { return { require: '^sbxGridColumn', restrict: 'E', transclude: true, link: function($scope, $element, $attrs, sbxGridColumnController, $transclude) { sbxGridColumnController.setRenderer($transclude, $scope); } }; }) .directive('sbxGridInternalTd', function() { return { restrict: 'A', priority: 500, // Must be below ngRepeat priority link: function($scope, $element, $attrs) { var property = $scope.columnDefinition.property; var rendererTranscludeFn = $scope.columnDefinition.rendererTranscludeFn; var rendererScope = $scope.columnDefinition.rendererScope; var rendererChildScope = null; var rawPropertyValue = null; if (angular.isFunction(rendererTranscludeFn)) { // Remove default rendering $element.empty(); rendererChildScope = rendererScope.$new(); rendererChildScope.rowObject = $scope.rowObject; $scope.$on('$destroy', function() { rendererChildScope.$destroy(); }); rawPropertyValue = $scope.rowObject[$scope.columnDefinition.property]; if ($scope.columnDefinition.property && $scope.columnDefinition.property.indexOf('[') !== -1) { rawPropertyValue = eval('$scope.rowObject.' + $scope.columnDefinition.property); } rendererChildScope.rawPropertyValue = rawPropertyValue; rendererChildScope.filteredPropertyValue = $scope.filteredCellValues[$scope.$parent.$index][$scope.columnDefinition.property]; rendererChildScope.isFirstRowObject = function() { return $scope.$parent.$first; }; rendererChildScope.isLastRowObject = function() { return $scope.$parent.$last; }; rendererTranscludeFn(rendererChildScope, function(rendererElement) { $element.append(rendererElement); }); } } }; });
slicebox/slicebox
src/main/assets/js/directives.js
JavaScript
apache-2.0
32,162
'use strict'; goog.provide('Blockly.Blocks.storage'); goog.require('Blockly.Blocks'); Blockly.Blocks.storage.HUE = 0; Blockly.Blocks.store_sd_init = { init: function () { this.appendDummyInput("") .appendField("SD") .appendField(Blockly.MIXLY_SETUP); this.appendValueInput("PIN_MOSI") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("MOSI") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_MISO") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("MISO") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_SCK") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("CLK") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_CS") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("CS") .appendField(Blockly.MIXLY_PIN); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setInputsInline(false); this.setTooltip(); this.setHelpUrl(''); } }; Blockly.Blocks.store_sd_init_32 = { init: function () { this.appendDummyInput("") .appendField("SD") .appendField(Blockly.MIXLY_SETUP); this.appendValueInput("PIN_MOSI") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("MOSI") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_MISO") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("MISO") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_SCK") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("CLK") .appendField(Blockly.MIXLY_PIN); this.appendValueInput("PIN_CS") .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField("CS") .appendField(Blockly.MIXLY_PIN); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setInputsInline(false); this.setTooltip(); this.setHelpUrl(''); } }; Blockly.Blocks.sd_card_type= { init: function() { this.appendDummyInput() .appendField("SD"+Blockly.MIXLY_TYPE); this.setOutput(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setTooltip(""); this.setHelpUrl(""); } }; Blockly.Blocks.sd_card_root_files= { init: function() { this.appendDummyInput() .appendField(Blockly.MIXLY_SD_LIST_FILES); this.setOutput(false, null); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setTooltip(""); this.setHelpUrl(""); } }; var volume_TYPE = [[Blockly.MIXLY_SD_clusterCount, 'volume.clusterCount()'], [Blockly.MIXLY_SD_blocksPerCluster, 'volume.blocksPerCluster()'], [Blockly.MIXLY_SD_TOTAL_blocks, 'volume.blocksPerCluster() * volume.clusterCount()'], ["FAT"+Blockly.MIXLY_TYPE, 'volume.fatType()'], [Blockly.MIXLY_volume+"(KB)", 'volume.blocksPerCluster()*volume.clusterCount()/2'], [Blockly.MIXLY_volume+"(MB)", 'volume.blocksPerCluster()*volume.clusterCount()/2/1024'], [Blockly.MIXLY_volume+"(GB)", 'volume.blocksPerCluster()*volume.clusterCount()/2/1024/1024.0'], ]; Blockly.Blocks.sd_volume = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendDummyInput() .appendField("SD") .appendField(new Blockly.FieldDropdown(volume_TYPE), 'volume_TYPE'); this.setOutput(true, Number); this.setTooltip(); } }; Blockly.Blocks.sd_exist= { init: function() { this.appendDummyInput() .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput("fileName.txt"), "FileName") .appendField(this.newQuote_(false)) .appendField(Blockly.MIXLY_SD_FILE_Exist); this.setOutput(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setTooltip(""); this.setHelpUrl(""); }, newQuote_: function(open) { if (open == this.RTL) { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg=='; } else { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC'; } return new Blockly.FieldImage(file, 12, 12, '"'); } }; Blockly.Blocks.sd_DelFile= { init: function() { this.appendDummyInput() .appendField(Blockly.MIXLY_MICROBIT_JS_DELETE_VAR) .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput("fileName.txt"), "FileName") .appendField(this.newQuote_(false)); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setTooltip(""); this.setHelpUrl(""); }, newQuote_: function(open) { if (open == this.RTL) { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg=='; } else { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC'; } return new Blockly.FieldImage(file, 12, 12, '"'); } }; Blockly.Blocks.sd_read= { init: function() { this.appendDummyInput() .appendField(Blockly.MIXLY_SERIAL_READ) .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput("fileName.txt"), "FileName") .appendField(this.newQuote_(false)); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setColour(Blockly.Blocks.storage.HUE); this.setTooltip(""); this.setHelpUrl(""); }, newQuote_: function(open) { if (open == this.RTL) { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg=='; } else { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC'; } return new Blockly.FieldImage(file, 12, 12, '"'); } }; Blockly.Blocks.store_sd_write = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendDummyInput() .appendField(Blockly.MIXLY_WRITE_SD_FILE) .appendField(this.newQuote_(true)) .appendField(new Blockly.FieldTextInput(''), 'FILE') .appendField(this.newQuote_(false)); this.appendValueInput("DATA", String) .setCheck([String,Number]) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.MIXLY_SD_DATA); this.appendValueInput("NEWLINE", Boolean) .setCheck(Boolean) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.MIXLY_SD_NEWLINE); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_SDWRITE); }, newQuote_: function(open) { if (open == this.RTL) { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg=='; } else { var file = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC'; } return new Blockly.FieldImage(file, 12, 12, '"'); } }; Blockly.Blocks.store_eeprom_write_long = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS", Number) .setCheck(Number) .appendField(Blockly.MIXLY_EEPROM_WRITE_LONG); this.appendValueInput("DATA", Number) .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.MIXLY_DATA); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_WRITELONG); } }; Blockly.Blocks.store_eeprom_read_long = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS", Number) .setCheck(Number) .appendField(Blockly.MIXLY_EEPROM_READ_LONG); this.setOutput(true, Number); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_READLONG); } }; Blockly.Blocks.store_eeprom_write_byte = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS", Number) .setCheck(Number) .appendField(Blockly.MIXLY_EEPROM_WRITE_BYTE); this.appendValueInput("DATA", Number) .setCheck(Number) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.MIXLY_DATA); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_WRITEBYTE); } }; Blockly.Blocks.store_eeprom_read_byte = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS", Number) .setCheck(Number) .appendField(Blockly.MIXLY_EEPROM_READ_BYTE); this.setOutput(true, Number); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_READBYTE); } }; Blockly.Blocks.store_eeprom_put = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS") .setCheck(null) .appendField(Blockly.MIXLY_ESP32_WRITE) //.appendField(new Blockly.FieldDropdown([[Blockly.LANG_MATH_INT,"int"],[Blockly.LANG_MATH_LONG,"long"],[Blockly.LANG_MATH_FLOAT,"float"],[Blockly.LANG_MATH_BYTE,"byte"],["字节数组","byte_array"],["字符数组","char_array"]]), "type") .appendField("EEPROM") .appendField(Blockly.MQTT_SERVER_ADD); this.appendValueInput("DATA") .setCheck(null) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.MIXLY_SD_DATA); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_PUT); } }; Blockly.Blocks.store_eeprom_get = { init: function() { this.setColour(Blockly.Blocks.storage.HUE); this.appendValueInput("ADDRESS") .setCheck(null) .appendField(Blockly.MIXLY_SERIAL_READ) //.appendField(new Blockly.FieldDropdown([[Blockly.LANG_MATH_INT,"int"],[Blockly.LANG_MATH_LONG,"long"],[Blockly.LANG_MATH_FLOAT,"float"],[Blockly.LANG_MATH_BYTE,"byte"],["字节数组","byte_array"],["字符数组","char_array"]]), "type") .appendField("EEPROM") .appendField(Blockly.MQTT_SERVER_ADD); this.appendValueInput("DATA") .setCheck(null) .setAlign(Blockly.ALIGN_RIGHT) .appendField(Blockly.SAVETO + ' ' + MSG["catVar"]); this.setPreviousStatement(true, null); this.setNextStatement(true, null); this.setTooltip(Blockly.MIXLY_TOOLTIP_STORE_EEPROM_GET); } };
xbed/Mixly_Arduino
mixly_arduino/blockly/blocks/arduino/storage.js
JavaScript
apache-2.0
12,272
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require twitter/bootstrap // require turbolinks //= require best_in_place //= require blockly/blockly_compressed //= require blockly/blocks_compressed //= require blockly/javascript_compressed //= require blockly/msg/js/en //= require JS-Interpreter/acorn //= require JS-Interpreter/interpreter //= require list_blocks //= require simulation_blocks //= require soil_patch //= require smartfarm //= require weather_blocks //= require soil_blocks //= require crop_blocks //= require_tree .
zombiepaladin/smartfarm
app/assets/javascripts/application.js
JavaScript
apache-2.0
1,117
/** * Test to check if the component renders correctly */ /* global it expect */ import 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import AboutView from '@containers/about/AboutView'; it('AboutView renders correctly', () => { const tree = renderer.create( <AboutView />, ).toJSON(); expect(tree).toMatchSnapshot(); });
elarasu/roverz-chat
src/containers/__tests__/aboutview-test.js
JavaScript
apache-2.0
378
var packageJSON = require("../../../package.json"); var config = { // @@ENV gets replaced by build system environment: "@@ENV", // If the UI is served through a proxied URL, this can be set here. rootUrl: "", // Defines the Marathon API URL, // leave empty to use the same as the UI is served. apiURL: "../", // Intervall of API request in ms updateInterval: 5000, // Local http server URI while tests run localTestserverURI: { address: "localhost", port: 8181 }, version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ? "@@TEAMCITY_UI_VERSION" : `${packageJSON.version}-SNAPSHOT` }; if (process.env.GULP_ENV === "development") { try { var configDev = require("./config.dev"); config = Object.assign(config, configDev); } catch (e) { // Do nothing } } module.exports = config;
yp-engineering/marathon-ui
src/js/config/config.js
JavaScript
apache-2.0
848
// // Vivado(TM) // rundef.js: a Vivado-generated Runs Script for WSH 5.1/5.6 // Copyright 1986-2016 Xilinx, Inc. All Rights Reserved. // var WshShell = new ActiveXObject( "WScript.Shell" ); var ProcEnv = WshShell.Environment( "Process" ); var PathVal = ProcEnv("PATH"); if ( PathVal.length == 0 ) { PathVal = "C:/Xilinx/Vivado/2016.4/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.4/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2016.4/bin;"; } else { PathVal = "C:/Xilinx/Vivado/2016.4/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2016.4/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2016.4/bin;" + PathVal; } ProcEnv("PATH") = PathVal; var RDScrFP = WScript.ScriptFullName; var RDScrN = WScript.ScriptName; var RDScrDir = RDScrFP.substr( 0, RDScrFP.length - RDScrN.length - 1 ); var ISEJScriptLib = RDScrDir + "/ISEWrap.js"; eval( EAInclude(ISEJScriptLib) ); ISEStep( "vivado", "-log main.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source main.tcl" ); function EAInclude( EAInclFilename ) { var EAFso = new ActiveXObject( "Scripting.FileSystemObject" ); var EAInclFile = EAFso.OpenTextFile( EAInclFilename ); var EAIFContents = EAInclFile.ReadAll(); EAInclFile.Close(); return EAIFContents; }
martinmiranda14/Digitales
Lab_6/project_7/project_7.runs/synth_1/rundef.js
JavaScript
apache-2.0
1,265
soul = { name: "Template", content: "Chariot", toonList: [{ viz: 1, id: "idle", speed: .3 }], awake: function (rock) { var glob = rock.glob; rock.display.alpha = 0; var delay = 5; var offSet = "+=" + delay; var duration = 2; var tl = new TimelineLite(); tl.to(rock.display, 2, { alpha: 1 }, offSet); tl.to(rock.display, 2, { alpha: 0 }, offSet); tl.play(); } }
s-r-c/globhammer
client/static/000000/globTitle/index.js
JavaScript
artistic-2.0
458
// Generated by CoffeeScript 1.8.0 (function() { var BubbleChart, root, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; BubbleChart = (function() { function BubbleChart(data) { this.hide_details = __bind(this.hide_details, this); this.show_details = __bind(this.show_details, this); this.hide_years = __bind(this.hide_years, this); this.display_years = __bind(this.display_years, this); this.move_towards_year = __bind(this.move_towards_year, this); this.display_by_year = __bind(this.display_by_year, this); this.move_towards_center = __bind(this.move_towards_center, this); this.display_group_all = __bind(this.display_group_all, this); this.start = __bind(this.start, this); this.create_vis = __bind(this.create_vis, this); this.create_nodes = __bind(this.create_nodes, this); var max_amount; this.data = data; this.width = 940; this.height = 600; this.tooltip = CustomTooltip("gates_tooltip", 240); this.center = { x: this.width / 2, y: this.height / 2 }; this.year_centers = { "2008": { x: this.width / 3, y: this.height / 2 }, "2009": { x: this.width / 2, y: this.height / 2 }, "2010": { x: 2 * this.width / 3, y: this.height / 2 } }; this.layout_gravity = -0.01; this.damper = 0.1; this.vis = null; this.nodes = []; this.force = null; this.circles = null; // Change color legend this.fill_color = d3.scale.ordinal().domain(["low", "medium", "high"]).range(["#f1f1f1", "#0148a4", "#ffb800"]); max_amount = d3.max(this.data, function(d) { return parseInt(d.total_amount); }); this.radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([2, 85]); this.create_nodes(); this.create_vis(); } BubbleChart.prototype.create_nodes = function() { this.data.forEach((function(_this) { return function(d) { var node; node = { id: d.id, radius: _this.radius_scale(parseInt(d.total_amount)), value: d.total_amount, name: d.grant_title, org: d.organization, group: d.group, year: d.start_year, x: Math.random() * 900, y: Math.random() * 800 }; return _this.nodes.push(node); }; })(this)); return this.nodes.sort(function(a, b) { return b.value - a.value; }); }; BubbleChart.prototype.create_vis = function() { var that; this.vis = d3.select("#vis").append("svg").attr("width", this.width).attr("height", this.height).attr("id", "svg_vis"); this.circles = this.vis.selectAll("circle").data(this.nodes, function(d) { return d.id; }); that = this; this.circles.enter().append("circle").attr("r", 0).attr("fill", (function(_this) { return function(d) { return _this.fill_color(d.group); }; })(this)).attr("stroke-width", 2).attr("stroke", (function(_this) { return function(d) { return d3.rgb(_this.fill_color(d.group)).darker(); }; })(this)).attr("id", function(d) { return "bubble_" + d.id; }).on("mouseover", function(d, i) { return that.show_details(d, i, this); }).on("mouseout", function(d, i) { return that.hide_details(d, i, this); }); return this.circles.transition().duration(2000).attr("r", function(d) { return d.radius; }); }; BubbleChart.prototype.charge = function(d) { return -Math.pow(d.radius, 2.0) / 8; }; BubbleChart.prototype.start = function() { return this.force = d3.layout.force().nodes(this.nodes).size([this.width, this.height]); }; BubbleChart.prototype.display_group_all = function() { this.force.gravity(this.layout_gravity).charge(this.charge).friction(0.9).on("tick", (function(_this) { return function(e) { return _this.circles.each(_this.move_towards_center(e.alpha)).attr("cx", function(d) { return d.x; }).attr("cy", function(d) { return d.y; }); }; })(this)); this.force.start(); return this.hide_years(); }; BubbleChart.prototype.move_towards_center = function(alpha) { return (function(_this) { return function(d) { d.x = d.x + (_this.center.x - d.x) * (_this.damper + 0.02) * alpha; return d.y = d.y + (_this.center.y - d.y) * (_this.damper + 0.02) * alpha; }; })(this); }; BubbleChart.prototype.display_by_year = function() { this.force.gravity(this.layout_gravity).charge(this.charge).friction(0.9).on("tick", (function(_this) { return function(e) { return _this.circles.each(_this.move_towards_year(e.alpha)).attr("cx", function(d) { return d.x; }).attr("cy", function(d) { return d.y; }); }; })(this)); this.force.start(); return this.display_years(); }; BubbleChart.prototype.move_towards_year = function(alpha) { return (function(_this) { return function(d) { var target; target = _this.year_centers[d.year]; d.x = d.x + (target.x - d.x) * (_this.damper + 0.02) * alpha * 1.1; return d.y = d.y + (target.y - d.y) * (_this.damper + 0.02) * alpha * 1.1; }; })(this); }; BubbleChart.prototype.display_years = function() { var years, years_data, years_x; years_x = { "2008": 160, "2009": this.width / 2, "2010": this.width - 160 }; years_data = d3.keys(years_x); years = this.vis.selectAll(".years").data(years_data); return years.enter().append("text").attr("class", "years").attr("x", (function(_this) { return function(d) { return years_x[d]; }; })(this)).attr("y", 40).attr("text-anchor", "middle").text(function(d) { return d; }); }; BubbleChart.prototype.hide_years = function() { var years; return years = this.vis.selectAll(".years").remove(); }; BubbleChart.prototype.show_details = function(data, i, element) { var content; d3.select(element).attr("stroke", "black"); content = "<span class=\"name\">Title:</span><span class=\"value\"> " + data.name + "</span><br/>"; content += "<span class=\"name\">Amount:</span><span class=\"value\"> $" + (addCommas(data.value)) + "</span><br/>"; content += "<span class=\"name\">Year:</span><span class=\"value\"> " + data.year + "</span>"; return this.tooltip.showTooltip(content, d3.event); }; BubbleChart.prototype.hide_details = function(data, i, element) { d3.select(element).attr("stroke", (function(_this) { return function(d) { return d3.rgb(_this.fill_color(d.group)).darker(); }; })(this)); return this.tooltip.hideTooltip(); }; return BubbleChart; })(); root = typeof exports !== "undefined" && exports !== null ? exports : this; $(function() { var chart, render_vis; chart = null; render_vis = function(csv) { chart = new BubbleChart(csv); chart.start(); return root.display_all(); }; root.display_all = (function(_this) { return function() { return chart.display_group_all(); }; })(this); root.display_year = (function(_this) { return function() { return chart.display_by_year(); }; })(this); root.toggle_view = (function(_this) { return function(view_type) { if (view_type === 'year') { return root.display_year(); } else { return root.display_all(); } }; })(this); return d3.csv("data/gates_money.csv", render_vis); }); }).call(this);
SoxFace/fhs-datavis
js/vis.js
JavaScript
bsd-2-clause
8,093
(function () { var t = 0, n = 10000, i , results = [] ; function asyncFn (i, cb) { setTimeout(function () { cb(null, 'foo' + i); }, t); } var fs = { stat: function (file, cb) { this.setTimeout(file, cb); }, setTimeout: function (file, cb) { setTimeout(function () { cb(null, 'file: ' + file)}, t); } }; var Sync = require('../lib/syncho'); Sync(function () { console.time('syncho-simple'); for (i = 0; i < n; i++) { results.push(asyncFn.sync(null, i)); } console.timeEnd('syncho-simple'); results = []; console.time('syncho-object'); for (i = 0; i < n; i++) { results.push(fs.stat.sync(fs, 'package.json')); } console.timeEnd('syncho-object'); }); // var thunk = require('thunkify'), co = require('co'); // co(function *() { // // results = []; // console.time('co-simple'); // for (i = 0; i < n; i++) { // var fn = thunk(asyncFn); // results.push(yield fn(i)); // } // console.timeEnd('co-simple'); // // results = []; // console.time('co-object'); // for (i = 0; i < n; i++) { // var stat = thunk(fs.stat.bind(fs)); // results.push(yield stat('package.json')); // } // console.timeEnd('co-object'); // // })(); })();
jtblin/syncho
benchmarks/co.js
JavaScript
bsd-2-clause
1,297
const tableName = 'koa2_api_movies' exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex(tableName).del() .then(function () { // Inserts seed entries return knex(tableName).insert([ { name: 'The Land Before Time', genre: 'Fantasy', rating: 7, explicit: false }, { name: 'Jurassic Park', genre: 'Science Fiction', rating: 9, explicit: true }, { name: 'Ice Age: Dawn of the Dinosaurs', genre: 'Action/Romance', rating: 5, explicit: false } ]); }); };
sharkspeed/dororis
packages/javascript/koajs/koa2-pg-api/src/server/db/seeds/movies_seed.js
JavaScript
bsd-2-clause
680
/* This file is generated automatically by generatejs.con. Do not edit. */ 'use strict'; if (!con.arch) con.arch = { }; con.arch._zip_open = this.__cjs__zip_open; con.arch.__zip_name_locate = this.__cjs___zip_name_locate; con.arch._zip_fopen = this.__cjs__zip_fopen; con.arch._zip_fopen_index = this.__cjs__zip_fopen_index; con.arch._zip_fread = this.__cjs__zip_fread; con.arch._zip_fclose = this.__cjs__zip_fclose; con.arch._zip_close = this.__cjs__zip_close; con.arch._zip_stat = this.__cjs__zip_stat; con.arch._zip_get_archive_comment = this.__cjs__zip_get_archive_comment; con.arch._zip_get_file_comment = this.__cjs__zip_get_file_comment; con.arch.__zip_get_name = this.__cjs___zip_get_name; con.arch._zip_get_num_files = this.__cjs__zip_get_num_files; con.arch._zip_add = this.__cjs__zip_add; con.arch.__zip_replace = this.__cjs___zip_replace; con.arch._zip_set_file_comment = this.__cjs__zip_set_file_comment; con.arch._zip_source_buffer = this.__cjs__zip_source_buffer; con.arch._zip_source_file = this.__cjs__zip_source_file; con.arch._zip_source_filep = this.__cjs__zip_source_filep; con.arch._zip_source_zip = this.__cjs__zip_source_zip; con.arch._zip_source_free = this.__cjs__zip_source_free; con.arch._zip_rename = this.__cjs__zip_rename; con.arch._zip_delete = this.__cjs__zip_delete; con.arch.__zip_unchange = this.__cjs___zip_unchange; con.arch._zip_unchange_all = this.__cjs__zip_unchange_all; con.arch._zip_unchange_archive = this.__cjs__zip_unchange_archive; con.arch._zip_set_archive_comment = this.__cjs__zip_set_archive_comment; con.arch._zip_strerror = this.__cjs__zip_strerror; con.arch._zip_file_strerror = this.__cjs__zip_file_strerror;
Devronium/ConceptApplicationServer
modules/_js/standard.arch.zip.js
JavaScript
bsd-2-clause
1,667
var util = require('util'); var AbstractWriter = require('./AbstractWriter'); /** * A dummy writer that doesn't actually write anything. * * @class guerrero.writer.NullWriter * @extend guerrero.writer.AbstractWriter * @constructor * @param {Object} options */ var NullWriter = function (options) { NullWriter.super_.apply(this, arguments); }; util.inherits(NullWriter, AbstractWriter); /** * @inheritdoc */ NullWriter.prototype.info = function (fileInfo) { }; /** * @ignore */ module.exports = NullWriter;
pigulla/guerrero
src/writer/NullWriter.js
JavaScript
bsd-2-clause
526
// Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Lexical declaration (const) not allowed in statement position esid: sec-if-statement es6id: 13.6 negative: phase: parse type: SyntaxError ---*/ throw "Test262: This statement should not be evaluated."; if (true) const x = null; else const y = null;
sebastienros/jint
Jint.Tests.Test262/test/language/statements/if/if-const-else-const.js
JavaScript
bsd-2-clause
412
var decryptRegex = new RegExp(config.template.replace(/__VALUE__/, "(.+)"), "m"); function decrypt(text) { var md, data, result = text; while (md = result.match(decryptRegex)) { data = GibberishAES.dec(md[1]+'\n', config.secret); //console.log(md, data); result = md.input.substring(0, md.index) + data + md.input.substring(md.index + md[0].length); } return result; } function encrypt(text) { var data = GibberishAES.enc(text, config.secret).replace(/\n$/, ""); return config.template.replace(/__VALUE__/, data); } $('form').submit(function() { $(this).find('input, textarea').each(function() { var obj = $(this); if ($.inArray(obj.attr('name'), config.encryptElements) > -1) { obj.val(encrypt(obj.val())); } }); }).find('input, textarea').each(function() { var obj = $(this); if ($.inArray(obj.attr('name'), config.encryptElements) > -1) { obj.val(decrypt(obj.val())); } }); $(config.decryptSelectors.join(",")).each(function() { var obj = $(this); obj.html(decrypt(obj.html())); });
viking/cryptify
chrome/cryptify.js
JavaScript
bsd-2-clause
1,055
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.foreach es5id: 15.4.4.18-7-b-12 description: > Array.prototype.forEach - deleting own property with prototype property causes prototype index property to be visited on an Array-like object ---*/ var testResult = false; function callbackfn(val, idx, obj) { if (idx === 1 && val === 1) { testResult = true; } } var obj = { 0: 0, 1: 111, length: 10 }; Object.defineProperty(obj, "0", { get: function() { delete obj[1]; return 0; }, configurable: true }); Object.prototype[1] = 1; Array.prototype.forEach.call(obj, callbackfn); assert(testResult, 'testResult !== true');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/prototype/forEach/15.4.4.18-7-b-12.js
JavaScript
bsd-2-clause
781
'use strict'; import rebound from 'rebound'; import React, { Component } from 'react'; import { Platform, Animated, PanResponder, Dimensions, View, } from 'react-native'; import Svg, { Path } from 'react-native-svg'; var { width, height } = Dimensions.get('window'); class JellySideMenu extends Component { constructor(props) { super(props); this.state = { is_dock : false, offsetDragX : 0, offsetDragY : height / 2, } this.makePanResponder(); this.onJellyUndocked = this.onJellyUndocked.bind(this); this.onJellyNotUndocked = this.onJellyNotUndocked.bind(this); } makePanResponder() { var self = this; this.panResponder = PanResponder.create({ onStartShouldSetPanResponder: function(e, gestureState) { return true }, onMoveShouldSetPanResponder: function(e, gestureState) { return true }, onPanResponderGrant: function(e, gestureState) { self.onDropSideMenuSvg() }, onPanResponderMove: function(e, gestureState) { self.onDragSideMenuSvg(gestureState.dx, gestureState.moveY) }, onPanResponderRelease: function(e, gestureState) { if (gestureState.dx > 100) { self.onDropSideMenuSvg(true) } else { self.onDropSideMenuSvg(false) } }, onPanResponderTerminate: function(e, gestureState) { if (gestureState.dx > 100) { self.onDropSideMenuSvg(true) } else { self.onDropSideMenuSvg(false) } }, }) } getPanHandlers() { return this.panResponder.panHandlers; } onDragSideMenuSvg(x, y) { this.refs.sideMenuSvgWrapper ? this.refs.sideMenuSvgWrapper.onJellyNotUndocked() : {}; this.refs.sideMenuSvg ? this.refs.sideMenuSvg.setOffsetDrag(x, y, false) : {}; } onDropSideMenuSvg(bool) { if (bool) { if (!this.state.is_dock) { this.setState({ is_dock: true }) } this.refs.sideMenuSvgWrapper ? this.refs.sideMenuSvgWrapper.onJellyNotUndocked() : {}; this.refs.sideMenuSvg ? this.refs.sideMenuSvg.dockOffsetDrag(true) : {}; } else { if (this.state.is_dock) { this.setState({ is_dock: false }) } this.refs.sideMenuSvg ? this.refs.sideMenuSvg.resetOffsetDrag(true) : {}; } } toggleSideMenu(bool) { if (bool == undefined) { this.onDropSideMenuSvg(!this.state.is_dock); } else { this.onDropSideMenuSvg(bool); } } onJellyNotUndocked() { this.refs.sideMenuSvgWrapper ? this.refs.sideMenuSvgWrapper.onJellyNotUndocked() : {}; } onJellyUndocked() { this.refs.sideMenuSvgWrapper ? this.refs.sideMenuSvgWrapper.onJellyUndocked() : {}; } render() { var dockPullWidth = 20; var dockWidth = 240; var offsetDragX = this.state.offsetDragX; var offsetDragY = this.state.offsetDragY; var pathSide = " 0 0 q " + offsetDragX + " " + offsetDragY + " 0 " + height; var dockStyle = {width: dockPullWidth}; if (this.state.is_dock) {dockStyle = {width: null, right: 0}}; return ( <View style={{position: 'absolute', top: 0, left: 0, bottom: 0, right: 0 }}> {this.props.children} <View style={[{position: 'absolute', top: 0, left: 0, bottom: 0, backgroundColor: this.state.is_dock ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0)'}, dockStyle]} {...this.getPanHandlers()}> </View> { this.renderSvg(dockWidth) } <JellySideMenuContent is_dock={this.state.is_dock} dockWidth={dockWidth}> {this.props.renderMenu()} </JellySideMenuContent> </View> ) } renderSvg(dockWidth) { console.log("sRwdd"); if (Platform.OS === "ios") { return ( <JellySideMenuSvgWrapper ref={'sideMenuSvgWrapper'} width={width} height={height}> <JellySideMenuSvg onJellyUndocked={this.onJellyUndocked} onJellyNotUndocked={this.onJellyNotUndocked} fill={this.props.fill || "#FFF"} fillOpacity={this.props.fillOpacity || 0.9} height={height} dockWidth={dockWidth} ref={'sideMenuSvg'}/> </JellySideMenuSvgWrapper> ) } return ( <View style={{position: 'absolute', top: 0, left: 0, bottom: 0, right: width - dockWidth - 30}}> <JellySideMenuSvgWrapper ref={'sideMenuSvgWrapper'} width={width} height={height}> <JellySideMenuSvg onJellyUndocked={this.onJellyUndocked} onJellyNotUndocked={this.onJellyNotUndocked} fill={this.props.fill || "#FFF"} fillOpacity={this.props.fillOpacity || 0.9} height={height} dockWidth={dockWidth} ref={'sideMenuSvg'}/> </JellySideMenuSvgWrapper> </View> ) } } class JellySideMenuSvgWrapper extends Component { constructor(props) { super(props); this.is_undocked = true; this.is_mounted = true; } componentDidMount() { this.is_mounted = true; this.forceUpdate(); } componentWillUnmount() { this.is_mounted = false; } onJellyNotUndocked() { this.is_undocked = false; if (this.is_mounted) { this.forceUpdate(); } } onJellyUndocked() { this.is_undocked = true; if (this.is_mounted) { this.forceUpdate(); } } render() { console.log("sR"); if (this.is_undocked) { return null } return ( <Svg style={[{position: 'absolute', top: 0, left: 0, bottom: 0, right: 0}]} width={this.props.width} height={this.props.height} > {this.props.children} </Svg> ) } } class JellySideMenuContent extends Component { constructor(props) { super(props); this.state = { dockOpacityAnim : new Animated.Value(0), dockLeftAnim : new Animated.Value(-this.props.dockWidth), } } componentWillUpdate(nextProps, nextState) { if (nextProps.is_dock != this.props.is_dock) { if (nextProps.is_dock) { Animated.spring(this.state.dockOpacityAnim, {toValue: 1, friction: 10}).start() Animated.spring(this.state.dockLeftAnim, {toValue: 0, friction: 5}).start() } else { Animated.spring(this.state.dockOpacityAnim, {toValue: 0, friction: 10}).start() Animated.spring(this.state.dockLeftAnim, {toValue: -this.props.dockWidth, friction: 5}).start() } } } render() { var style = {width: this.props.dockWidth, position: 'absolute', top: 0, opacity: this.state.dockOpacityAnim, left: this.state.dockLeftAnim, bottom: 0, backgroundColor: 'transparent'} return ( <Animated.View style={style}> {this.props.children} </Animated.View> ) } } class JellySideMenuSvg extends Component { constructor(props) { super(props); this.state = { is_dock : false, is_undocked : true, offsetDragX : 0, offsetDragY : height / 2, offsetDragXSm : 0, } this.is_mounted = true; this.isBusy = false this.isBusyY = false this.isBusySm = false this.springSystem = new rebound.SpringSystem() this.springSystem2 = new rebound.SpringSystem() this.ssOffsetDragX = this.springSystem.createSpring() this.ssOffsetDragY = this.springSystem.createSpring() this.ssOffsetDragX.setCurrentValue(0) this.ssOffsetDragY.setCurrentValue(height / 2) this.ssOffsetDragX.addListener({onSpringUpdate: () => { if (!this.is_mounted) { return } if (this.isBusy) { return } this.isBusy = true; if (this.ssOffsetDragX.getEndValue() <= 0) { if (this.state.offsetDragX <= 0 && !this.state.is_undocked) { this.setState({offsetDragX: this.ssOffsetDragX.getCurrentValue(), is_undocked: true}); this.ssOffsetDragX.setCurrentValue(0); this.ssOffsetDragXSm.setCurrentValue(0); return; } else { this.setState({offsetDragX: this.ssOffsetDragX.getCurrentValue()}); return; } } else { if (this.state.is_undocked) { this.setState({offsetDragX: this.ssOffsetDragX.getCurrentValue(), is_undocked: false}); return; } else { this.setState({offsetDragX: this.ssOffsetDragX.getCurrentValue()}); return; } } }}) this.ssOffsetDragY.addListener({onSpringUpdate: () => { if (!this.is_mounted) { return } if (this.isBusyY) { return } this.isBusyY = true; this.setState({offsetDragY: this.ssOffsetDragY.getCurrentValue()})} }) this.ssOffsetDragXSm = this.springSystem2.createSpring() this.ssOffsetDragXSm.setCurrentValue(0) this.ssOffsetDragXSm.addListener({onSpringUpdate: () => { if (!this.is_mounted) { return } if (this.isBusySm) { return } this.isBusySm = true; this.setState({offsetDragXSm: this.ssOffsetDragXSm.getCurrentValue()})} }) var sscX = this.ssOffsetDragX.getSpringConfig(); var sscY = this.ssOffsetDragY.getSpringConfig(); var sscXSm = this.ssOffsetDragXSm.getSpringConfig(); sscX.tension = 500; sscX.friction = 10; sscY.tension = 500; sscY.friction = 10; sscXSm.tension = 500; sscXSm.friction = 15; } componentDidMount() { this.is_mounted = true; this.isBusy = false; this.isBusyY = false; this.isBusySm = false; } componentWillUnmount() { this.is_mounted = false; } componentWillUpdate(nextProps, nextState) { if (nextState.is_undocked != this.state.is_undocked) { if (nextState.is_undocked == true) { this.props.onJellyUndocked(); } else { this.props.onJellyNotUndocked(); } } } setOffsetDrag(x, y, animated) { if (animated) { this.ssOffsetDragX.setEndValue(x / 2); this.ssOffsetDragY.setEndValue(y); this.ssOffsetDragXSm.setEndValue(x / 5); } else { this.ssOffsetDragX.setCurrentValue(x / 2); this.ssOffsetDragY.setCurrentValue(y); this.ssOffsetDragXSm.setCurrentValue(x / 5); } } resetOffsetDrag(animated) { if (animated) { this.ssOffsetDragX.setEndValue(0); this.ssOffsetDragY.setEndValue(height / 2); this.ssOffsetDragXSm.setEndValue(0); } else { this.ssOffsetDragX.setCurrentValue(0); this.ssOffsetDragY.setCurrentValue(height / 2); this.ssOffsetDragXSm.setCurrentValue(0); } } dockOffsetDrag(animated) { if (animated) { this.ssOffsetDragX.setEndValue(this.props.dockWidth); this.ssOffsetDragY.setEndValue(height / 2); this.ssOffsetDragXSm.setEndValue(this.props.dockWidth); } else { this.ssOffsetDragX.setCurrentValue(this.props.dockWidth); this.ssOffsetDragY.setCurrentValue(height / 2); this.ssOffsetDragXSm.setCurrentValue(this.props.dockWidth); } } render() { this.isBusy = false; this.isBusyY = false; this.isBusySm = false; var offsetDragX = this.state.offsetDragX; var offsetDragY = this.state.offsetDragY; var offsetDragXSm = this.state.offsetDragXSm; var pathSide = ""; var path = ""; pathSide = "M" + offsetDragXSm + " 0"; pathSide += " Q" + offsetDragX + " " + 0 + " " + offsetDragX + " " + offsetDragY; pathSide += " Q" + offsetDragX + " " + height + " " + offsetDragXSm + " " + height; path = pathSide + " L" + " 0 " + this.props.height + " L0 0 Z"; return ( <Path d={path} fill={this.props.fill} fillOpacity={this.props.fillOpacity}/> ) } } module.exports = JellySideMenu;
VansonLeung/react-native-jelly-side-menu
JellySideMenu.js
JavaScript
bsd-2-clause
11,635
var $iframe = $('#pagePreview'), iframeDoc, $iframeBody; $iframe.load(function() { var $overlay = $('<div/>'); console.log('iframe loaded'); iframeDoc = $iframe[0].contentDocument; $iframeBody = $(iframeDoc.body); $overlay.css({ 'height': $iframeBody.height(), 'width': $iframeBody.width(), 'position': 'absolute', 'top': 0, 'left': 0 }); $iframeBody.append($overlay); $iframe.hideLoading(); }).showLoading({ overlayBorder: true, afterShow: function() { $iframe.attr('src', '<?php echo $this->baseUrl(); ?>' + '/site/preview'); } }); /* <div class="upload-progress"> <div class="bar"></div> <div class="percent"></div> </div> */ var $form = $('#siteThemeForm'), //$uploadProgressBar = $('.bar', $form), //$uploadProgressLabel = $('.percent', $uploadProgressBar); $uploadProgressBar = $('<div class="bar"></div>'), $uploadProgressLabel = $('<div class="percent"></div>'); if(window.ProgressEvent) { // XHR2 support $('#siteThemeForm-logo').after($('<div class="upload-progress"></div>').append($uploadProgressBar).append($uploadProgressLabel)); $form.ajaxForm({ beforeSend: function() { $uploadProgressBar.width('0%'); $uploadProgressLabel.html('0%'); $iframe.showLoading({overlayBorder: true}); }, uploadProgress: function(e, position, total, percentComplete) { $uploadProgressBar.width(percentComplete + '%'); $uploadProgressLabel.html(percentComplete + '%'); }, complete: function(xhr) { var data = $.parseJSON(xhr.responseText), url = '<?php echo $this->url(array(), "previewImage"); ?>' + '?t=theme&n=' + data.filename; console.log('Complete', xhr); console.log('url', url); $iframeBody.find('#site-logo > a > img').load(function() { $(this).attr('width', data.width).attr('height', data.height).off('load'); $iframe.hideLoading(); }).attr('src', url); } }); }
rexmac/zyndax
application/modules/admin/views/scripts/site/theme.js
JavaScript
bsd-2-clause
1,965
(function () { 'use strict'; APP.GraphLib.getGraphStyle = function (ds_schema) { if (ds_schema === undefined || ds_schema.attributes === undefined) { return ""; } var dsAttrs = ds_schema.attributes; return dsAttrs.graph ? (dsAttrs.graph.style || "") : "" }; APP.GraphLib.datetimeFormats = function () { return { millisecond: '%H:%M:%S.%L<br>%e-%b-%y', second: '%H:%M:%S<br>%e-%b-%y', minute: '%H:%M:%S<br>%e-%b-%y', hour: '%H:%M<br>%e-%b-%y', day: '%e-%b-%Y', week: '%e-%b-%Y', month: '%b-%Y', year: '%Y' }; }; APP.GraphLib.getSeriesLastTime = function (chart) { var series = chart.series, series0 = series[0], lastTime; if (! series0.xData.length) { return 0; } lastTime = series0.xData[series0.xData.length-1]; return lastTime; }; })();
scion-network/scion_ui
app/scripts/libs/graph_utils.js
JavaScript
bsd-2-clause
1,011
window.playground = function() { 'use strict'; var chessboard; function createChessboard() { var rows = 8 , cols = 8 , r , c , chessboard; chessboard = new Array(rows); for (r = 0; r < rows; r = r + 1) { chessboard[r] = new Array(cols); for (c = 0; c < cols; c = c + 1) { chessboard[r][c] = 0; } } return chessboard; } chessboard = createChessboard(); mcl('createChessboard code', createChessboard); mcl('chessboard', chessboard); };
cjus/jsplayground
js/playground.js
JavaScript
bsd-2-clause
523
var class_grape_f_s_1_1_interface_f_u_s_e = [ [ "Create", "class_grape_f_s_1_1_interface_f_u_s_e.html#a387b9c196c23b9b3fc82e16b6aba612c", null ], [ "access", "class_grape_f_s_1_1_interface_f_u_s_e.html#a5231c684ce9603168127cb0a93163b42", null ], [ "chmod", "class_grape_f_s_1_1_interface_f_u_s_e.html#abf2b18e7db8d065aa4651647d9f8f83c", null ], [ "chown", "class_grape_f_s_1_1_interface_f_u_s_e.html#ac0b0f9f8dcffefbb06f73cc3fb851566", null ], [ "create", "class_grape_f_s_1_1_interface_f_u_s_e.html#ac0529208c1e3f0da605662e68e3d108f", null ], [ "getxattr", "class_grape_f_s_1_1_interface_f_u_s_e.html#ae9b4de889f93a27f07435421638b3896", null ], [ "listxattr", "class_grape_f_s_1_1_interface_f_u_s_e.html#aada4a4f4bf1cfe7bc196abf49c9f1945", null ], [ "mkdir", "class_grape_f_s_1_1_interface_f_u_s_e.html#a91e194e8720189346f37c76ef7a04a59", null ], [ "open", "class_grape_f_s_1_1_interface_f_u_s_e.html#ae5d5562e14d7c9eecf449a9fab41ac1f", null ], [ "opendir", "class_grape_f_s_1_1_interface_f_u_s_e.html#adce88ce2fb33684489325c7ae5188795", null ], [ "read", "class_grape_f_s_1_1_interface_f_u_s_e.html#a8f3d567a24b79df04fb94c4fcdd9e595", null ], [ "readdir", "class_grape_f_s_1_1_interface_f_u_s_e.html#a15e45636bab1c6ca445cd0b486a34aae", null ], [ "readlink", "class_grape_f_s_1_1_interface_f_u_s_e.html#a5abb4e4d13685eca2ac739726854c3dc", null ], [ "release", "class_grape_f_s_1_1_interface_f_u_s_e.html#ac4348478e67d97683d1c4e943837a4f6", null ], [ "releasedir", "class_grape_f_s_1_1_interface_f_u_s_e.html#a44f43b873f6f0e3cbd1da5c5b56674ef", null ], [ "removexattr", "class_grape_f_s_1_1_interface_f_u_s_e.html#a0bf83c8f99d040e426592c02fe8e4174", null ], [ "rename", "class_grape_f_s_1_1_interface_f_u_s_e.html#ab56682e5c1df4a9d7c3c823c3009c0b3", null ], [ "rmdir", "class_grape_f_s_1_1_interface_f_u_s_e.html#a17ae2cc37db891d8b36595ddfe03f642", null ], [ "setxattr", "class_grape_f_s_1_1_interface_f_u_s_e.html#a9a90b8e01206168335c9819027a5f981", null ], [ "statNode", "class_grape_f_s_1_1_interface_f_u_s_e.html#abe0b6d5e0b57f3680d775e763104a0e3", null ], [ "symlink", "class_grape_f_s_1_1_interface_f_u_s_e.html#afa12ed2afaaba65f0f76d7667f21754a", null ], [ "truncate", "class_grape_f_s_1_1_interface_f_u_s_e.html#a0aefac28b339dba9f4ec2b20f6d481e4", null ], [ "unlink", "class_grape_f_s_1_1_interface_f_u_s_e.html#a9afd3a87b02897c06e86f74145c2edb8", null ], [ "utime", "class_grape_f_s_1_1_interface_f_u_s_e.html#a219ea9228f6ed7c27ffb46bb20aa9489", null ], [ "write", "class_grape_f_s_1_1_interface_f_u_s_e.html#afd0709b21624ae0e3fb2a062ca606a92", null ] ];
crurik/GrapeFS
Doxygen/html/class_grape_f_s_1_1_interface_f_u_s_e.js
JavaScript
bsd-2-clause
2,663
/** * Copyright 2016 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f){ if (typeof define === 'function' && define.amd) { define(["kendo.core"], f); } else { f(); } }(function(){ (function( window, undefined ) { kendo.cultures["se"] = { name: "se", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-%n","%n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { name: "", abbr: "", pattern: ["$ -n","$ n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "kr" } }, calendars: { standard: { days: { names: ["sotnabeaivi","vuossárga","maŋŋebárga","gaskavahkku","duorastat","bearjadat","lávvardat"], namesAbbr: ["sotn","vuos","maŋ","gask","duor","bear","láv"], namesShort: ["s","v","m","g","d","b","l"] }, months: { names: ["ođđajagemánnu","guovvamánnu","njukčamánnu","cuoŋománnu","miessemánnu","geassemánnu","suoidnemánnu","borgemánnu","čakčamánnu","golggotmánnu","skábmamánnu","juovlamánnu"], namesAbbr: ["ođđj","guov","njuk","cuoŋ","mies","geas","suoi","borg","čakč","golg","skáb","juov"] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "dddd, MMMM d'. b. 'yyyy", F: "dddd, MMMM d'. b. 'yyyy HH:mm:ss", g: "dd.MM.yyyy HH:mm", G: "dd.MM.yyyy HH:mm:ss", m: "MMMM d'. b.'", M: "MMMM d'. b.'", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); }));
gngeorgiev/platform-friends
friends-hybrid/bower_components/kendo-ui/src/js/cultures/kendo.culture.se.js
JavaScript
bsd-2-clause
6,639
// Grunt build tasks for averylawfirm.com // // See also: package.json module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { // Environment: Development debug: { options: { style: 'expanded', debugInfo: false }, files: { 'public/css/common.css' : 'sass/common.scss', 'public/css/error.css' : 'sass/error.scss', 'public/css/mobile.css' : 'sass/mobile.scss', 'public/css/style.css' : 'sass/style.scss' } }, // Environment: Production release: { options: { style: 'compressed', debugInfo: false }, files: [{ expand: true, cwd: 'sass', src: ['*.scss'], dest: './public/css', ext: '.css' }] }, }, watch: { config: { files: [ 'Gruntfile.js', 'app.js', '.env*' ], options: { reload: true } }, templates: { files: [ 'views/*.jade' ], options: { livereload: true }, }, scripts: { files: [ 'lib/*.js', 'models/*.js', 'routes/*.js' ], options: { reload: true }, }, stylesheets: { files: [ 'sass/*.scss' ], tasks: ['sass'], options: { livereload: true }, }, }, jshint: { options: { reporter: require('jshint-stylish') }, all: [ 'app.js', 'Gruntfile.js', 'lib/**/*.js', 'models/*.js', 'routes/*.js' ], }, }); // Dependencies // https://github.com/gruntjs/grunt-contrib-watch grunt.loadNpmTasks('grunt-contrib-watch'); // https://github.com/gruntjs/grunt-contrib-sass grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('default', ['watch', 'sass:debug']); // TODO(jeff): Install validation lints for HTML, CSS, SASS and so on grunt.registerTask('lint', [ 'jshint' ]); // grunt.registerTask('runapp', ['shell:runapp']); // Sourced in package.json -- called from bin/heroku_deploy.sh grunt.registerTask('heroku', ['sass:release']); };
i8degrees/blew-infosys
Gruntfile.js
JavaScript
bsd-2-clause
2,317
(function ($) { $(function() { // Shortcut, if there isn't any change form if (!$('body').hasClass('change-form')) return; var LOCALIZED_FIELDS, ADMIN_URL, $translation_field; if (window.location.pathname.substr(-7) === 'change/') { // When inside Django /change/ url, step back two path increments ADMIN_URL = window.location.pathname + '../../localizedfields/'; } else { // When inside Django /add/ url (or others without a pk), step back one path increment ADMIN_URL = window.location.pathname + '../localizedfields/'; } $.getJSON(ADMIN_URL, function (data) { }) .done(function (data) { LOCALIZED_FIELDS = data; // Shortcut, if there isn't any data if (!LOCALIZED_FIELDS) return; $translation_field = $('div.field-translated_languages input'); if (window.location.search.match(/lang=(\w{2})/)) { visible_translations([LOCALIZED_FIELDS.default_language, RegExp.$1]); } $('fieldset.language').wrapAll('<div id="all_languages"/>'); // move default language to first position $('fieldset.language.' + LOCALIZED_FIELDS.default_language).prependTo($('#all_languages')); prepare_language_selector(); if (prepare_visibility_fields()) { prepare_fallback_checkbox(); } }) .fail(function () { console.error('API endpoint admin/localizedfields not found.'); }); function prepare_language_selector() { // add checkboxes to turn display of individual languages on and off var lang_selectors = '<div id="language-selector" class="inline-group">' + '<div class="form-row">' + LOCALIZED_FIELDS.translation_label + ': ', translations = visible_translations(); $.each(LOCALIZED_FIELDS.languages, function () { var lang = this[0], name = this[1]; // primary language can't be toggled if (lang == LOCALIZED_FIELDS.default_language) { return; } var show_fields_for_language = $.inArray(lang, translations) > -1; lang_selectors += '<input id="id_translation_show_' + lang + '" type="checkbox" value="' + lang + '" ' + (show_fields_for_language ? 'checked="checked"' : '') + ' /> ' + '<label for="id_translation_show_' + lang + '">' + name + ' (' + lang + ')</label>&nbsp;&nbsp;'; }); lang_selectors += '</div></div>'; $('.breadcrumbs').after(lang_selectors); $('#language-selector').on('click', 'input', function () { if ($(this).is(':checked')) { visible_translations(this.value); } else { visible_translations(undefined, this.value); } show_hide_elements() }); show_hide_elements() } function prepare_visibility_fields() { // add button to make all language versions visible $($('div[class*=field-visible][class*=field-box]')[0]) // before the first checkbox .before('<div class="field-box"><input id="id_visible_all" type="checkbox"> ' + '<label for="id_visible_all" class="vCheckboxLabel">Visible (all)</label></div>'); $('#id_visible_all').change(function () { if ($(this).is(':checked')) { $('input[name^=visible]').attr('checked', false); } else { $('input[name^=visible]').attr('checked', true); } }); $('input[name^=visible]').change(function () { // check or uncheck "all visible" checkbox when applicable if ($(this).is(':checked')) { if (!$('input[name^=visible]:not(:checked)').length) { $('#id_visible_all').attr('checked', true); } } else { $('#id_visible_all').attr('checked', false); } }).change(); return $('div.field-translated_languages').hide().length > 0; } function prepare_fallback_checkbox() { var fallback_toggle_label_color = $('fieldset.language h2').css('color'), fallback_title = LOCALIZED_FIELDS.fallback_label.replace(/\{language\}/, LOCALIZED_FIELDS.languages[0][1]), active = active_translations(); $.each(LOCALIZED_FIELDS.languages, function () { var lang = this[0], name = this[1], fallback_active = false; fallback_toggle_id = 'fallback-toggle-' + lang; if (lang == LOCALIZED_FIELDS.default_language) { return; } if ($.inArray(lang, active) == -1) { fallback_active = true; } else { $('#language-selector label[for=id_translation_show_' + lang + ']').addClass('translated'); } $fallback_toggle = $( '<div class="fallback-toggle">' + '<input type="checkbox" id="' + fallback_toggle_id + '" ' + (fallback_active ? 'checked="checked"' : '') + ' value="' + lang + '"/> <label style="color: ' + fallback_toggle_label_color + '" for=' + fallback_toggle_id + '>' + fallback_title + '</label>' + '</div>' ); $('fieldset.language.' + lang + ' h2').text(name).append($fallback_toggle); }); function align_objects() { var field_types = [ 'link', 'key_fact', 'document', 'title', 'tile', 'text', 'name', 'button', 'image', 'cropping', 'headline', 'teaser', 'black_overlay_text' ]; for (i = 0; i < field_types.length; i++) { $('div[class*=' + field_types[i] + ']').addClass('field-' + field_types[i]); } $.each($('fieldset'), function () { for (i = 0; i < field_types.length; i++) { $(this).find($('.field-' + field_types[i])).wrapAll("<div class='" + field_types[i] + "-wrapper' />"); } }); } align_objects(); $('#all_languages').on('click', '.fallback-toggle input', function () { var $this = $(this), lang = $this.val(), $lang_label = $('#language-selector label[for=id_translation_show_' + lang + ']'); if ($this.is(':checked')) { // remove from existing translations active_translations(undefined, lang); $lang_label.removeClass('translated'); } else { // activate language active_translations(lang); $lang_label.addClass('translated'); } show_hide_elements(); }); // update FeinCMS content blocks if (typeof(contentblock_init_handlers) != 'undefined') { contentblock_init_handlers.push(function () { show_hide_elements(); var def_lang_fields = $('#main > div fieldset.module:not(.lang-processed) > .form-row').filter(function () { return $(this).attr('class').indexOf('_' + LOCALIZED_FIELDS.default_language) > 0; }); // languages should be next to each in feincms contents // clear the left float on the primary language def_lang_fields.css('clear', 'left'); // prevent multiple execution def_lang_fields.each(function () { $(this).closest('fieldset').addClass('lang-processed'); }); }); } } function show_hide_elements() { var visible = visible_translations(), active = active_translations(); $('#all_languages, #main').css('width', 460 * (visible.length)); // loop over fields and show/hide as appropriate $.each(LOCALIZED_FIELDS.languages, function () { var lang = this[0], name = this[1]; if (lang == LOCALIZED_FIELDS.default_language) { return; } // hide elements where class name contains "_lang" (e.g. "_de") var $elements = $('fieldset.language.' + lang), $feincms_elements = $('div.item-content div.form-row') .filter('[class*="_' + lang + ' "], [class$="_' + lang + '"]'); if ($.inArray(lang, visible) > -1) { // show this language's fieldset $elements.show(); $feincms_elements.show(); if ((active === false) || ($.inArray(lang, active) > -1)) { // no visibility checking or language exists - show all fields $elements.find('.form-row').show(); $feincms_elements.css('visibility', 'visible'); if ($.show_tinymce !== undefined) { $.show_tinymce(); } } else { // language doesn't exist yet $elements.find('.form-row').hide(); $feincms_elements.css('visibility', 'hidden'); } } else { $elements.hide(); $feincms_elements.hide(); } }); } function visible_translations(add, remove) { var translations = (Cookies.get('admin_translations') || LOCALIZED_FIELDS.default_language).split(/,/); if (add || remove) { if (add && ($.inArray(add, translations) == -1)) { translations.push(add); } if (remove) { translations = $.grep(translations, function (v) { return v != remove }); } Cookies.set('admin_translations', translations.join(','), {path: '/'}); } return translations; } function active_translations(add, remove) { if (!$translation_field.length) { return false; } var translations = $translation_field.val().replace(/,,/g, ',').replace(/^,/, '').replace(/,$/, '').split(/,/); if (add || remove) { if (add && ($.inArray(add, translations) == -1)) { translations.push(add); $('#language-selector label[for=id_translation_show_' + add + ']').addClass('translated'); } if (remove) { translations = $.grep(translations, function (v) { return v != remove }); $('#language-selector label[for=id_translation_show_' + remove + ']').removeClass('translated'); } $translation_field.val(translations.join(',')); } return translations; } }); })(django.jQuery);
jonasundderwolf/django-localizedfields
localizedfields/static/localizedfields/localizedfields.js
JavaScript
bsd-3-clause
12,057
/** Created by charles.sexton on 2/26/2016 */ var webdriver = require('selenium-webdriver'); var IllegalArgumentError = require('../src/errors/IllegalArgumentError'); var FrameHandler = function(driver) { var driver = driver.getDriver(); this.switchToFrame = function(name) { if (typeof name !== 'string' || name === '' || !name) { throw new IllegalArgumentError('Please enter a valid name for the switch to frame.'); } else { return driver.switchTo().frame(name); } }; this.getCurrentFrameName = function() { return driver.executeScript('return self.name').then(function(name) { return name; }); }; this.switchToParentFrame = function() { var currentFrameName = this.getCurrentFrameName(); driver.findElements(webdriver.By.css('frame')).then(function(frames) { console.log(frames); for(var i = 0; i < frames.length; i++) { console.log(frames[i].name); if(frames[i].name === currentFrameName && i > 0) { console.log(frames[i].name); return driver.switchTo().frame(frames[i - 1].name); } } }); }; this.switchToParentIFrame = function() { driver.findElements(webdriver.By.css('iframe')).then(function(frames) { return }) } }; module.exports = FrameHandler;
Orasi/JS-Selenium-Toolkit
JS-Selenium-Toolkit/src/FrameHandler.js
JavaScript
bsd-3-clause
1,482
'use strict'; // Based on Resig's pretty date function prettyDate(time) { var diff = (Date.now() - time) / 1000; var day_diff = Math.floor(diff / 86400); if (isNaN(day_diff)) return '(incorrect date)'; if (day_diff < 0 || diff < 0) { // future time return (new Date(time)).toLocaleFormat('%x %R'); } return day_diff == 0 && ( diff < 60 && 'Just Now' || diff < 120 && '1 Minute Ago' || diff < 3600 && Math.floor(diff / 60) + ' Minutes Ago' || diff < 7200 && '1 Hour Ago' || diff < 86400 && Math.floor(diff / 3600) + ' Hours Ago') || day_diff == 1 && 'Yesterday' || day_diff < 7 && (new Date(time)).toLocaleFormat('%A') || (new Date(time)).toLocaleFormat('%x'); } (function() { var updatePrettyDate = function updatePrettyDate() { var labels = document.querySelectorAll('[data-time]'); var i = labels.length; while (i--) { labels[i].textContent = prettyDate(labels[i].dataset.time); } }; var timer = setInterval(updatePrettyDate, 60 * 1000); window.addEventListener('message', function visibleAppUpdatePrettyDate(evt) { var data = evt.data; if (data.message !== 'visibilitychange') return; clearTimeout(timer); if (!data.hidden) { updatePrettyDate(); timer = setInterval(updatePrettyDate, 60 * 1000); } }); })();
yurydelendik/gaia
apps/dialer/js/helper.js
JavaScript
bsd-3-clause
1,343
const models = require('../../../models/index'); const User = models.User; const Contact = models.Contact; module.exports = { getPendingContactRequests: function (socket, json) { User.find({ where: { userid: json.userid } }).then(user => { return Contact.findAll({ where : {contact: user.userid, status: 'PENDING'} }).then(contacts => { let userIDs = []; for (let c of contacts) userIDs.push(c.user); return User.findAll({ where: {userid: {$in: userIDs}} }).then(userContacts => { let resp = []; for (let uc of userContacts) resp.push(uc.responsify()); socket.write(JSON.stringify({ ACTION: 'GET_PENDING_CONTACT_REQUEST', CONTACTS: resp }) + '\n'); }).catch(err => { console.log(err); socket.write(JSON.stringify({request: 'ERROR - sockGetPendingContactRequests C'}) + '\n'); }); }).catch(err => { console.log(err); socket.write(JSON.stringify({request: 'ERROR - sockGetPendingContactRequests B'}) + '\n'); }); }).catch(err => { console.log(err); socket.write(JSON.stringify({request: 'ERROR - sockGetPendingContactRequests A'}) + '\n'); }); } };
AntoineJanvier/Slyx
Server/tools/socketManagement/contacts/getPendingContactRequests.js
JavaScript
bsd-3-clause
1,547
function propertiesViewModel () { var self = this; // TODO: make function to map properties with test self.showPropertyPanels = ko.observable(false); self.propertyList = ko.observableArray(); self.showEditPanel = ko.observable(false); self.showDetailPanel = ko.observable(false); self.showCreatePanel = ko.observable(false); self.showDrawHelpPanel = ko.observable(false); self.showUploadPanel = ko.observable(false); self.drawingActivated = ko.observable(false); self.preventUpdates = ko.observable(false); self.showPropertyList = ko.observable(true); self.showNoPropertiesHelp = ko.observable(true); self.selectedProperty = ko.observable(); self.actionPanelType = ko.observable(false); self.selectProperty = function (property, event, zoomTo) { var bbox = OpenLayers.Bounds.fromArray(property.bbox()); // TODO: Make active! if (! self.preventUpdates()) { if (event) { $(event.target).closest('tr'); // .addClass('active') // .siblings().removeClass('active'); app.selectFeature.unselectAll(); app.selectFeature.select(property.feature); } // set the selected property for the viewmodel self.selectedProperty(property); //for global tabs app.selectedPropertyName(self.selectedProperty().name()); app.selectedPropertyUID(self.selectedProperty().uid()); app.updateUrlProperty(self.selectedProperty().uid()); self.showDetailPanel(true); //zoom the map to the selected property map.zoomToExtent(bbox); } }; self.selectPropertyByUID = function (uid, zoomTo) { $.each(self.propertyList(), function (i, property) { if (property.uid() === uid) { self.selectProperty(property, null, zoomTo); } }); // learning knockout fail - wm app.selectedPropertyUID(uid); }; self.zoomToExtent = function () { bounds = app.property_layer.getDataExtent(); if (!bounds) { bounds = app.bounds; } map.zoomToExtent(bounds); }; self.cleanupForm = function ($form) { // remove the submit button, strip out the geometry $form .find('input:submit').remove().end() .find('#id_geometry_final').closest('.field').remove(); // put the form in a well and focus the first field $form.addClass('well'); $form.find('.field').each(function () { var $this = $(this); // add the bootstrap classes $this.addClass('control-group'); $this.find('label').addClass('control-label'); $this.find('input').wrap($('<div/>', { "class": "controls"})); $this.find('.controls').append($('<p/>', { "class": "help-block"})); }); $form.find('input:visible').first().focus(); }; self.showEditForm = function () { var formUrl = '/features/forestproperty/{uid}/form/'.replace('{uid}', self.selectedProperty().uid()); $.get(formUrl, function (data) { var $form = $(data).find('form'); self.cleanupForm($form); // show the form in the panel self.showDetailPanel(false); self.showEditPanel(true); self.preventUpdates(true); $('#edit-panel').empty().append($form); $form.find('input:visible:first').focus(); $form.bind('submit', function (event) { event.preventDefault(); self.updateFeature(self, event); }); app.modifyFeature.selectFeature(self.selectedProperty().feature); app.modifyFeature.activate(); self.showPropertyList(false); }); }; self.startAddDrawing = function () { self.showDetailPanel(false); self.showDrawHelpPanel(true); self.drawingActivated(true); self.showNoPropertiesHelp(false); self.preventUpdates(true); app.drawFeature.activate(); self.showPropertyList(false); }; self.startUpload = function () { self.showDetailPanel(false); self.showUploadPanel(true); self.showNoPropertiesHelp(false); self.preventUpdates(true); self.showPropertyList(false); }; self.showAddForm = function () { var formUrl = '/features/forestproperty/form/'; $.get(formUrl, function (data) { var $form = $(data).find('form'); self.cleanupForm($form); // show the form in a modal self.showDetailPanel(false); self.showCreatePanel(true); $('#create-panel').empty().append($form); $form.find('input:visible:first').focus(); $form.bind('submit', function (event) { event.preventDefault(); self.addFeature(self, event); }); }); }; self.addFeature = function (self, event) { self.saveFeature(event, null, app.newGeometry); }; app.saveFeature = function (f) { app.newGeometry = f.geometry.toString(); self.showAddForm(); }; self.updateFeature = function (self, event) { var geometry = app.modifyFeature.feature.geometry.toString(); self.saveFeature(event, self.selectedProperty(), geometry); }; self.saveFeature = function (event, property, geometry) { var $dialog = $(event.target).closest('.form-panel'), $form = $dialog.find('form'), actionUrl = $form.attr('action'), values = {}, error=false; $form.find('input').each(function () { var $input = $(this); if ($input.closest('.field').hasClass('required') && $input.attr('type') !== 'hidden' && ! $input.val()) { error = true; $input.closest('.control-group').addClass('error'); $input.siblings('p.help-block').text('This field is required.'); } else { values[$input.attr('name')] = $input.val(); } }); $form.find('select').each(function () { var $select = $(this); if ($select.closest('.field').hasClass('required') && $select.attr('type') !== 'hidden' && ! $select.val()) { error = true; $select.closest('.control-group').addClass('error'); $select.siblings('p.help-block').text('This field is required.'); } else { option = $select[0].children[$select[0].selectedIndex]; values[$select.attr('name')] = option.value; } }); if (error) { return false; } if (geometry.indexOf("POLY") === 0) { // Properties expect multipolygons even if only a single polygon was digitized geometry = geometry.replace("POLYGON", "MULTIPOLYGON(") + ")"; } values.geometry_final = geometry; $form.addClass('form-horizontal'); self.showEditPanel(false); self.showCreatePanel(false); self.preventUpdates(false); $.ajax({ url: actionUrl, type: "POST", data: values, success: function (data, textStatus, jqXHR) { // property is not defined if new self.updateOrCreateProperty(JSON.parse(data), property); self.showPropertyList(true); app.drawFeature.deactivate(); app.modifyFeature.deactivate(); self.showNoPropertiesHelp(false); app.new_features.removeAllFeatures(); app.setTabs(); }, error: function (jqXHR, textStatus, errorThrown) { alert("Failed to save property drawing: " + errorThrown); self.cancelEdit(self); } }); }; self.updateOrCreateProperty = function (data, property) { var updateUrl = '/features/generic-links/links/geojson/{uid}/'.replace('{uid}', data["X-Madrona-Select"]); $.get(updateUrl, function (data) { var newPropertyVM, newProperty = data.features[0].properties; if (property) { // updating existing property ko.mapping.fromJS(newProperty, property); self.selectProperty(property); } else { // add a new property self.selectPropertyByUID(data.features[0].uid); app.property_layer.addFeatures(app.geojson_format.read(data)); } }); }; self.showDeleteDialog = function () { $("#delete-dialog").modal("show"); }; self.editStands = function () { window.location.hash = "#stands"; }; self.deleteFeature = function () { var url = "/features/generic-links/links/delete/{uid}/".replace("{uid}", self.selectedProperty().uid()); $('#delete-dialog').modal('hide'); self.showEditPanel(false); self.showCreatePanel(false); self.showDetailPanel(true); self.preventUpdates(false); $.ajax({ url: url, type: "DELETE", success: function (data, textStatus, jqXHR) { app.modifyFeature.deactivate(); app.property_layer.removeFeatures(self.selectedProperty().feature); self.propertyList.remove(self.selectedProperty()); if (self.propertyList().length) { app.selectedPropertyName(""); app.selectedPropertyUID(""); self.selectProperty(self.propertyList()[0]); window.location.hash = "#properties"; //$("#properties-list tbody").find('tr').first().not(':only-child').addClass('active'); } else { self.showDetailPanel(false); self.showNoPropertiesHelp(true); app.selectedPropertyName(""); app.selectedPropertyUID(""); window.location.hash = "#properties"; } map.updateSize(); } }); }; self.closeDialog = function (self, event) { $(event.target).closest(".modal").modal("hide"); }; self.cancelEdit = function (self, event) { self.showEditPanel(false); self.showCreatePanel(false); self.showDrawHelpPanel(false); self.preventUpdates(false); self.showNoPropertiesHelp(self.propertyList().length ? false: true); app.modifyFeature.resetVertices(); app.modifyFeature.deactivate(); app.drawFeature.deactivate(); self.showDetailPanel(self.propertyList().length ? true: false); app.new_features.removeAllFeatures(); self.showPropertyList(true); }; self.afterUploadSuccess = function(data) { var property; // undefined ~> new self.updateOrCreateProperty(data, property); self.showEditPanel(false); self.showCreatePanel(false); self.showUploadPanel(false); self.preventUpdates(false); self.showNoPropertiesHelp(self.propertyList().length ? false: true); self.showDetailPanel(self.propertyList().length ? true: false); self.showPropertyList(true); self.selectPropertyByUID(data['X-Madrona-Select']); }; self.cancelUpload = function (self, event) { self.showEditPanel(false); self.showCreatePanel(false); self.showUploadPanel(false); self.preventUpdates(false); self.showNoPropertiesHelp(self.propertyList().length ? false: true); self.showDetailPanel(self.propertyList().length ? true: false); self.showPropertyList(true); }; self.manageStands = function (self, event) { // create active property layer // copy active property to new layer // hide other properties // initialize stand manager // it's possible to get here via tab click instead of from a property detail button if(self.propertyList()[0] == undefined){ alert('Please create a property first!'); window.location.hash = "#properties"; return; } if(self.selectedProperty() == undefined){ self.selectedProperty(self.propertyList()[0]); } if (app.stands.viewModel) { app.stands.viewModel.reloadStands(self.selectedProperty()); } else { if ( !self.selectedProperty() ){ alert('Please create a property first!'); window.location.hash = "#properties"; return; } else{ app.stands.viewModel = new standsViewModel(); app.stands.viewModel.initialize(self.selectedProperty()); } } //for global tabs app.selectedPropertyName(self.selectedProperty().name()); // hide property panels app.stands.viewModel.showStandPanels(true); self.showPropertyPanels(false); }; self.manageScenarios = function (self, event) { if(self.propertyList()[0] == undefined){ alert('Please create a property first!'); window.location.hash = "#properties"; return; } if (app.scenarios.viewModel) { app.scenarios.viewModel.reloadScenarios(self.selectedProperty()); } else { app.scenarios.viewModel = new scenarioViewModel(); app.scenarios.viewModel.initialize(self.selectedProperty()); } app.scenarios.viewModel.selectedFeatures.removeAll(); // hide property panels app.scenarios.viewModel.showScenarioPanels(true); if (app.stands.viewModel) { app.stands.viewModel.showStandPanels(false); } self.showPropertyPanels(false); $('#map').hide(); $('#searchbox-container').hide(); $('#legend-container').hide(); $('#legend-button').hide(); $('#scenario-outputs').fadeIn(); }; self.loadPropertiesFromServer = $.get('/trees/user_property_list/'); // initialize properties and vm // return request object to apply bindings when done self.init = function () { return $.when(self.loadPropertiesFromServer).then(function(data){ self.showPropertyPanels(true); app.bounds = OpenLayers.Bounds.fromArray(data.features.length > 0 ? data.bbox : [-13954802.50397, 5681411.4375898, -13527672.389972, 5939462.8450446]); map.zoomToExtent(app.bounds); // bind event to selected feature app.properties.featureAdded = function (feature) { app.drawFeature.deactivate(); self.showDrawHelpPanel(false); app.saveFeature(feature); }; app.drawFeature.featureAdded = app.properties.featureAdded; // map interaction callbacks app.property_layer.events.on({ 'featureselected': function (feature) { self.selectPropertyByUID(feature.feature.data.uid, true); }, 'featureadded': function (feature) { var featureViewModel = ko.mapping.fromJS(feature.feature.data); // save a reference to the feature featureViewModel.feature = feature.feature; // add it to the viewmodel self.propertyList.unshift(featureViewModel); }, 'featuresadded': function (data) { self.showNoPropertiesHelp(false); // if only adding one layer, select and zoom // otherwise just select the last one and zoom to the full extent of the layer if (data.features.length === 1) { self.selectPropertyByUID(data.features[0].data.uid); } else if( window.location.hash.indexOf('/') > 1){ // hash may contain a property uid. If so, make that the selected property if( window.location.hash.split('/')[1].indexOf('trees') == 0){ self.selectPropertyByUID(window.location.hash.split('/')[1]); } } else { self.selectPropertyByUID(data.features[data.features.length-1].data.uid); } } }); // add the features to the map and trigger the callbacks if (data.features.length) { app.property_layer.addFeatures(app.geojson_format.read(data)); } app.onResize(); self.zoomToExtent(); }); }; }
Ecotrust/forestplanner
media/common/property.js
JavaScript
bsd-3-clause
14,934
/*! * remark v1.0.7 (http://getbootstrapadmin.com/remark) * Copyright 2015 amazingsurge * Licensed under the Themeforest Standard Licenses */ $.components.register("slidePanel",{mode:"manual",defaults:{closeSelector:".slidePanel-close",mouseDragHandler:".slidePanel-handler",loading:{template:function(options){return'<div class="'+options.classes.loading+'"><div class="loader loader-default"></div></div>'},showCallback:function(options){this.$el.addClass(options.classes.loading+"-show")},hideCallback:function(options){this.$el.removeClass(options.classes.loading+"-show")}}}});
afquinterog/mkitserverapp
web/js/components/slidepanel.min.js
JavaScript
bsd-3-clause
586
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. load('../base.js'); load('toNumber.js'); load('toLocaleString.js'); load('toHexString.js'); function PrintResult(name, result) { console.log(name); console.log(name + '-Numbers(Score): ' + result); } function PrintError(name, error) { PrintResult(name, error); } BenchmarkSuite.config.doWarmup = undefined; BenchmarkSuite.config.doDeterministic = undefined; BenchmarkSuite.RunSuites({ NotifyResult: PrintResult, NotifyError: PrintError });
youtube/cobalt
third_party/v8/test/js-perf-test/Numbers/run.js
JavaScript
bsd-3-clause
644
/** * 微信相关 js 收集整理 * */ // 判断用户是不是用微信打开了浏览器 // @see: https://gist.github.com/anhulife/8470534 function isWeixinBrowser(){ // 截至2014年2月12日,这个方法不能测试 windows phone 中的微信浏览器 return (/MicroMessenger/i).test(window.navigator.userAgent); } // 方法二 var _is_weixin_browser = 0; document.addEventListener('WeixinJSBridgeReady', function(){ //如果执行到这块的代码,就说明是在微信内部浏览器内打开的. _is_weixin_browser = 1; console.log('当前页面在微信内嵌浏览器中打开!'); }); // 屏蔽和打开微信分享按钮 var invoke_wx = function(invoke_func){ if (typeof WeixinJSBridge == "undefined") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', invoke_func, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', invoke_func); document.attachEvent('onWeixinJSBridgeReady', invoke_func); } } else { invoke_func(); } } var switch_wx_share = {} switch_wx_share.opt = 'show'; switch_wx_share.set_opt = function(opt) { this.opt = opt; } switch_wx_share.invoke = function(){ var flag = 'show' == this.opt ? 'showOptionMenu' : 'hideOptionMenu'; WeixinJSBridge.call(flag); if ('show' != opt) { WeixinJSBridge.call('hideToolbar'); } } switch_wx_share.show = function(){ /** 此处不能使用 this, 在微信的回调中, this 的指向不明,会导致调用失败 */ switch_wx_share.set_opt('show'); switch_wx_share.invoke(); } switch_wx_share.hide = function(){ switch_wx_share.set_opt('hide'); switch_wx_share.invoke(); } invoke_wx(switch_wx_share.hide); setTimeout(function(){ invoke_wx(switch_wx_share.show); }, 5000);
hy0kl/study
js/wx.js
JavaScript
bsd-3-clause
1,899
var path = require('path'); module.exports = { entry: './input', output: { filename: 'output.js', }, resolve: { root: path.resolve('../../../build/packages'), alias: { 'react': 'react/dist/react', 'react-dom': 'react-dom/dist/react-dom', }, }, };
sekiyaeiji/react
fixtures/packaging/webpack-alias/config.js
JavaScript
bsd-3-clause
286
//= require admin/spree_core //= require admin/jquery.uploadify
meinekleinefarm/spree_mkf_theme
app/assets/javascripts/admin/spree_mkf_theme.js
JavaScript
bsd-3-clause
65
define(["jquery"], function ($) { /*** * Displays an overlay on top of a given cell range. * * TODO: * Currently, it blocks mouse events to DOM nodes behind it. * Use FF and WebKit-specific "pointer-events" CSS style, or some kind of event forwarding. * Could also construct the borders separately using 4 individual DIVs. * * @param {Grid} grid * @param {Object} options */ function CellRangeDecorator(grid, options) { var _elem; var _defaults = { selectionCssClass: 'bk-slick-range-decorator', selectionCss: { "zIndex": "9999", "border": "2px dashed red" } }; options = $.extend(true, {}, _defaults, options); function show(range) { if (!_elem) { _elem = $("<div></div>", {css: options.selectionCss}) .addClass(options.selectionCssClass) .css("position", "absolute") .appendTo(grid.getCanvasNode()); } var from = grid.getCellNodeBox(range.fromRow, range.fromCell); var to = grid.getCellNodeBox(range.toRow, range.toCell); _elem.css({ top: from.top - 1, left: from.left - 1, height: to.bottom - from.top - 2, width: to.right - from.left - 2 }); return _elem; } function hide() { if (_elem) { _elem.remove(); _elem = null; } } $.extend(this, { "show": show, "hide": hide }); } return CellRangeDecorator; });
almarklein/bokeh
bokehjs/src/vendor/slick-grid-2.1.0/plugins/slick.cellrangedecorator.js
JavaScript
bsd-3-clause
1,488
var searchData= [ ['junctiontreetype',['JunctionTreeType',['../a00073.html#a09b40d82e5be58829294d734b90e74cb',1,'gtsam::EliminateableFactorGraph::JunctionTreeType()'],['../a00075.html#a3105cd6512d1674d6d433034c87b4e0c',1,'gtsam::EliminationTraits&lt; DiscreteFactorGraph &gt;::JunctionTreeType()'],['../a00076.html#ac9a6d5a1e133796f4ef7957aced8c785',1,'gtsam::EliminationTraits&lt; GaussianFactorGraph &gt;::JunctionTreeType()']]] ];
devbharat/gtsam
doc/html/search/typedefs_7.js
JavaScript
bsd-3-clause
436
var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var config = require('./webpack.config'); new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, }).listen(3000, 'localhost', function(err, result) { });
comlewod/document
pages/tests/server.js
JavaScript
bsd-3-clause
279
/** * * Changes the current plate name * **/ function change_plate_name() { $('#updateNameBtn').prop('disabled', true).find('span').addClass('glyphicon glyphicon-refresh gly-spin'); $('#newNameInput').prop('disabled', true); var value = $('#newNameInput').val().trim(); var plateId = $('#plateName').prop('pm-data-plate-id'); if (plateId !== undefined) { // Modifying a plate that already exists, ask the server to change the // plate configuration $.ajax({url: '/plate/' + plateId + '/', type: 'PATCH', data: {'op': 'replace', 'path': '/name', 'value': value}, success: function (data) { $('#plateName').html(value); $('#updatePlateName').modal('hide'); }, error: function (jqXHR, textStatus, errorThrown) { bootstrapAlert(jqXHR.responseText, 'danger'); $('#updatePlateName').modal('hide'); } }); } else { $('#plateName').html(value); $('#updatePlateName').modal('hide'); } // This is only needed when the modal was open for first time automatically when // creating a new plate. However, it doesn't hurt having it here executed always $('#updatePlateNameCloseBtn').prop('hidden', false); $('#updatePlateName').data('bs.modal').options.keyboard = true; $('#updatePlateName').data('bs.modal').options.backdrop = true; // Remove the cancel button from the modal $('#cancelUpdateNameBtn').remove(); }; /** * * Adds a study to the plating procedure * * @param {integer} studyId Id of the study to add * **/ function add_study(studyId) { $.get('/study/' + studyId + '/', function (data) { // Create the element containing the study information and add it to the list var $aElem = $("<a href='#' onclick='activate_study(" + studyId + ")'>"); $aElem.addClass('list-group-item').addClass('study-list-item'); $aElem.attr('id', 'study-' + studyId); $aElem.attr('pm-data-study-id', studyId); $aElem.append('<label><h4>' + data.study_title + '</h4></label>'); $aElem.append(' Total Samples: ' + data.total_samples); var $buttonElem = $("<button class='btn btn-danger btn-circle pull-right' onclick='remove_study(" + studyId + ");'>"); $buttonElem.append("<span class='glyphicon glyphicon-remove'></span>") $aElem.append($buttonElem); $('#study-list').append($aElem); if($('#study-list').children().length === 1) { activate_study(studyId); } // Disable the button to add the study to the list $('#addBtnStudy' + studyId).prop('disabled', true); // Hide the modal to add studies $('#addStudyModal').modal('hide'); }) .fail(function (jqXHR, textStatus, errorThrown) { bootstrapAlert(jqXHR.responseText, 'danger'); $('#addStudyModal').modal('hide'); }); }; /** * * Removes a study from the plating procedure * * @param {integer} studyId Id of the study to remove * **/ function remove_study(studyId) { // Remove the study from the list: $('#study-' + studyId).remove(); // Re-enable the button to add the study to the list $('#addBtnStudy' + studyId).prop('disabled', false); } function activate_study(studyId) { var $elem = $('#study-' + studyId); if ($elem.hasClass('active')) { // If the current element already has the active class, remove it, // so no study is active $elem.removeClass('active'); } else { // Otherwise choose the curernt study as the active $elem.parent().find('a').removeClass('active'); $elem.addClass('active'); } } /** * * Changes the configuration of a plate * **/ function change_plate_configuration() { var pv, $opt; $opt = $('#plate-conf-select option:selected'); var plateId = $('#plateName').prop('pm-data-plate-id'); if (plateId !== undefined) { throw "Can't change the plate configuration of an existing plate" } else { pv = new PlateViewer('plate-map-div', undefined, undefined, $opt.attr('pm-data-rows'), $opt.attr('pm-data-cols')); } }
josenavas/labman
labman/gui/static/js/plate.js
JavaScript
bsd-3-clause
4,011
/** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import FormatDateFormatter from './format-date'; /** * @private * @hide */ export default class FormatTime extends FormatDateFormatter {}
yahoo/ember-intl
addon/-private/formatters/format-time.js
JavaScript
bsd-3-clause
277
// vim:ts=4:sw=4:expandtab x11vis = (function() { var used_names = []; var details = {}; function type_to_color(type) { if (type === 'event') { return '#ffffc0'; } else if (type === 'reply') { return '#c0ffc0'; } else if (type === 'error') { return '#ffc0c0'; } else { return '#c0c0c0'; } } // TODO: formatting needs to be more beautiful function detail_obj_to_html(obj, indent) { var result = ''; $.each(obj, function(key, val) { var formatted_value; if (val === null) { formatted_value = ""; } else if (typeof(val) === 'object') { formatted_value = detail_obj_to_html(val, indent + 1); } else { formatted_value = val; } result += '<p style="margin-left: ' + indent + 'em"><strong>' + key + '</strong>: ' + formatted_value + '</p>'; }); return result; } function toggle_expand_packet(pkt) { var html = $(pkt).find('.moredetails') // if it's visible, hide it if (html.css('display') === 'block') { html.css('display', 'none'); } else { // otherwise, format the details (if not expanded) and show it if ($(pkt).data('expanded') === undefined) { html.append(detail_obj_to_html($(pkt).data('moredetails'), 0)); $(pkt).data('expanded', true); } html.css('display', 'block'); } } function create_request_layout(obj) { // concat'ing strings instead of using the DOM saves us ~ 350 ms // (measured with 547 bursts of a typical i3 startup) var html = '<div class="request singlepacket" style="background-color: ' + type_to_color(obj.type) + '">\ <div class="expandbtn"></div>\ <span class="sequence">' + obj.seq + '</span>\ <span class="name">' + obj.name + '</span>\ <span class="details">' + parse_detail(obj.details) + '</span>\ <span class="moredetails"></span>\ </div>\ '; var rdiv = $(html); // store object type and moredetails for later (used type_to_color and // detail_obj_to_html, respectively) rdiv.data('type', obj.type); rdiv.data('moredetails', obj.moredetails); return rdiv; } function parse_detail(detail) { var result = detail; var matches = detail.match(/%([^%]+)%/g) || []; var c = matches.length; while (c--) { var id = matches[c].replace(/%/g, ''); result = result.replace(matches[c], '<span class="id_name" id="' + id + '"></span>'); } return result; } function save_cleverness(obj) { //console.log('obj is clever: ' + obj.id + ' to ' + obj.title); var title = obj.title; var cnt = 2; while ($.inArray(title, used_names) !== -1) { title = obj.title + ' (' + cnt + ')'; cnt = cnt + 1; } obj.title = title; used_names.push(title); details[obj.id] = obj; } function handle_marker(marker) { var div = $(tmpl.get('marker')); div.find("span.name").replaceWith(marker.title); $('body').append(div); } function handle_burst(burst) { // TODO: what about zero-length bursts? if (burst.packets.length === 0) { return; } var div = $(tmpl.get('request_buffer')); div.find(".request_info").append(burst.elapsed); if (burst.direction === 'to_client') { div.css('margin-left', '2em'); div.find(".client").replaceWith(parse_detail('%conn_' + burst.fd + '%←')); } else { div.find(".client").replaceWith(parse_detail('%conn_' + burst.fd + '%→')); div.css('margin-right', '2em'); } var len = burst.packets.length; for (var c = 0; c < len; c++) { var obj = burst.packets[c]; if (obj.type === 'cleverness') { save_cleverness(obj); } else { div.append(create_request_layout(obj)); } } $('body').append(div); } function update_hide_packets() { // add all event types (once) to the 'hide'-panel // TODO: group by type // TODO: start with collapsed 'hide' panel var t = _.map($('span.name'), function(elm) { return $(elm).text(); }); t.sort(); $.each(_.uniq(t, true), function(idx, elm) { var cb = $('<input type="checkbox" class="display_cb" id="display_cb_' + idx + '" checked="checked"><label for="display_cb_' + idx + '">' + elm + '</label><br>'); cb.data('element', elm); $('div#display').append(cb); }); $('input.display_cb').click(function() { var elm = $(this).data('element'); $("span.name:contains('" + elm + "')") .parent() .css('display', ($(this).attr('checked') ? 'block' : 'none')); }); } function update_hide_clients() { // add all clients (once) to 'hide' panel t = _.map($('div.reqbuf .header .id_name'), function (elm) { return $(elm).attr('id'); }); t.sort(); $.each(_.uniq(t, true), function(idx, elm) { console.log('client: ' + elm); var cb = $('<input type="checkbox" class="client_cb" id="client_cb_' + idx + '" checked="checked"><label for="client_cb_' + idx + '">' + parse_detail('%' + elm + '%') + '</label><br>'); cb.data('element', elm); $('div#filter_clients').append(cb); }); $('input.client_cb').click(function() { var elm = $(this).data('element'); $('div.reqbuf .header .id_name#' + elm) .parent() .parent() .css('display', ($(this).attr('checked') ? 'block' : 'none')); }); } function fold_boring_packets() { // TODO: marking packets for folding could be done in the interceptor // go through all reqbufs and fold series of 'boring' requests (like InternAtom) var boring_packets = [ 'InternAtom', 'GrabKey', 'ImageText8', 'ImageText16' ]; $('div.reqbuf').each(function() { var last_name = ''; var to_fold = []; var samecnt = 0; var singlepkts = $(this).find('div.singlepacket span.name'); var len = singlepkts.length; if (len < 5) { return; } var c = len; while (c--) { var name = $(singlepkts[c]).text(); if ($.inArray(name, to_fold) !== -1) { continue; } samecnt = (last_name === name ? samecnt + 1 : 0); if (samecnt === 5 && $.inArray(last_name, boring_packets) !== -1) { // more than 5 packets of the same type, fold them to_fold.push(last_name); } last_name = name; } var that = this; $.each(to_fold, function(idx, elm) { var folded = $('<div class="folded"></div>'); var info = $('<div class="folded_info"><img src="/toggle-expand.gif"> lots of <strong>' + elm + '</strong></div>'); var to_expand = $('<div class="to_expand" style="display: none"></div>'); var elements = $(that).find('div.singlepacket span.name:econtains("' + elm + '")').parent(); var type = elements.first().data('type'); folded.data('type', type); folded.css('background-color', type_to_color(type)); info.append(' (' + elements.size() + ' packets folded)'); elements.wrapAll(to_expand); $(that).find('.to_expand') .wrap(folded) .parent() .prepend(info); }); }); } function setup_expand_button() { // set up the expand button $('.singlepacket').live('click', function() { toggle_expand_packet(this); }); $('.folded_info').live('click', function() { var to_expand = $(this).parent().find('.to_expand'); if (to_expand.css('display') === 'block') { to_expand.css('display', 'none'); } else { to_expand.css('display', 'block'); } }); // TODO: only show button if the request has details $('.request.singlepacket, .folded').each(function() { $(this).hover(function() { var expandBtn = $(this).children('.expandbtn'); // if the expand image is not yet loaded, add it if (expandBtn.find('img').size() === 0) { expandBtn.append($('<img src="/toggle-expand.gif">')); } expandBtn.find('img').css('display', 'inline'); $(this).css('background-color', '#eff8c6'); }, function() { $(this).find('.expandbtn img').css('display', 'none'); $(this).css('background-color', type_to_color($(this).data('type'))); }); }); } function display_cleverness() { // resolve all the cleverness placeholders var cleverspans = $('span.id_name'); var c = cleverspans.length; while (c--) { var t = $(cleverspans[c]); var id = t.attr('id'); if (details[id] !== undefined) { t.append(details[id].title); if (details[id].idtype === 'atom') { t.css('background-color', '#82caff'); } else if (details[id].idtype === 'font') { t.css('background-color', '#f87217'); } else if (details[id].idtype === 'pixmap') { t.css('background-color', '#d462ff'); } else if (details[id].idtype === 'gcontext') { t.css('background-color', '#f433ff'); } else { t.css('background-color', '#f75d59'); } } else { t.append(id); } } } var process_json = function(json) { var len = json.length; for (var c = 0; c < len; c++) { var obj = json[c]; if (obj.type === 'cleverness') { save_cleverness(obj); } else if (obj.type === 'marker') { handle_marker(obj); } else { handle_burst(obj); } } update_hide_packets(); update_hide_clients(); fold_boring_packets(); setup_expand_button(); display_cleverness(); // initialize the markerbar markerbar().update(); }; var process_cleverness = function(json) { json.forEach(function(obj) { save_cleverness(obj); }); }; return function() { return { process_json: process_json, process_cleverness: process_cleverness }; }; })();
x11vis/x11vis
gui/x11vis.js
JavaScript
bsd-3-clause
11,369
"use strict"; module.exports = (sequelize, DataTypes) => { const AcWatching = sequelize.define("AcWatching", { priority: { type: DataTypes.INTEGER, allowNull: false }, type: { type: DataTypes.INTEGER, allowNull: false }, deleted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false } }, { defaultScope: { where: { deleted: false } }, timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', underscored: true, tableName: 'ac_watching' }); AcWatching.associate = (models) => { AcWatching.belongsTo(models.Domain,{ foreignKey: 'domain_id' }); AcWatching.belongsTo(models.Community,{ foreignKey: 'community_id' }); AcWatching.belongsTo(models.Group,{ foreignKey: 'group_id' }); AcWatching.belongsTo(models.Post,{ foreignKey: 'post_id' }); AcWatching.belongsTo(models.Point,{ foreignKey: 'point_id' }); AcWatching.belongsTo(models.User,{ foreignKey: 'user_id' }); AcWatching.belongsTo(models.User, { as: 'WatchingUser' }); }; AcWatching.watchCommunity = function(community, user) { }; return AcWatching; };
rbjarnason/active-citizen
models/ac_watching.js
JavaScript
bsd-3-clause
1,139
/* jshint ignore:start */ import Component from 'metal-component/src/Component'; import Soy from 'metal-soy/src/Soy'; var templates; goog.loadModule(function(exports) { // This file was automatically generated from MetalPlayground.soy. // Please don't edit this file by hand. /** * @fileoverview Templates in namespace MetalPlayground. * @public */ goog.module('MetalPlayground.incrementaldom'); /** @suppress {extraRequire} */ var soy = goog.require('soy'); /** @suppress {extraRequire} */ var soydata = goog.require('soydata'); /** @suppress {extraRequire} */ goog.require('goog.i18n.bidi'); /** @suppress {extraRequire} */ goog.require('goog.asserts'); var IncrementalDom = goog.require('incrementaldom'); var ie_open = IncrementalDom.elementOpen; var ie_close = IncrementalDom.elementClose; var ie_void = IncrementalDom.elementVoid; var ie_open_start = IncrementalDom.elementOpenStart; var ie_open_end = IncrementalDom.elementOpenEnd; var itext = IncrementalDom.text; var iattr = IncrementalDom.attr; var $templateAlias1 = Soy.getTemplate('Tooltip.incrementaldom', 'render'); /** * @param {Object<string, *>=} opt_data * @param {(null|undefined)=} opt_ignored * @param {Object<string, *>=} opt_ijData * @return {void} * @suppress {checkTypes} */ function $render(opt_data, opt_ignored, opt_ijData) { ie_open('div', null, null, 'class', 'metal-playground'); $renderNavigation(opt_data, null, opt_ijData); $renderColumns(null, null, opt_ijData); $renderSidenav(opt_data, null, opt_ijData); $renderTooltips(null, null, opt_ijData); ie_close('div'); } exports.render = $render; if (goog.DEBUG) { $render.soyTemplateName = 'MetalPlayground.render'; } /** * @param {Object<string, *>=} opt_data * @param {(null|undefined)=} opt_ignored * @param {Object<string, *>=} opt_ijData * @return {void} * @suppress {checkTypes} */ function $renderColumns(opt_data, opt_ignored, opt_ijData) { ie_open('div', null, null, 'class', 'container-fluid'); ie_open('div', null, null, 'class', 'col-md-4'); ie_void('div', null, null, 'class', 'metal-playground-editor'); ie_close('div'); ie_open('div', null, null, 'class', 'col-md-8'); ie_open('div', null, null, 'class', 'flex-container metal-playground-live-view'); ie_open('div', null, null, 'class', 'metal-playground-rendered-component'); itext('component will be displayed here...'); ie_close('div'); ie_close('div'); ie_close('div'); ie_close('div'); } exports.renderColumns = $renderColumns; if (goog.DEBUG) { $renderColumns.soyTemplateName = 'MetalPlayground.renderColumns'; } /** * @param {Object<string, *>=} opt_data * @param {(null|undefined)=} opt_ignored * @param {Object<string, *>=} opt_ijData * @return {void} * @suppress {checkTypes} */ function $renderNavigation(opt_data, opt_ignored, opt_ijData) { ie_open('nav', null, null, 'class', 'collapse-basic-search navbar navbar-default navbar-no-collapse'); ie_open('ul', null, null, 'class', 'nav navbar-nav'); ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon', 'data-content', 'body', 'data-toggle', 'sidenav', 'data-type', 'fixed-push', 'href', '#metalSidenav'); ie_void('span', null, null, 'class', 'icon-align-justify metal-playground-component-selector'); ie_close('a'); ie_close('li'); ie_open('li', null, null, 'class', 'active'); ie_open('a', null, null, 'href', '#'); itext('Metal Playground'); ie_close('a'); ie_close('li'); ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon', 'data-onclick', opt_data.onPlayingClickHandler_, 'href', '#'); ie_void('span', null, null, 'class', (opt_data.isPlaying ? 'icon-stop' : 'icon-play') + ' metal-playground-play-stop'); ie_close('a'); ie_close('li'); if (opt_data.isPlaying) { ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon'); ie_void('div', null, null, 'class', 'bounceball metal-playground-loading-indicator'); ie_close('a'); ie_close('li'); } ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon', 'href', 'index.html'); ie_void('span', null, null, 'class', 'icon-refresh metal-playground-reset'); ie_close('a'); ie_close('li'); if (opt_data.currentComponent != null) { ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon', 'data-onclick', opt_data.onSaveCurrentStateClickHandler_, 'href', '#'); ie_void('span', null, null, 'class', 'icon-save metal-playground-save-current-state'); ie_close('a'); ie_close('li'); } ie_open('li'); ie_open('a', null, null, 'class', 'control-menu-icon'); ie_open('span', null, null, 'class', 'text-main'); itext('Component state changes will get propageted to the editor, unless you press the STOP button.'); ie_close('span'); ie_close('a'); ie_close('li'); ie_close('ul'); ie_close('nav'); } exports.renderNavigation = $renderNavigation; if (goog.DEBUG) { $renderNavigation.soyTemplateName = 'MetalPlayground.renderNavigation'; } /** * @param {Object<string, *>=} opt_data * @param {(null|undefined)=} opt_ignored * @param {Object<string, *>=} opt_ijData * @return {void} * @suppress {checkTypes} */ function $renderSidenav(opt_data, opt_ignored, opt_ijData) { ie_open('div', null, null, 'class', 'sidenav-fixed sidenav-menu-slider closed', 'id', 'metalSidenav'); ie_open('div', null, null, 'class', 'sidebar sidebar-inverse sidenav-menu'); ie_open('div', null, null, 'class', 'sidebar-header'); ie_open('h4'); itext('Available components'); ie_close('h4'); ie_close('div'); ie_open('div', null, null, 'class', 'sidebar-body'); ie_open('div', null, null, 'class', 'row row-spacing'); ie_open('div', null, null, 'class', 'col-md-12'); var current_componentList59 = opt_data.componentList; var current_componentListLen59 = current_componentList59.length; for (var current_componentIndex59 = 0; current_componentIndex59 < current_componentListLen59; current_componentIndex59++) { var current_componentData59 = current_componentList59[current_componentIndex59]; ie_open('div'); ie_open('blockquote', null, null, 'class', 'blockquote-sm blockquote-primary'); ie_open('a', null, null, 'class', 'control-menu-icon', 'href', '#', 'data-onclick', opt_data.onComponentClickHandler_, 'data-componentindex', current_componentIndex59); itext((goog.asserts.assert((current_componentData59.NAME) != null), current_componentData59.NAME)); ie_close('a'); ie_close('blockquote'); if (current_componentData59.savedStates != null) { ie_open('ul', null, null, 'class', 'metal-playground-state-list'); var stateNameList55 = current_componentData59.savedStateNames; var stateNameListLen55 = stateNameList55.length; for (var stateNameIndex55 = 0; stateNameIndex55 < stateNameListLen55; stateNameIndex55++) { var stateNameData55 = stateNameList55[stateNameIndex55]; ie_open('li'); ie_open('blockquote', null, null, 'class', 'blockquote-sm blockquote-main'); ie_open('a', null, null, 'class', 'control-menu-icon', 'href', '#', 'data-onclick', opt_data.onComponentStateClickHandler_, 'data-componentindex', current_componentIndex59, 'data-stateindex', stateNameIndex55); itext((goog.asserts.assert((stateNameData55) != null), stateNameData55)); ie_close('a'); ie_close('blockquote'); ie_close('li'); } ie_close('ul'); } ie_close('div'); } ie_close('div'); ie_close('div'); ie_void('div', null, null, 'class', 'sidebar-footer'); ie_close('div'); ie_close('div'); ie_close('div'); } exports.renderSidenav = $renderSidenav; if (goog.DEBUG) { $renderSidenav.soyTemplateName = 'MetalPlayground.renderSidenav'; } /** * @param {Object<string, *>=} opt_data * @param {(null|undefined)=} opt_ignored * @param {Object<string, *>=} opt_ijData * @return {void} * @suppress {checkTypes} */ function $renderTooltips(opt_data, opt_ignored, opt_ijData) { var resetTitleHtml__soy63 = function() { itext('Resets the application'); }; $templateAlias1({delay: [300, 150], elementClasses: 'fade', selector: '.metal-playground-reset', title: resetTitleHtml__soy63, visible: false}, null, opt_ijData); var liveReloadingTitleHtml__soy71 = function() { itext('Toggles the live reloading of the editor if the components state changes'); }; $templateAlias1({delay: [300, 150], elementClasses: 'fade', selector: '.metal-playground-play-stop', title: liveReloadingTitleHtml__soy71, visible: false}, null, opt_ijData); var openComponentSelectorTitleHtml__soy79 = function() { itext('Opens the component selector'); }; $templateAlias1({delay: [300, 150], elementClasses: 'fade', selector: '.metal-playground-component-selector', title: openComponentSelectorTitleHtml__soy79, visible: false}, null, opt_ijData); var saveStateTitleHtml__soy87 = function() { itext('Saves the current state with the given name'); }; $templateAlias1({delay: [300, 150], elementClasses: 'fade', selector: '.metal-playground-save-current-state', title: saveStateTitleHtml__soy87, visible: false}, null, opt_ijData); } exports.renderTooltips = $renderTooltips; if (goog.DEBUG) { $renderTooltips.soyTemplateName = 'MetalPlayground.renderTooltips'; } exports.render.params = ["componentList","currentComponent","isPlaying","onComponentClickHandler_","onComponentStateClickHandler_","onPlayingClickHandler_","onSaveCurrentStateClickHandler_"]; exports.render.types = {"componentList":"any","currentComponent":"any","isPlaying":"any","onComponentClickHandler_":"any","onComponentStateClickHandler_":"any","onPlayingClickHandler_":"any","onSaveCurrentStateClickHandler_":"any"}; exports.renderColumns.params = []; exports.renderColumns.types = {}; exports.renderNavigation.params = ["currentComponent","isPlaying","onPlayingClickHandler_","onSaveCurrentStateClickHandler_"]; exports.renderNavigation.types = {"currentComponent":"any","isPlaying":"any","onPlayingClickHandler_":"any","onSaveCurrentStateClickHandler_":"any"}; exports.renderSidenav.params = ["componentList","onComponentClickHandler_","onComponentStateClickHandler_"]; exports.renderSidenav.types = {"componentList":"any","onComponentClickHandler_":"any","onComponentStateClickHandler_":"any"}; exports.renderTooltips.params = []; exports.renderTooltips.types = {}; templates = exports; return exports; }); class MetalPlayground extends Component {} Soy.register(MetalPlayground, templates); export { MetalPlayground, templates }; export default templates; /* jshint ignore:end */
LeventeHudak/metal-playground
src/MetalPlayground.soy.js
JavaScript
bsd-3-clause
12,043
const Cast = require('../util/cast'); class Scratch3DataBlocks { constructor (runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; } /** * Retrieve the block primitives implemented by this package. * @return {object.<string, Function>} Mapping of opcode to Function. */ getPrimitives () { return { data_variable: this.getVariable, data_setvariableto: this.setVariableTo, data_changevariableby: this.changeVariableBy, data_listcontents: this.getListContents, data_addtolist: this.addToList, data_deleteoflist: this.deleteOfList, data_insertatlist: this.insertAtList, data_replaceitemoflist: this.replaceItemOfList, data_itemoflist: this.getItemOfList, data_lengthoflist: this.lengthOfList, data_listcontainsitem: this.listContainsItem }; } getVariable (args, util) { const variable = util.target.lookupOrCreateVariable(args.VARIABLE); return variable.value; } setVariableTo (args, util) { const variable = util.target.lookupOrCreateVariable(args.VARIABLE); variable.value = args.VALUE; } changeVariableBy (args, util) { const variable = util.target.lookupOrCreateVariable(args.VARIABLE); const castedValue = Cast.toNumber(variable.value); const dValue = Cast.toNumber(args.VALUE); variable.value = castedValue + dValue; } getListContents (args, util) { const list = util.target.lookupOrCreateList(args.LIST); // Determine if the list is all single letters. // If it is, report contents joined together with no separator. // If it's not, report contents joined together with a space. let allSingleLetters = true; for (let i = 0; i < list.contents.length; i++) { const listItem = list.contents[i]; if (!((typeof listItem === 'string') && (listItem.length === 1))) { allSingleLetters = false; break; } } if (allSingleLetters) { return list.contents.join(''); } return list.contents.join(' '); } addToList (args, util) { const list = util.target.lookupOrCreateList(args.LIST); list.contents.push(args.ITEM); } deleteOfList (args, util) { const list = util.target.lookupOrCreateList(args.LIST); const index = Cast.toListIndex(args.INDEX, list.contents.length); if (index === Cast.LIST_INVALID) { return; } else if (index === Cast.LIST_ALL) { list.contents = []; return; } list.contents.splice(index - 1, 1); } insertAtList (args, util) { const item = args.ITEM; const list = util.target.lookupOrCreateList(args.LIST); const index = Cast.toListIndex(args.INDEX, list.contents.length + 1); if (index === Cast.LIST_INVALID) { return; } list.contents.splice(index - 1, 0, item); } replaceItemOfList (args, util) { const item = args.ITEM; const list = util.target.lookupOrCreateList(args.LIST); const index = Cast.toListIndex(args.INDEX, list.contents.length); if (index === Cast.LIST_INVALID) { return; } list.contents.splice(index - 1, 1, item); } getItemOfList (args, util) { const list = util.target.lookupOrCreateList(args.LIST); const index = Cast.toListIndex(args.INDEX, list.contents.length); if (index === Cast.LIST_INVALID) { return ''; } return list.contents[index - 1]; } lengthOfList (args, util) { const list = util.target.lookupOrCreateList(args.LIST); return list.contents.length; } listContainsItem (args, util) { const item = args.ITEM; const list = util.target.lookupOrCreateList(args.LIST); if (list.contents.indexOf(item) >= 0) { return true; } // Try using Scratch comparison operator on each item. // (Scratch considers the string '123' equal to the number 123). for (let i = 0; i < list.contents.length; i++) { if (Cast.compare(list.contents[i], item) === 0) { return true; } } return false; } } module.exports = Scratch3DataBlocks;
isabela-angelo/scratch-tangible-blocks
src/blocks/scratch3_data.js
JavaScript
bsd-3-clause
4,584
/* @flow */ import * as Immutable from "immutable"; import { createContentRef, makeStateRecord, makeEntitiesRecord, makeContentsRecord, makeNotebookContentRecord, makeDocumentRecord } from "@nteract/core"; import { ipcRenderer as ipc } from "../../__mocks__/electron"; import * as globalEvents from "../../src/notebook/global-events"; import { makeDesktopNotebookRecord, DESKTOP_NOTEBOOK_CLOSING_NOT_STARTED, DESKTOP_NOTEBOOK_CLOSING_STARTED, DESKTOP_NOTEBOOK_CLOSING_READY_TO_CLOSE } from "../../src/notebook/state.js"; import * as actions from "../../src/notebook/actions.js"; const createStore = ( contentRef, content, closingState: DesktopNotebookClosingState ) => ({ getState: () => ({ core: makeStateRecord({ entities: makeEntitiesRecord({ contents: makeContentsRecord({ byRef: Immutable.Map({ // $FlowFixMe: This really is a content ref, Flow can't handle typing it though [contentRef]: content }) }) }) }), desktopNotebook: makeDesktopNotebookRecord().set( "closingState", closingState ) }) }); describe("onBeforeUnloadOrReload", () => { test("if we are not yet closing the notebook, should initiate closeNotebook and cancel close event", done => { const contentRef = createContentRef(); const store = createStore( contentRef, makeNotebookContentRecord({ model: makeDocumentRecord({ notebook: "not same", savedNotebook: "different" }) }), DESKTOP_NOTEBOOK_CLOSING_NOT_STARTED ); store.dispatch = action => { expect(action).toEqual( actions.closeNotebook({ contentRef: contentRef, reloading: false }) ); done(); }; const event = {}; const result = globalEvents.onBeforeUnloadOrReload( contentRef, store, false, event ); expect(result).toBe(false); }); test("if we are in the process of closing the notebook, should continue to cancel close event", () => { const contentRef = createContentRef(); const store = createStore( contentRef, makeNotebookContentRecord({ model: makeDocumentRecord({ notebook: "not same", savedNotebook: "different" }) }), DESKTOP_NOTEBOOK_CLOSING_STARTED ); const event = {}; const result = globalEvents.onBeforeUnloadOrReload( contentRef, store, event, false ); expect(result).toBe(false); }); test("if we have completed closing the notebook, should not cancel close event", () => { const contentRef = createContentRef(); const store = createStore( contentRef, makeNotebookContentRecord({ model: makeDocumentRecord({ notebook: "not same", savedNotebook: "different" }) }), DESKTOP_NOTEBOOK_CLOSING_READY_TO_CLOSE ); const event = {}; const result = globalEvents.onBeforeUnloadOrReload( contentRef, store, event, false ); expect(result).toBeUndefined(); }); }); describe("initGlobalHandlers", () => { test("adds an unload property to the window object", () => { const contentRef = createContentRef(); const store = createStore(contentRef); globalEvents.initGlobalHandlers(contentRef, store); expect(global.window.onbeforeunload).toBeDefined(); }); test("wires a listener for a reload msg from main process", done => { const contentRef = createContentRef(); const store = createStore(contentRef); ipc.on = event => { if (event == "reload") done(); }; globalEvents.initGlobalHandlers(contentRef, store); }); });
rgbkrk/nteract
applications/desktop/__tests__/renderer/global-events-spec.js
JavaScript
bsd-3-clause
3,718
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Extends OverlayView to provide a canvas "Layer". * @author Brendan Kenny */ /** * A map layer that provides a canvas over the slippy map and a callback * system for efficient animation. Requires canvas and CSS 2D transform * support. * @constructor * @extends google.maps.OverlayView * @param {CanvasLayerOptions=} opt_options Options to set in this CanvasLayer. */ function CanvasLayer(opt_options) { /** * If true, canvas is in a map pane and the OverlayView is fully functional. * See google.maps.OverlayView.onAdd for more information. * @type {boolean} * @private */ this.isAdded_ = false; /** * If true, each update will immediately schedule the next. * @type {boolean} * @private */ this.isAnimated_ = false; /** * The name of the MapPane in which this layer will be displayed. * @type {string} * @private */ this.paneName_ = CanvasLayer.DEFAULT_PANE_NAME_; /** * A user-supplied function called whenever an update is required. Null or * undefined if a callback is not provided. * @type {?function=} * @private */ this.updateHandler_ = null; /** * A user-supplied function called whenever an update is required and the * map has been resized since the last update. Null or undefined if a * callback is not provided. * @type {?function} * @private */ this.resizeHandler_ = null; /** * The LatLng coordinate of the top left of the current view of the map. Will * be null when this.isAdded_ is false. * @type {google.maps.LatLng} * @private */ this.topLeft_ = null; /** * The map-pan event listener. Will be null when this.isAdded_ is false. Will * be null when this.isAdded_ is false. * @type {?function} * @private */ this.centerListener_ = null; /** * The map-resize event listener. Will be null when this.isAdded_ is false. * @type {?function} * @private */ this.resizeListener_ = null; /** * If true, the map size has changed and this.resizeHandler_ must be called * on the next update. * @type {boolean} * @private */ this.needsResize_ = true; /** * A browser-defined id for the currently requested callback. Null when no * callback is queued. * @type {?number} * @private */ this.requestAnimationFrameId_ = null; var canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.style.pointerEvents = 'none'; /** * The canvas element. * @type {!HTMLCanvasElement} */ this.canvas = canvas; /** * The CSS width of the canvas, which may be different than the width of the * backing store. * @private {number} */ this.canvasCssWidth_ = 300; /** * The CSS height of the canvas, which may be different than the height of * the backing store. * @private {number} */ this.canvasCssHeight_ = 150; /** * A value for scaling the CanvasLayer resolution relative to the CanvasLayer * display size. * @private {number} */ this.resolutionScale_ = 1; /** * Simple bind for functions with no args for bind-less browsers (Safari). * @param {Object} thisArg The this value used for the target function. * @param {function} func The function to be bound. */ function simpleBindShim(thisArg, func) { return function() { func.apply(thisArg); }; } /** * A reference to this.repositionCanvas_ with this bound as its this value. * @type {function} * @private */ this.repositionFunction_ = simpleBindShim(this, this.repositionCanvas_); /** * A reference to this.resize_ with this bound as its this value. * @type {function} * @private */ this.resizeFunction_ = simpleBindShim(this, this.resize_); /** * A reference to this.update_ with this bound as its this value. * @type {function} * @private */ this.requestUpdateFunction_ = simpleBindShim(this, this.update_); // set provided options, if any if (opt_options) { this.setOptions(opt_options); } } var global = typeof window === 'undefined' ? {} : window; if (global.google && global.google.maps) { CanvasLayer.prototype = new google.maps.OverlayView(); /** * The default MapPane to contain the canvas. * @type {string} * @const * @private */ CanvasLayer.DEFAULT_PANE_NAME_ = 'overlayLayer'; /** * Transform CSS property name, with vendor prefix if required. If browser * does not support transforms, property will be ignored. * @type {string} * @const * @private */ CanvasLayer.CSS_TRANSFORM_ = (function() { var div = document.createElement('div'); var transformProps = [ 'transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ]; for (var i = 0; i < transformProps.length; i++) { var prop = transformProps[i]; if (div.style[prop] !== undefined) { return prop; } } // return unprefixed version by default return transformProps[0]; })(); /** * The requestAnimationFrame function, with vendor-prefixed or setTimeout-based * fallbacks. MUST be called with window as thisArg. * @type {function} * @param {function} callback The function to add to the frame request queue. * @return {number} The browser-defined id for the requested callback. * @private */ CanvasLayer.prototype.requestAnimFrame_ = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function(callback) { return global.setTimeout(callback, 1000 / 60); }; /** * The cancelAnimationFrame function, with vendor-prefixed fallback. Does not * fall back to clearTimeout as some platforms implement requestAnimationFrame * but not cancelAnimationFrame, and the cost is an extra frame on onRemove. * MUST be called with window as thisArg. * @type {function} * @param {number=} requestId The id of the frame request to cancel. * @private */ CanvasLayer.prototype.cancelAnimFrame_ = global.cancelAnimationFrame || global.webkitCancelAnimationFrame || global.mozCancelAnimationFrame || global.oCancelAnimationFrame || global.msCancelAnimationFrame || function(requestId) {}; /** * Sets any options provided. See CanvasLayerOptions for more information. * @param {CanvasLayerOptions} options The options to set. */ CanvasLayer.prototype.setOptions = function(options) { if (options.animate !== undefined) { this.setAnimate(options.animate); } if (options.paneName !== undefined) { this.setPaneName(options.paneName); } if (options.updateHandler !== undefined) { this.setUpdateHandler(options.updateHandler); } if (options.resizeHandler !== undefined) { this.setResizeHandler(options.resizeHandler); } if (options.resolutionScale !== undefined) { this.setResolutionScale(options.resolutionScale); } if (options.map !== undefined) { this.setMap(options.map); } }; /** * Set the animated state of the layer. If true, updateHandler will be called * repeatedly, once per frame. If false, updateHandler will only be called when * a map property changes that could require the canvas content to be redrawn. * @param {boolean} animate Whether the canvas is animated. */ CanvasLayer.prototype.setAnimate = function(animate) { this.isAnimated_ = !!animate; if (this.isAnimated_) { this.scheduleUpdate(); } }; /** * @return {boolean} Whether the canvas is animated. */ CanvasLayer.prototype.isAnimated = function() { return this.isAnimated_; }; /** * Set the MapPane in which this layer will be displayed, by name. See * {@code google.maps.MapPanes} for the panes available. * @param {string} paneName The name of the desired MapPane. */ CanvasLayer.prototype.setPaneName = function(paneName) { this.paneName_ = paneName; this.setPane_(); }; /** * @return {string} The name of the current container pane. */ CanvasLayer.prototype.getPaneName = function() { return this.paneName_; }; /** * Adds the canvas to the specified container pane. Since this is guaranteed to * execute only after onAdd is called, this is when paneName's existence is * checked (and an error is thrown if it doesn't exist). * @private */ CanvasLayer.prototype.setPane_ = function() { if (!this.isAdded_) { return; } // onAdd has been called, so panes can be used var panes = this.getPanes(); if (!panes[this.paneName_]) { throw new Error('"' + this.paneName_ + '" is not a valid MapPane name.'); } panes[this.paneName_].appendChild(this.canvas); }; /** * Set a function that will be called whenever the parent map and the overlay's * canvas have been resized. If opt_resizeHandler is null or unspecified, any * existing callback is removed. * @param {?function=} opt_resizeHandler The resize callback function. */ CanvasLayer.prototype.setResizeHandler = function(opt_resizeHandler) { this.resizeHandler_ = opt_resizeHandler; }; /** * Sets a value for scaling the canvas resolution relative to the canvas * display size. This can be used to save computation by scaling the backing * buffer down, or to support high DPI devices by scaling it up (by e.g. * window.devicePixelRatio). * @param {number} scale */ CanvasLayer.prototype.setResolutionScale = function(scale) { if (typeof scale === 'number') { this.resolutionScale_ = scale; this.resize_(); } }; /** * Set a function that will be called when a repaint of the canvas is required. * If opt_updateHandler is null or unspecified, any existing callback is * removed. * @param {?function=} opt_updateHandler The update callback function. */ CanvasLayer.prototype.setUpdateHandler = function(opt_updateHandler) { this.updateHandler_ = opt_updateHandler; }; /** * @inheritDoc */ CanvasLayer.prototype.onAdd = function() { if (this.isAdded_) { return; } this.isAdded_ = true; this.setPane_(); this.resizeListener_ = google.maps.event.addListener(this.getMap(), 'resize', this.resizeFunction_); this.centerListener_ = google.maps.event.addListener(this.getMap(), 'center_changed', this.repositionFunction_); this.resize_(); this.repositionCanvas_(); }; /** * @inheritDoc */ CanvasLayer.prototype.onRemove = function() { if (!this.isAdded_) { return; } this.isAdded_ = false; this.topLeft_ = null; // remove canvas and listeners for pan and resize from map this.canvas.parentElement.removeChild(this.canvas); if (this.centerListener_) { google.maps.event.removeListener(this.centerListener_); this.centerListener_ = null; } if (this.resizeListener_) { google.maps.event.removeListener(this.resizeListener_); this.resizeListener_ = null; } // cease canvas update callbacks if (this.requestAnimationFrameId_) { this.cancelAnimFrame_.call(global, this.requestAnimationFrameId_); this.requestAnimationFrameId_ = null; } }; /** * The internal callback for resize events that resizes the canvas to keep the * map properly covered. * @private */ CanvasLayer.prototype.resize_ = function() { if (!this.isAdded_) { return; } var map = this.getMap(); var mapWidth = map.getDiv().offsetWidth; var mapHeight = map.getDiv().offsetHeight; var newWidth = mapWidth * this.resolutionScale_; var newHeight = mapHeight * this.resolutionScale_; var oldWidth = this.canvas.width; var oldHeight = this.canvas.height; // resizing may allocate a new back buffer, so do so conservatively if (oldWidth !== newWidth || oldHeight !== newHeight) { this.canvas.width = newWidth; this.canvas.height = newHeight; this.needsResize_ = true; this.scheduleUpdate(); } // reset styling if new sizes don't match; resize of data not needed if (this.canvasCssWidth_ !== mapWidth || this.canvasCssHeight_ !== mapHeight) { this.canvasCssWidth_ = mapWidth; this.canvasCssHeight_ = mapHeight; this.canvas.style.width = mapWidth + 'px'; this.canvas.style.height = mapHeight + 'px'; } }; /** * @inheritDoc */ CanvasLayer.prototype.draw = function() { this.repositionCanvas_(); }; /** * Internal callback for map view changes. Since the Maps API moves the overlay * along with the map, this function calculates the opposite translation to * keep the canvas in place. * @private */ CanvasLayer.prototype.repositionCanvas_ = function() { // TODO(bckenny): *should* only be executed on RAF, but in current browsers // this causes noticeable hitches in map and overlay relative // positioning. var map = this.getMap(); // topLeft can't be calculated from map.getBounds(), because bounds are // clamped to -180 and 180 when completely zoomed out. Instead, calculate // left as an offset from the center, which is an unwrapped LatLng. var top = map.getBounds().getNorthEast().lat(); var center = map.getCenter(); var scale = Math.pow(2, map.getZoom()); var left = center.lng() - (this.canvasCssWidth_ * 180) / (256 * scale); this.topLeft_ = new google.maps.LatLng(top, left); // Canvas position relative to draggable map's container depends on // overlayView's projection, not the map's. Have to use the center of the // map for this, not the top left, for the same reason as above. var projection = this.getProjection(); var divCenter = projection.fromLatLngToDivPixel(center); var offsetX = -Math.round(this.canvasCssWidth_ / 2 - divCenter.x); var offsetY = -Math.round(this.canvasCssHeight_ / 2 - divCenter.y); this.canvas.style[CanvasLayer.CSS_TRANSFORM_] = 'translate(' + offsetX + 'px,' + offsetY + 'px)'; this.scheduleUpdate(); }; /** * Internal callback that serves as main animation scheduler via * requestAnimationFrame. Calls resize and update callbacks if set, and * schedules the next frame if overlay is animated. * @private */ CanvasLayer.prototype.update_ = function() { this.requestAnimationFrameId_ = null; if (!this.isAdded_) { return; } if (this.isAnimated_) { this.scheduleUpdate(); } if (this.needsResize_ && this.resizeHandler_) { this.needsResize_ = false; this.resizeHandler_(); } if (this.updateHandler_) { this.updateHandler_(); } }; /** * A convenience method to get the current LatLng coordinate of the top left of * the current view of the map. * @return {google.maps.LatLng} The top left coordinate. */ CanvasLayer.prototype.getTopLeft = function() { return this.topLeft_; }; /** * Schedule a requestAnimationFrame callback to updateHandler. If one is * already scheduled, there is no effect. */ CanvasLayer.prototype.scheduleUpdate = function() { if (this.isAdded_ && !this.requestAnimationFrameId_) { this.requestAnimationFrameId_ = this.requestAnimFrame_.call(global, this.requestUpdateFunction_); } }; } export default CanvasLayer;
huiyan-fe/mapv
src/map/google-map/CanvasLayer.js
JavaScript
bsd-3-clause
15,556
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import SignatureAddFormComponent from 'Theme/signature-add-form' import { signPetition, devLocalSignPetition } from '../actions/petitionActions' import { actions as sessionActions } from '../actions/sessionActions' import { isValidEmail, FormTracker } from '../lib' import Config from '../config' class SignatureAddForm extends React.Component { constructor(props) { super(props) this.state = { name: false, email: false, country: 'United States', address1: false, address2: false, city: false, state: false, region: false, zip: false, postal: false, comment: false, volunteer: false, phone: false, validationTried: false, mobile_optin: false, thirdparty_optin: props.hiddenOptin || props.showOptinCheckbox, hidden_optin: props.hiddenOptin, required: {}, hideUntilInteract: true, dynamic_sms_flow: props.query.sms || false } this.validationFunction = { email: isValidEmail, name: name => !isValidEmail(name), // See https://github.com/MoveOnOrg/mop-frontend/issues/560 zip: zip => /(\d\D*){5}/.test(zip), phone: phone => /(\d\D*){10}/.test(phone) // 10-digits } this.volunteer = this.volunteer.bind(this) this.submit = this.submit.bind(this) this.validationError = this.validationError.bind(this) this.updateStateFromValue = this.updateStateFromValue.bind(this) this.updateValueFromState = this.updateValueFromState.bind(this) this.formTracker = new FormTracker({ experiment: 'current', formvariant: props.id, variationname: 'current' }) } componentDidMount() { const ref = this.form if (ref && this.formTracker.isVisible(ref)) this.formTracker.setForm(ref, ref.id) } componentDidUpdate(prevProps, prevState) { const ref = this.form if (ref && this.formTracker.isVisible(ref)) { if (!this.state.hideUntilInteract) this.formTracker.setForm(ref, ref.id) if ((!prevState.phone && this.state.phone) || (!prevState.name && this.state.name) || (!prevState.volunteer && this.state.volunteer)) { this.formTracker.formExpandTracker() } } } getOsdiSignature() { const { petition, query, showOptinCheckbox, user } = this.props const osdiSignature = { petition: { name: petition.name, petition_id: petition.petition_id, show_optin: showOptinCheckbox, _links: petition._links }, person: { full_name: this.state.name, email_addresses: [], postal_addresses: [] } } if (this.state.comment) { osdiSignature.comments = this.state.comment } if (this.state.name) { osdiSignature.person.full_name = this.state.name } else if (user.given_name) { osdiSignature.person.given_name = user.given_name } if (this.state.email) { osdiSignature.person.email_addresses.push({ address: this.state.email }) } if (user.token) { osdiSignature.person.identifiers = [user.token] } if (this.state.phone) { osdiSignature.person.phone_numbers = [this.state.phone] } if (this.state.city) { osdiSignature.person.postal_addresses.push({ locality: this.state.city, region: ((this.state.country === 'United States') ? this.state.state : this.state.region), postal_code: ((this.state.country === 'United States') ? this.state.zip : this.state.postal), country_name: this.state.country }) } if (this.state.address1) { const lines = [this.state.address1] if (this.state.address2) { lines.push(this.state.address2) } osdiSignature.person.postal_addresses[0].address_lines = lines } const referrerKeys = [ 'source', 'r_by', 'fb_test', 'abid', 'abver', 'test_group', 'no_mo', 'mailing_id', 'r_hash'] const referrerData = referrerKeys.filter(k => query[k]).map(k => ({ [k]: query[k] })) if (referrerData.length) { osdiSignature.referrer_data = Object.assign({}, ...referrerData) } const customFields = ['thirdparty_optin', 'hidden_optin', 'volunteer', 'mobile_optin', 'dynamic_sms_flow'] const customData = customFields.filter(k => this.state[k]).map(k => ({ [k]: this.state[k] })) if (customData.length) { osdiSignature.person.custom_fields = Object.assign({}, ...customData) } // Console.log('signature!', osdiSignature) return osdiSignature } validationError(key) { if (this.state.validationTried || this.state[`${key}Validated`]) { const validFunc = this.validationFunction[key] if (!this.state[key]) { if (key in this.state.required) { return ( <div className='alert alert-danger red' role='alert'>{this.state.required[key]}</div> ) } } else if (validFunc) { const isValid = validFunc(String(this.state[key])) if (isValid === false) { return ( <div className='alert alert-danger red' role='alert'>Invalid input for {key}</div> ) } else if (isValid && isValid.warning) { return ( <div className='alert alert-danger red' role='alert'>{isValid.warning}</div> ) } } } return null } formIsValid() { this.setState({ validationTried: true }) this.updateRequiredFields(true) return Object.keys(this.state.required).map( key => !!(this.state[key] && (!this.validationFunction[key] || this.validationFunction[key](String(this.state[key])))) ).reduce((a, b) => a && b, true) } updateValueFromState(field) { return (this.state[field] ? this.state[field] : '') } updateStateFromValue(field, isCheckbox = false, validateNow = false) { return event => { const value = isCheckbox ? event.target.checked : event.target.value if (this.state[field] !== value) { this.formTracker.updateFormProgress({ fieldchanged: field, fieldfocused: field, userInfo: this.props.user }) } this.setState({ [field]: value, hideUntilInteract: false // show some hidden fields if they are hidden }) if (validateNow && value && this.validationFunction[field]) { this.setState({ [`${field}Validated`]: true }) } } } volunteer(event) { const vol = event.target.checked const req = this.updateRequiredFields(false) if (vol) { req.phone = 'We need a phone number to coordinate volunteers.' } else { delete req.phone } if (!this.state.volunteer) this.formTracker.formExpandTracker() this.setState({ volunteer: vol, required: req }) } updateRequiredFields(doUpdate) { // This is a separate method because it can change when state or props are changed const { user, requireAddressFields } = this.props const required = this.state.required let changeRequiredFields = false if (!user.signonId) { Object.assign(required, { name: 'Name is required.', email: 'Email address is required.', state: 'State is required.', zip: 'Zip code is required.' }) changeRequiredFields = true } else { delete required.name delete required.email delete required.state delete required.zip } if (requireAddressFields) { Object.assign(required, { address1: 'Full address is required.', city: 'City is required.', state: 'State is required.', zip: 'Zip code is required.' }) changeRequiredFields = true } else { delete required.address1 delete required.city delete required.state } if (this.state.country !== 'United States') { delete required.state delete required.zip } if (changeRequiredFields && doUpdate) { this.setState({ required }) } return required } submit(event) { event.preventDefault() const { dispatch, petition } = this.props // In dev, by default, don't actually call the api const signAction = Config.API_WRITABLE ? signPetition : devLocalSignPetition if (this.formIsValid()) { this.formTracker.submitForm({ loginstate: (this.props.user.anonymous ? 0 : 1) }) const osdiSignature = this.getOsdiSignature() return dispatch(signAction(osdiSignature, petition, { redirectOnSuccess: true })) } this.setState({ hideUntilInteract: false }) // show fields so we can show validation error this.formTracker.validationErrorTracker() return false } render() { const { dispatch, petition, user, query, showAddressFields, requireAddressFields, showOptinCheckbox, showOptinWarning, setRef, innerRef, id } = this.props const creator = (petition._embedded && petition._embedded.creator) || {} const petitionBy = creator.name || petition.contact_name return ( <SignatureAddFormComponent submit={this.submit} creator={creator} petitionBy={petitionBy} petition={petition} user={user} query={query} showAddressFields={showAddressFields} requireAddressFields={requireAddressFields} onUnrecognize={() => { dispatch(sessionActions.unRecognize()) }} volunteer={this.state.volunteer} onClickVolunteer={this.volunteer} thirdPartyOptin={this.state.thirdparty_optin} displayMobileOptIn={!!this.state.phone} country={this.state.country} onChangeCountry={event => this.setState({ country: event.target.value })} updateStateFromValue={this.updateStateFromValue} updateValueFromState={this.updateValueFromState} validationError={this.validationError} showOptinWarning={showOptinWarning} showOptinCheckbox={showOptinCheckbox} setRef={setRef} innerRef={ref => { this.form = ref; if (innerRef) { innerRef(ref) } }} id={id} // Don't hide at first if the user doesn't have an address and the petition needs one hideUntilInteract={ user.signonId && !(user.postal_addresses && user.postal_addresses.length) && petition.needs_full_addresses ? false : this.state.hideUntilInteract } /> ) } } SignatureAddForm.propTypes = { petition: PropTypes.object.isRequired, user: PropTypes.object, dispatch: PropTypes.func, query: PropTypes.object, showAddressFields: PropTypes.bool, requireAddressFields: PropTypes.bool, showOptinWarning: PropTypes.bool, showOptinCheckbox: PropTypes.bool, hiddenOptin: PropTypes.bool, setRef: PropTypes.func, innerRef: PropTypes.func, id: PropTypes.string } function shouldShowAddressFields(user, petition) { if (!user.signonId) return true const userHasAddress = user.postal_addresses && user.postal_addresses.length if (petition.needs_full_addresses && !userHasAddress) { return true } return false } function mapStateToProps(store, ownProps) { const user = store.userStore const { petition, query } = ownProps const creator = ((petition._embedded && petition._embedded.creator) || {}) const source = query.source || '' const newProps = { user, showAddressFields: shouldShowAddressFields(user, petition), requireAddressFields: petition.needs_full_addresses && shouldShowAddressFields(user, petition), fromCreator: (/^c\./.test(source) || /^s\.icn/.test(source)), fromMailing: /\.imn/.test(source) } newProps.showOptinWarning = !!(!user.signonId && (creator.source || (creator.custom_fields && creator.custom_fields.may_optin))) newProps.hiddenOptin = !!(!user.signonId && ((creator.source && ((newProps.fromCreator && !query.mailing_id) || !newProps.fromMailing)) || (!creator.source && creator.custom_fields && creator.custom_fields.may_optin && newProps.fromCreator && !query.mailing_id))) newProps.showOptinCheckbox = !!(!user.signonId && newProps.showOptinWarning && !newProps.hiddenOptin) return newProps } export default connect(mapStateToProps)(SignatureAddForm) export const WrappedComponent = SignatureAddForm
MoveOnOrg/mop-frontend
src/containers/signature-add-form.js
JavaScript
bsd-3-clause
12,722
/** * Copyright (c) 2015-present, Alejandro Mantilla <@AlejoJamC>. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree or translated in the assets folder. */ // Load required packages var Logger = require('../config/logger'); var logger = Logger.logger; var passport = require('passport'); var BasicStrategy = require('passport-http').BasicStrategy; var BearerStrategy = require('passport-http-bearer').Strategy; var LocalStrategy = require('passport-local').Strategy; // Load required models var UserDataModel = require('../models/users'); var User = UserDataModel.User; var ClientDataModel = require('../models/clients'); var Client = ClientDataModel.Client; var TokenDataModel = require('../models/tokens'); var Token = TokenDataModel.Token; passport.use(new BasicStrategy( function(email, password, callback) { User.findOne({ email : email }, function (err, user) { if (err) { logger.error(err); return callback(err); } // No user found with that email if (!user) { return callback(null, false); } // Make sure the password is correct user.verifyPassword(password, function(err, isMatch) { if (err) { logger.error(err); return callback(err); } // Password did not match if (!isMatch) { return callback(null, false); } // Success return callback(null, user); }); }); } )); passport.use('Login-Basic',new BasicStrategy( function(email, password, callback) { User.findOne({ email : email }, function (err, user) { if (err) { logger.error(err); return callback(err); } // No user found with that email if (!user) { return callback(null, false); } // Make sure the password is correct user.verifyPassword(password, function(err, isMatch) { if (err) { logger.error(err); return callback(err); } // Password did not match if (!isMatch) { return callback(null, false); } // Success return callback(null, user); }); }); } )); passport.use('client-basic', new BasicStrategy( function(email, password, callback) { Client.findOne({ id: email }, function (err, client) { if (err) { logger.error(err); return callback(err); } // No client found with that id or bad password if (!client || client.secret !== password) { return callback(null, false); } // Success return callback(null, client); }); } )); passport.use(new BearerStrategy( function(accessToken, callback) { Token.findOne({ value: accessToken }, function (err, token) { if (err) { logger.error(err); return callback(err); } // No token found if (!token) { return callback(null, false); } User.findOne({ _id: token.idUser }, function (err, user) { if (err){ logger.error(err); return callback(err); } // No user found if (!user) { return callback(null, false); } // Simple example with no scope // TODO: verificar el alcance de la respuesta de la BearerStrategy callback(null, user, { scope: '*' }); }); }); } )); passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'pwd' }, function(email, password, callback) { User.findOne({ email : email }, function (err, user) { if (err) { return callback(err); } // No user found with that username if (!user) { return callback(null, false); } // Make sure the password is correct user.verifyPassword(password, function(err, isMatch) { if (err) { return callback(err); } // Password did not match if (!isMatch) { return callback(null, false); } // Success return callback(null, user); }); }); } )); //exports.isAuthenticated = passport.authenticate(['local', 'bearer'], { session : false }); exports.isAuthenticated = passport.authenticate(['basic', 'bearer'], { session : false }); exports.isLoginAuthenticated = passport.authenticate(['Login-Basic', 'bearer'], { session : false }); exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false }); exports.isBearerAuthenticated = passport.authenticate('bearer', { session: false });
AlejoJamC/avaritia
routes/auth.js
JavaScript
bsd-3-clause
5,284
import React from 'react'; import {browserHistory, Route, Router} from 'react-router'; import {withInfo} from '@storybook/addon-info'; import PropTypes from 'prop-types'; import StreamGroup from 'app/components/stream/group'; import GroupStore from 'app/stores/groupStore'; export default { title: 'Features/Issues/Stream Group', }; const selection = { projects: [1], environments: ['production', 'staging'], datetime: { start: '2019-10-09T11:18:59', end: '2019-09-09T11:18:59', period: '', utc: true, }, }; const organization = { id: '1', slug: 'test-org', features: [], }; function loadGroups() { const group = { assignedTo: null, count: '327482', culprit: 'fetchData(app/components/group/suggestedOwners/suggestedOwners)', firstRelease: null, firstSeen: '2020-10-05T19:44:05.963Z', hasSeen: false, id: '1', isBookmarked: false, isPublic: false, isSubscribed: false, lastSeen: '2020-10-11T01:08:59Z', level: 'warning', logger: null, metadata: {function: 'fetchData', type: 'RequestError'}, numComments: 0, permalink: 'https://foo.io/organizations/foo/issues/1234/', platform: 'javascript', project: { platform: 'javascript', id: 1, slug: 'test-project', }, shareId: null, shortId: 'JAVASCRIPT-6QS', stats: { '24h': [ [1517281200, 2], [1517310000, 1], ], '30d': [ [1514764800, 1], [1515024000, 122], ], }, status: 'unresolved', title: 'RequestError: GET /issues/ 404', type: 'error', userCount: 35097, userReportCount: 0, inbox: { date_added: '2020-11-24T13:17:42.248751Z', reason: 0, reason_details: null, }, }; const unhandledGroup = { ...group, id: '2', culprit: 'sentry.tasks.email.send_email', isUnhandled: true, level: 'error', count: '12', userCount: 1337, metadata: { function: 'send_messages', type: 'SMTPServerDisconnected', value: 'Connection unexpectedly closed', filename: 'sentry/utils/email.py', }, annotations: ['<a href="https://sentry.io">PROD-72</a>'], title: 'UnhandledError: GET /issues/ 404', inbox: { date_added: '2020-11-24T13:17:42.248751Z', reason: 2, reason_details: null, }, }; const resolvedGroup = { ...group, id: '3', status: 'resolved', isUnhandled: true, metadata: {function: 'fetchData', type: 'ResolvedError'}, numComments: 2, inbox: null, }; const ignoredGroup = { ...group, id: '4', status: 'ignored', culprit: 'culprit', metadata: {function: 'fetchData', type: 'IgnoredErrorType'}, inbox: null, }; const bookmarkedGroup = { ...group, id: '5', metadata: { function: 'send_messages', type: 'BookmarkedError', value: 'Connection unexpectedly closed', filename: 'sentry/utils/email.py', }, culprit: '', isBookmarked: true, logger: 'sentry.incidents.tasks', inbox: { date_added: '2020-11-24T13:17:42.248751Z', reason: 3, reason_details: null, }, }; const slimGroup = { ...group, id: '6', title: 'Monitor failure: getsentry-expire-plan-trials (missed_checkin)', metadata: { type: 'Monitor failure: getsentry-expire-plan-trials (missed_checkin)', }, culprit: '', logger: 'sentry.incidents.tasks', annotations: ['<a href="https://sentry.io">PROD-72</a>'], inbox: { date_added: '2020-11-24T13:17:42.248751Z', reason: 1, reason_details: null, }, }; GroupStore.loadInitialData([ group, unhandledGroup, resolvedGroup, ignoredGroup, bookmarkedGroup, slimGroup, ]); } class LocationContext extends React.Component { static childContextTypes = { location: PropTypes.object, }; getChildContext() { return {location: {query: {}}}; } render() { return ( <Router history={browserHistory}> <Route path="/*" component={() => this.props.children} /> </Router> ); } } export const Default = withInfo('default')(() => { loadGroups(); return ( <LocationContext> <StreamGroup id="1" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="2" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="3" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="4" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="5" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="6" canSelect withChart={null} memberList={[]} organization={organization} selection={selection} query="" isGlobalSelectionReady /> </LocationContext> ); }); export const WithInbox = withInfo('withInbox')(() => { const inboxOrganization = {...organization, features: ['inbox']}; loadGroups(); return ( <LocationContext> <StreamGroup id="1" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="2" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="3" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="4" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="5" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> <StreamGroup id="6" canSelect withChart={null} memberList={[]} organization={inboxOrganization} selection={selection} query="" isGlobalSelectionReady /> </LocationContext> ); });
beeftornado/sentry
docs-ui/components/streamGroup.stories.js
JavaScript
bsd-3-clause
7,195
var a00166 = [ [ "Ptr", "a00166.html#ae27b748b63b02e4b72f90f645ec14ff2", null ], [ "Node", "a00166.html#ada3566b0aeea909906ad5efd78138eca", null ], [ "~Node", "a00166.html#af157cf8d47cb333def0bd09a4e343279", null ], [ "apply", "a00166.html#ad12be70c49797ca5d16da021b6241d07", null ], [ "apply_f_op_g", "a00166.html#a67a36925a1263293f93232720604281c", null ], [ "apply_g_op_fC", "a00166.html#a1895793f10c78efb17031443119f0d0b", null ], [ "apply_g_op_fL", "a00166.html#acb5ae7e50b64f1c34941ec4be21d5bf7", null ], [ "choose", "a00166.html#ab9d0892ac2961b98f8dc641be58d9f10", null ], [ "dot", "a00166.html#a43c4c3199f1221d64fb0a6739ea366fe", null ], [ "equals", "a00166.html#a93b13d06ded137cd7e2a4ab136f509b6", null ], [ "id", "a00166.html#ada32d726ed7671b67b029fde48730831", null ], [ "isLeaf", "a00166.html#a7449a3f45a2879c54930a166474147d1", null ], [ "operator()", "a00166.html#a740f46c9edbfb42d9ecb281a7ccadf75", null ], [ "print", "a00166.html#a5e6afa3caa55e82cf1e5cf5f1d32a50c", null ], [ "sameLeaf", "a00166.html#a06fafb26ac37ec98adb568a848c31cc7", null ], [ "sameLeaf", "a00166.html#acf3e6467b83a9ac5d851141b1e03a471", null ] ];
devbharat/gtsam
doc/html/a00166.js
JavaScript
bsd-3-clause
1,197
var lastProviderState={}; /********************************************************************************** * DOCUMENT.READY FUNCTION **********************************************************************************/ $(document).ready(function() { var addConsent_tmp = null; var isProviderAdminUser_tmp = null; var in_addConsent_tmp = $('input#input_isAddConsent').val(); var in_isProviderAdminUser_tmp = $('input#input_isProviderAdminUser').val(); //Convert string input for in_addConsent_tmp to boolean type if(in_addConsent_tmp === "true"){ addConsent_tmp = true; }else if(in_addConsent_tmp === "false"){ addConsent_tmp = false; }else{ addConsent_tmp = null; } //Check if addConsent is a valid boolean value if((addConsent_tmp !== true) && (addConsent_tmp !== false)){ addConsent_tmp = null; throw new ReferenceError("addConsent_tmp variable is not a valid boolean value"); } //Convert string input for in_isProviderAdminUser_tmp to boolean type if(in_isProviderAdminUser_tmp === "true"){ isProviderAdminUser_tmp = true; }else if(in_isProviderAdminUser_tmp === "false"){ isProviderAdminUser_tmp = false; }else{ isProviderAdminUser_tmp = false; } //Check if isProviderAdminUser_tmp is a valid boolean value if((isProviderAdminUser_tmp !== true) && (isProviderAdminUser_tmp !== false)){ isProviderAdminUser_tmp = null; throw new ReferenceError("isProviderAdminUser_tmp variable is not a valid boolean value"); } var specMedSetObj_tmp = null; if(addConsent_tmp === false){ specMedSetObj_tmp = new Array(); $('.specmedinfo-input').each(function(){ var str_code = $(this).attr('id'); var str_codesys = $(this).data('codesys'); var str_dispname = $(this).data('dispname'); var newEntry = createSpecMedInfoObj(str_code, str_codesys, str_dispname); specMedSetObj_tmp.push(newEntry); newEntry = null; }); } setupPage(addConsent_tmp, isProviderAdminUser_tmp, specMedSetObj_tmp); //Setup search for provider modal event handlers $('#search_phone1, #search_phone2, #search_phone3').autotab_magic().autotab_filter('numeric'); cityEnableDisable(); zipEnableDisable(); /* Builds list of providers already added so that results in the search results * modal can be disabled if that provider has already been added. */ $('.npi-list-input').each(function(){ var in_NPI = $(this).val(); npiLists.push(in_NPI); }); //Binds an event handler to the change event for the state_name element $('#search_state_name').change(function(e){ e.stopPropagation(); cityEnableDisable(); zipEnableDisable(); }); //Binds an event handler to the change event for the state_name element $('#search_zip_code').bind("propertychange keyup input", function(e){ e.stopPropagation(); city_stateEnableDisable(); }); $('div#org_prov_search_group').on("propertychange keyup input", "input.form-control", function(e){ e.stopPropagation(); lnameEnableDisable(); }); $('div#indv_prov_search_group').on("propertychange keyup input", "input.form-control", function(e){ e.stopPropagation(); facilitynameEnableDisable(); }); $('div#indv_prov_search_group').on("change", "select.form-control", function(e){ e.stopPropagation(); facilitynameEnableDisable(); }); //Binds an event handler to clear search by location panel $('button#btn_provSearchClearLocation').click(function(e){ clearLocation(); }); //Binds an event handler to clear search by location panel $('button#btn_provSearchClearNameAndOthers').click(function(e){ clearNameAndOthers(); }); }); /*********************************************************************************** * START OF setupPage ************************************************************************************/ function setupPage(addConsent_tmp, isProviderAdminUser_tmp, specMedSetObj_tmp) { var addConsent = addConsent_tmp; var isProviderAdminUser = isProviderAdminUser_tmp; //Check if addConsent is a valid boolean value if((addConsent !== true) && (addConsent !== false)){ addConsent = null; throw new ReferenceError("addConsent variable is not a valid boolean value"); } //Check if isProviderAdminUser is a valid boolean value if((isProviderAdminUser !== true) && (isProviderAdminUser !== false)){ isProviderAdminUser = null; throw new ReferenceError("isProviderAdminUser variable is not a valid boolean value"); } //Set popover 'a' element data attributes based on dynamic hidden form values prior to popup initialization $('.input_i-text').each(function(){ var linkID = $(this).data("linkid"); var in_content = $(this).attr("value"); var in_title = $(this).data("intitle"); document.getElementById(linkID).setAttribute("data-content", in_content); document.getElementById(linkID).setAttribute("data-title", in_title); }); var specMedSetObj = null; var specMedSet = null; if(addConsent === false){ specMedSetObj = specMedSetObj_tmp; try{ specMedSet = specMedSetObj; }catch(e){ if(e.name == "TypeError"){ specMedSet = null; }else{ throw e; } } } // set providers in consent being edited to be checked $('.prov-npi-checked-input').each(function(){ var prov = $(this).val(); document.getElementById(prov).checked = true; }); // set sensitivity policy codes in consent being edited to be checked $('.sensitivity-policy-code-checked-input').each(function(){ var sens_code = $(this).val(); document.getElementById(sens_code).checked = true; }); // set clinical document section type codes in consent being edited to be checked $('.doc-sec-type-code-checked-input').each(function(){ var docsectyp_code = $(this).val(); document.getElementById(docsectyp_code).checked = true; }); // set clinical document section codes in consent being edited to be checked $('.doc-sec-code-checked-input').each(function(){ var docsec_code = $(this).val(); document.getElementById(docsec_code).checked = true; }); // set purpose of use codes in consent being edited to be checked $('.purpose-use-code-checked-input').each(function(){ var puruse_code = $(this).val(); document.getElementById(puruse_code).checked = true; }); $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); //Initialize page for adding/editing consent initAddConsent(addConsent, isProviderAdminUser, specMedSet); //Initialize popovers $('[data-toggle=popover]').popover(); //Close all currently showing popovers when user clicks the page outside of a popover $('html').on('mouseup', function(e) { if((!$(e.target).closest('.popover').length)) { if((!$(e.target).closest('[data-toggle=popover]').length)){ $('.popover-showing').each(function(){ $(this).popover('toggle'); }); } } }); /* When show.bs.popover event is thrown, close any other visible popovers, then flag triggered * popover element with popover-showing class. * show.bs.popover event is thrown immediately when show instance method is called. * It will not wait for the popover's CSS transitions to complete first. */ $('[data-toggle=popover]').on('show.bs.popover', function(e){ $('[data-toggle=popover].popover-showing').not(this).popover('toggle'); //all but this $(this).addClass('popover-showing'); }); /* When hide.bs.popover event is thrown, remove popover-showing class from popover element. * hide.bs.popover event is thrown immediately when hide instance method is called. * It will not wait for the popover's CSS transitions to complete first. */ $('[data-toggle=popover]').on('hide.bs.popover', function(e){ $(this).removeClass('popover-showing'); }); // populate for edit consent page $("#authorizers").empty(); $("#authorize-list input").each(function() { if($(this).attr("checked")=="checked"){ $("#authorizers").append('<li class="uneditable-input"><span class="fa fa-user"></span>' +$(this).parent().parent().children("span").text() +'</li>'); } }); $("#consentmadetodisplay").empty(); $("#disclose-list input").each(function() { if($(this).attr("checked")=="checked"){ $("#consentmadetodisplay").append('<li class="uneditable-input" ><span class="fa fa-user"></span>' +$(this).parent().parent().children("span").text() +'</li>'); } }); $("body").removeClass('fouc_loading'); if(!isProviderAdminUser){ $("ul#pulldown_menu").sidebar({ position:"top", open:"click", close:"click", //labelText:"GUIDE", callback: { item : { enter : function(){}, leave : function(){} }, sidebar : { open : function(){}, close : function(){} } }, inject : $("<div><span>GUIDE</span></div>") }); $("div.sidebar-container").addClass("guide-pulldown-tab"); $("div.sidebar-inject.top > span").addClass("sidebar-label"); $('#tourtest').joyride({ tipContainer: '#consent-add-main', heightPadding: $('footer').outerHeight() + 10, mode: 'focus', autoStart: true, 'preStepCallback': function() { var int_next_index = 0; try{ int_next_index = $('#tourtest').joyride('get_next_index'); }catch(e){ int_next_index = 0; } var li_field_id = $('#tourtest li').get(int_next_index); var isShowDelayedNext = $(li_field_id).hasClass('show-delayed-next'); var str_field_id = $(li_field_id).data("id"); var tempVarIconUser = $('div#' + str_field_id).find('.fa-user'); var tempVarBadge = $('div#' + str_field_id).find('.badge'); var isDataPopulated = false; if(tempVarIconUser.length > 0 || tempVarBadge.length > 0){ isDataPopulated = true; }else{ isDataPopulated = false; } var obj_next_tip = $('#tourtest').joyride('get_next_tip'); var btn_next_button = $(obj_next_tip).find('.joyride-next-tip'); $(btn_next_button).addClass('hidden'); if(isDataPopulated || isShowDelayedNext){ setTimeout(function(){ $(btn_next_button).removeClass('hidden'); }, 500); } }, 'postRideCallback': function() { setGuideButtonStateOff(); } }); if(jQuery.storage.getItem('guideStatus', 'sessionStorage') == 'on'){ turnGuideOn(); }else if(jQuery.storage.getItem('guideStatus', 'sessionStorage') == 'off'){ turnGuideOff(); }else{ if($('#btn_guide_OnOff').hasClass('guide-off-flag') === false){ turnGuideOn(); }else{ turnGuideOff(); } } $('#btn_guide_OnOff').click(function() { if($('#btn_guide_OnOff').hasClass('guide-off-flag') === true){ turnGuideOn(); }else{ turnGuideOff(); } }); $('#saveauthorizer').click(function() { ifGuideOnGoNext(); }); $('#saveconsentmadeto').click(function() { ifGuideOnGoNext(); }); $('#btn_close_share_settings').click(function() { ifGuideOnGoNext(); }); $('#btn_save_selected_purposes').click(function() { ifGuideOnGoNext(); }); $('#selectInfo').change(function() { if($('#selectInfo').prop('checked') == true){ ifGuideOnGoNext(); } }); $('#selectPurposesToggle').change(function() { if($('#selectPurposesToggle').prop('checked') == true){ ifGuideOnGoNext(); } }); $("a[id*=i-icon]").bind('click', function() { var id = $(this).attr("id").split('_')[1]; $("#message-block_"+id).css("display","block"); }); $("body").on("closeJoyrideClick", function(e){ e.stopImmediatePropagation(); $('#tourtest').joyride('end'); turnGuideOff(); }); } function ifGuideOnGoNext(){ if(!isProviderAdminUser){ if(jQuery.storage.getItem('guideStatus', 'sessionStorage') == 'on'){ $('#tourtest').joyride("go_next"); } } } //Turn Joyride Guide Off function turnGuideOff(){ if(!isProviderAdminUser){ $('#tourtest').joyride('end'); setGuideButtonStateOff(); } } //Set Joyride Guide Button State Off function setGuideButtonStateOff(){ if(!isProviderAdminUser){ $('#btn_guide_OnOff').addClass('guide-off-flag'); jQuery.storage.setItem('guideStatus', 'off', 'sessionStorage'); $('#btn_guide_OnOff').text("Guide On"); } } //Turn Joyride Guide On function turnGuideOn(){ if(!isProviderAdminUser){ $('#tourtest').joyride('end'); $('#tourtest').joyride(); setGuideButtonStateOn(); } } //Set Joyride Guide Button State On function setGuideButtonStateOn(){ if(!isProviderAdminUser){ if($('#btn_guide_OnOff').hasClass('guide-off-flag') === true){ $('#btn_guide_OnOff').removeClass('guide-off-flag'); } jQuery.storage.setItem('guideStatus', 'on', 'sessionStorage'); $('#btn_guide_OnOff').text("Guide Off"); } } } /********************************************************************************** * END OF setupPage ***********************************************************************************/ /*********************************************************************************** * FUNCTION TO INITIALIZE PAGE WHEN ADDING/EDITING A CONSENT ***********************************************************************************/ /*Fix issue #493 Start This is only a problem found in Internet Explorer browser. After it was fixed, admin could press "Space" Key to select.*/ function radioOnClick() { var SPACE_KEY = 32; if (event.keyCode == SPACE_KEY) { var button = document.getElementById("saveauthorizer"); // button.click(); } } function butOnClick() { var SPACE_KEY = 32; if (event.keyCode == SPACE_KEY) { var button = document.getElementById("saveconsentmadeto"); // button.click(); } } /*Fix issue #493 End*/ function initAddConsent(addConsent, isProviderAdminUser, specMedSet) { //Check if addConsent is a valid boolean value if((addConsent !== true) && (addConsent !== false)){ throw new ReferenceError("addConsent variable is not a valid boolean value"); } //Check if isProviderAdminUser is a valid boolean value if((isProviderAdminUser !== true) && (isProviderAdminUser !== false)){ throw new ReferenceError("isProviderAdminUser variable is not a valid boolean value"); } /******************************************************************************************* * MAIN CODE *******************************************************************************************/ var specmedinfoary = new Array(); var specmedinfoid=0; var specmedinfoary_final = new Array(); var lastInfoState={}; var lastSpecificMedicalInfoState={}; var lastPurposeState={}; var isSaveButtonClicked=false; lastProviderState={}; /********* Initialize Date Picker **********/ var dateToday = new Date(); var startDate = new Date(); var endDate = new Date(); if (addConsent === true) { dateToday = new Date(); startDate = new Date(dateToday.getFullYear(), dateToday.getMonth(), dateToday.getDate(), 0, 0, 0, 0); endDate = new Date(dateToday.getFullYear()+1, dateToday.getMonth(), dateToday.getDate(), 0, 0, 0, 0); // set end date as a day minus 1 year endDate.setDate(endDate.getDate() - 1); } else { dateToday = new Date($('#date-picker-start').attr('value')); startDate = new Date(dateToday.getFullYear(), dateToday.getMonth(), dateToday.getDate(), 0, 0, 0, 0); dateToday = new Date($('#date-picker-end').attr('value')); endDate = new Date(dateToday.getFullYear(), dateToday.getMonth(), dateToday.getDate(), 0, 0, 0, 0); var intAryLength = $(specMedSet).length; for(var i = 0; i < intAryLength; i++){ initSpecMedInfoArray(specMedSet[i]); } } var nowTemp = new Date(); var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0); $('#date-picker-start').datepicker({ onRender: function(date) { return date.valueOf() < now.valueOf() ? 'disabled' : ''; } }); $('#date-picker-end').datepicker({ onRender: function(date) { return date.valueOf() < now.valueOf() ? 'disabled' : ''; } }); $('#date-picker-start').datepicker('setValue',startDate); $('#date-picker-start').attr('value',$('#date-picker-start').attr('value')); $('#date-picker-start').attr('data-date-format',startDate); $('#date-picker-end').datepicker('setValue',endDate); $('#date-picker-end').attr('value',$('#date-picker-end').attr('value')); /********* End Inititialize Date Picker **********/ //Check if adding or editing consent if (addConsent === true) { //ADDING CONSENT: $("#allInfo").iCheck("check"); $("#edit1").hide(); }else{ //EDITING CONSENT: loadAllSharePreferences(); loadAllPurposeofshareform(); loadAllLastSpecificMedicalInfoState(); // disable providers in made to list that are checked in to disclose list $(".isMadeToList").each(function(){ var providerId=$(this).attr("id").substr(2,$(this).attr("id").length-2); if($("#from"+providerId).prop('checked')==true){ toggleToProviderDisabled(providerId); } }); // disable providers in to disclose list that are checked in to made list $(".toDiscloseList").each(function(){ var providerId=$(this).attr("id").substr(4,$(this).attr("id").length-4); if($("#to"+providerId).prop('checked')==true){ toggleFromProviderDisabled(providerId); } }); if (areAllInfoUnSelected()) { $("#allInfo").iCheck("check"); $("#edit1").hide(); }else{ $("#selectInfo").iCheck("check"); $("#sensitivityinfo input").each(function(){ if ($(this).prop('checked') == true) { var toAppendMain='<div id="TagMain'+ $(this).attr('id')+ '" class="badge">'+ $(this).parent().text()+ "</div>"; $("#notsharedmainpage").append(toAppendMain); } }); $("#medicalinfo input").each(function(){ if ($(this).prop('checked') == true) { var toAppendMain='<div id="TagMain'+ $(this).attr('id')+ '" class="badge">'+ $(this).parent().text()+ "</div>"; $("#notsharedmainpage").append(toAppendMain); } }); $("#clinicalDocumentType input").each(function(){ if ($(this).prop('checked') == true) { var toAppendMain='<div id="TagMain'+ $(this).attr('id')+ '" class="badge">'+ $(this).parent().text()+ "</div>"; $("#notsharedmainpage").append(toAppendMain); } }); $("#purposeOfSharingInputs input").each(function(){ if ($(this).prop('checked') == true) { var toAppendMain='<div id="TagMain'+ $(this).attr('id')+ '" class="badge">'+ $(this).parent().text()+ "</div>"; $("#sharedpurpose").append(toAppendMain); } }); } //FIXME (MH): REMOVE THE FOLLOWING IF/ELSE CODE BLOCK AS IT IS OBSOLETE if (areAllPurposesUnselected()) { $("#allPurposes").iCheck("check"); } else { $("#selectPurposes").iCheck("check"); } } // check all only if page is add consent (not edit) if (addConsent === true) { uncheckAllSharePreferences(loadAllSharePreferences); checkRecommendedPurposeofsharing(loadAllPurposeofshareform); }else{ loadAllSharePreferences(); loadAllPurposeofshareform(); } loadAllProviders(); reAppendMediInfoBadges(); reAppendPurposeOfUse(); /******************************************************************************************* * EVENT HANDLERS *******************************************************************************************/ $(".removeEntry").on("click",function(){ var entryId=$(this).attr("id").substr(11,$(this).attr("id").length-11); delete specmedinfoary[entryId]; $("#TagSpec"+entryId).remove(); $("#entry"+entryId).remove(); }); $("div#disclose-list-container").on("ifToggled", "input.isMadeToList", function(){ var providerId=$(this).attr("id").substr(2,$(this).attr("id").length-2); toggleFromProviderDisabled(providerId); }); $("div#authorize-list-container").on("ifToggled", "input.toDiscloseList", function(){ var providerId=$(this).attr("id").substr(4,$(this).attr("id").length-4); toggleToProviderDisabled(providerId); }); $("div#disclose-list-container").on('ifChecked', "input.indv-prov", function(event) { $("div#disclose-list-container input.org-prov").iCheck("uncheck"); }); $("div#disclose-list-container").on('ifChecked', "input.org-prov", function(event) { $("div#disclose-list-container input.indv-prov").iCheck("uncheck"); }); $("div#authorize-list-container").on('ifChecked', "input.indv-prov", function(event) { $("div#authorize-list-container input.org-prov").iCheck("uncheck"); }); $("div#authorize-list-container").on('ifChecked', "input.org-prov", function(event) { $("div#authorize-list-container input.indv-prov").iCheck("uncheck"); }); $("button#consent-add-save").click(function(){ $('div.validation-alert').empty(); if(areAnyProvidersSelected() === true && areDateCorrected() === true){ $(".inputformPerson input").each(function(){ if($(this).prop("checked")==true){ $(this).not(':submit').clone().hide().appendTo('#formToBeSubmitted'); } }); $(".purposeofshareform input").each(function(){ if($(this).prop("checked")==true){ $(this).not(':submit').clone().hide().appendTo('#formToBeSubmitted'); } }); $(".inputformDate").each(function(){ $(this).find("input").not(':submit').clone().hide().appendTo('#formToBeSubmitted'); }); $(".inputform input").each(function(){ if($(this).prop("checked")==true){ $(this).not(':submit').clone().hide().appendTo('#formToBeSubmitted'); } }); for (var i=0;i<specmedinfoary.length;i++){ if(specmedinfoary[i]!=undefined){ specmedinfoary_final.push(specmedinfoary[i]); } } for (var i=0;i<specmedinfoary_final.length;i++){ if(specmedinfoary_final[i]!=undefined){ var tempStr = '<input type="text" name="' + specmedinfoary_final[i].codeSystem + '" value="' + specmedinfoary_final[i].code + ";" + specmedinfoary_final[i].description + '" />'; $('#formToBeSubmitted').append(tempStr.replace(/,/g,"^^^")); } } $("div#sharedpurpose div").each(function(){ var sharedPurposeOfUseName = $(this).text(); $("<input type='hidden' value='" + sharedPurposeOfUseName + "' />" ).attr("name","sharedPurposeNames").appendTo('#formToBeSubmitted'); }); $("ul#authorizers li").each(function(){ var authorizersName = $(this).text(); $("<input type='hidden' value='" + authorizersName + "' />" ).attr("name","authorizerNames").appendTo('#formToBeSubmitted'); }); $("ul#consentmadetodisplay li").each(function(){ var madeToName = $(this).text(); $("<input type='hidden' value='" + madeToName + "' />" ).attr("name","madeToNames").appendTo('#formToBeSubmitted'); }); //Disable save button to prevent multiple submits $('button#consent-add-save').prop("disabled", true); //Submit form $('#formToBeSubmitted').submit(); }else{ if(areAnyProvidersSelected() === false) $('div.navbar-inner-header').after("<div class='validation-alert'><span><div class='alert alert-danger rounded'><button type='button' class='close' data-dismiss='alert'>&times;</button>You must add provider(s).</div></span></div>"); if(areDateCorrected() === false) $('div.navbar-inner-header').after("<div class='validation-alert'><span><div class='alert alert-danger rounded'><button type='button' class='close' data-dismiss='alert'>&times;</button>You must select correct dates.</div></span></div>"); } }); //callback handler for form submit var frm = $('#formToBeSubmitted'); $("#formToBeSubmitted").submit(function(e) { $.ajax( { url: frm.attr('action'), type: frm.attr('method'), data: frm.serialize(), success:function(data, textStatus, jqXHR) { //data: return data from server var jsonData = JSON.parse(data); if(jsonData["isSuccess"] === true){ if(jsonData["isAdmin"] === true){ // staff is creating a consent on behalf of patient if(jsonData["isAdd"] === false){ window.location.href = "adminPatientView.html?notify=editpatientconsent&status=success&id="+ jsonData["patientId"] ; } else { window.location.href = "adminPatientView.html?notify=createpatientconsent&status=success&id="+ jsonData["patientId"]; } } else{ if($('input#input_isAddConsent').val()==="true"){ //patient creating a consent window.location.href = "listConsents.html?notify=add"; } else { window.location.href = "listConsents.html"; } } } }, error: function(jqXHR, textStatus, errorThrown) { //Re-enable "save" button $('button#consent-add-save').prop("disabled", false); //TODO (MH): Handle different error types from controller //If response HTTP Status Code is 440 (Session has expired) if(jqXHR.status == 440){ $('div#consent_session_expired_modal').modal(); $('.redirectToLogin').click(function() { window.location.reload(); }); } //If response HTTP Status Code is 409 (Conflict) else if(jqXHR.status == 409){ resetFormToBeSubmitted(); populateModalData(jqXHR.responseText, isProviderAdminUser); $('div#consent_validation_modal').modal(); }else{ window.alert("ERROR: " + jqXHR.responseText); } } }); e.preventDefault(); //STOP default action }); $("#addspecmedi").click(function(){ updateSpecMedInfo(); }); $("#allInfo").on("ifChecked",function(){ uncheckAllSharePreferences(); clearAllSpecificMedicalInfo(); $("#notsharedmainpage").empty(); $('#edit1').hide(); loadAllSharePreferences(); }); /*Fix issue #448 Start * After resolving issue, the datepicker is closed immediately when a date is selected. * And also add TAB keyup function to close datepicker if no date need to be selected. */ $('input.datepicker').bind('keyup', function(e) { var TAB_KEY = 9; var keyCode = e.keyCode; if (keyCode == TAB_KEY) { $('.datepicker.dropdown-menu').hide(); e.preventDefault(); } }); $("#date-picker-start").datepicker().on('changeDate', function(ev){ $('#date-picker-start').attr('value',ev.target.value); $('#date-picker-start').datepicker({minDate: 0}) ; $('.datepicker.dropdown-menu').hide(); }); $("#date-picker-end").datepicker().on('changeDate', function(ev){ $('#date-picker-end').attr('value',ev.target.value); $('#date-picker-end').datepicker({minDate: 0}) ; $('.datepicker.dropdown-menu').hide(); }); //Fix issue #448 end $("#selectInfo").on("ifChecked",function(){ $('#edit1').show(); showShareSettingsModal(); loadAllSharePreferences(); uncheckAllMedicalInfo(); }); $("#btn_save_selected_purposes").click(function(){ isSaveButtonClicked=true; handleLastStoredStates(reAppendPurposeOfUse); }); $("#btn_save_selected_medinfo").click(function(){ isSaveButtonClicked=true; handleLastStoredStates(reAppendMediInfoBadges); if (areAllInfoUnSelected()==true) $("#allInfo").iCheck("check"); }); $("#share-settings-modal").on('hidden.bs.modal', function(){ setTimeout(function(){ handleLastStoredStates(); isSaveButtonClicked=false; if (areAllInfoUnSelected()==true){ $("#allInfo").iCheck("check"); } $('#condition').val(""); },300); }); $("#selected-purposes-modal").on('hide.bs.modal',function(event){ if(event.target.id == "selected-purposes-modal"){ setTimeout(function(){ handleLastStoredStates(); isSaveButtonClicked=false; if (areAllPurposesUnselected()==true){ $("#allPurposes").iCheck("check"); } },300); } }); $("#authorize-modal,#disclose-modal").on('hide.bs.modal',function(event){ if((event.target.id == "authorize-modal") || (event.target.id == "disclose-modal")){ setTimeout(function(){ handleLastStoredStates(); isSaveButtonClicked=false; },300); } }); $("#saveauthorizer").click(function(){ isSaveButtonClicked=true; handleLastStoredStates(); $("#authorizers").empty(); $("#authorize-list input").each(function() { if($(this).attr("checked")=="checked"){ $("#authorizers").append('<li class="uneditable-input"><span class="fa fa-user"></span>' +$(this).parent().parent().children("span").text() +'</li>'); } }); }); $("#saveconsentmadeto").click(function(){ isSaveButtonClicked=true; handleLastStoredStates(); $("#consentmadetodisplay").empty(); $("#disclose-list input").each(function() { if($(this).attr("checked")=="checked"){ $("#consentmadetodisplay").append('<li class="uneditable-input"><span class="fa fa-user"></span>' +$(this).parent().parent().children("span").text() +'</li>'); } }); }); $('button.btn-sel-all-tab').click(function(e){ var $target = $(e.target); switch($target.attr('id')){ case "btn_sensitivity_select_all": $('input[name=doNotShareSensitivityPolicyCodes]').iCheck('check'); break; case "btn_med_info_select_all": $('input[name=doNotShareClinicalDocumentSectionTypeCodes]').iCheck('check'); break; case "btn_clinical_doc_select_all": $('input[name=doNotShareClinicalDocumentTypeCodes]').iCheck('check'); break; case "btn_share_purposes_select_all": $('input[name=shareForPurposeOfUseCodes]').iCheck('check'); break; default: break; } }); $('button.btn-desel-all-tab').click(function(e){ var $target = $(e.target); switch($target.attr('id')){ case "btn_sensitivity_deselect_all": $('input[name=doNotShareSensitivityPolicyCodes]').iCheck('uncheck'); break; case "btn_med_info_deselect_all": $('input[name=doNotShareClinicalDocumentSectionTypeCodes]').iCheck('uncheck'); break; case "btn_clinical_doc_deselect_all": $('input[name=doNotShareClinicalDocumentTypeCodes]').iCheck('uncheck'); break; case "btn_share_purposes_deselect_all": $('input[name=shareForPurposeOfUseCodes]').iCheck('uncheck'); break; default: break; } }); $('#consent_validation_modal button#btn_continue_editing').click(function(e){ $('#consent_validation_modal').modal('hide'); }); //Show search for providers modal when add provider button is clicked $('#btn_add_provider_search').click(function(e){ $('#disclose-modal').modal('hide'); $('#providerSearchSelect-modal').modal(); }); /****************************************************************************************** * FUNCTION DEFINITIONS *******************************************************************************************/ $(function() { $( "#condition" ) .autocomplete({appendTo:"#autocomplete"}, {source: function( request, response ) { $.getJSON( "callHippaSpace.html", { q: request.term, domain:"icd9", rt:"json" }, function (data) { response($.map(data.ICD9, function (item) { return { codeSystem:"ICD9", description:getDescriptionString(item.Description).replace(/,/g,"^^^"), code:item.Code, label: getDescriptionString(item.Description), value: getDescriptionString(item.Description), }; })); } ); }, search: function() { var term = this.value; if ( term.length < 2 ) { return false; } }, select: function( event, ui ) { var isThisEntryAlreadyEntered=false; for(key in specmedinfoary){ if (specmedinfoary[key].code==ui.item.code){ isThisEntryAlreadyEntered=true; return; } } if(isThisEntryAlreadyEntered==false){ addSpecMedInfoToArray(ui.item); } } }); }); function areAnyProvidersSelected(){ var flag=0; $(".isMadeToList").each(function(){ if($(this).prop("checked")==true){ flag++; return false; } return true; }); $(".toDiscloseList").each(function(){ if($(this).prop("checked")==true){ flag++; return false; } return true; }); if (flag>1) return true; else return false; } function getDescriptionString(rawString){ var fatalErrorFlag = false; if (rawString.indexOf("(")!=-1 && rawString.substr(rawString.length-1)==")"){ var num_open_paren = 0; var num_close_paren = 0; var isEqualNum = false; var strTemp = rawString; var subResult = ""; var endPar = 0; var openPar = 0; try{ endPar = strTemp.lastIndexOf(")"); openPar = strTemp.lastIndexOf("(", endPar + 1); subResult = strTemp.substring(openPar, endPar + 1); }catch(e){ fatalErrorFlag = true; endPar = 0; openPar = 0; subResult = ""; throw e; } num_open_paren = countOpenParen(subResult); num_close_paren = countCloseParen(subResult); if(num_open_paren === num_close_paren){ isEqualNum = true; } while((num_open_paren !== num_close_paren) && (isEqualNum === false) && (openPar > 0) && (fatalErrorFlag === false)){ try{ openPar = strTemp.lastIndexOf("(", openPar - 1); subResult = strTemp.substring(openPar, endPar + 1); }catch(e){ fatalErrorFlag = true; endPar = 0; openPar = 0; subResult = ""; throw e; } num_open_paren = countOpenParen(subResult); num_close_paren = countCloseParen(subResult); if(num_open_paren === num_close_paren){ isEqualNum = true; } } if((isEqualNum === true) && (fatalErrorFlag === false)){ subResult = subResult.slice(1, subResult.length - 1); return subResult; }else if(fatalErrorFlag !== false){ return ""; }else{ return rawString; } } return rawString; } function checkRecommendedPurposeofsharing(callback){ $("#TREATMENT").iCheck('check'); // $("#ETREAT").iCheck('check'); // $("#CAREMGT").iCheck('check'); if(typeof callback === 'function'){ callback(); } } function loadAllSharePreferences(){ $(".inputform input").each(function(){ if($(this).prop("id")!=null) lastInfoState[$(this).prop( "id")]=$(this).prop("checked"); }); } function loadAllLastSpecificMedicalInfoState(){ clearLastSpecificMedicalInfo(); for (var i=0;i<specmedinfoary.length;i++){ if($("#specmedinfo"+i).length==0) delete specmedinfoary[i]; if(specmedinfoary[i]!=undefined){ lastSpecificMedicalInfoState[specmedinfoary[i].code]=specmedinfoary[i].description.replace(/\^\^\^/g,","); } } } function loadAllPurposeofshareform(){ $(".purposeofshareform input").each(function(){ lastPurposeState[$(this).prop("id")]=$(this).prop("checked"); }); } function uncheckAllSharePreferences(callback){ $("input.checkBoxClass1").iCheck('uncheck'); if(typeof callback === 'function') callback(); } function clearLastSpecificMedicalInfo(){ for (var key in lastSpecificMedicalInfoState){ delete lastSpecificMedicalInfoState[key]; } } function clearAllSpecificMedicalInfo(callback){ clearLastSpecificMedicalInfo(); specmedinfoary.length=0; $(".removeEntry").each(function(){ var entryId=$(this).attr("id").substr(11,$(this).attr("id").length-11); $("#entry"+entryId).remove(); }); } function uncheckAllMedicalInfo(callback){ $("input.checkBoxClass1").iCheck('uncheck'); if(typeof callback === 'function') callback(); } function reAppendMediInfoBadges(){ $("#notsharedmainpage").empty(); for(var key in lastInfoState){ if (lastInfoState.hasOwnProperty(key)) { if (lastInfoState[key]==true){ var description=$('label[for="' + key + '"]').text(); var toAppendMain='<div id="TagMain'+ key+ '" class="badge">'+ description+ "</div>"; $("#notsharedmainpage").append(toAppendMain); } } } for(var key in lastSpecificMedicalInfoState){ if (lastSpecificMedicalInfoState.hasOwnProperty(key)) { if (lastSpecificMedicalInfoState[key]!=undefined){ var description=lastSpecificMedicalInfoState[key]; var toAppendMain='<div id="TagMain'+ key+ '" class="badge">'+ description+ "</div>"; $("#notsharedmainpage").append(toAppendMain); } } } } function reAppendPurposeOfUse(){ $("#sharedpurpose").empty(); for(var key in lastPurposeState){ if (lastPurposeState.hasOwnProperty(key)) { if (lastPurposeState[key]==true){ var description=$('label[for="' + key + '"]').text(); var toAppendMain='<div id="TagMain'+ key+ '" class="badge">'+ description+ "</div>"; $("#sharedpurpose").append(toAppendMain); } } } } function areDateCorrected(){ if($('#date-picker-start').attr('value').trim()===""||$('#date-picker-end').attr('value').trim()==="") return false; dateToday2 = new Date(); startDate2 = new Date($('#date-picker-start').attr('value')); todayDate2 = new Date(dateToday2.getFullYear(), dateToday2.getMonth(), dateToday2.getDate(), 0, 0, 0, 0); endDate2 = new Date($('#date-picker-end').attr('value')); if(startDate2.valueOf()<todayDate2.valueOf()||endDate2.valueOf()<todayDate2.valueOf()||endDate2.valueOf()<startDate2.valueOf()||startDate2.valueOf()===NaN||endDate2.valueOf()===NaN) return false; else return true; } function revertAllStates(){ for (var key in lastInfoState) { if (lastInfoState.hasOwnProperty(key)) { if (lastInfoState[key]==true) $("#"+key).iCheck('check'); else $("#"+key).iCheck('uncheck'); } } for (var key in lastPurposeState) { if (lastPurposeState.hasOwnProperty(key)) { if (lastPurposeState[key]==true) $("#"+key).iCheck('check'); else $("#"+key).iCheck('uncheck'); } } for (var key in lastProviderState) { if (lastProviderState.hasOwnProperty(key)) { if (lastProviderState[key]==true) $("#"+key).iCheck('check'); else $("#"+key).iCheck('uncheck'); } } } function handleLastStoredStates(callback){ if (isSaveButtonClicked==true){ loadAllProviders(); loadAllSharePreferences(); loadAllPurposeofshareform(); loadAllLastSpecificMedicalInfoState(); isSaveButtonClicked=false; } else{ revertAllStates(); } if(typeof callback === 'function') callback(); } function areAllInfoUnSelected(){ for (var key in lastInfoState){ if (key!="") if (lastInfoState[key]==true){ return false; } } for (var key in lastSpecificMedicalInfoState){ if (key!="") if (lastSpecificMedicalInfoState[key]!=undefined){ return false; } } return true; } function areAllPurposesUnselected(){ for (var key in lastPurposeState){ if (key!="") if (lastPurposeState[key]==true){ return false; } } return true; } function updateSpecMedInfo() { if(specmedinfoary[specmedinfoid]!=undefined){ $("#specmedinfo").append('<li class="spacing" id="'+'entry'+specmedinfoid+ '"><div><span>'+ specmedinfoary[specmedinfoary.length-1].displayName+ '</span><span>'+ '<button id="specmedinfo'+specmedinfoid +'" class="btn btn-danger btn-xs list-btn removeEntry">'+ '<span class="fa fa-minus fa-white"></span></button></span></div></li>'); $("#condition").val(""); specmedinfoary[specmedinfoid].added=true; specmedinfoid=specmedinfoid+1; } } function addSpecMedInfoToArray(item){ newEntry=new Object(); newEntry.displayName=item.value; newEntry.codeSystem=item.codeSystem; newEntry.code=item.code; newEntry.description=item.description; specmedinfoary[specmedinfoid]=newEntry; } function initSpecMedInfoArray(item){ newEntry=new Object(); newEntry.displayName=item.displayName; newEntry.codeSystem=item.codeSystem; newEntry.code=item.code; newEntry.description=item.displayName; specmedinfoary[specmedinfoid]=newEntry; updateSpecMedInfo(); } } /*********************************************************************************** * GLOBAL SCOPE FUNCTIONS ***********************************************************************************/ function resetFormToBeSubmitted(){ $("form#formToBeSubmitted > input:not(input[name='_csrf'], input#patientUsername, input#patientId, input#consentId)").remove(); } function loadAllProviders(){ $(".inputformPerson input.toDiscloseList").each(function(){ if($(this).prop("id")!=null) lastProviderState[$(this).prop("id")]=$(this).prop("checked"); }); $(".inputformPerson input.isMadeToList").each(function(){ if($(this).prop("id")!=null) lastProviderState[$(this).prop("id")]=$(this).prop("checked"); }); } //Toggle from provider state disabled/enabled function toggleFromProviderDisabled(in_providerID){ var providerId = in_providerID; if(isNaN(providerId)){ throw new ReferenceError("providerId variable is not a valid numeric value"); } if($("#from"+providerId).prop('disabled')==false){ $("#from"+providerId).iCheck('disable'); $("#from"+providerId).closest('label').addClass("joe"); } else{ $("#from"+providerId).iCheck('enable'); $("#from"+providerId).closest('label').removeClass("joe"); } } //Toggle to provider state disabled/enabled function toggleToProviderDisabled(in_providerID){ var providerId = in_providerID; if(isNaN(providerId)){ throw new ReferenceError("providerId variable is not a valid numeric value"); } if($("#to"+providerId).prop('disabled')==false){ $("#to"+providerId).iCheck('disable'); $("#to"+providerId).closest('label').addClass("joe"); } else{ $("#to"+providerId).iCheck('enable'); $("#to"+providerId).closest('label').removeClass("joe"); } } function createSpecMedInfoObj(str_code, str_codeSystem, str_displayName){ newEntry = new Object(); newEntry.displayName = str_displayName; newEntry.codeSystem = str_codeSystem; newEntry.code = str_code; return newEntry; } function showShareSettingsModal(){ $("#share-settings-modal").modal({ keyboard: false }); } //Count number of opening parentheses '(' in string function countOpenParen(in_str){ //regular expression pattern to specify a global search for the open parenthesis '(' character var open_paren_regexp =/\(/g; var num_open_paren = 0; //calls countChar function to count number of occurances of open parentheses num_open_paren = countChar(open_paren_regexp, in_str); return num_open_paren; } //Count number of closing parentheses ')' in string function countCloseParen(in_str){ //regular expression pattern to specify a global search for the close parenthesis ')' character var close_paren_regexp =/\)/g; var num_close_paren = 0; //calls countChar function to count number of occurances of close parentheses num_close_paren = countChar(close_paren_regexp, in_str); return num_close_paren; } //Count number of occurances of the character specified by the regular expression pattern function countChar(in_regexp_patt, in_str){ var num_char = 0; //counts the number of occurances of the character specified by the regular expression pattern /* NOTE: the .match() function returns null if no match is found. Since that would result in the .length() function throwing a TypeError if called on a null value, "||[]" is included after the .match() function call. This causes .match() to return a 0 length array instead of null if no match is found, which allows .length() to return a count of '0' instead of throwing a TypeError. */ try{ num_char = (in_str.match(in_regexp_patt)||[]).length; }catch(e){ switch(e.name){ case "TypeError": num_char = 0; break; default: throw e; num_char = 0; break; } } return num_char; } //#ISSUE 138 Fix Start //Resetting the Checked values to avoid saving duplicate consents function clearConsent(form){ $("form input").each(function(){ if($(this).prop("checked")==true){ $(this).prop('checked', false); } }); } //#ISSUE 138 Fix End function populateModalData(jsonObj, isProviderAdminUser) { //TODO (MH): Add try/catch block for JSON.parse var validationDataObj = JSON.parse(jsonObj); var selected_authorized_providers_ary = validationDataObj.selectedAuthorizedProviders; var selected_discloseTo_providers_ary = validationDataObj.selectedDiscloseToProviders; var selected_purposeOf_use_ary = validationDataObj.selectedPurposeOfUse; var existing_authorized_providers_ary = validationDataObj.existingAuthorizedProviders; var existing_discloseTo_providers_ary = validationDataObj.existingDiscloseToProviders; var existing_purposeOf_use_ary = validationDataObj.existingPurposeOfUse; var selected_authorized_providers_string = ""; var selected_discloseTo_providers_string = ""; var selected_purposeOf_use_string = ""; try{ selected_authorized_providers_string = arrayToUlString(selected_authorized_providers_ary); selected_discloseTo_providers_string = arrayToUlString(selected_discloseTo_providers_ary); selected_purposeOf_use_string = arrayToUlString(selected_purposeOf_use_ary); }catch(err){ if(err.name === "RangeError"){ selected_authorized_providers_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; selected_discloseTo_providers_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; selected_purposeOf_use_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; } } var selected_consent_start_date_string = validationDataObj.selectedConsentStartDate; var selected_consent_end_date_string = validationDataObj.selectedConsentEndDate; var existing_authorized_providers_string = ""; var existing_discloseTo_providers_string = ""; var existing_purposeOf_use_string = ""; try{ existing_authorized_providers_string = arrayToUlString(existing_authorized_providers_ary); existing_discloseTo_providers_string = arrayToUlString(existing_discloseTo_providers_ary); existing_purposeOf_use_string = arrayToUlString(existing_purposeOf_use_ary); }catch(err){ existing_authorized_providers_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; existing_discloseTo_providers_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; existing_purposeOf_use_string = "<ul><li>ERROR DISPLAYING DATA</li></ul>"; } var existing_consent_start_date_string = validationDataObj.existingConsentStartDate; var existing_consent_end_date_string = validationDataObj.existingConsentEndDate; var existing_consent_status_string = validationDataObj.existingConsentStatus; var existing_consent_id = validationDataObj.existingConsentId; var selectedConsentPanelElement = $('div#consent_validation_modal form#frm_consent_validation_form > div#pnl_selected_consent'); var existingConsentPanelElement = $('div#consent_validation_modal form#frm_consent_validation_form > div#pnl_existing_consent'); selectedConsentPanelElement.find('div#selected_authorized_providers > span.selected-consent-field-data#selected_authorized_providers_data').empty().html(selected_authorized_providers_string); selectedConsentPanelElement.find('div#selected_discloseTo_providers > span.selected-consent-field-data#selected_discloseTo_providers_data').empty().html(selected_discloseTo_providers_string); selectedConsentPanelElement.find('div#selected_purposeOf_use > span.selected-consent-field-data#selected_purposeOf_use_data').empty().html(selected_purposeOf_use_string); selectedConsentPanelElement.find('div#selected_consent_start_date > span.selected-consent-field-data#selected_consent_start_date_data').text(selected_consent_start_date_string); selectedConsentPanelElement.find('div#selected_consent_end_date > span.selected-consent-field-data#selected_consent_end_date_data').text(selected_consent_end_date_string); existingConsentPanelElement.find('div#existing_authorized_providers > span.existing-consent-field-data#existing_authorized_providers_data').empty().html(existing_authorized_providers_string); existingConsentPanelElement.find('div#existing_discloseTo_providers > span.existing-consent-field-data#existing_discloseTo_providers_data').empty().html(existing_discloseTo_providers_string); existingConsentPanelElement.find('div#existing_purposeOf_use > span.existing-consent-field-data#existing_purposeOf_use_data').empty().html(existing_purposeOf_use_string); existingConsentPanelElement.find('div#existing_consent_start_date > span.existing-consent-field-data#existing_consent_start_date_data').text(existing_consent_start_date_string); existingConsentPanelElement.find('div#existing_consent_end_date > span.existing-consent-field-data#existing_consent_end_date_data').text(existing_consent_end_date_string); existingConsentPanelElement.find('div#existing_consent_status > span.existing-consent-field-data#existing_consent_status_data').text(existing_consent_status_string); //Bind new click event handler to "View Existing Consent" button $('div#pnl_existing_consent button#btn_view_existing_consent').on("click", function(e){ e.preventDefault(); if(isProviderAdminUser === true){ var patientId = $('input#patientId').val(); window.location.href="adminPatientView.html?duplicateconsent=" + existing_consent_id + "&id=" + patientId; }else{ window.location.href="listConsents.html?duplicateconsent=" + existing_consent_id + "#jump_consent_" + existing_consent_id; } }); }
OBHITA/Consent2Share
DS4P/consent2share/pg/web-pg/src/main/webapp/resources/js/consent/addConsent.js
JavaScript
bsd-3-clause
52,910
/** * Created by KP_TerminalUser2 on 05/09/2014. */ var ClinicalEvaluationModel = require('../schema/clinical_evaluation_schema'); var MedicalHistory = require('../models/medical_history'); var DrugAllergy = require('../models/drug_allergy'); var PregnancyInfo = require('../models/pregnancy_info'); var CD4Info = require('../models/cd4_info'); var VLInfo = require('../models/vl_info'); var ARVInfo = require('../models/arv_info'); var PhysicalExam = require('../models/physical_exam'); var WHOStage = require('../models/who_stage'); //Create sub-docs exports.createMedicalHistory = function(args,next){ var medicalHistory = new MedicalHistory(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.medical_history.push(medicalHistory); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createDrugAllergy = function(args,next){ var drugAllergy = new DrugAllergy(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.drug_allergy.push(drugAllergy); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createPregnancyInfo = function(args,next){ var pregnancyInfo = new PregnancyInfo(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.pregnancy_info.push(pregnancyInfo); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createCD4Info = function(args,next){ var cd4Info = new CD4Info(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.cd4_info.push(cd4Info); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createVLInfo = function(args,next){ var vlInfo = new VLInfo(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.vl_info.push(vlInfo); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createARVInfo = function(args,next){ var arvInfo = new ARVInfo(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.arv_info.push(arvInfo); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createPhysicalExam = function(args,next){ var physicalExam = new PhysicalExam(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.physical_exam.push(physicalExam); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; exports.createWHOStage = function(args,next){ var whoStage = new WHOStage(args); ClinicalEvaluationModel.findOne({hospitalId:args.hospital_Id}, function(err,doc){ if(err){ next(err,null); } if(doc){ doc.who_stage.push(whoStage); doc.save(function(err,result){ if(err){ next(err, null); } if(result){ next(null, result) } }); } }); }; //Delete sub-docs exports.removeMedicalHistory = function(clinical, medicalHistory, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.medical_history.splice(doc.medical_history.indexOf(medicalHistory.symptom_description), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removeDrugAllergy = function(clinical, drugAllergy, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.drug_allergy.splice(doc.drug_allergy.indexOf(drugAllergy.description), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removePregnancyInfo = function(clinical, pregnancyInfo, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.pregnancy_info.splice(doc.pregnancy_info.indexOf(pregnancyInfo.date_delivery_expected), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removeCD4Info = function(clinical, cd4Info, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.cd4_info.splice(doc.cd4_info.indexOf(cd4Info.date_recorded), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removeVLInfo = function(clinical, vlInfo, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.vl_info.splice(doc.vl_info.indexOf(vlInfo.date_recorded), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removeARVInfo = function(clinical, arvInfo, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.arv_info.splice(doc.arv_info.indexOf(arvInfo.date_recorded), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removePhysicalExam = function(clinical, physicalExam, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.physical_exam.splice(doc.physical_exam.indexOf(physicalExam.description), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); }; exports.removeWHOStage = function(clinical, whoStage, next){ ClinicalEvaluationModel.findOne(clinical.hospital_Id, function(err, doc){ if(err){ return next(err, null); } if(doc){ doc.who_stage.splice(doc.who_stage.indexOf(whoStage.stage_name), 1); doc.save(function(err){ if(err){ return next(err, null); } }); } }); };
ODItina/dtsms_patient_manager
lib/clinical_evaluation_manager.js
JavaScript
bsd-3-clause
8,716
require([ 'xapp/manager/Context', 'require', 'dcl/dcl', "xide/utils", "delite/popup", "deliteful/Combobox", "deliteful/list/List", "dstore/Memory", "xide/types" ], function (Context, require, dcl,utils,popup,Combobox, List, Memory,types) { var context = null; var fileServerDeviceInstance = null; var StoreClass = null; console.log('app module loaded4x'); Context.notifier.subscribe('onContextReady', function (_context) { console.error('context ready'); context = _context; Context.notifier.subscribe('DevicesConnected', function (evt) { console.log('DevicesConnected'); var deviceManager = context.getDeviceManager(); var deviceName = "File-Server"; //device instance var instance = deviceManager.getInstanceByName(deviceName); if (!instance) { return; } fileServerDeviceInstance = instance; console.log('got file-server instance'); function createStore(ext){ var config = {}; var options = { fields: types.FIELDS.SHOW_ISDIR | types.FIELDS.SHOW_OWNER | types.FIELDS.SHOW_SIZE | types.FIELDS.SHOW_FOLDER_SIZE | types.FIELDS.SHOW_MIME | types.FIELDS.SHOW_PERMISSIONS | types.FIELDS.SHOW_TIME | types.FIELDS.SHOW_MEDIA_INFO }; return new StoreClass({ data: [], config: config, mount: 'none', options: options, driver: fileServerDeviceInstance, glob:ext, micromatch:"!(*.*)" // Only folders }); } function createPopup(button,fileGrid) { var value = []; var _popup; /** * callback when ok */ function ok() { //var value = combo.value; if (value && value[0]) { //set driver variable without network updates //instance.setVariable(targetVariable, value[0], false, false, false); //instance.callCommand(targetCommand); } console.log('ok'); utils.destroy(fileGrid); utils.destroy(_popup); } var dataSource = new Memory({idProperty: "label", data: []}); var list = new List({source: dataSource, righttextAttr: "value"}); var combo = new Combobox({ list: list, id: "combo-single", selectionMode: 'single' }); var gridNode = fileGrid.template.domNode; _popup = new Popup({ /** * Called when clicking the OK button of the popup. * @protected */ okHandler: function () { this.combobox._validateMultiple(this.combobox.inputNode); this.combobox.closeDropDown(); popup.close(button.popup); ok(); }, /** * Called when clicking the Cancel button of the popup. * @protected */ cancelHandler: function () { this.combobox.list.selectedItems = this.combobox._selectedItems; this.combobox.closeDropDown(); popup.close(button.popup); console.log('cancel'); utils.destroy(fileGrid); utils.destroy(_popup); }, combobox: combo }); //extend button utils.mixin(button, { popup:_popup, _setLabelAttr: function (label) { this.textContent = label; this._set("label", label); }, closePopup: function () { if (this.open) { popup.close(this.popup); this.open = false; } }, _deactivatedHandler: function () { //this.closePopup(); }, _openPopup: function () { $(combo.list).css('height','600px'); $(combo.list).css('width','800px'); $(combo.list).empty(); $(combo.list).append(gridNode); this._openRet = popup.open({ popup: this.popup, parent: this, around: this, orient: ['center'], maxHeight: -1 }); this.open = true; fileGrid._parent = combo.list; $(gridNode).css('height','100%'); $(gridNode).css('width','100%'); //fileGrid.resize(); setTimeout(function(){ fileGrid.refresh().then(function(){ fileGrid.collection._loadPath('.',true).then(function(){ fileGrid.refresh(); fileGrid.showColumn("0",true); fileGrid.showColumn("1",true); }); //fileGrid._showColumn(1); }); $(gridNode).css('height','100%'); },1000); } }); button.on("delite-deactivated", function () { button._deactivatedHandler(); }); button._openPopup(); } function createPickerPopup(button,picker,Popup) { var value = []; var _popup; /** * callback when ok */ function ok() { console.log('ok ',picker._selection[0].path); utils.destroy(picker); utils.destroy(_popup); } var dataSource = new Memory({idProperty: "label", data: []}); var list = new List({source: dataSource, righttextAttr: "value"}); var combo = new Combobox({ list: list, id: "combo-single", selectionMode: 'single' }); var gridNode = picker.domNode; _popup = new Popup({ /** * Called when clicking the OK button of the popup. * @protected */ okHandler: function () { this.combobox._validateMultiple(this.combobox.inputNode); this.combobox.closeDropDown(); popup.close(button.popup); ok(); }, /** * Called when clicking the Cancel button of the popup. * @protected */ cancelHandler: function () { this.combobox.list.selectedItems = this.combobox._selectedItems; this.combobox.closeDropDown(); popup.close(button.popup); console.log('cancel'); utils.destroy(picker); utils.destroy(_popup); }, combobox: combo }); //extend button utils.mixin(button, { popup:_popup, _setLabelAttr: function (label) { this.textContent = label; this._set("label", label); }, closePopup: function () { if (this.open) { popup.close(this.popup); this.open = false; } }, _deactivatedHandler: function () { //this.closePopup(); }, _openPopup: function () { $(combo.list).css('height','600px'); $(combo.list).css('width','800px'); $(combo.list).empty(); $(combo.list).append(gridNode); this._openRet = popup.open({ popup: this.popup, parent: this, around: this, orient: ['center'], maxHeight: -1 }); this.open = true; picker._parent = combo.list; $(gridNode).css('height','100%'); $(gridNode).css('width','100%'); function refreshGrid(fileGrid){ fileGrid.collection._loadPath('.',true).then(function(){ fileGrid.refresh(); }); } setTimeout(function() { refreshGrid(picker.leftGrid); setTimeout(function() { refreshGrid(picker.rightGrid); },1000); },1000); } }); button.on("delite-deactivated", function () { button._deactivatedHandler(); }); button._openPopup(); } window['openFolderPicker'] = function(button){ require(['xfile/build/xfiler'],function(){ require([ "workspace_user/Widgets/Popup", 'xfile/views/FileGridLight', 'xide/utils', 'xfile/data/DriverStore', 'xide/types', 'dojo/Deferred', 'xide/_Popup', 'xfile/views/FilePicker', "dojo/_base/declare", "requirejs-dplugins/css!../../../css/xfile/main_lib.css" ], function (Popup,FileGridLight, utils, DriverStore, types,Deferred,_Popup,FilePicker,declare) { _Popup.setStartIndex(2000); var config = {}; var options = { fields: types.FIELDS.SHOW_ISDIR | types.FIELDS.SHOW_OWNER | types.FIELDS.SHOW_SIZE | types.FIELDS.SHOW_FOLDER_SIZE | types.FIELDS.SHOW_MIME | types.FIELDS.SHOW_PERMISSIONS | types.FIELDS.SHOW_TIME | types.FIELDS.SHOW_MEDIA_INFO }; //device manager var deviceManager = context.getDeviceManager(); var deviceName = "File-Server"; //device instance fileServerDeviceInstance = deviceManager.getInstanceByName(deviceName); StoreClass = DriverStore; var owner = {}; var permissions =utils.clone(types.DEFAULT_FILE_GRID_PERMISSIONS); var picker = utils.addWidget(FilePicker,utils.mixin({ ctx: context, owner: owner, selection: '.', resizeToParent: true, storeOptionsMixin: { "includeList": "*,.*", "excludeList": "" }, Module: FileGridLight, permissions: permissions, leftStore:createStore("/*"), rightStore:createStore("/*") },{}),this,$('#root')[0],true); createPickerPopup(button,picker,Popup); }); }); }; //openFolderPicker($('#picker')[0]); }); }); });
xblox/control-freak
example_workspace/workspace/AXFile.js
JavaScript
bsd-3-clause
13,328
/*! * Copyright 2012 Tsvetan Tsvetkov * * 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. * * Author: Tsvetan Tsvetkov ([email protected]) */ (function (win) { /* Safari native methods required for Notifications do NOT run in strict mode. */ //"use strict"; var PERMISSION_DEFAULT = "default", PERMISSION_GRANTED = "granted", PERMISSION_DENIED = "denied", PERMISSION = [PERMISSION_GRANTED, PERMISSION_DEFAULT, PERMISSION_DENIED], defaultSetting = { pageVisibility: false, autoClose: 0 }, empty = {}, emptyString = "", isSupported = (function () { var isSupported = false; /* * Use try {} catch() {} because the check for IE may throws an exception * if the code is run on browser that is not Safar/Chrome/IE or * Firefox with html5notifications plugin. * * Also, we canNOT detect if msIsSiteMode method exists, as it is * a method of host object. In IE check for existing method of host * object returns undefined. So, we try to run it - if it runs * successfully - then it is IE9+, if not - an exceptions is thrown. */ try { isSupported = !!(/* Safari, Chrome */win.Notification || /* Chrome & ff-html5notifications plugin */win.webkitNotifications || /* Firefox Mobile */navigator.mozNotification || /* IE9+ */(win.external && win.external.msIsSiteMode() !== undefined)); } catch (e) {} return isSupported; }()), ieVerification = Math.floor((Math.random() * 10) + 1), isFunction = function (value) { return (value && (value).constructor === Function); }, isString = function (value) {return (value && (value).constructor === String); }, isObject = function (value) {return (value && (value).constructor === Object); }, /** * Dojo Mixin */ mixin = function (target, source) { var name, s; for (name in source) { s = source[name]; if (!(name in target) || (target[name] !== s && (!(name in empty) || empty[name] !== s))) { target[name] = s; } } return target; // Object }, noop = function () {}, settings = defaultSetting; function getNotification(title, options) { var notification; if (win.Notification) { /* Safari 6, Chrome (23+) */ notification = new win.Notification(title, { /* The notification's icon - For Chrome in Windows, Linux & Chrome OS */ icon: isString(options.icon) ? options.icon : options.icon.x32, /* The notification’s subtitle. */ body: options.body || emptyString, /* The notification’s unique identifier. This prevents duplicate entries from appearing if the user has multiple instances of your website open at once. */ tag: options.tag || emptyString }); } else if (win.webkitNotifications) { /* FF with html5Notifications plugin installed */ notification = win.webkitNotifications.createNotification(options.icon, title, options.body); notification.show(); } else if (navigator.mozNotification) { /* Firefox Mobile */ notification = navigator.mozNotification.createNotification(title, options.body, options.icon); notification.show(); } else if (win.external && win.external.msIsSiteMode()) { /* IE9+ */ //Clear any previous notifications win.external.msSiteModeClearIconOverlay(); win.external.msSiteModeSetIconOverlay((isString(options.icon) ? options.icon : options.icon.x16), title); win.external.msSiteModeActivate(); notification = { "ieVerification": ieVerification + 1 }; } return notification; } function getWrapper(notification) { return { close: function () { if (notification) { if (notification.close) { //http://code.google.com/p/ff-html5notifications/issues/detail?id=58 notification.close(); } else if (notification.cancel) { notification.cancel(); } else if (win.external && win.external.msIsSiteMode()) { if (notification.ieVerification === ieVerification) { win.external.msSiteModeClearIconOverlay(); } } } } }; } function requestPermission(callback) { if (!isSupported) { return; } var callbackFunction = isFunction(callback) ? callback : noop; if (win.webkitNotifications && win.webkitNotifications.checkPermission) { /* * Chrome 23 supports win.Notification.requestPermission, but it * breaks the browsers, so use the old-webkit-prefixed * win.webkitNotifications.checkPermission instead. * * Firefox with html5notifications plugin supports this method * for requesting permissions. */ win.webkitNotifications.requestPermission(callbackFunction); } else if (win.Notification && win.Notification.requestPermission) { win.Notification.requestPermission(callbackFunction); } } function permissionLevel() { var permission; if (!isSupported) { return; } if (win.Notification && win.Notification.permissionLevel) { //Safari 6 permission = win.Notification.permissionLevel(); } else if (win.webkitNotifications && win.webkitNotifications.checkPermission) { //Chrome & Firefox with html5-notifications plugin installed permission = PERMISSION[win.webkitNotifications.checkPermission()]; } else if (win.Notification && win.Notification.permission) { // Firefox 23+ permission = win.Notification.permission; } else if (navigator.mozNotification) { //Firefox Mobile permission = PERMISSION_GRANTED; } else if (win.external && (win.external.msIsSiteMode() !== undefined)) { /* keep last */ //IE9+ permission = win.external.msIsSiteMode() ? PERMISSION_GRANTED : PERMISSION_DEFAULT; } return permission; } /** * */ function config(params) { if (params && isObject(params)) { mixin(settings, params); } return settings; } function createNotification(title, options) { var notification, notificationWrapper; /* Return undefined if notifications are not supported. Return undefined if no permissions for displaying notifications. Title and icons are required. Return undefined if not set. */ if (isSupported && isString(title) && (options && (isString(options.icon) || isObject(options.icon))) && (permissionLevel() === PERMISSION_GRANTED)) { notification = getNotification(title, options); } notificationWrapper = getWrapper(notification); //Auto-close notification if (settings.autoClose && notification && !notification.ieVerification && notification.addEventListener) { notification.addEventListener("show", function () { var notification = notificationWrapper; win.setTimeout(function () { notification.close(); }, settings.autoClose); }); } return notificationWrapper; } win.notify = { PERMISSION_DEFAULT: PERMISSION_DEFAULT, PERMISSION_GRANTED: PERMISSION_GRANTED, PERMISSION_DENIED: PERMISSION_DENIED, isSupported: isSupported, config: config, createNotification: createNotification, permissionLevel: permissionLevel, requestPermission: requestPermission }; if (isFunction(Object.seal)) { Object.seal(win.notify); } }(window)); /** * @name ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause * * @version 1.1 dev * * This bits acts as middle-man between the notify (above) and the ElkNotifications * providing the interface required by the latter. */ (function() { var ElkDesktop = (function(opt) { 'use strict'; opt = (opt) ? opt : {}; var notif, aleradyChecked = false, permission_granted = false; var init = function(opt) { notif = notify; }; var send = function(request) { if (request.desktop_notifications.new_from_last > 0) { if (!hasPermissions()) return; notif.createNotification(request.desktop_notifications.title, { body: request.desktop_notifications.message, icon: elk_images_url + '/mobile.png' }); } }; var hasPermissions = function() { if (aleradyChecked) return permission_granted; notif.requestPermission(); permission_granted = notif.permissionLevel() === notif.PERMISSION_GRANTED; aleradyChecked = true; return permission_granted; } init(opt); return { send: send } }); // AMD / RequireJS if ( typeof define !== 'undefined' && define.amd) { define([], function() { return ElkDesktop; }); } // CommonJS else if ( typeof module !== 'undefined' && module.exports) { module.exports = ElkDesktop; } // included directly via <script> tag else { this.ElkDesktop = ElkDesktop; } })();
joshuaadickerson/Elkarte2
Elkarte/www/themes/default/scripts/desktop-notify.js
JavaScript
bsd-3-clause
10,439
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.5.2.1_A1_T1; * @section: 15.5.2.1; * @assertion: When "String" is called as part of a new expression, it is a constructor: it initialises the newly created object and * The [[Value]] property of the newly constructed object is set to ToString(value), or to the empty string if value is not supplied; * @description: Creating string object with expression "new String"; */ var __str = new String; ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (typeof __str !== "object") { $ERROR('#1: __str = new String; typeof __str === "object". Actual: typeof __str ==='+typeof __str ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#1.5 if (__str.constructor !== String) { $ERROR('#1.5: __str = new String; __str.constructor === String. Actual: __str.constructor ==='+__str.constructor ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__str != "") { $ERROR('#2: __str = new String; __str == "". Actual: __str =='+__str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if ( __str === "") { $ERROR('#3: __str = new String; __str !== ""'); } // //////////////////////////////////////////////////////////////////////////////
luboid/ES5.Script
TestScripts/sputniktests/tests/Conformance/15_Native_ECMA_Script_Objects/15.5_String_Objects/15.5.2_The_String_Constructor/S15.5.2.1_A1_T1.js
JavaScript
bsd-3-clause
1,701
// 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 * @implements {WebInspector.App} * @implements {WebInspector.TargetManager.Observer} */ WebInspector.ScreencastApp = function() { this._enabledSetting = WebInspector.settings.createSetting("screencastEnabled", true); this._toggleButton = new WebInspector.ToolbarToggle(WebInspector.UIString("Toggle screencast"), "phone-toolbar-item"); this._toggleButton.setToggled(this._enabledSetting.get()); this._toggleButton.addEventListener("click", this._toggleButtonClicked, this); WebInspector.targetManager.observeTargets(this); }; WebInspector.ScreencastApp.prototype = { /** * @override * @param {!Document} document */ presentUI: function(document) { var rootView = new WebInspector.RootView(); this._rootSplitWidget = new WebInspector.SplitWidget(false, true, "InspectorView.screencastSplitViewState", 300, 300); this._rootSplitWidget.setVertical(true); this._rootSplitWidget.setSecondIsSidebar(true); this._rootSplitWidget.show(rootView.element); this._rootSplitWidget.hideMain(); this._rootSplitWidget.setSidebarWidget(WebInspector.inspectorView); WebInspector.inspectorView.showInitialPanel(); rootView.attachToDocument(document); }, /** * @override * @param {!WebInspector.Target} target */ targetAdded: function(target) { if (this._target) return; this._target = target; if (target.hasBrowserCapability()) { this._screencastView = new WebInspector.ScreencastView(target); this._rootSplitWidget.setMainWidget(this._screencastView); this._screencastView.initialize(); } else { this._toggleButton.setEnabled(false); } this._onScreencastEnabledChanged(); }, /** * @override * @param {!WebInspector.Target} target */ targetRemoved: function(target) { if (this._target === target) { delete this._target; if (!this._screencastView) return; this._toggleButton.setEnabled(false); this._screencastView.detach(); delete this._screencastView; this._onScreencastEnabledChanged(); } }, _toggleButtonClicked: function() { var enabled = !this._toggleButton.toggled(); this._enabledSetting.set(enabled); this._onScreencastEnabledChanged(); }, _onScreencastEnabledChanged: function() { if (!this._rootSplitWidget) return; var enabled = this._enabledSetting.get() && this._screencastView; this._toggleButton.setToggled(enabled); if (enabled) this._rootSplitWidget.showBoth(); else this._rootSplitWidget.hideMain(); } }; /** @type {!WebInspector.ScreencastApp} */ WebInspector.ScreencastApp._appInstance; /** * @return {!WebInspector.ScreencastApp} */ WebInspector.ScreencastApp._instance = function() { if (!WebInspector.ScreencastApp._appInstance) WebInspector.ScreencastApp._appInstance = new WebInspector.ScreencastApp(); return WebInspector.ScreencastApp._appInstance; }; /** * @constructor * @implements {WebInspector.ToolbarItem.Provider} */ WebInspector.ScreencastApp.ToolbarButtonProvider = function() { } WebInspector.ScreencastApp.ToolbarButtonProvider.prototype = { /** * @override * @return {?WebInspector.ToolbarItem} */ item: function() { return WebInspector.ScreencastApp._instance()._toggleButton; } } /** * @constructor * @implements {WebInspector.AppProvider} */ WebInspector.ScreencastAppProvider = function() { }; WebInspector.ScreencastAppProvider.prototype = { /** * @override * @return {!WebInspector.App} */ createApp: function() { return WebInspector.ScreencastApp._instance(); } };
danakj/chromium
third_party/WebKit/Source/devtools/front_end/screencast/ScreencastApp.js
JavaScript
bsd-3-clause
4,119
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Using.js - Simple JavaScript module loader. Copyright (c) 2015 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name using.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* global document, console */ var using = (function () { "use strict"; var modules = {}, loadedScripts = {}, dependencies = {}, definitions = {}, dependingOn = {}; var runners = [], selectors = {}, runnersCheckInProgress = false; var getAbsoluteUrl = (function () { var a = document.createElement('a'); return function (url) { a.href = url; return a.href; }; }()); function updateModule (moduleName) { var deps = [], depNames = dependencies[moduleName], moduleResult; var currentSelectors = selectors[moduleName]; if (modules[moduleName]) { return; } if (depNames.length === 0) { moduleResult = definitions[moduleName](); if (!moduleResult) { console.error("Module '" + moduleName + "' returned nothing"); } modules[moduleName] = moduleResult; dependingOn[moduleName].forEach(updateModule); } else if (allModulesLoaded(depNames)) { //console.log("currentSelectors, depNames:", currentSelectors, depNames); depNames.forEach(function (name, i) { deps.push(select(name, currentSelectors[i])); }); moduleResult = definitions[moduleName].apply(undefined, deps); if (!moduleResult) { console.error("Module '" + moduleName + "' returned nothing."); } modules[moduleName] = moduleResult; dependingOn[moduleName].forEach(updateModule); } startRunnersCheck(); } function startRunnersCheck () { if (runnersCheckInProgress) { return; } runnersCheckInProgress = true; checkRunners(); } function checkRunners () { runners.forEach(function (runner) { runner(); }); if (runners.length) { setTimeout(checkRunners, 20); } else { runnersCheckInProgress = false; } } function allModulesLoaded (moduleNames) { var loaded = true; moduleNames.forEach(function (name) { if (!modules[name]) { loaded = false; } }); return loaded; } function select (moduleName, selectors) { var argSelectors, mod; mod = modules[moduleName]; if (!selectors) { console.log("Module has no selectors:", moduleName); return mod; } argSelectors = selectors.slice(); while (argSelectors.length) { if (typeof mod !== "object" || mod === null) { throw new TypeError("Module '" + moduleName + "' has no property '" + argSelectors.join("::") + "'."); } mod = mod[argSelectors.shift()]; } return mod; } function using (/* module names */) { var args, moduleNames, moduleSelectors, capabilityObject; moduleNames = []; moduleSelectors = []; args = [].slice.call(arguments); args.forEach(function (arg, index) { var selector, moduleName; var parts = arg.split("::"); var protocolParts = parts[0].split(":"); var protocol = protocolParts.length > 1 ? protocolParts[0] : ""; parts[0] = protocolParts.length > 1 ? protocolParts[1] : protocolParts[0]; selector = parts.slice(1); moduleName = parts[0]; if (protocol === "ajax") { moduleNames.push(arg); } else { moduleNames.push(moduleName); } moduleSelectors.push(selector); if (!(moduleName in dependencies) && !(moduleName in modules)) { if (protocol === "ajax") { dependencies[arg] = []; if (!dependingOn[arg]) { dependingOn[arg] = []; } using.ajax(using.ajax.HTTP_METHOD_GET, arg.replace(/^ajax:/, ""), null, ajaxResourceSuccessFn, ajaxResourceSuccessFn); } else { dependencies[moduleName] = []; if (!dependingOn[moduleName]) { dependingOn[moduleName] = []; } loadModule(moduleName); } } function ajaxResourceSuccessFn (request) { modules[arg] = request; dependingOn[arg].forEach(updateModule); } }); capabilityObject = { run: run, define: define }; return capabilityObject; function run (callback) { if (!runner(true)) { runners.push(runner); } startRunnersCheck(); return capabilityObject; function runner (doNotRemove) { var deps = []; if (allModulesLoaded(moduleNames)) { //console.log("moduleSelectors, moduleNames:", moduleSelectors, moduleNames); moduleNames.forEach(function (name, i) { deps.push(select(name, moduleSelectors[i])); }); callback.apply(undefined, deps); if (!doNotRemove) { runners.splice(runners.indexOf(runner), 1); } return true; } return false; } } function define (moduleName, callback) { if (exists(moduleName)) { console.warn("Module '" + moduleName + "' is already defined."); return capabilityObject; } definitions[moduleName] = callback; dependencies[moduleName] = moduleNames; selectors[moduleName] = moduleSelectors; if (!dependingOn[moduleName]) { dependingOn[moduleName] = []; } moduleNames.forEach(function (name) { if (!dependingOn[name]) { dependingOn[name] = []; } dependingOn[name].push(moduleName); }); updateModule(moduleName); return capabilityObject; } } function exists (name) { return name in definitions; } using.exists = exists; using.path = ""; (function () { var scripts = document.getElementsByTagName("script"); using.path = scripts[scripts.length - 1].src.replace(/using\.js$/, ""); }()); using.modules = {}; function loadModule (moduleName) { if (!(moduleName in using.modules)) { throw new Error("Unknown module '" + moduleName + "'."); } using.loadScript(using.modules[moduleName]); } using.loadScript = function (url) { url = getAbsoluteUrl(url); var script = document.createElement("script"); if (loadedScripts[url] || scriptExists(url)) { return; } script.setAttribute("data-inserted-by", "using.js"); script.src = url; loadedScripts[url] = true; document.body.appendChild(script); }; function scriptExists (url) { var exists = false; var scripts = document.getElementsByTagName("script"); [].forEach.call(scripts, function (script) { var src = script.getAttribute("src"); if (src && getAbsoluteUrl(src) === url) { exists = true; } }); return exists; } return using; }()); /* global using, XMLHttpRequest, ActiveXObject */ using.ajax = (function () { var HTTP_STATUS_OK = 200; var READY_STATE_UNSENT = 0; var READY_STATE_OPENED = 1; var READY_STATE_HEADERS_RECEIVED = 2; var READY_STATE_LOADING = 3; var READY_STATE_DONE = 4; function ajax (method, url, data, onSuccess, onError, timeout) { var requestObject = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); requestObject.open(method, url + "?random=" + Math.random(), true); if (timeout) { requestObject.timeout = timeout; requestObject.ontimeout = function () { requestObject.abort(); if (!onError) { return; } onError(new Error("Connection has reached the timeout of " + timeout + " ms.")); }; } requestObject.onreadystatechange = function() { var done, statusOk; done = requestObject.readyState === READY_STATE_DONE; if (done) { try { statusOk = requestObject.status === HTTP_STATUS_OK; } catch (error) { console.error(error); statusOk = false; } if (statusOk) { onSuccess(requestObject); } else { onError(requestObject); } } }; if (data) { requestObject.send(data); } else { requestObject.send(); } return requestObject; } ajax.HTTP_STATUS_OK = HTTP_STATUS_OK; ajax.READY_STATE_UNSENT = READY_STATE_UNSENT; ajax.READY_STATE_OPENED = READY_STATE_OPENED; ajax.READY_STATE_HEADERS_RECEIVED = READY_STATE_HEADERS_RECEIVED; ajax.READY_STATE_LOADING = READY_STATE_LOADING; ajax.READY_STATE_DONE = READY_STATE_DONE; ajax.HTTP_METHOD_GET = "GET"; ajax.HTTP_METHOD_POST = "POST"; ajax.HTTP_METHOD_PUT = "PUT"; ajax.HTTP_METHOD_DELETE = "DELETE"; ajax.HTTP_METHOD_HEAD = "HEAD"; return ajax; }()); /* WebStory Engine dependencies (v2016.7.1-final.1608060015) Build time: Fri, 02 Sep 2016 20:22:53 GMT */ (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){ /* global using, require */ using().define("class-manipulator", function () { return require("class-manipulator"); }); using().define("databus", function () { return require("databus"); }); using().define("eases", function () { return require("eases"); }); using().define("easy-ajax", function () { return require("easy-ajax"); }); using().define("enjoy-core", function () { return require("enjoy-core"); }); using().define("enjoy-typechecks", function () { return require("enjoy-typechecks"); }); using().define("howler", function () { return require("howler"); }); using().define("string-dict", function () { return require("string-dict"); }); using().define("transform-js", function () { return require("transform-js"); }); using().define("xmugly", function () { return require("xmugly"); }); },{"class-manipulator":2,"databus":3,"eases":23,"easy-ajax":38,"enjoy-core":58,"enjoy-typechecks":85,"howler":86,"string-dict":87,"transform-js":88,"xmugly":121}],2:[function(require,module,exports){ // // # class-manipulator // // A chainable wrapper API for manipulating a DOM Element's classes or class strings. // /* global module */ // // ## Public API // // // **list(element) / list(classString)** // // Creates a chainable API for manipulating an element's list of classes. No changes // are made to the DOM Element unless `.apply()` is called. // // DOMElement|string -> object // function list (element) { element = typeof element === "object" ? element : dummy(element); var classes = parse(element), controls; // // **.apply()** // // Applies class list to the source element. // // void -> object // function apply () { element.setAttribute("class", toString()); return controls; } // // **.add(name)** // // Adds a class to the element's list of class names. // // string -> object // function add (name) { if (hasSpaces(name)) { return addMany(classStringToArray(name)); } if (!has(name)) { classes.push(name); } return controls; } // // **.addMany(names)** // // Adds many classes to the list at once. // // [string] -> object // function addMany (newClasses) { if (!Array.isArray(newClasses)) { return add(newClasses); } newClasses.forEach(add); return controls; } // // **.has(name)** // // Checks whether a class is in the element's list of class names. // // string -> boolean // function has (name) { if (hasSpaces(name)) { return hasAll(name); } return classes.indexOf(name) >= 0; } // // **.hasSome(names)** // // Checks whether the list contains at least one of the supplied classes. // // [string] -> boolean // function hasSome (names) { return Array.isArray(names) ? names.some(has) : hasSome(classStringToArray(names)); } // // **.hasAll(names)** // // Checks whether the list contains all of the supplied classes. // // [string] -> boolean // function hasAll (names) { return Array.isArray(names) ? names.every(has) : hasAll(classStringToArray(names)); } // // **.remove(name)** // // Removes a class from the element's list of class names. // // string -> object // function remove (name) { if (hasSpaces(name)) { return removeMany(classStringToArray(name)); } if (has(name)) { classes.splice(classes.indexOf(name), 1); } return controls; } // // **.removeMany(names)** // // Removes many classes from the list at once. // // [string] -> object // function removeMany (toRemove) { if (!Array.isArray(toRemove)) { return remove(toRemove); } toRemove.forEach(remove); return controls; } // // **.toggle(name)** // // Removes a class from the class list when it's present or adds it to the list when it's not. // // string -> object // function toggle (name) { if (hasSpaces(name)) { return toggleMany(classStringToArray(name)); } return (has(name) ? remove(name) : add(name)); } // // **.toggleMany(names)** // // Toggles many classes at once. // // [string] -> object // function toggleMany (names) { if (Array.isArray(names)) { names.forEach(toggle); return controls; } return toggleMany(classStringToArray(names)); } // // **.toArray()** // // Creates an array containing all of the list's class names. // // void -> [string] // function toArray () { return classes.slice(); } // // **.toString()** // // Returns a string containing all the classes in the list separated by a space character. // function toString () { return classes.join(" "); } // // **.copyTo(otherElement)** // // Creates a new empty list for another element and copies the source element's class list to it. // // DOM Element -> object // function copyTo (otherElement) { return list(otherElement).clear().addMany(classes); } // // **.clear()** // // Removes all classes from the list. // // void -> object // function clear () { classes.length = 0; return controls; } // // **.filter(fn)** // // Removes those class names from the list that fail a predicate test function. // // (string -> number -> object -> boolean) -> object // function filter (fn) { classes.forEach(function (name, i) { if (!fn(name, i, controls)) { remove(name); } }); return controls; } // // **.sort([fn])** // // Sorts the names in place. A custom sort function can be applied optionally. It must have // the same signature as JS Array.prototype.sort() callbacks. // // void|function -> object // function sort (fn) { classes.sort(fn); return controls; } // // **.size()** // // Returns the number of classes in the list. // // void -> number // function size () { return classes.length; } controls = { add: add, addMany: addMany, has: has, hasSome: hasSome, hasAll: hasAll, remove: remove, removeMany: removeMany, toggle: toggle, toggleMany: toggleMany, apply: apply, clear: clear, copyTo: copyTo, toArray: toArray, toString: toString, filter: filter, sort: sort, size: size }; return controls; } // // **add(element, name)** // // Adds a class to a DOM Element. // // DOM Element -> string -> object // function add (element, name) { return list(element).add(name).apply(); } // // **remove(element, name)** // // Removes a class from a DOM Element. // // DOM Element -> string -> object // function remove (element, name) { return list(element).remove(name).apply(); } // // **toggle(element, name)** // // Removes a class from a DOM Element when it has the class or adds it when the element doesn't // have it. // // DOMElement -> string -> object // function toggle (element, name) { return list(element).toggle(name).apply(); } // // **has(element, name)** // // Checks whether a DOM Element has a class. // // DOMElement -> string -> boolean // function has (element, name) { return list(element).has(name); } // // ## Exported functions // module.exports = { add: add, remove: remove, toggle: toggle, has: has, list: list }; // // ## Private functions // // // Extracts the class names from a DOM Element and returns them in an array. // // DOMElement -> [string] // function parse (element) { return classStringToArray(element.getAttribute("class") || ""); } // // string -> [string] // function classStringToArray (classString) { return ("" + classString).replace(/\s+/, " ").trim().split(" ").filter(stringNotEmpty); } // // string -> boolean // function stringNotEmpty (str) { return str !== ""; } // // string -> boolean // function hasSpaces (str) { return !!str.match(/\s/); } // // Creates a dummy DOMElement for when we don't have an actual one for a list. // // string -> object // function dummy (classList) { if (typeof classList !== "string") { throw new Error("Function list() expects an object or string as its argument."); } var attributes = { "class": "" + classStringToArray(classList).join(" ") }; return { setAttribute: function (name, value) { attributes[name] = value; }, getAttribute: function (name) { return attributes[name]; } }; } },{}],3:[function(require,module,exports){ /* global require, module */ module.exports = require("./src/databus"); },{"./src/databus":4}],4:[function(require,module,exports){ /* global using, setTimeout, console, window, module */ (function DataBusBootstrap () { if (typeof require === "function") { module.exports = DataBusModule(); } else if (typeof using === "function") { using().define("databus", DataBusModule); } else { window.DataBus = DataBusModule(); } function DataBusModule () { "use strict"; function DataBus (args) { var self = this; args = args || {}; this.debug = args.debug || false; this.interceptErrors = args.interceptErrors || false; this.log = args.log || false; this.logData = args.logData || false; this.defaults = args.defaults || {}; this.defaults.flowType = this.defaults.flowType || DataBus.FLOW_TYPE_ASYNCHRONOUS; this.callbacks = { "*": [] }; this.subscribe(errorListener, "EventBus.error"); function errorListener (data) { var name; if (self.debug !== true) { return; } name = data.error.name || "Error"; console.log(name + " in listener; Event: " + data.info.event + "; Message: " + data.error.message); } } DataBus.FLOW_TYPE_ASYNCHRONOUS = 0; DataBus.FLOW_TYPE_SYNCHRONOUS = 1; DataBus.create = function(args) { args = args || {}; return new DataBus(args); }; DataBus.prototype.subscribe = function(parameter1, parameter2) { var listener, event, self = this; if (parameter2 === undefined) { event = "*"; listener = parameter1; } else if (typeof parameter1 === "string" || typeof parameter1 === "number") { event = parameter1; listener = parameter2; } else if (typeof parameter2 === "string" || typeof parameter2 === "number") { event = parameter2; listener = parameter1; } if (typeof event !== "string" && typeof event !== "number") { throw new Error("Event names can only be strings or numbers! event: ", event); } if (typeof listener !== "function") { throw new Error("Only functions may be used as listeners!"); } event = event || '*'; this.callbacks[event] = this.callbacks[event] || []; this.callbacks[event].push(listener); this.trigger( "EventBus.subscribe", { listener: listener, event: event, bus: this } ); return function unsubscriber () { self.unsubscribe(listener, event); }; }; DataBus.prototype.unsubscribe = function(parameter1, parameter2) { var cbs, len, i, listener, event; if (parameter2 === undefined) { event = "*"; listener = parameter1; } else if (typeof parameter1 === "string" || typeof parameter1 === "number") { event = parameter1; listener = parameter2; } else if (typeof parameter2 === "string" || typeof parameter2 === "number") { event = parameter2; listener = parameter1; } if (typeof event !== "string" && typeof event !== "number") { throw new Error("Event names can only be strings or numbers! event: ", event); } if (typeof listener !== "function") { throw new Error("Only functions may be used as listeners!"); } event = event || '*'; cbs = this.callbacks[event] || []; len = cbs.length; for (i = 0; i < len; ++i) { if (cbs[i] === listener) { this.callbacks[event].splice(i, 1); } } this.trigger( "EventBus.unsubscribe", { listener: listener, event: event, bus: this } ); }; DataBus.prototype.once = function (listenerOrEvent1, listenerOrEvent2) { var fn, self = this, event, listener; var firstParamIsFunction, secondParamIsFunction, called = false; firstParamIsFunction = typeof listenerOrEvent1 === "function"; secondParamIsFunction = typeof listenerOrEvent2 === "function"; if ((firstParamIsFunction && secondParamIsFunction) || (!firstParamIsFunction && !secondParamIsFunction)) { throw new Error("Parameter mismatch; one parameter needs to be a function, " + "the other one must be a string."); } if (firstParamIsFunction) { listener = listenerOrEvent1; event = listenerOrEvent2; } else { listener = listenerOrEvent2; event = listenerOrEvent1; } event = event || "*"; fn = function (data, info) { if (called) { return; } called = true; self.unsubscribe(fn, event); listener(data, info); }; this.subscribe(fn, event); }; DataBus.prototype.trigger = function(event, data, async) { var cbs, len, info, j, f, cur, self, flowType; if ( typeof event !== "undefined" && typeof event !== "string" && typeof event !== "number" ) { throw new Error("Event names can only be strings or numbers! event: ", event); } self = this; event = arguments.length ? event : "*"; flowType = (typeof async !== "undefined" && async === false) ? DataBus.FLOW_TYPE_SYNCHRONOUS : this.defaults.flowType; // get subscribers in all relevant namespaces cbs = (function() { var n, words, wc, matches, k, kc, old = "", out = []; // split event name into namespaces and get all subscribers words = event.split("."); for (n = 0, wc = words.length ; n < wc ; ++n) { old = old + (n > 0 ? "." : "") + words[n]; matches = self.callbacks[old] || []; for (k = 0, kc = matches.length; k < kc; ++k) { out.push(matches[k]); } } if (event === "*") { return out; } // get subscribers for "*" and add them, too matches = self.callbacks["*"] || []; for (k = 0, kc = matches.length ; k < kc ; ++k) { out.push( matches[ k ] ); } return out; }()); len = cbs.length; info = { event: event, subscribers: len, async: flowType === DataBus.FLOW_TYPE_ASYNCHRONOUS ? true : false, getQueueLength: function() { if (len === 0) { return 0; } return len - (j + 1); } }; function asyncThrow (e) { setTimeout( function () { throw e; }, 0 ); } // function for iterating through the list of relevant listeners f = function() { if (self.log === true) { console.log( "EventBus event triggered: " + event + "; Subscribers: " + len, self.logData === true ? "; Data: " + data : "" ); } for (j = 0; j < len; ++j) { cur = cbs[j]; try { cur(data, info); } catch (e) { console.log(e); self.trigger( "EventBus.error", { error: e, info: info } ); if (self.interceptErrors !== true) { asyncThrow(e); } } } }; if (flowType === DataBus.FLOW_TYPE_ASYNCHRONOUS) { setTimeout(f, 0); } else { f(); } }; DataBus.prototype.triggerSync = function (event, data) { return this.trigger(event, data, false); }; DataBus.prototype.triggerAsync = function (event, data) { return this.trigger(event, data, true); }; DataBus.inject = function (obj, args) { args = args || {}; var squid = new DataBus(args); obj.subscribe = function (listener, event) { squid.subscribe(listener, event); }; obj.unsubscribe = function (listener, event) { squid.unsubscribe(listener, event); }; obj.once = function (listener, event) { squid.once(listener, event); }; obj.trigger = function (event, data, async) { async = (typeof async !== "undefined" && async === false) ? false : true; squid.trigger(event, data, async); }; obj.triggerSync = squid.triggerSync.bind(squid); obj.triggerAsync = squid.triggerAsync.bind(squid); obj.subscribe("destroyed", function () { squid.callbacks = []; }); }; return DataBus; } }()); },{}],5:[function(require,module,exports){ function backInOut(t) { var s = 1.70158 * 1.525 if ((t *= 2) < 1) return 0.5 * (t * t * ((s + 1) * t - s)) return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2) } module.exports = backInOut },{}],6:[function(require,module,exports){ function backIn(t) { var s = 1.70158 return t * t * ((s + 1) * t - s) } module.exports = backIn },{}],7:[function(require,module,exports){ function backOut(t) { var s = 1.70158 return --t * t * ((s + 1) * t + s) + 1 } module.exports = backOut },{}],8:[function(require,module,exports){ var bounceOut = require('./bounce-out') function bounceInOut(t) { return t < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - t * 2.0)) : 0.5 * bounceOut(t * 2.0 - 1.0) + 0.5 } module.exports = bounceInOut },{"./bounce-out":10}],9:[function(require,module,exports){ var bounceOut = require('./bounce-out') function bounceIn(t) { return 1.0 - bounceOut(1.0 - t) } module.exports = bounceIn },{"./bounce-out":10}],10:[function(require,module,exports){ function bounceOut(t) { var a = 4.0 / 11.0 var b = 8.0 / 11.0 var c = 9.0 / 10.0 var ca = 4356.0 / 361.0 var cb = 35442.0 / 1805.0 var cc = 16061.0 / 1805.0 var t2 = t * t return t < a ? 7.5625 * t2 : t < b ? 9.075 * t2 - 9.9 * t + 3.4 : t < c ? ca * t2 - cb * t + cc : 10.8 * t * t - 20.52 * t + 10.72 } module.exports = bounceOut },{}],11:[function(require,module,exports){ function circInOut(t) { if ((t *= 2) < 1) return -0.5 * (Math.sqrt(1 - t * t) - 1) return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1) } module.exports = circInOut },{}],12:[function(require,module,exports){ function circIn(t) { return 1.0 - Math.sqrt(1.0 - t * t) } module.exports = circIn },{}],13:[function(require,module,exports){ function circOut(t) { return Math.sqrt(1 - ( --t * t )) } module.exports = circOut },{}],14:[function(require,module,exports){ function cubicInOut(t) { return t < 0.5 ? 4.0 * t * t * t : 0.5 * Math.pow(2.0 * t - 2.0, 3.0) + 1.0 } module.exports = cubicInOut },{}],15:[function(require,module,exports){ function cubicIn(t) { return t * t * t } module.exports = cubicIn },{}],16:[function(require,module,exports){ function cubicOut(t) { var f = t - 1.0 return f * f * f + 1.0 } module.exports = cubicOut },{}],17:[function(require,module,exports){ function elasticInOut(t) { return t < 0.5 ? 0.5 * Math.sin(+13.0 * Math.PI/2 * 2.0 * t) * Math.pow(2.0, 10.0 * (2.0 * t - 1.0)) : 0.5 * Math.sin(-13.0 * Math.PI/2 * ((2.0 * t - 1.0) + 1.0)) * Math.pow(2.0, -10.0 * (2.0 * t - 1.0)) + 1.0 } module.exports = elasticInOut },{}],18:[function(require,module,exports){ function elasticIn(t) { return Math.sin(13.0 * t * Math.PI/2) * Math.pow(2.0, 10.0 * (t - 1.0)) } module.exports = elasticIn },{}],19:[function(require,module,exports){ function elasticOut(t) { return Math.sin(-13.0 * (t + 1.0) * Math.PI/2) * Math.pow(2.0, -10.0 * t) + 1.0 } module.exports = elasticOut },{}],20:[function(require,module,exports){ function expoInOut(t) { return (t === 0.0 || t === 1.0) ? t : t < 0.5 ? +0.5 * Math.pow(2.0, (20.0 * t) - 10.0) : -0.5 * Math.pow(2.0, 10.0 - (t * 20.0)) + 1.0 } module.exports = expoInOut },{}],21:[function(require,module,exports){ function expoIn(t) { return t === 0.0 ? t : Math.pow(2.0, 10.0 * (t - 1.0)) } module.exports = expoIn },{}],22:[function(require,module,exports){ function expoOut(t) { return t === 1.0 ? t : 1.0 - Math.pow(2.0, -10.0 * t) } module.exports = expoOut },{}],23:[function(require,module,exports){ module.exports = { 'backInOut': require('./back-in-out'), 'backIn': require('./back-in'), 'backOut': require('./back-out'), 'bounceInOut': require('./bounce-in-out'), 'bounceIn': require('./bounce-in'), 'bounceOut': require('./bounce-out'), 'circInOut': require('./circ-in-out'), 'circIn': require('./circ-in'), 'circOut': require('./circ-out'), 'cubicInOut': require('./cubic-in-out'), 'cubicIn': require('./cubic-in'), 'cubicOut': require('./cubic-out'), 'elasticInOut': require('./elastic-in-out'), 'elasticIn': require('./elastic-in'), 'elasticOut': require('./elastic-out'), 'expoInOut': require('./expo-in-out'), 'expoIn': require('./expo-in'), 'expoOut': require('./expo-out'), 'linear': require('./linear'), 'quadInOut': require('./quad-in-out'), 'quadIn': require('./quad-in'), 'quadOut': require('./quad-out'), 'quartInOut': require('./quart-in-out'), 'quartIn': require('./quart-in'), 'quartOut': require('./quart-out'), 'quintInOut': require('./quint-in-out'), 'quintIn': require('./quint-in'), 'quintOut': require('./quint-out'), 'sineInOut': require('./sine-in-out'), 'sineIn': require('./sine-in'), 'sineOut': require('./sine-out') } },{"./back-in":6,"./back-in-out":5,"./back-out":7,"./bounce-in":9,"./bounce-in-out":8,"./bounce-out":10,"./circ-in":12,"./circ-in-out":11,"./circ-out":13,"./cubic-in":15,"./cubic-in-out":14,"./cubic-out":16,"./elastic-in":18,"./elastic-in-out":17,"./elastic-out":19,"./expo-in":21,"./expo-in-out":20,"./expo-out":22,"./linear":24,"./quad-in":26,"./quad-in-out":25,"./quad-out":27,"./quart-in":29,"./quart-in-out":28,"./quart-out":30,"./quint-in":32,"./quint-in-out":31,"./quint-out":33,"./sine-in":35,"./sine-in-out":34,"./sine-out":36}],24:[function(require,module,exports){ function linear(t) { return t } module.exports = linear },{}],25:[function(require,module,exports){ function quadInOut(t) { t /= 0.5 if (t < 1) return 0.5*t*t t-- return -0.5 * (t*(t-2) - 1) } module.exports = quadInOut },{}],26:[function(require,module,exports){ function quadIn(t) { return t * t } module.exports = quadIn },{}],27:[function(require,module,exports){ function quadOut(t) { return -t * (t - 2.0) } module.exports = quadOut },{}],28:[function(require,module,exports){ function quarticInOut(t) { return t < 0.5 ? +8.0 * Math.pow(t, 4.0) : -8.0 * Math.pow(t - 1.0, 4.0) + 1.0 } module.exports = quarticInOut },{}],29:[function(require,module,exports){ function quarticIn(t) { return Math.pow(t, 4.0) } module.exports = quarticIn },{}],30:[function(require,module,exports){ function quarticOut(t) { return Math.pow(t - 1.0, 3.0) * (1.0 - t) + 1.0 } module.exports = quarticOut },{}],31:[function(require,module,exports){ function qinticInOut(t) { if ( ( t *= 2 ) < 1 ) return 0.5 * t * t * t * t * t return 0.5 * ( ( t -= 2 ) * t * t * t * t + 2 ) } module.exports = qinticInOut },{}],32:[function(require,module,exports){ function qinticIn(t) { return t * t * t * t * t } module.exports = qinticIn },{}],33:[function(require,module,exports){ function qinticOut(t) { return --t * t * t * t * t + 1 } module.exports = qinticOut },{}],34:[function(require,module,exports){ function sineInOut(t) { return -0.5 * (Math.cos(Math.PI*t) - 1) } module.exports = sineInOut },{}],35:[function(require,module,exports){ function sineIn (t) { var v = Math.cos(t * Math.PI * 0.5) if (Math.abs(v) < 1e-14) return 1 else return 1 - v } module.exports = sineIn },{}],36:[function(require,module,exports){ function sineOut(t) { return Math.sin(t * Math.PI/2) } module.exports = sineOut },{}],37:[function(require,module,exports){ (function () { var HTTP_STATUS_OK = 200; var READY_STATE_UNSENT = 0; var READY_STATE_OPENED = 1; var READY_STATE_HEADERS_RECEIVED = 2; var READY_STATE_LOADING = 3; var READY_STATE_DONE = 4; function ajax (method, url, options, then) { var timeout, data; var requestObject = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); options = options || {}; if (typeof options === "function" && !then) { then = options; options = {}; } then = then || function () {}; data = ("data" in options) ? options.data : undefined; timeout = options.timeout; url += options.randomize ? "?random=" + Math.random() : ""; requestObject.open(method, url, true); if (timeout) { requestObject.timeout = timeout; requestObject.ontimeout = function () { requestObject.abort(); then(new Error("Connection reached timeout of " + timeout + " ms."), requestObject); }; } requestObject.onreadystatechange = function() { var done, statusOk; done = requestObject.readyState === READY_STATE_DONE; if (done) { try { statusOk = requestObject.status === HTTP_STATUS_OK; } catch (error) { console.error(error); statusOk = false; } if (statusOk) { then(null, requestObject); } else { then(new Error("AJAX request wasn't successful."), requestObject); } } }; if (data) { requestObject.send(data); } else { requestObject.send(); } return requestObject; } ajax.HTTP_STATUS_OK = HTTP_STATUS_OK; ajax.READY_STATE_UNSENT = READY_STATE_UNSENT; ajax.READY_STATE_OPENED = READY_STATE_OPENED; ajax.READY_STATE_HEADERS_RECEIVED = READY_STATE_HEADERS_RECEIVED; ajax.READY_STATE_LOADING = READY_STATE_LOADING; ajax.READY_STATE_DONE = READY_STATE_DONE; ajax.HTTP_METHOD_GET = "GET"; ajax.HTTP_METHOD_POST = "POST"; ajax.HTTP_METHOD_PUT = "PUT"; ajax.HTTP_METHOD_DELETE = "DELETE"; ajax.HTTP_METHOD_HEAD = "HEAD"; ajax.get = function (url, options, then) { return ajax(ajax.HTTP_METHOD_GET, url, options, then); }; ajax.post = function (url, data, options, then) { if (typeof options === "function" && !then) { then = options; options = {}; } options.data = data; return ajax(ajax.HTTP_METHOD_POST, url, options, then); }; if (typeof require === "function") { module.exports = ajax; } else { window.ajax = ajax; } }()); },{}],38:[function(require,module,exports){ module.exports = require("./easy-ajax.js"); },{"./easy-ajax.js":37}],39:[function(require,module,exports){ function add () { return Array.prototype.reduce.call(arguments, function (a, b) { return a + b; }); } module.exports = add; },{}],40:[function(require,module,exports){ function apply (fn, args) { if (typeof fn !== "function") { throw new TypeError("Argument 'fn' must be a function."); } return fn.apply(undefined, args); } module.exports = apply; },{}],41:[function(require,module,exports){ function at (collection, key) { return collection[key]; } module.exports = at; },{}],42:[function(require,module,exports){ var bind = require("./bind"); var apply = require("./apply"); // // **auto(fn)** // // Wraps `fn` so that if it is called with only a function as its first argument, // a partial application is returned. This means that you can do this: // // each(fn)(collection); // // Instead of this: // // each(fn, collection); // function auto (fn) { return function () { return ( (arguments.length === 1 && typeof arguments[0] === "function") ? bind(fn, arguments[0]) : apply(fn, arguments) ); }; } module.exports = auto; },{"./apply":40,"./bind":43}],43:[function(require,module,exports){ function bind (fn) { var args = [].slice.call(arguments); args.shift(); return function () { var allArgs = args.slice(), i; for (i = 0; i < arguments.length; i += 1) { allArgs.push(arguments[i]); } return fn.apply(undefined, allArgs); }; } module.exports = bind; },{}],44:[function(require,module,exports){ function call (fn) { var args = [].slice.call(arguments); args.shift(); return fn.apply(undefined, args); } module.exports = call; },{}],45:[function(require,module,exports){ var apply = require("./apply"); var pipe = require("./pipe"); var toArray = require("./toArray"); function compose () { var functions = toArray(arguments); return function (value) { var args = functions.slice(); args.unshift(value); return apply(pipe, args); }; } module.exports = compose; },{"./apply":40,"./pipe":69,"./toArray":83}],46:[function(require,module,exports){ var some = require("./some"); function contains (collection, item) { return some(collection, function (currentItem) { return item === currentItem; }) || false; } module.exports = contains; },{"./some":79}],47:[function(require,module,exports){ function divide () { return Array.prototype.reduce.call(arguments, function (a, b) { return a / b; }); } module.exports = divide; },{}],48:[function(require,module,exports){ var types = require("enjoy-typechecks"); var auto = require("./auto"); function eachInArray (fn, collection) { [].forEach.call(collection, fn); } function eachInObject (fn, collection) { Object.keys(collection).forEach(function (key) { fn(collection[key], key, collection); }); } function each (fn, collection) { return types.isArrayLike(collection) ? eachInArray(fn, collection) : eachInObject(fn, collection); } module.exports = auto(each); },{"./auto":42,"enjoy-typechecks":65}],49:[function(require,module,exports){ var some = require("./some"); var auto = require("./auto"); function every (fn, collection) { var result = true; some(someToEvery, collection); function someToEvery (item, key) { if (!fn(item, key, collection)) { result = false; return true; } return false; } return result; } module.exports = auto(every); },{"./auto":42,"./some":79}],50:[function(require,module,exports){ var each = require("./each"); // // Turns an array of objects into an object where the keys are the // values of a property of the objects contained within the original array. // // Example: // // [{name: "foo"},{name: "bar"}] => {foo: {name: "foo"}, bar: {name: "bar"}} // function expose (collection, key) { var result = {}; each(function (item) { result[item[key]] = item; }, collection); return result; } module.exports = expose; },{"./each":48}],51:[function(require,module,exports){ var each = require("./each"); var auto = require("./auto"); function filter (fn, collection) { var items = []; each(applyFilter, collection); function applyFilter (item, key) { if (fn(item, key, collection)) { items.push(item); } } return items; } module.exports = auto(filter); },{"./auto":42,"./each":48}],52:[function(require,module,exports){ var some = require("./some"); var auto = require("./auto"); function find (fn, collection) { var value; some(function (item, key) { if (fn(item, key, collection)) { value = item; return true; } return false; }, collection); return value; } module.exports = auto(find); },{"./auto":42,"./some":79}],53:[function(require,module,exports){ var apply = require("./apply"); var toArray = require("./toArray"); // // Reverses a function's order of arguments. // function flip (fn) { return function () { return apply(fn, toArray(arguments).reverse()) }; } module.exports = flip; },{"./apply":40,"./toArray":83}],54:[function(require,module,exports){ function free (method) { return Function.prototype.call.bind(method); } module.exports = free; },{}],55:[function(require,module,exports){ var at = require("./at"); var bind = require("./bind"); // // ### Function getter(collection) // // collection -> (string | number -> any) // // Binds `at` to a `collection`. // function getter (collection) { return bind(at, collection); } module.exports = getter; },{"./at":41,"./bind":43}],56:[function(require,module,exports){ var some = require("./some"); function has (collection, key) { return some(function (item, currentKey) { return key === currentKey; }, collection) || false; } module.exports = has; },{"./some":79}],57:[function(require,module,exports){ function id (thing) { return thing; } module.exports = id; },{}],58:[function(require,module,exports){ /* eslint "global-require": "off" */ module.exports = { "add": require("./add"), "apply": require("./apply"), "at": require("./at"), "auto": require("./auto"), "bind": require("./bind"), "call": require("./call"), "contains": require("./contains"), "divide": require("./divide"), "each": require("./each"), "every": require("./every"), "expose": require("./expose"), "filter": require("./filter"), "find": require("./find"), "flip": require("./flip"), "free": require("./free"), "getter": require("./getter"), "has": require("./has"), "id": require("./id"), "join": require("./join"), "keys": require("./keys"), "loop": require("./loop"), "map": require("./map"), "mod": require("./mod"), "multiply": require("./multiply"), "not": require("./not"), "partial": require("./partial"), "picker": require("./picker"), "pipe": require("./pipe"), "compose": require("./compose"), "pluck": require("./pluck"), "privatize": require("./privatize"), "put": require("./put"), "putter": require("./putter"), "reduce": require("./reduce"), "repeat": require("./repeat"), "reverse": require("./reverse"), "setter": require("./setter"), "slice": require("./slice"), "some": require("./some"), "sort": require("./sort"), "split": require("./split"), "subtract": require("./subtract"), "toArray": require("./toArray"), "values": require("./values") }; },{"./add":39,"./apply":40,"./at":41,"./auto":42,"./bind":43,"./call":44,"./compose":45,"./contains":46,"./divide":47,"./each":48,"./every":49,"./expose":50,"./filter":51,"./find":52,"./flip":53,"./free":54,"./getter":55,"./has":56,"./id":57,"./join":59,"./keys":60,"./loop":61,"./map":62,"./mod":63,"./multiply":64,"./not":66,"./partial":67,"./picker":68,"./pipe":69,"./pluck":70,"./privatize":71,"./put":72,"./putter":73,"./reduce":74,"./repeat":75,"./reverse":76,"./setter":77,"./slice":78,"./some":79,"./sort":80,"./split":81,"./subtract":82,"./toArray":83,"./values":84}],59:[function(require,module,exports){ var free = require("./free"); var reduce = require("./reduce"); var isArrayLike = require("enjoy-typechecks").isArrayLike; var joinArrayLike = free(Array.prototype.join); function join (collection, glue) { if (arguments.length < 2) { glue = ""; } if (isArrayLike(collection)) { return joinArrayLike(collection, glue); } return reduce(function (previous, current) { return previous + "" + glue + current }, collection, ""); } module.exports = join; },{"./free":54,"./reduce":74,"enjoy-typechecks":65}],60:[function(require,module,exports){ var map = require("./map"); function keys (collection) { return map(function (value, key) { return key; }, collection); } module.exports = keys; },{"./map":62}],61:[function(require,module,exports){ function loop (fn) { while (fn()) { /* do nothing */ } } module.exports = loop; },{}],62:[function(require,module,exports){ var each = require("./each"); var auto = require("./auto"); function map (fn, collection) { var items = []; each(function (item, key) { items.push(fn(item, key, collection)); }, collection); return items; } module.exports = auto(map); },{"./auto":42,"./each":48}],63:[function(require,module,exports){ function mod () { return Array.prototype.reduce.call(arguments, function (a, b) { return a % b; }); } module.exports = mod; },{}],64:[function(require,module,exports){ function multiply () { return Array.prototype.reduce.call(arguments, function (a, b) { return a * b; }); } module.exports = multiply; },{}],65:[function(require,module,exports){ /* eslint no-self-compare: off */ function isNull (a) { return a === null; } function isUndefined (a) { return typeof a === "undefined"; } function isBoolean (a) { return typeof a === "boolean"; } function isNumber (a) { return typeof a === "number"; } function isFiniteNumber (a) { return isNumber(a) && isFinite(a); } function isInfiniteNumber (a) { return isNumber(a) && !isFinite(a); } function isInfinity (a) { return isPositiveInfinity(a) || isNegativeInfinity(a); } function isPositiveInfinity (a) { return a === Number.POSITIVE_INFINITY; } function isNegativeInfinity (a) { return a === Number.NEGATIVE_INFINITY; } function isNaN (a) { return a !== a; } // // Checks if a number is an integer. Please note that there's currently no way // to identify "x.000" and similar as either integer or float in JavaScript because // those are automatically truncated to "x". // function isInteger (n) { return isFiniteNumber(n) && n % 1 === 0; } function isFloat (n) { return isFiniteNumber(n) && n % 1 !== 0; } function isString (a) { return typeof a === "string"; } function isChar (a) { return isString(a) && a.length === 1; } function isCollection (a) { return isObject(a) || isArray(a); } function isObject (a) { return typeof a === "object" && a !== null; } function isArray (a) { return Array.isArray(a); } function isArrayLike (a) { return (isArray(a) || isString(a) || ( isObject(a) && ("length" in a) && isFiniteNumber(a.length) && ( (a.length > 0 && (a.length - 1) in a) || (a.length === 0) ) )); } function isFunction (a) { return typeof a === "function"; } function isPrimitive (a) { return isNull(a) || isUndefined(a) || isNumber(a) || isString(a) || isBoolean(a); } function isDate (a) { return isObject(a) && Object.prototype.toString.call(a) === "[object Date]"; } function isRegExp (a) { return isObject(a) && Object.prototype.toString.call(a) === "[object RegExp]"; } function isError (a) { return isObject(a) && Object.prototype.toString.call(a) === "[object Error]"; } function isArgumentsObject (a) { return isObject(a) && Object.prototype.toString.call(a) === "[object Arguments]"; } function isMathObject (a) { return a === Math; } function isType (a) { return isDerivable(a) && a.$__type__ === "type" && isFunction(a.$__checker__); } function isDerivable (a) { return isObject(a) && "$__children__" in a && Array.isArray(a.$__children__); } function isMethod (a) { return isFunction(a) && a.$__type__ === "method" && isFunction(a.$__default__) && isArray(a.$__implementations__) && isArray(a.$__dispatchers__); } module.exports = { isArgumentsObject: isArgumentsObject, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isChar: isChar, isCollection: isCollection, isDate: isDate, isDerivable: isDerivable, isError: isError, isFiniteNumber: isFiniteNumber, isFloat: isFloat, isFunction: isFunction, isInfiniteNumber: isInfiniteNumber, isInfinity: isInfinity, isInteger: isInteger, isMathObject: isMathObject, isMethod: isMethod, isNaN: isNaN, isNegativeInfinity: isNegativeInfinity, isNull: isNull, isNumber: isNumber, isPositiveInfinity: isPositiveInfinity, isPrimitive: isPrimitive, isRegExp: isRegExp, isString: isString, isType: isType, isUndefined: isUndefined }; },{}],66:[function(require,module,exports){ function not (thing) { return !thing; } module.exports = not; },{}],67:[function(require,module,exports){ var apply = require("./apply"); function partial (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { var callArgs = Array.prototype.slice.call(arguments); var allArgs = args.map(function (arg) { if (typeof arg === "undefined") { return callArgs.shift(); } return arg; }); if (callArgs.length) { callArgs.forEach(function (arg) { allArgs.push(arg); }); } return apply(fn, allArgs); }; } module.exports = partial; },{"./apply":40}],68:[function(require,module,exports){ var at = require("./at"); var partial = require("./partial"); // // ### Function picker(key) // // string | number -> (collection -> any) // // Binds `at` to a `key`. // function picker (key) { return partial(at, undefined, key); } module.exports = picker; },{"./at":41,"./partial":67}],69:[function(require,module,exports){ var each = require("./each"); function pipe (value) { each(function (fn, index) { if (index > 0) { value = fn(value); } }, arguments); return value; } module.exports = pipe; },{"./each":48}],70:[function(require,module,exports){ var map = require("./map"); function pluck (collection, key) { var result = []; map(function (item) { if (key in item || (Array.isArray(item) && key < item.length)) { result.push(item[key]); } }, collection); return result; } module.exports = pluck; },{"./map":62}],71:[function(require,module,exports){ var each = require("./each"); // // Turns an object into an array by putting its keys into the objects // contained within the array. // // Example: // // {foo: {}, bar: {}} => [{name: "foo"},{name: "bar"}] // function privatize (collection, key) { var result = []; each(function (item, currentKey) { item[key] = currentKey; result.push(item); }, collection); return result; } module.exports = privatize; },{"./each":48}],72:[function(require,module,exports){ // // ### Function put(collection, key, value) // // collection -> string -> any -> undefined // // Puts a `value` into a collection at `key`. // function put (collection, key, value) { collection[key] = value; } module.exports = put; },{}],73:[function(require,module,exports){ var put = require("./put"); var partial = require("./partial"); // // ### Function putter(key) // // string -> (collection -> value -> undefined) // // Binds `put` to a key. // function putter (key) { return partial(put, undefined, key, undefined); } module.exports = putter; },{"./partial":67,"./put":72}],74:[function(require,module,exports){ var each = require("./each"); var auto = require("./auto"); var isArrayLike = require("enjoy-typechecks").isArrayLike; // // ### Function reduce(fn, collection[, value]) // // (any -> any -> string|number -> collection) -> collection -> any -> any // // Reduces a collection to a single value by applying every item in the collection // along with the item's key, the previously reduced value (or the start value) // and the collection itself to a reducer function `fn`. // function reduce (fn, collection, value) { var hasValue = arguments.length > 2; // If the collection is array-like, the native .reduce() method is used for performance: if (isArrayLike(collection)) { if (hasValue) { return Array.prototype.reduce.call(collection, fn, value); } return Array.prototype.reduce.call(collection, fn); } each(function (item, key) { if (!hasValue) { hasValue = true; value = item; return; } value = fn(value, item, key, collection); }, collection); return value; } module.exports = auto(reduce); },{"./auto":42,"./each":48,"enjoy-typechecks":65}],75:[function(require,module,exports){ var auto = require("./auto"); function repeat (fn, times) { for (var i = 0; i < times; i += 1) { fn(); } } module.exports = auto(repeat); },{"./auto":42}],76:[function(require,module,exports){ var free = require("./free"); var slice = require("./slice"); var compose = require("./compose"); module.exports = compose(slice, free(Array.prototype.reverse)); },{"./compose":45,"./free":54,"./slice":78}],77:[function(require,module,exports){ var put = require("./put"); var bind = require("./bind"); // // ### Function setter(collection) // // collection -> (string -> value -> undefined) // // Binds `put` to a collection. // function setter (collection) { return bind(put, collection); } module.exports = setter; },{"./bind":43,"./put":72}],78:[function(require,module,exports){ var free = require("./free"); module.exports = free(Array.prototype.slice); },{"./free":54}],79:[function(require,module,exports){ var auto = require("./auto"); var free = require("./free"); var types = require("enjoy-typechecks"); var someArray = free(Array.prototype.some); function some (fn, collection) { if (types.isArrayLike(collection)) { return someArray(collection, fn); } else { return someObject(fn, collection); } } function someObject (fn, collection) { return Object.keys(collection).some(function (key) { return fn(collection[key], key, collection); }); } module.exports = auto(some); },{"./auto":42,"./free":54,"enjoy-typechecks":65}],80:[function(require,module,exports){ var free = require("./free"); var slice = require("./slice"); var compose = require("./compose"); module.exports = compose(slice, free(Array.prototype.sort)); },{"./compose":45,"./free":54,"./slice":78}],81:[function(require,module,exports){ var free = require("./free"); module.exports = free(String.prototype.split); },{"./free":54}],82:[function(require,module,exports){ function subtract () { return Array.prototype.reduce.call(arguments, function (a, b) { return a - b; }); } module.exports = subtract; },{}],83:[function(require,module,exports){ function toArray (thing) { return Array.prototype.slice.call(thing); } module.exports = toArray; },{}],84:[function(require,module,exports){ var map = require("./map"); var id = require("./id"); // // ### Function values(collection) // // collection -> [any] // // Extracts all values from a collection such as `array` or `object`. // function values (collection) { return map(id, collection); } module.exports = values; },{"./id":57,"./map":62}],85:[function(require,module,exports){ arguments[4][65][0].apply(exports,arguments) },{"dup":65}],86:[function(require,module,exports){ /*! * howler.js v1.1.29 * howlerjs.com * * (c) 2013-2016, James Simpson of GoldFire Studios * goldfirestudios.com * * MIT License */ (function() { // setup var cache = {}; // setup the audio context var ctx = null, usingWebAudio = true, noAudio = false; try { if (typeof AudioContext !== 'undefined') { ctx = new AudioContext(); } else if (typeof webkitAudioContext !== 'undefined') { ctx = new webkitAudioContext(); } else { usingWebAudio = false; } } catch(e) { usingWebAudio = false; } if (!usingWebAudio) { if (typeof Audio !== 'undefined') { try { new Audio(); } catch(e) { noAudio = true; } } else { noAudio = true; } } // create a master gain node if (usingWebAudio) { var masterGain = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain(); masterGain.gain.value = 1; masterGain.connect(ctx.destination); } // create global controller var HowlerGlobal = function(codecs) { this._volume = 1; this._muted = false; this.usingWebAudio = usingWebAudio; this.ctx = ctx; this.noAudio = noAudio; this._howls = []; this._codecs = codecs; this.iOSAutoEnable = true; }; HowlerGlobal.prototype = { /** * Get/set the global volume for all sounds. * @param {Float} vol Volume from 0.0 to 1.0. * @return {Howler/Float} Returns self or current volume. */ volume: function(vol) { var self = this; // make sure volume is a number vol = parseFloat(vol); if (vol >= 0 && vol <= 1) { self._volume = vol; if (usingWebAudio) { masterGain.gain.value = vol; } // loop through cache and change volume of all nodes that are using HTML5 Audio for (var key in self._howls) { if (self._howls.hasOwnProperty(key) && self._howls[key]._webAudio === false) { // loop through the audio nodes for (var i=0; i<self._howls[key]._audioNode.length; i++) { self._howls[key]._audioNode[i].volume = self._howls[key]._volume * self._volume; } } } return self; } // return the current global volume return (usingWebAudio) ? masterGain.gain.value : self._volume; }, /** * Mute all sounds. * @return {Howler} */ mute: function() { this._setMuted(true); return this; }, /** * Unmute all sounds. * @return {Howler} */ unmute: function() { this._setMuted(false); return this; }, /** * Handle muting and unmuting globally. * @param {Boolean} muted Is muted or not. */ _setMuted: function(muted) { var self = this; self._muted = muted; if (usingWebAudio) { masterGain.gain.value = muted ? 0 : self._volume; } for (var key in self._howls) { if (self._howls.hasOwnProperty(key) && self._howls[key]._webAudio === false) { // loop through the audio nodes for (var i=0; i<self._howls[key]._audioNode.length; i++) { self._howls[key]._audioNode[i].muted = muted; } } } }, /** * Check for codec support. * @param {String} ext Audio file extension. * @return {Boolean} */ codecs: function(ext) { return this._codecs[ext]; }, /** * iOS will only allow audio to be played after a user interaction. * Attempt to automatically unlock audio on the first user interaction. * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ * @return {Howler} */ _enableiOSAudio: function() { var self = this; // only run this on iOS if audio isn't already eanbled if (ctx && (self._iOSEnabled || !/iPhone|iPad|iPod/i.test(navigator.userAgent))) { return; } self._iOSEnabled = false; // call this method on touch start to create and play a buffer, // then check if the audio actually played to determine if // audio has now been unlocked on iOS var unlock = function() { // create an empty buffer var buffer = ctx.createBuffer(1, 1, 22050); var source = ctx.createBufferSource(); source.buffer = buffer; source.connect(ctx.destination); // play the empty buffer if (typeof source.start === 'undefined') { source.noteOn(0); } else { source.start(0); } // setup a timeout to check that we are unlocked on the next event loop setTimeout(function() { if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) { // update the unlocked state and prevent this check from happening again self._iOSEnabled = true; self.iOSAutoEnable = false; // remove the touch start listener window.removeEventListener('touchend', unlock, false); } }, 0); }; // setup a touch start listener to attempt an unlock in window.addEventListener('touchend', unlock, false); return self; } }; // check for browser codec support var audioTest = null; var codecs = {}; if (!noAudio) { audioTest = new Audio(); codecs = { mp3: !!audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''), opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '') }; } // allow access to the global audio controls var Howler = new HowlerGlobal(codecs); // setup the audio object var Howl = function(o) { var self = this; // setup the defaults self._autoplay = o.autoplay || false; self._buffer = o.buffer || false; self._duration = o.duration || 0; self._format = o.format || null; self._loop = o.loop || false; self._loaded = false; self._sprite = o.sprite || {}; self._src = o.src || ''; self._pos3d = o.pos3d || [0, 0, -0.5]; self._volume = o.volume !== undefined ? o.volume : 1; self._urls = o.urls || []; self._rate = o.rate || 1; // allow forcing of a specific panningModel ('equalpower' or 'HRTF'), // if none is specified, defaults to 'equalpower' and switches to 'HRTF' // if 3d sound is used self._model = o.model || null; // setup event functions self._onload = [o.onload || function() {}]; self._onloaderror = [o.onloaderror || function() {}]; self._onend = [o.onend || function() {}]; self._onpause = [o.onpause || function() {}]; self._onplay = [o.onplay || function() {}]; self._onendTimer = []; // Web Audio or HTML5 Audio? self._webAudio = usingWebAudio && !self._buffer; // check if we need to fall back to HTML5 Audio self._audioNode = []; if (self._webAudio) { self._setupAudioNode(); } // automatically try to enable audio on iOS if (typeof ctx !== 'undefined' && ctx && Howler.iOSAutoEnable) { Howler._enableiOSAudio(); } // add this to an array of Howl's to allow global control Howler._howls.push(self); // load the track self.load(); }; // setup all of the methods Howl.prototype = { /** * Load an audio file. * @return {Howl} */ load: function() { var self = this, url = null; // if no audio is available, quit immediately if (noAudio) { self.on('loaderror', new Error('No audio support.')); return; } // loop through source URLs and pick the first one that is compatible for (var i=0; i<self._urls.length; i++) { var ext, urlItem; if (self._format) { // use specified audio format if available ext = self._format; } else { // figure out the filetype (whether an extension or base64 data) urlItem = self._urls[i]; ext = /^data:audio\/([^;,]+);/i.exec(urlItem); if (!ext) { ext = /\.([^.]+)$/.exec(urlItem.split('?', 1)[0]); } if (ext) { ext = ext[1].toLowerCase(); } else { self.on('loaderror', new Error('Could not extract format from passed URLs, please add format parameter.')); return; } } if (codecs[ext]) { url = self._urls[i]; break; } } if (!url) { self.on('loaderror', new Error('No codec support for selected audio sources.')); return; } self._src = url; if (self._webAudio) { loadBuffer(self, url); } else { var newNode = new Audio(); // listen for errors with HTML5 audio (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror) newNode.addEventListener('error', function () { if (newNode.error && newNode.error.code === 4) { HowlerGlobal.noAudio = true; } self.on('loaderror', {type: newNode.error ? newNode.error.code : 0}); }, false); self._audioNode.push(newNode); // setup the new audio node newNode.src = url; newNode._pos = 0; newNode.preload = 'auto'; newNode.volume = (Howler._muted) ? 0 : self._volume * Howler.volume(); // setup the event listener to start playing the sound // as soon as it has buffered enough var listener = function() { // round up the duration when using HTML5 Audio to account for the lower precision self._duration = Math.ceil(newNode.duration * 10) / 10; // setup a sprite if none is defined if (Object.getOwnPropertyNames(self._sprite).length === 0) { self._sprite = {_default: [0, self._duration * 1000]}; } if (!self._loaded) { self._loaded = true; self.on('load'); } if (self._autoplay) { self.play(); } // clear the event listener newNode.removeEventListener('canplaythrough', listener, false); }; newNode.addEventListener('canplaythrough', listener, false); newNode.load(); } return self; }, /** * Get/set the URLs to be pulled from to play in this source. * @param {Array} urls Arry of URLs to load from * @return {Howl} Returns self or the current URLs */ urls: function(urls) { var self = this; if (urls) { self.stop(); self._urls = (typeof urls === 'string') ? [urls] : urls; self._loaded = false; self.load(); return self; } else { return self._urls; } }, /** * Play a sound from the current time (0 by default). * @param {String} sprite (optional) Plays from the specified position in the sound sprite definition. * @param {Function} callback (optional) Returns the unique playback id for this sound instance. * @return {Howl} */ play: function(sprite, callback) { var self = this; // if no sprite was passed but a callback was, update the variables if (typeof sprite === 'function') { callback = sprite; } // use the default sprite if none is passed if (!sprite || typeof sprite === 'function') { sprite = '_default'; } // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('load', function() { self.play(sprite, callback); }); return self; } // if the sprite doesn't exist, play nothing if (!self._sprite[sprite]) { if (typeof callback === 'function') callback(); return self; } // get the node to playback self._inactiveNode(function(node) { // persist the sprite being played node._sprite = sprite; // determine where to start playing from var pos = (node._pos > 0) ? node._pos : self._sprite[sprite][0] / 1000; // determine how long to play for var duration = 0; if (self._webAudio) { duration = self._sprite[sprite][1] / 1000 - node._pos; if (node._pos > 0) { pos = self._sprite[sprite][0] / 1000 + pos; } } else { duration = self._sprite[sprite][1] / 1000 - (pos - self._sprite[sprite][0] / 1000); } // determine if this sound should be looped var loop = !!(self._loop || self._sprite[sprite][2]); // set timer to fire the 'onend' event var soundId = (typeof callback === 'string') ? callback : Math.round(Date.now() * Math.random()) + '', timerId; (function() { var data = { id: soundId, sprite: sprite, loop: loop }; timerId = setTimeout(function() { // if looping, restart the track if (!self._webAudio && loop) { self.stop(data.id).play(sprite, data.id); } // set web audio node to paused at end if (self._webAudio && !loop) { self._nodeById(data.id).paused = true; self._nodeById(data.id)._pos = 0; // clear the end timer self._clearEndTimer(data.id); } // end the track if it is HTML audio and a sprite if (!self._webAudio && !loop) { self.stop(data.id); } // fire ended event self.on('end', soundId); }, (duration / self._rate) * 1000); // store the reference to the timer self._onendTimer.push({timer: timerId, id: data.id}); })(); if (self._webAudio) { var loopStart = self._sprite[sprite][0] / 1000, loopEnd = self._sprite[sprite][1] / 1000; // set the play id to this node and load into context node.id = soundId; node.paused = false; refreshBuffer(self, [loop, loopStart, loopEnd], soundId); self._playStart = ctx.currentTime; node.gain.value = self._volume; if (typeof node.bufferSource.start === 'undefined') { loop ? node.bufferSource.noteGrainOn(0, pos, 86400) : node.bufferSource.noteGrainOn(0, pos, duration); } else { loop ? node.bufferSource.start(0, pos, 86400) : node.bufferSource.start(0, pos, duration); } } else { if (node.readyState === 4 || !node.readyState && navigator.isCocoonJS) { node.readyState = 4; node.id = soundId; node.currentTime = pos; node.muted = Howler._muted || node.muted; node.volume = self._volume * Howler.volume(); setTimeout(function() { node.play(); }, 0); } else { self._clearEndTimer(soundId); (function(){ var sound = self, playSprite = sprite, fn = callback, newNode = node; var listener = function() { sound.play(playSprite, fn); // clear the event listener newNode.removeEventListener('canplaythrough', listener, false); }; newNode.addEventListener('canplaythrough', listener, false); })(); return self; } } // fire the play event and send the soundId back in the callback self.on('play'); if (typeof callback === 'function') callback(soundId); return self; }); return self; }, /** * Pause playback and save the current position. * @param {String} id (optional) The play instance ID. * @return {Howl} */ pause: function(id) { var self = this; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.pause(id); }); return self; } // clear 'onend' timer self._clearEndTimer(id); var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { activeNode._pos = self.pos(null, id); if (self._webAudio) { // make sure the sound has been created if (!activeNode.bufferSource || activeNode.paused) { return self; } activeNode.paused = true; if (typeof activeNode.bufferSource.stop === 'undefined') { activeNode.bufferSource.noteOff(0); } else { activeNode.bufferSource.stop(0); } } else { activeNode.pause(); } } self.on('pause'); return self; }, /** * Stop playback and reset to start. * @param {String} id (optional) The play instance ID. * @return {Howl} */ stop: function(id) { var self = this; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.stop(id); }); return self; } // clear 'onend' timer self._clearEndTimer(id); var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { activeNode._pos = 0; if (self._webAudio) { // make sure the sound has been created if (!activeNode.bufferSource || activeNode.paused) { return self; } activeNode.paused = true; if (typeof activeNode.bufferSource.stop === 'undefined') { activeNode.bufferSource.noteOff(0); } else { activeNode.bufferSource.stop(0); } } else if (!isNaN(activeNode.duration)) { activeNode.pause(); activeNode.currentTime = 0; } } return self; }, /** * Mute this sound. * @param {String} id (optional) The play instance ID. * @return {Howl} */ mute: function(id) { var self = this; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.mute(id); }); return self; } var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { if (self._webAudio) { activeNode.gain.value = 0; } else { activeNode.muted = true; } } return self; }, /** * Unmute this sound. * @param {String} id (optional) The play instance ID. * @return {Howl} */ unmute: function(id) { var self = this; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.unmute(id); }); return self; } var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { if (self._webAudio) { activeNode.gain.value = self._volume; } else { activeNode.muted = false; } } return self; }, /** * Get/set volume of this sound. * @param {Float} vol Volume from 0.0 to 1.0. * @param {String} id (optional) The play instance ID. * @return {Howl/Float} Returns self or current volume. */ volume: function(vol, id) { var self = this; // make sure volume is a number vol = parseFloat(vol); if (vol >= 0 && vol <= 1) { self._volume = vol; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.volume(vol, id); }); return self; } var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { if (self._webAudio) { activeNode.gain.value = vol; } else { activeNode.volume = vol * Howler.volume(); } } return self; } else { return self._volume; } }, /** * Get/set whether to loop the sound. * @param {Boolean} loop To loop or not to loop, that is the question. * @return {Howl/Boolean} Returns self or current looping value. */ loop: function(loop) { var self = this; if (typeof loop === 'boolean') { self._loop = loop; return self; } else { return self._loop; } }, /** * Get/set sound sprite definition. * @param {Object} sprite Example: {spriteName: [offset, duration, loop]} * @param {Integer} offset Where to begin playback in milliseconds * @param {Integer} duration How long to play in milliseconds * @param {Boolean} loop (optional) Set true to loop this sprite * @return {Howl} Returns current sprite sheet or self. */ sprite: function(sprite) { var self = this; if (typeof sprite === 'object') { self._sprite = sprite; return self; } else { return self._sprite; } }, /** * Get/set the position of playback. * @param {Float} pos The position to move current playback to. * @param {String} id (optional) The play instance ID. * @return {Howl/Float} Returns self or current playback position. */ pos: function(pos, id) { var self = this; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('load', function() { self.pos(pos); }); return typeof pos === 'number' ? self : self._pos || 0; } // make sure we are dealing with a number for pos pos = parseFloat(pos); var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { if (pos >= 0) { self.pause(id); activeNode._pos = pos; self.play(activeNode._sprite, id); return self; } else { return self._webAudio ? activeNode._pos + (ctx.currentTime - self._playStart) : activeNode.currentTime; } } else if (pos >= 0) { return self; } else { // find the first inactive node to return the pos for for (var i=0; i<self._audioNode.length; i++) { if (self._audioNode[i].paused && self._audioNode[i].readyState === 4) { return (self._webAudio) ? self._audioNode[i]._pos : self._audioNode[i].currentTime; } } } }, /** * Get/set the 3D position of the audio source. * The most common usage is to set the 'x' position * to affect the left/right ear panning. Setting any value higher than * 1.0 will begin to decrease the volume of the sound as it moves further away. * NOTE: This only works with Web Audio API, HTML5 Audio playback * will not be affected. * @param {Float} x The x-position of the playback from -1000.0 to 1000.0 * @param {Float} y The y-position of the playback from -1000.0 to 1000.0 * @param {Float} z The z-position of the playback from -1000.0 to 1000.0 * @param {String} id (optional) The play instance ID. * @return {Howl/Array} Returns self or the current 3D position: [x, y, z] */ pos3d: function(x, y, z, id) { var self = this; // set a default for the optional 'y' & 'z' y = (typeof y === 'undefined' || !y) ? 0 : y; z = (typeof z === 'undefined' || !z) ? -0.5 : z; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('play', function() { self.pos3d(x, y, z, id); }); return self; } if (x >= 0 || x < 0) { if (self._webAudio) { var activeNode = (id) ? self._nodeById(id) : self._activeNode(); if (activeNode) { self._pos3d = [x, y, z]; activeNode.panner.setPosition(x, y, z); activeNode.panner.panningModel = self._model || 'HRTF'; } } } else { return self._pos3d; } return self; }, /** * Fade a currently playing sound between two volumes. * @param {Number} from The volume to fade from (0.0 to 1.0). * @param {Number} to The volume to fade to (0.0 to 1.0). * @param {Number} len Time in milliseconds to fade. * @param {Function} callback (optional) Fired when the fade is complete. * @param {String} id (optional) The play instance ID. * @return {Howl} */ fade: function(from, to, len, callback, id) { var self = this, diff = Math.abs(from - to), dir = from > to ? 'down' : 'up', steps = diff / 0.01, stepTime = len / steps; // if the sound hasn't been loaded, add it to the event queue if (!self._loaded) { self.on('load', function() { self.fade(from, to, len, callback, id); }); return self; } // set the volume to the start position self.volume(from, id); for (var i=1; i<=steps; i++) { (function() { var change = self._volume + (dir === 'up' ? 0.01 : -0.01) * i, vol = Math.round(1000 * change) / 1000, toVol = to; setTimeout(function() { self.volume(vol, id); if (vol === toVol) { if (callback) callback(); } }, stepTime * i); })(); } }, /** * [DEPRECATED] Fade in the current sound. * @param {Float} to Volume to fade to (0.0 to 1.0). * @param {Number} len Time in milliseconds to fade. * @param {Function} callback * @return {Howl} */ fadeIn: function(to, len, callback) { return this.volume(0).play().fade(0, to, len, callback); }, /** * [DEPRECATED] Fade out the current sound and pause when finished. * @param {Float} to Volume to fade to (0.0 to 1.0). * @param {Number} len Time in milliseconds to fade. * @param {Function} callback * @param {String} id (optional) The play instance ID. * @return {Howl} */ fadeOut: function(to, len, callback, id) { var self = this; return self.fade(self._volume, to, len, function() { if (callback) callback(); self.pause(id); // fire ended event self.on('end'); }, id); }, /** * Get an audio node by ID. * @return {Howl} Audio node. */ _nodeById: function(id) { var self = this, node = self._audioNode[0]; // find the node with this ID for (var i=0; i<self._audioNode.length; i++) { if (self._audioNode[i].id === id) { node = self._audioNode[i]; break; } } return node; }, /** * Get the first active audio node. * @return {Howl} Audio node. */ _activeNode: function() { var self = this, node = null; // find the first playing node for (var i=0; i<self._audioNode.length; i++) { if (!self._audioNode[i].paused) { node = self._audioNode[i]; break; } } // remove excess inactive nodes self._drainPool(); return node; }, /** * Get the first inactive audio node. * If there is none, create a new one and add it to the pool. * @param {Function} callback Function to call when the audio node is ready. */ _inactiveNode: function(callback) { var self = this, node = null; // find first inactive node to recycle for (var i=0; i<self._audioNode.length; i++) { if (self._audioNode[i].paused && self._audioNode[i].readyState === 4) { // send the node back for use by the new play instance callback(self._audioNode[i]); node = true; break; } } // remove excess inactive nodes self._drainPool(); if (node) { return; } // create new node if there are no inactives var newNode; if (self._webAudio) { newNode = self._setupAudioNode(); callback(newNode); } else { self.load(); newNode = self._audioNode[self._audioNode.length - 1]; // listen for the correct load event and fire the callback var listenerEvent = navigator.isCocoonJS ? 'canplaythrough' : 'loadedmetadata'; var listener = function() { newNode.removeEventListener(listenerEvent, listener, false); callback(newNode); }; newNode.addEventListener(listenerEvent, listener, false); } }, /** * If there are more than 5 inactive audio nodes in the pool, clear out the rest. */ _drainPool: function() { var self = this, inactive = 0, i; // count the number of inactive nodes for (i=0; i<self._audioNode.length; i++) { if (self._audioNode[i].paused) { inactive++; } } // remove excess inactive nodes for (i=self._audioNode.length-1; i>=0; i--) { if (inactive <= 5) { break; } if (self._audioNode[i].paused) { // disconnect the audio source if using Web Audio if (self._webAudio) { self._audioNode[i].disconnect(0); } inactive--; self._audioNode.splice(i, 1); } } }, /** * Clear 'onend' timeout before it ends. * @param {String} soundId The play instance ID. */ _clearEndTimer: function(soundId) { var self = this, index = -1; // loop through the timers to find the one associated with this sound for (var i=0; i<self._onendTimer.length; i++) { if (self._onendTimer[i].id === soundId) { index = i; break; } } var timer = self._onendTimer[index]; if (timer) { clearTimeout(timer.timer); self._onendTimer.splice(index, 1); } }, /** * Setup the gain node and panner for a Web Audio instance. * @return {Object} The new audio node. */ _setupAudioNode: function() { var self = this, node = self._audioNode, index = self._audioNode.length; // create gain node node[index] = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain(); node[index].gain.value = self._volume; node[index].paused = true; node[index]._pos = 0; node[index].readyState = 4; node[index].connect(masterGain); // create the panner node[index].panner = ctx.createPanner(); node[index].panner.panningModel = self._model || 'equalpower'; node[index].panner.setPosition(self._pos3d[0], self._pos3d[1], self._pos3d[2]); node[index].panner.connect(node[index]); return node[index]; }, /** * Call/set custom events. * @param {String} event Event type. * @param {Function} fn Function to call. * @return {Howl} */ on: function(event, fn) { var self = this, events = self['_on' + event]; if (typeof fn === 'function') { events.push(fn); } else { for (var i=0; i<events.length; i++) { if (fn) { events[i].call(self, fn); } else { events[i].call(self); } } } return self; }, /** * Remove a custom event. * @param {String} event Event type. * @param {Function} fn Listener to remove. * @return {Howl} */ off: function(event, fn) { var self = this, events = self['_on' + event]; if (fn) { // loop through functions in the event for comparison for (var i=0; i<events.length; i++) { if (fn === events[i]) { events.splice(i, 1); break; } } } else { self['_on' + event] = []; } return self; }, /** * Unload and destroy the current Howl object. * This will immediately stop all play instances attached to this sound. */ unload: function() { var self = this; // stop playing any active nodes var nodes = self._audioNode; for (var i=0; i<self._audioNode.length; i++) { // stop the sound if it is currently playing if (!nodes[i].paused) { self.stop(nodes[i].id); self.on('end', nodes[i].id); } if (!self._webAudio) { // remove the source if using HTML5 Audio nodes[i].src = ''; } else { // disconnect the output from the master gain nodes[i].disconnect(0); } } // make sure all timeouts are cleared for (i=0; i<self._onendTimer.length; i++) { clearTimeout(self._onendTimer[i].timer); } // remove the reference in the global Howler object var index = Howler._howls.indexOf(self); if (index !== null && index >= 0) { Howler._howls.splice(index, 1); } // delete this sound from the cache delete cache[self._src]; self = null; } }; // only define these functions when using WebAudio if (usingWebAudio) { /** * Buffer a sound from URL (or from cache) and decode to audio source (Web Audio API). * @param {Object} obj The Howl object for the sound to load. * @param {String} url The path to the sound file. */ var loadBuffer = function(obj, url) { // check if the buffer has already been cached if (url in cache) { // set the duration from the cache obj._duration = cache[url].duration; // load the sound into this object loadSound(obj); return; } if (/^data:[^;]+;base64,/.test(url)) { // Decode base64 data-URIs because some browsers cannot load data-URIs with XMLHttpRequest. var data = atob(url.split(',')[1]); var dataView = new Uint8Array(data.length); for (var i=0; i<data.length; ++i) { dataView[i] = data.charCodeAt(i); } decodeAudioData(dataView.buffer, obj, url); } else { // load the buffer from the URL var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.onload = function() { decodeAudioData(xhr.response, obj, url); }; xhr.onerror = function() { // if there is an error, switch the sound to HTML Audio if (obj._webAudio) { obj._buffer = true; obj._webAudio = false; obj._audioNode = []; delete obj._gainNode; delete cache[url]; obj.load(); } }; try { xhr.send(); } catch (e) { xhr.onerror(); } } }; /** * Decode audio data from an array buffer. * @param {ArrayBuffer} arraybuffer The audio data. * @param {Object} obj The Howl object for the sound to load. * @param {String} url The path to the sound file. */ var decodeAudioData = function(arraybuffer, obj, url) { // decode the buffer into an audio source ctx.decodeAudioData( arraybuffer, function(buffer) { if (buffer) { cache[url] = buffer; loadSound(obj, buffer); } }, function(err) { obj.on('loaderror', err); } ); }; /** * Finishes loading the Web Audio API sound and fires the loaded event * @param {Object} obj The Howl object for the sound to load. * @param {Objecct} buffer The decoded buffer sound source. */ var loadSound = function(obj, buffer) { // set the duration obj._duration = (buffer) ? buffer.duration : obj._duration; // setup a sprite if none is defined if (Object.getOwnPropertyNames(obj._sprite).length === 0) { obj._sprite = {_default: [0, obj._duration * 1000]}; } // fire the loaded event if (!obj._loaded) { obj._loaded = true; obj.on('load'); } if (obj._autoplay) { obj.play(); } }; /** * Load the sound back into the buffer source. * @param {Object} obj The sound to load. * @param {Array} loop Loop boolean, pos, and duration. * @param {String} id (optional) The play instance ID. */ var refreshBuffer = function(obj, loop, id) { // determine which node to connect to var node = obj._nodeById(id); // setup the buffer source for playback node.bufferSource = ctx.createBufferSource(); node.bufferSource.buffer = cache[obj._src]; node.bufferSource.connect(node.panner); node.bufferSource.loop = loop[0]; if (loop[0]) { node.bufferSource.loopStart = loop[1]; node.bufferSource.loopEnd = loop[1] + loop[2]; } node.bufferSource.playbackRate.value = obj._rate; }; } /** * Add support for AMD (Asynchronous Module Definition) libraries such as require.js. */ if (typeof define === 'function' && define.amd) { define(function() { return { Howler: Howler, Howl: Howl }; }); } /** * Add support for CommonJS libraries such as browserify. */ if (typeof exports !== 'undefined') { exports.Howler = Howler; exports.Howl = Howl; } // define globally in case AMD is not available or available but not used if (typeof window !== 'undefined') { window.Howler = Howler; window.Howl = Howl; } })(); },{}],87:[function(require,module,exports){ // // A simple dictionary prototype for JavaScript, avoiding common object pitfalls // and offering some handy convenience methods. // /* global module, require, window */ var prefix = "string-dict_"; function makeKey (k) { return prefix + k; } function revokeKey (k) { return k.replace(new RegExp(prefix), ""); } function Dict (content) { var key; this.clear(); if (content) { for (key in content) { this.set(key, content[key]); } } } Dict.prototype.clear = function () { this.items = {}; this.count = 0; }; Dict.prototype.length = function () { return this.count; }; Dict.prototype.set = function (k, value) { var key = makeKey(k); if (!k) { throw new Error("Dictionary keys cannot be falsy."); } if (this.has(key)) { this.remove(key); } this.items[key] = value; this.count += 1; return this; }; Dict.prototype.get = function (k) { var key = makeKey(k); if (!this.items.hasOwnProperty(key)) { return undefined; } return this.items[key]; }; // // The same as .get(), but throws when the key doesn't exist. // This can be useful if you want to use a dict as some sort of registry. // Dict.prototype.require = function (key) { if (!this.has(key)) { throw new Error("Required key '" + key + "' does not exist."); } return this.get(key); }; Dict.prototype.remove = function (k) { var key = makeKey(k); if (this.has(k)) { delete this.items[key]; this.count -= 1; } return this; }; Dict.prototype.has = function (k) { var key = makeKey(k); return this.items.hasOwnProperty(key); }; Dict.prototype.forEach = function (fn) { if (!fn || typeof fn !== "function") { throw new Error("Argument 1 is expected to be of type function."); } for (var key in this.items) { fn(this.items[key], revokeKey(key), this); } return this; }; Dict.prototype.filter = function (fn) { var matches = new Dict(); this.forEach(function (item, key, all) { if (fn(item, key, all)) { matches.set(key, item); } }); return matches; }; Dict.prototype.find = function (fn) { var value; this.some(function (item, key, all) { if (fn(item, key, all)) { value = item; return true; } return false; }); return value; }; Dict.prototype.map = function (fn) { var mapped = new Dict(); this.forEach(function (item, key, all) { mapped.set(key, fn(item, key, all)); }); return mapped; }; Dict.prototype.reduce = function (fn, initialValue) { var result = initialValue; this.forEach(function (item, key, all) { result = fn(result, item, key, all); }); return result; }; Dict.prototype.every = function (fn) { return this.reduce(function (last, item, key, all) { return last && fn(item, key, all); }, true); }; Dict.prototype.some = function (fn) { for (var key in this.items) { if (fn(this.items[key], revokeKey(key), this)) { return true; } } return false; }; // // Returns an array containing the dictionary's keys. // Dict.prototype.keys = function () { var keys = []; this.forEach(function (item, key) { keys.push(key); }); return keys; }; // // Returns the dictionary's values in an array. // Dict.prototype.values = function () { var values = []; this.forEach(function (item) { values.push(item); }); return values; }; // // Creates a normal JS object containing the contents of the dictionary. // Dict.prototype.toObject = function () { var jsObject = {}; this.forEach(function (item, key) { jsObject[key] = item; }); return jsObject; }; // // Creates another dictionary with the same contents as this one. // Dict.prototype.clone = function () { var clone = new Dict(); this.forEach(function (item, key) { clone.set(key, item); }); return clone; }; // // Adds the content of another dictionary to this dictionary's content. // Dict.prototype.addMap = function (otherMap) { var self = this; otherMap.forEach(function (item, key) { self.set(key, item); }); return this; }; // // Returns a new map which is the result of joining this map // with another map. This map isn't changed in the process. // The keys from otherMap will replace any keys from this map that // are the same. // Dict.prototype.join = function (otherMap) { return this.clone().addMap(otherMap); }; module.exports = Dict; },{}],88:[function(require,module,exports){ /* global requestAnimationFrame */ var eases = require("eases"); if (typeof requestAnimationFrame === "undefined") { var requestAnimationFrame = function (fn) { setTimeout(fn, 1000 / 60); } } function transformation (from, to, callback, args, after) { var dur, easing, cv, diff, c, lastExecution, fps; var canceled, paused, running, stopped; var timeElapsed, startTime, pauseTimeElapsed, pauseStartTime; args = args || {}; if (typeof args === "function" && !after) { after = args; args = {}; } after = typeof after === "function" ? after : function () {}; if (typeof callback === "undefined" || !callback) { throw new Error("Argument callback must be a function."); } init(); function init () { dur = typeof args.duration !== "undefined" && args.duration >= 0 ? args.duration : 500; cv = from; diff = to - from; c = 0, // number of times loop get's executed lastExecution = 0; fps = args.fps || 60; canceled = false; paused = false; running = false; stopped = false; timeElapsed = 0; startTime = 0; pauseTimeElapsed = 0; pauseStartTime = 0; easing = eases.linear; if (args.easing) { if (typeof args.easing === "function") { easing = args.easing; } else { easing = eases[args.easing]; } } } function loop () { var dt, tElapsed; if (!running) { return; } if ((Date.now() - lastExecution) > (1000 / fps)) { if (canceled || paused) { return; } c += 1; tElapsed = elapsed(); if (tElapsed > dur || stopped) { cv = from + diff; if (!stopped) { stop(); } return; } cv = easing(tElapsed / dur) * diff + from; callback(cv); dt = elapsed() - tElapsed; lastExecution = Date.now(); } requestAnimationFrame(loop); }; function elapsed () { if (running && !paused) { timeElapsed = ((+(new Date()) - startTime) - pauseTimeElapsed); } return timeElapsed; } function start () { reset(); startTime = +(new Date()); pauseStartTime = startTime; running = true; requestAnimationFrame(loop); } function stop () { running = false; paused = false; callback(to); after(); } function resume () { if (!paused) { return; } paused = false; pauseTimeElapsed += +(new Date()) - pauseStartTime; requestAnimationFrame(loop); } function pause () { paused = true; pauseStartTime = +(new Date()); } function cancel () { if (!running) { return; } elapsed(); canceled = true; running = false; paused = false; after(); } function reset () { if (running) { cancel(); } init(); } return { start: start, stop: stop, pause: pause, resume: resume, cancel: cancel, elapsed: elapsed, reset: reset }; } function transform () { var t = transformation.apply(undefined, arguments); t.start(); return t; } module.exports = { transformation: transformation, transform: transform }; },{"eases":107}],89:[function(require,module,exports){ arguments[4][5][0].apply(exports,arguments) },{"dup":5}],90:[function(require,module,exports){ arguments[4][6][0].apply(exports,arguments) },{"dup":6}],91:[function(require,module,exports){ arguments[4][7][0].apply(exports,arguments) },{"dup":7}],92:[function(require,module,exports){ arguments[4][8][0].apply(exports,arguments) },{"./bounce-out":94,"dup":8}],93:[function(require,module,exports){ arguments[4][9][0].apply(exports,arguments) },{"./bounce-out":94,"dup":9}],94:[function(require,module,exports){ arguments[4][10][0].apply(exports,arguments) },{"dup":10}],95:[function(require,module,exports){ arguments[4][11][0].apply(exports,arguments) },{"dup":11}],96:[function(require,module,exports){ arguments[4][12][0].apply(exports,arguments) },{"dup":12}],97:[function(require,module,exports){ arguments[4][13][0].apply(exports,arguments) },{"dup":13}],98:[function(require,module,exports){ arguments[4][14][0].apply(exports,arguments) },{"dup":14}],99:[function(require,module,exports){ arguments[4][15][0].apply(exports,arguments) },{"dup":15}],100:[function(require,module,exports){ arguments[4][16][0].apply(exports,arguments) },{"dup":16}],101:[function(require,module,exports){ arguments[4][17][0].apply(exports,arguments) },{"dup":17}],102:[function(require,module,exports){ arguments[4][18][0].apply(exports,arguments) },{"dup":18}],103:[function(require,module,exports){ arguments[4][19][0].apply(exports,arguments) },{"dup":19}],104:[function(require,module,exports){ arguments[4][20][0].apply(exports,arguments) },{"dup":20}],105:[function(require,module,exports){ arguments[4][21][0].apply(exports,arguments) },{"dup":21}],106:[function(require,module,exports){ arguments[4][22][0].apply(exports,arguments) },{"dup":22}],107:[function(require,module,exports){ arguments[4][23][0].apply(exports,arguments) },{"./back-in":90,"./back-in-out":89,"./back-out":91,"./bounce-in":93,"./bounce-in-out":92,"./bounce-out":94,"./circ-in":96,"./circ-in-out":95,"./circ-out":97,"./cubic-in":99,"./cubic-in-out":98,"./cubic-out":100,"./elastic-in":102,"./elastic-in-out":101,"./elastic-out":103,"./expo-in":105,"./expo-in-out":104,"./expo-out":106,"./linear":108,"./quad-in":110,"./quad-in-out":109,"./quad-out":111,"./quart-in":113,"./quart-in-out":112,"./quart-out":114,"./quint-in":116,"./quint-in-out":115,"./quint-out":117,"./sine-in":119,"./sine-in-out":118,"./sine-out":120,"dup":23}],108:[function(require,module,exports){ arguments[4][24][0].apply(exports,arguments) },{"dup":24}],109:[function(require,module,exports){ arguments[4][25][0].apply(exports,arguments) },{"dup":25}],110:[function(require,module,exports){ arguments[4][26][0].apply(exports,arguments) },{"dup":26}],111:[function(require,module,exports){ arguments[4][27][0].apply(exports,arguments) },{"dup":27}],112:[function(require,module,exports){ arguments[4][28][0].apply(exports,arguments) },{"dup":28}],113:[function(require,module,exports){ arguments[4][29][0].apply(exports,arguments) },{"dup":29}],114:[function(require,module,exports){ arguments[4][30][0].apply(exports,arguments) },{"dup":30}],115:[function(require,module,exports){ arguments[4][31][0].apply(exports,arguments) },{"dup":31}],116:[function(require,module,exports){ arguments[4][32][0].apply(exports,arguments) },{"dup":32}],117:[function(require,module,exports){ arguments[4][33][0].apply(exports,arguments) },{"dup":33}],118:[function(require,module,exports){ arguments[4][34][0].apply(exports,arguments) },{"dup":34}],119:[function(require,module,exports){ arguments[4][35][0].apply(exports,arguments) },{"dup":35}],120:[function(require,module,exports){ arguments[4][36][0].apply(exports,arguments) },{"dup":36}],121:[function(require,module,exports){ /* global module, require */ module.exports = require("./src/xmugly.js"); },{"./src/xmugly.js":122}],122:[function(require,module,exports){ /* global module */ (function () { // // Compiles // . some_element attr1 val1, attr2 val2 // to: // <some_element attr1="val1", attr2="val2" /> // and // . some_element attr1 val1 : // ... // -- // to // <some_element attr1="val1"> // ... // </some_element> // function compile (text, defaultMacros) { // // A stack of element names, so that know which "--" closes which element. // var stack = []; var lines = toLines(text); var macros = processMacros(lines); if (Array.isArray(defaultMacros)) { defaultMacros.forEach(function (macro) { macros.push(macro); }); } lines = removeMacroDefinitions(lines); lines = lines.map(function (line, i) { var name, attributes, parts, trimmed, head, whitespace, strings, result, hasContent; trimmed = line.trim(); strings = []; whitespace = line.replace(/^([\s]*).*$/, "$1"); if (trimmed === "--") { if (!stack.length) { throw new SyntaxError( "Closing '--' without matching opening tag on line " + (i + 1) ); } return whitespace + '</' + stack.pop() + '>'; } if (trimmed[0] !== ".") { return line; } trimmed = trimmed.replace(/"([^"]+)"/g, function (match, p1) { strings.push(p1); return "{{" + strings.length + "}}"; }); if (trimmed[trimmed.length - 1] === ":") { hasContent = true; trimmed = trimmed.replace(/:$/, ""); } parts = trimmed.split(","); head = parts[0].split(" "); head.shift(); name = head[0]; if (hasContent) { stack.push(name); } head.shift(); parts[0] = head.join(" "); attributes = []; parts.forEach(function (current) { var split, name, value, enlarged; split = normalizeWhitespace(current).split(" "); name = split[0].trim(); if (!name) { return; } enlarged = applyMacros(name, macros); if (enlarged) { value = enlarged.value; name = enlarged.name; } else { split.shift(); value = split.join(" "); } attributes.push(name + '="' + value + '"'); }); result = whitespace + '<' + name + (attributes.length ? ' ' : '') + attributes.join(" ") + (hasContent ? '>' : ' />'); strings.forEach(function (value, i) { result = result.replace("{{" + (i + 1) + "}}", value); }); return result; }); return toText(lines); } function toLines (text) { return text.split("\n"); } function toText (lines) { return lines.join("\n"); } // // Creates a replacement rule from an attribute macro line. // Attribute macros look like this: // // ~ @ asset _ // // The ~ at the start of a line signalizes that this is an attribute macro. // The first non-whitespace part (@ in this case) is the character or text part // which will be used as the macro identifier. // The second part (asset in this case) is the attribute name. // The third and last part (_ here) is the attribute value. // The "_" character will be replaced by whatever follows the macro identifier. // // The example above will result in this transformation: // // . move @frodo => <move asset="frodo" /> // // Some more examples: // // Macro: ~ : duration _ // Transformation: . wait :200 => <wait duration="200" /> // // Macro: ~ + _ true // Macro: ~ - _ false // Transformation: . stage -resize, +center => <stage resize="false" center="true" /> // function processAttributeMacro (line) { var parts = normalizeWhitespace(line).split(" "); parts.shift(); return { identifier: parts[0], attribute: parts[1], value: parts[2] }; } function processMacros (lines) { var macros = []; lines.forEach(function (line) { if (line.trim()[0] !== "~") { return; } macros.push(processAttributeMacro(line)); }); return macros; } function applyMacros (raw, macros) { var name, value; macros.some(function (macro) { var macroValue; if (raw[0] !== macro.identifier) { return false; } macroValue = raw.replace(macro.identifier, ""); name = (macro.attribute === "_" ? macroValue : macro.attribute); value = (macro.value === "_" ? macroValue : macro.value); return true; }); if (!name) { return null; } return { name: name, value: value }; } function removeMacroDefinitions (lines) { return lines.filter(function (line) { return line.trim()[0] !== "~"; }); } // // Replaces all whitespace with a single space character. // function normalizeWhitespace (text) { return text.trim().replace(/[\s]+/g, " "); } if (typeof module !== "undefined") { module.exports = { compile: compile }; } else { window.xmugly = { compile: compile }; } }()); },{}]},{},[1]); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - Modular JavaScript. Batteries included. Copyright (c) 2015 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, require, process, document, console */ if (typeof window !== "undefined") { // If the browser doesn't support requestAnimationFrame, use a fallback. window.requestAnimationFrame = (function () { "use strict"; return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; }()); } // [].forEach() shim (function () { if (Array.prototype.forEach) { return; } Array.prototype.forEach = function (callback) { for (var i = 0, len = this.length; i < len; i += 1) { callback(this[i], i, this); } }; }()); // [].indexOf() shim (function () { if (Array.prototype.indexOf) { return; } Array.prototype.indexOf = function (searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; }()); if (typeof console === "undefined") { this.console = {}; } if (!console.log) { console.log = function () {}; } if (!console.dir) { console.dir = console.log; } if (!console.error) { console.error = console.log; } if (!console.warn) { console.warn = console.log; } (function () { var scripts = document.getElementsByTagName("script"); var path = scripts[scripts.length - 1].src.replace(/MO5\.js$/, ""); using.modules = { "MO5.ajax": path + "ajax.js", "MO5.assert": path + "assert.js", "MO5.Exception": path + "Exception.js", "MO5.fail": path + "fail.js", "MO5.EventBus": path + "EventBus.js", "MO5.CoreObject": path + "CoreObject.js", "MO5.List": path + "List.js", "MO5.Queue": path + "Queue.js", "MO5.Map": path + "Map.js", "MO5.Set": path + "Set.js", "MO5.Result": path + "Result.js", // deprecated - use MO5.Promise instead! "MO5.Promise": path + "Promise.js", "MO5.Timer": path + "Timer.js", "MO5.TimerWatcher": path + "TimerWatcher.js", "MO5.easing": path + "easing.js", "MO5.transform": path + "transform.js", "MO5.range": path + "range.js", "MO5.tools": path + "tools.js", "MO5.Point": path + "Point.js", "MO5.Size": path + "Size.js", "MO5.Animation": path + "Animation.js", "MO5.dom.effects.typewriter": path + "dom.effects.typewriter.js", "MO5.dom.Element": path + "dom.Element.js", "MO5.dom.escape": path + "dom.escape.js", "MO5.globals.document": path + "globals.document.js", "MO5.globals.window": path + "globals.window.js", "MO5.types": path + "types.js" }; }()); var $__WSEScripts = document.getElementsByTagName('script'); WSEPath = $__WSEScripts[$__WSEScripts.length - 1].src; using.modules['MO5.ajax'] = WSEPath; using.modules['MO5.Animation'] = WSEPath; using.modules['MO5.assert'] = WSEPath; using.modules['MO5.CoreObject'] = WSEPath; using.modules['MO5.dom.effects.typewriter'] = WSEPath; using.modules['MO5.dom.Element'] = WSEPath; using.modules['MO5.dom.escape'] = WSEPath; using.modules['MO5.easing'] = WSEPath; using.modules['MO5.EventBus'] = WSEPath; using.modules['MO5.Exception'] = WSEPath; using.modules['MO5.fail'] = WSEPath; using.modules['MO5.globals.document'] = WSEPath; using.modules['MO5.globals.window'] = WSEPath; using.modules['MO5.List'] = WSEPath; using.modules['MO5.Map'] = WSEPath; using.modules['MO5.Point'] = WSEPath; using.modules['MO5.Promise'] = WSEPath; using.modules['MO5.Queue'] = WSEPath; using.modules['MO5.range'] = WSEPath; using.modules['MO5.Result'] = WSEPath; using.modules['MO5.Set'] = WSEPath; using.modules['MO5.Size'] = WSEPath; using.modules['MO5.Timer'] = WSEPath; using.modules['MO5.TimerWatcher'] = WSEPath; using.modules['MO5.tools'] = WSEPath; using.modules['MO5.transform'] = WSEPath; using.modules['MO5.types'] = WSEPath; using.modules['WSE.assets'] = WSEPath; using.modules['WSE.commands'] = WSEPath; using.modules['WSE.functions'] = WSEPath; using.modules['WSE.dataSources'] = WSEPath; using.modules['WSE'] = WSEPath; using.modules['WSE.Keys'] = WSEPath; using.modules['WSE.tools'] = WSEPath; using.modules['WSE.loader'] = WSEPath; using.modules['WSE.dataSources.LocalStorage'] = WSEPath; using.modules['WSE.Trigger'] = WSEPath; using.modules['WSE.Game'] = WSEPath; using.modules['WSE.Interpreter'] = WSEPath; using.modules['WSE.LoadingScreen'] = WSEPath; using.modules['WSE.tools.ui'] = WSEPath; using.modules['WSE.tools.reveal'] = WSEPath; using.modules['WSE.tools.compile'] = WSEPath; using.modules['WSE.savegames'] = WSEPath; using.modules['WSE.DisplayObject'] = WSEPath; using.modules['WSE.assets.Animation'] = WSEPath; using.modules['WSE.assets.Audio'] = WSEPath; using.modules['WSE.assets.Character'] = WSEPath; using.modules['WSE.assets.Curtain'] = WSEPath; using.modules['WSE.assets.Imagepack'] = WSEPath; using.modules['WSE.assets.Textbox'] = WSEPath; using.modules['WSE.assets.Background'] = WSEPath; using.modules['WSE.assets.Composite'] = WSEPath; using.modules['WSE.commands.alert'] = WSEPath; using.modules['WSE.commands.break'] = WSEPath; using.modules['WSE.commands.choice'] = WSEPath; using.modules['WSE.commands.confirm'] = WSEPath; using.modules['WSE.commands.do'] = WSEPath; using.modules['WSE.commands.fn'] = WSEPath; using.modules['WSE.commands.global'] = WSEPath; using.modules['WSE.commands.globalize'] = WSEPath; using.modules['WSE.commands.goto'] = WSEPath; using.modules['WSE.commands.line'] = WSEPath; using.modules['WSE.commands.localize'] = WSEPath; using.modules['WSE.commands.prompt'] = WSEPath; using.modules['WSE.commands.restart'] = WSEPath; using.modules['WSE.commands.sub'] = WSEPath; using.modules['WSE.commands.trigger'] = WSEPath; using.modules['WSE.commands.var'] = WSEPath; using.modules['WSE.commands.set_vars'] = WSEPath; using.modules['WSE.commands.wait'] = WSEPath; using.modules['WSE.commands.with'] = WSEPath; using.modules['WSE.commands.while'] = WSEPath; /* global using */ /** * A wrapper module for ajax. */ using().define("MO5.ajax", function () { return using.ajax; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 - 2014 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global MO5, setTimeout, window, module, require */ (function MO5AnimationBootstrap () { if (typeof using === "function") { using("MO5.Exception", "MO5.CoreObject", "MO5.Queue", "MO5.Timer", "MO5.TimerWatcher"). define("MO5.Animation", MO5AnimationModule); } else if (typeof window !== "undefined") { window.MO5.Animation = MO5AnimationModule( MO5.Exception, MO5.CoreObject, MO5.Queue, MO5.Timer, MO5.TimerWatcher ); } else { module.exports = MO5AnimationModule( require("./Exception.js"), require("./CoreObject.js"), require("./Queue.js"), require("./Timer.js"), require("./TimerWatcher.js") ); } function MO5AnimationModule (Exception, CoreObject, Queue, Timer, TimerWatcher) { /** * Uses callbacks to animate. * @param callbacks Optional list of callbacks. Can be of type Array or MO5.Queue. */ function Animation (callbacks) { CoreObject.call(this); this.callbacks = new Queue(); this.queue = new Queue(); this.running = false; this.canceled = false; this.paused = false; this.limit = 0; this.count = 0; this.currentWatcher = null; if (callbacks && callbacks instanceof Queue) { this.callbacks = callbacks; } else if (callbacks && callbacks instanceof Array) { this.callbacks.replace(callbacks.slice()); } else if (callbacks) { throw new Error("Parameter 1 is expected to be of type Array or MO5.Queue."); } } Animation.prototype = new CoreObject(); Animation.prototype.constructor = Animation; Animation.prototype.addStep = function (cb) { if (this.running) { throw new Error("Cannot add steps to a running animation."); } this.callbacks.add(cb); this.trigger("updated", null, false); return this; }; Animation.prototype.isRunning = function () { return this.running; }; Animation.prototype.isCanceled = function () { return this.canceled; }; Animation.prototype.isPaused = function () { return this.paused; }; Animation.prototype.start = function () { var fn, self = this, cbs; if (this.running) { throw new Error("Animation is already running."); } cbs = this.callbacks.clone(); this.queue = cbs; this.running = true; this.canceled = false; fn = function () { var next, watcher; if (!cbs.hasNext()) { self.count += 1; if (self.isRunning()) { if (self.limit && self.count == self.limit) { self.running = false; self.trigger("stopped", null, false); self.count = 0; self.limit = 0; return; } cbs = self.callbacks.clone(); this.queue = cbs; setTimeout(fn, 0); return; } self.trigger("stopped", null, false); return; } next = cbs.next(); watcher = next(); if (watcher && watcher instanceof TimerWatcher) { self.currentWatcher = watcher; watcher.once(fn, "stopped"); } else { setTimeout(fn, 0); } }; setTimeout(fn, 0); return this; }; Animation.prototype.pause = function () { if (this.paused) { throw new Error("Trying to pause an already paused animation."); } this.paused = true; if (this.currentWatcher) { this.currentWatcher.pause(); } this.trigger("paused", null, false); return this; }; Animation.prototype.resume = function () { if (!this.paused) { throw new Error("Trying to resume an animation that isn't paused."); } this.paused = false; if (this.currentWatcher) { this.currentWatcher.resume(); } this.trigger("resumed", null, false); return this; }; Animation.prototype.cancel = function () { if (this.canceled) { throw new Error("Trying to cancel an already canceled animation."); } this.canceled = true; this.running = false; this.count = 0; this.limit = 0; if (this.currentWatcher) { this.currentWatcher.cancel(); } this.trigger("canceled", null, false); return this; }; Animation.prototype.stop = function () { if (!this.running) { throw new Error("Trying to stop an animation that isn't running. " + "Check isRunning() beforehand."); } this.running = false; this.count = 0; this.limit = 0; return this; }; Animation.prototype.loop = function (c) { if (c < 1) { throw new Error("Parameter 1 is expected to be greater than zero."); } this.count = 0; this.limit = c; return this.start(); }; Animation.prototype.promise = function () { return Timer.prototype.promise.call(this); }; return Animation; } }()); /* global using */ using("MO5.Exception").define("MO5.assert", function (Exception) { function AssertionException () { Exception.apply(this, arguments); this.name = "AssertionException"; } AssertionException.prototype = new Exception(); function assert (condition, message) { if (!condition) { throw new AssertionException(message); } } return assert; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 - 2015 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, MO5, window, module, require */ (function MO5CoreObjectBootstrap () { if (typeof using === "function") { using("MO5.Exception", "MO5.fail", "MO5.EventBus"). define("MO5.CoreObject", MO5CoreObjectModule); } else if (typeof window !== "undefined") { window.MO5.CoreObject = MO5CoreObjectModule(MO5.Exception, MO5.fail, MO5.EventBus); } else { module.exports = MO5CoreObjectModule( require("./Exception.js"), require("./fail.js"), require("./EventBus.js") ); } function MO5CoreObjectModule (Exception, fail, EventBus) { var flags = {}, prefix = "CoreObject", highestId = 0; /** * The MO5 base type for almost all other types used in MO5. * * All CoreObject instances are observable by subscribing * to the events that they emit. * * @type object -> CoreObject * @event flag_removed(name_of_flag) When the flag has been removed. * @event flag_set(name_of_flag) When the flag has been set. * @event destroyed() * @return CoreObject */ function CoreObject (args) { args = args || {}; args.bus = args.bus || {}; highestId += 1; if (Object.defineProperty) { Object.defineProperty(this, "id", { value: highestId, configurable: false, enumerable: false, writable: false }); } else { this.id = highestId; } this.destroyed = false; EventBus.inject(this, args.bus); flags[this.id] = {}; this.$children = []; this.$parent = null; } /** * Checks whether an object has an ID property. * * @type any -> boolean * @param obj The object to be checked. * @return boolean Is the argument an object and has an ID property? */ CoreObject.hasId = function (obj) { return typeof obj === "object" && obj !== null && typeof obj.id === "number"; }; /** * Checks whether an object is an instance of CoreObject. * * @type any -> boolean * @param obj The object to check. * @return boolean Is the argument a CoreObject instance? */ CoreObject.isCoreObject = function (obj) { return obj instanceof CoreObject; }; CoreObject.prototype.addChild = function (child) { if (this.$children.indexOf(child) >= 0) { return; } child.$parent = this; this.$children.push(child); }; CoreObject.prototype.removeChild = function (child) { var index = this.$children.indexOf(child); if (index < 0) { return; } child.$parent = null; this.$children.splice(index, 1); }; CoreObject.prototype.hasChild = function (child) { return this.$children.indexOf(child) >= 0; }; /** * Sets a flag on this object. Flags can be used to specify abilities of * a CoreObject. A flag has no value and can be in on of two * states - it can either exist or not exist. * * @type string -> CoreObject * @event flag_set(name_of_flag) When the flag has been set. * @param flag The name of the flag. * @return The CoreObject itself. */ CoreObject.prototype.setFlag = function (flag) { var internalKey = externalKeyToInternalKey(flag); if (!flags[this.id]) { return; } flags[this.id][internalKey] = true; this.trigger("flag_set", flag); return this; }; /** * Removes a flag from this object. * * @type string -> CoreObject * @event flag_removed(name_of_flag) When the flag has been removed. * @param flag The name of the flag. * @return The CoreObject itself. */ CoreObject.prototype.removeFlag = function (flag) { if (!this.hasFlag(flag)) { return; } delete flags[this.id][externalKeyToInternalKey(flag)]; this.trigger("flag_removed", flag); return this; }; /** * Checks whether this object has a flag set. * * @type string -> boolean * @param flag The name of the flag. * @return Is the flag set on this CoreObject instance? */ CoreObject.prototype.hasFlag = function (flag) { var internalKey = externalKeyToInternalKey(flag); return flags[this.id] && flags[this.id].hasOwnProperty(internalKey); }; /** * Returns an array containing all the flags set on this CoreObject. * * @type void -> [string] * @return An array containing the names of the flags. */ CoreObject.prototype.getFlags = function () { var arr = []; for (var key in flags[this.id]) { arr.push(internalKeyToExternalKey(key)); } return arr; }; /** * Connects an event on this CoreObject to an event on another CoreObject. * This means that if CoreObject A emits the specified event then CoreObject B * will emit another event as a reaction. * * @type string -> CoreObject -> string -> (boolean ->) CoreObject * @param event1 The event on this CoreObject. * @param obj2 The other CoreObject. * @param event2 The event on the other CoreObject. * @param async boolean Should the event on the other CoreObject be triggered async? * This is optional. The default is true. * @return This CoreObject. */ CoreObject.prototype.connect = function (event1, obj2, event2, async) { var self = this; event1 = event1 || "*"; event2 = event2 || "*"; if (!obj2 || !(obj2 instanceof CoreObject)) { throw new Exception("Cannot connect events: Parameter 3 is " + "expected to be of type CoreObject."); } function listener (data) { data = data || null; if (typeof async !== "undefined" && (async === true || async === false)) { obj2.trigger(event2, data, async); } else { obj2.trigger(event2, data); } } this.subscribe(listener, event1); obj2.once(function () { self.unsubscribe(listener, event1); }, "destroyed"); return this; }; /** * Checks whether this CoreObject complies to an interface by * comparing each properties type. * * @type object -> boolean * @param interface An object representing the interface. * @return Does this CoreObject implement the interface? */ CoreObject.prototype.implements = function (interface) { for (var key in interface) { if (typeof this[key] !== typeof interface[key]) { return false; } } return true; }; /** * CoreObject instances have a unique ID; when used as a string, * the ID of the object is used as a representation. * * @type string * @return This CoreObjet's ID as a string. */ CoreObject.prototype.toString = function () { return "" + this.id; }; /** * Returns this CoreObject's ID. * * @type number * @return This CoreObject's ID. */ CoreObject.prototype.valueOf = function () { return this.id; }; /** * Emits the destroyed() event and deletes all of the instances properties. * After this method has been called on an CoreObject, it can not be used * anymore and should be considered dead. * * All users of a CoreObject should hook to the destroyed() event and delete * their references to the CoreObject when its destroyed() event is emitted. * * @event destroyed() * @return void */ CoreObject.prototype.destroy = function () { var id = this.id; if (this.$parent) { this.$parent.removeChild(this); } this.$children.forEach(function (child) { if (typeof child === "object" && typeof child.destroy === "function") { child.destroy(); } }); this.destroyed = true; this.trigger("destroyed", null, false); for (var key in this) { this[key] = null; } delete flags[id]; this.destroyed = true; this.id = id; delete this.toString; delete this.valueOf; }; CoreObject.prototype.subscribeTo = function (bus, event, listener) { var self = this; if (!(typeof bus.subscribe === "function" && typeof bus.unsubscribe === "function")) { throw new Exception("Cannot subscribe: Parameter 1 is " + "expected to be of type CoreObject or EventBus."); } if (typeof event !== "string") { throw new Exception("Cannot subscribe: Parameter 2 is " + "expected to be of type String."); } if (typeof listener !== "function") { throw new Exception("Cannot subscribe: Parameter 3 is " + "expected to be of type Function."); } listener = listener.bind(this); bus.subscribe(event, listener); this.subscribe("destroyed", thisDestroyed); bus.subscribe("destroyed", busDestroyed); return this; function thisDestroyed () { bus.unsubscribe(event, listener); self.unsubscribe("destroyed", thisDestroyed); bus.unsubscribe("destroyed", busDestroyed); } function busDestroyed () { bus.unsubscribe("destroyed", busDestroyed); self.unsubscribe("destroyed", thisDestroyed); } }; return CoreObject; /////////////////////////////////// // Helper functions /////////////////////////////////// function externalKeyToInternalKey (key) { return prefix + key; } function internalKeyToExternalKey (key) { return key.replace(new RegExp(prefix), ""); } } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, setTimeout */ using().define("MO5.dom.effects.typewriter", function () { function typewriter (element, args) { var TYPE_ELEMENT = 1, TYPE_TEXT = 3, speed, cb; args = args || {}; speed = args.speed || 50; cb = args.onFinish || null; function hideChildren(el) { var childNodes = el.childNodes, i, len; if (el.nodeType === TYPE_ELEMENT) { el.style.display = 'none'; for (i = 0, len = childNodes.length; i < len; i += 1) { hideChildren(childNodes[i]); } } } hideChildren(element); function showChildren(el, cb) { if (el.nodeType === TYPE_ELEMENT) { (function () { var children = []; while (el.hasChildNodes()) { children.push(el.removeChild(el.firstChild)); } el.style.display = ''; (function loopChildren() { if (children.length > 0) { showChildren(children[0], loopChildren); el.appendChild(children.shift()); } else if (cb) { setTimeout(cb, 0); } }()); }()); } else if (el.nodeType === TYPE_TEXT) { (function () { var textContent = el.data.replace(/ +/g, ' '), i, len; el.data = ''; i = 0; len = textContent.length; function insertTextContent() { el.data += textContent[i]; i += 1; if (i < len) { setTimeout(insertTextContent, 1000 / speed); } else if (cb) { setTimeout(cb, 0); } } insertTextContent(); }()); } } showChildren(element, cb); } return typewriter; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, document, console */ using("MO5.CoreObject", "MO5.transform", "MO5.TimerWatcher", "MO5.dom.effects.typewriter", "MO5.types", "MO5.Point", "MO5.Size"). define("MO5.dom.Element", function (CoreObject, transform, TimerWatcher, typewriter, types, Point, Size) { function Element (args) { var self = this; args = args || {}; CoreObject.call(this); this.parent = args.parent || document.body; this.nodeType = args.nodeType || "div"; this.element = args.element || document.createElement(this.nodeType); wrapElement(this, this.element); Element.propertiesToExclude.forEach(function (property) { delete self[property]; }); } // Properties that should not shadow the DOM element's properties. // If you want to add a method with the same name as a DOM element's // property to the prototype, you need to add the method's name to this array. Element.propertiesToExclude = [ "appendChild", "removeChild" ]; /** * Creates an Element instance for a DOMElement. */ Element.fromDomElement = function (domElement) { return new Element({element: domElement, nodeType: domElement.nodeName}); }; Element.prototype = new CoreObject(); Element.prototype.constructor = Element; Element.prototype.appendTo = function (element) { return element.appendChild(this.element); }; Element.prototype.remove = function () { return this.element.parentNode.removeChild(this.element); }; Element.prototype.appendChild = function (child) { var node = child instanceof Element ? child.element : child; return this.element.appendChild(node); }; /** * Adds a child element as the first child of this element. */ Element.prototype.addAsFirstChild = function (child) { var node = child instanceof Element ? child.element : child; return this.element.childElementCount > 0 ? this.element.insertBefore(node, this.element.childNodes[0]) : this.element.appendChild(node); }; Element.prototype.fadeIn = function (args) { args = args || {}; var element = this.element; if (this._lastFadeTimer && this._lastFadeTimer.isRunning()) { this._lastFadeTimer.cancel(); } this.show(); this._lastFadeTimer = transform( function (v) { element.style.opacity = v; }, parseInt(element.style.opacity, 10) || 0, 1, args ); return this._lastFadeTimer; }; Element.prototype.fadeOut = function (args) { args = args || {}; var element = this.element; if (this._lastFadeTimer && this._lastFadeTimer.isRunning()) { this._lastFadeTimer.cancel(); } this._lastFadeTimer = transform( function (v) { element.style.opacity = v; }, parseInt(element.style.opacity, 10) || 1, 0, args ); this._lastFadeTimer.once("stopped", this.hide.bind(this)); return this._lastFadeTimer; }; Element.prototype.opacity = function (value) { if (typeof value === "number") { this.element.style.opacity = value; } return this.element.style.opacity; }; Element.prototype.position = function (point) { var element = this.element, rect = {}, scrollLeft, scrollTop; if (types.isObject(point)) { element.style.left = "" + (+point.x) + "px"; element.style.top = "" + (+point.y) + "px"; } rect.left = element.offsetLeft; rect.top = element.offsetTop; if (element.getBoundingClientRect) { rect = element.getBoundingClientRect(); } scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft); scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop); return new Point(scrollLeft + rect.left, scrollTop + rect.top); }; Element.prototype.size = function (size) { if (types.isObject(size)) { this.element.style.width = "" + size.width + "px"; this.element.style.height = "" + size.height + "px"; } return new Size(this.element.offsetWidth, this.element.offsetHeight); }; Element.prototype.width = function (width) { if (types.isNumber(width)) { this.element.style.width = "" + width + "px"; } return this.element.offsetWidth; }; Element.prototype.height = function (height) { if (types.isNumber(height)) { this.element.style.height = "" + height + "px"; } return this.element.offsetHeight; }; Element.prototype.moveTo = function (x, y, args) { args = args || {}; var element = this.element, ox = element.offsetLeft, oy = element.offsetTop, t0, t1; t0 = transform( function (v) { element.style.left = v + "px"; }, ox, x, args ); t1 = transform( function (v) { element.style.top = v + "px"; }, oy, y, args ); return new TimerWatcher().addTimer(t0).addTimer(t1); }; Element.prototype.move = function (x, y, args) { args = args || {}; var element = this.element, dx = element.offsetLeft + x, dy = element.offsetTop + y; return this.moveTo(dx, dy, args); }; Element.prototype.display = function () { this.element.style.visibility = ""; }; Element.prototype.show = Element.prototype.display; Element.prototype.hide = function () { this.element.style.visibility = "hidden"; }; Element.prototype.typewriter = function (args) { args = args || {}; typewriter(this.element, args); }; Element.prototype.addCssClass = function (classToAdd) { var classes; if (this.element.classList) { this.element.classList.add(classToAdd); return this; } classes = this.getCssClasses(); if (!contains(classes, classToAdd)) { classes.push(classToAdd); this.element.setAttribute("class", classes.join(" ")); } return this; }; Element.prototype.removeCssClass = function (classToRemove) { var classes; if (this.element.classList) { this.element.classList.remove(classToRemove); } classes = this.getCssClasses(); if (contains(classes, classToRemove)) { this.element.setAttribute("class", classes.filter(function (item) { return item !== classToRemove; }).join(" ")); } return this; }; Element.prototype.getCssClasses = function () { return (this.element.getAttribute("class") || "").split(" "); }; Element.prototype.hasCssClass = function (classToCheckFor) { return this.element.classList ? this.element.classList.contains(classToCheckFor) : contains(this.getCssClasses(), classToCheckFor); }; Element.prototype.clearCssClasses = function () { this.element.setAttribute("class", ""); return this; }; Element.prototype.setCssId = function (cssId) { this.element.setAttribute("id", cssId); return this; }; Element.prototype.destroy = function () { try { this.element.parentNode.removeChild(this.element); } catch (e) { console.log(e); } CoreObject.prototype.destroy.call(this); }; //////////////////////////////////////// // dom.Element helper functions //////////////////////////////////////// function wrapElement (element, domElement) { for (var key in domElement) { (function (currentProperty, key) { if (key === "id") { return; } if (typeof currentProperty === "function") { element[key] = function () { return domElement[key].apply(domElement, arguments); }; } else { element[key] = function (content) { if (arguments.length) { domElement[key] = content; return element; } return domElement[key]; }; } }(domElement[key], key)); } } function contains (array, item) { return array.indexOf(item) !== -1; } return Element; }); /* global using */ using().define("MO5.dom.escape", function () { function escape (unescapedHtml) { var escaped = ""; escaped = unescapedHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;"). replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); return escaped; } return escape; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window */ using().define("MO5.easing", function () { /** * Acceleration functions for use in MO5.transform(). */ var easing = (function (stdLib) { "use asm"; /*! * TERMS OF USE - EASING EQUATIONS * Open source under the BSD License. * Copyright 2001 Robert Penner All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Function for linear transformations. */ function linear (d, t) { d = d|0; t = t|0; return +(t / d); } /** * Function for sine transformations. */ function sineEaseOut (d, t) { d = d|0; t = t|0; var s = +(stdLib.Math.PI / (2 * d)); var y = +(stdLib.Math.abs(stdLib.Math.sin(t * s))); return +y; } function sineEaseIn (d, t) { d = d|0; t = t|0; var s = +(stdLib.Math.PI / (2 * d)); var y = +(stdLib.Math.abs(-stdLib.Math.cos(t * s) + 1)); return +y; } function sineEaseInOut (d, t) { d = d|0; t = t|0; if (+(t / (d / 2) < 1)) { return +sineEaseIn(d, t); } else { return +sineEaseOut(d, t); } } /* * EaseOutBounce for JavaScript, taken from jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ function easeOutBounce (d, t) { d = d|0; t = t|0; var b = 0, c = 1, val = 0.0; if ((t /= d) < (1 / 2.75)) { val = +(c * (7.5625 * t * t) + b); } else if (t < (2 / 2.75)) { val = +(c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b); } else if (t < (2.5 / 2.75)) { val = +(c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b); } else { val = +(c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b); } return +val; } function easeOut (potency, d, t) { d = d|0; t = t|0; return +(1 - stdLib.Math.pow(1 - (t / d), potency)); } function easeIn (potency, d, t) { d = d|0; t = t|0; return +(stdLib.Math.pow((t / d), potency)); } function easeInOut (potency, d, t) { d = d|0; t = t|0; var val = 0.0; if (t > d / 2) { val = +easeOut(potency, d, t); } else { val = +easeIn(potency, d, t); } return +val; } return { linear: linear, sineEaseOut: sineEaseOut, sineEaseIn: sineEaseIn, sineEaseInOut: sineEaseInOut, easeOutBounce: easeOutBounce, easeIn: easeIn, easeOut: easeOut, easeInOut: easeInOut }; }(window)); easing.easingFunctionGenerator = easingFunctionGenerator; easing.createEaseInFunction = createEaseInFunction; easing.createEaseOutFunction = createEaseOutFunction; easing.createEaseInOutFunction = createEaseInOutFunction; easing.easeInQuad = createEaseInFunction(2); easing.easeInCubic = createEaseInFunction(3); easing.easeInQuart = createEaseInFunction(4); easing.easeInQuint = createEaseInFunction(5); easing.easeOutQuad = createEaseOutFunction(2); easing.easeOutCubic = createEaseOutFunction(3); easing.easeOutQuart = createEaseOutFunction(4); easing.easeOutQuint = createEaseOutFunction(5); easing.easeInOutQuad = createEaseInOutFunction(2); easing.easeInOutCubic = createEaseInOutFunction(3); easing.easeInOutQuart = createEaseInOutFunction(4); easing.easeInOutQuint = createEaseInOutFunction(5); return easing; function easingFunctionGenerator (type) { return function (potency) { return function (d, t) { return easing[type](potency, d, t); }; }; } function createEaseInFunction (potency) { return easingFunctionGenerator("easeIn")(potency); } function createEaseOutFunction (potency) { return easingFunctionGenerator("easeOut")(potency); } function createEaseInOutFunction (potency) { return easingFunctionGenerator("easeInOut")(potency); } }); /* global using, MO5, setTimeout, console, window, module */ (function MO5EventBusBootstrap () { if (typeof using === "function") { using().define("MO5.EventBus", MO5EventBusModule); } else if (typeof window !== "undefined") { window.MO5 = MO5 || {}; window.MO5.EventBus = MO5EventBusModule(); } else { module.exports = MO5EventBusModule(); } function MO5EventBusModule () { "use strict"; function EventBus (args) { var self = this; args = args || {}; this.debug = args.debug || false; this.interceptErrors = args.interceptErrors || false; this.log = args.log || false; this.logData = args.logData || false; this.defaults = args.defaults || {}; this.defaults.flowType = this.defaults.flowType || EventBus.FLOW_TYPE_ASYNCHRONOUS; this.callbacks = { "*": [] }; this.subscribe(errorListener, "EventBus.error"); function errorListener (data) { var name; if (self.debug !== true) { return; } name = data.error.name || "Error"; console.log(name + " in listener; Event: " + data.info.event + "; Message: " + data.error.message); } } EventBus.FLOW_TYPE_ASYNCHRONOUS = 0; EventBus.FLOW_TYPE_SYNCHRONOUS = 1; EventBus.create = function(args) { args = args || {}; return new EventBus(args); }; EventBus.prototype.subscribe = function(parameter1, parameter2) { var listener, event, self = this; if (parameter2 === undefined) { event = "*"; listener = parameter1; } else if (typeof parameter1 === "string" || typeof parameter1 === "number") { event = parameter1; listener = parameter2; } else if (typeof parameter2 === "string" || typeof parameter2 === "number") { event = parameter2; listener = parameter1; } if (typeof event !== "string" && typeof event !== "number") { throw new Error("Event names can only be strings or numbers! event: ", event); } if (typeof listener !== "function") { throw new Error("Only functions may be used as listeners!"); } event = event || '*'; this.callbacks[event] = this.callbacks[event] || []; this.callbacks[event].push(listener); this.trigger( "EventBus.subscribe", { listener: listener, event: event, bus: this } ); return function unsubscriber () { self.unsubscribe(listener, event); }; }; EventBus.prototype.unsubscribe = function(parameter1, parameter2) { var cbs, len, i, listener, event; if (parameter2 === undefined) { event = "*"; listener = parameter1; } else if (typeof parameter1 === "string" || typeof parameter1 === "number") { event = parameter1; listener = parameter2; } else if (typeof parameter2 === "string" || typeof parameter2 === "number") { event = parameter2; listener = parameter1; } if (typeof event !== "string" && typeof event !== "number") { throw new Error("Event names can only be strings or numbers! event: ", event); } if (typeof listener !== "function") { throw new Error("Only functions may be used as listeners!"); } event = event || '*'; cbs = this.callbacks[event] || []; len = cbs.length; for (i = 0; i < len; ++i) { if (cbs[i] === listener) { this.callbacks[event].splice(i, 1); } } this.trigger( "EventBus.unsubscribe", { listener: listener, event: event, bus: this } ); }; EventBus.prototype.once = function (listenerOrEvent1, listenerOrEvent2) { var fn, self = this, event, listener; var firstParamIsFunction, secondParamIsFunction, called = false; firstParamIsFunction = typeof listenerOrEvent1 === "function"; secondParamIsFunction = typeof listenerOrEvent2 === "function"; if ((firstParamIsFunction && secondParamIsFunction) || (!firstParamIsFunction && !secondParamIsFunction)) { throw new Error("Parameter mismatch; one parameter needs to be a function, " + "the other one must be a string."); } if (firstParamIsFunction) { listener = listenerOrEvent1; event = listenerOrEvent2; } else { listener = listenerOrEvent2; event = listenerOrEvent1; } event = event || "*"; fn = function (data, info) { if (called) { return; } called = true; self.unsubscribe(fn, event); listener(data, info); }; this.subscribe(fn, event); }; EventBus.prototype.trigger = function(event, data, async) { var cbs, len, info, j, f, cur, self, flowType; if ( typeof event !== "undefined" && typeof event !== "string" && typeof event !== "number" ) { throw new Error("Event names can only be strings or numbers! event: ", event); } self = this; event = arguments.length ? event : "*"; flowType = (typeof async !== "undefined" && async === false) ? EventBus.FLOW_TYPE_SYNCHRONOUS : this.defaults.flowType; // get subscribers in all relevant namespaces cbs = (function() { var n, words, wc, matches, k, kc, old = "", out = []; // split event name into namespaces and get all subscribers words = event.split("."); for (n = 0, wc = words.length ; n < wc ; ++n) { old = old + (n > 0 ? "." : "") + words[n]; matches = self.callbacks[old] || []; for (k = 0, kc = matches.length; k < kc; ++k) { out.push(matches[k]); } } if (event === "*") { return out; } // get subscribers for "*" and add them, too matches = self.callbacks["*"] || []; for (k = 0, kc = matches.length ; k < kc ; ++k) { out.push( matches[ k ] ); } return out; }()); len = cbs.length; info = { event: event, subscribers: len, async: flowType === EventBus.FLOW_TYPE_ASYNCHRONOUS ? true : false, getQueueLength: function() { if (len === 0) { return 0; } return len - (j + 1); } }; function asyncThrow (e) { setTimeout( function () { throw e; }, 0 ); } // function for iterating through the list of relevant listeners f = function() { if (self.log === true) { console.log( "EventBus event triggered: " + event + "; Subscribers: " + len, self.logData === true ? "; Data: " + data : "" ); } for (j = 0; j < len; ++j) { cur = cbs[j]; try { cur(data, info); } catch (e) { console.log(e); self.trigger( "EventBus.error", { error: e, info: info } ); if (self.interceptErrors !== true) { asyncThrow(e); } } } }; if (flowType === EventBus.FLOW_TYPE_ASYNCHRONOUS) { setTimeout(f, 0); } else { f(); } }; EventBus.prototype.triggerSync = function (event, data) { return this.trigger(event, data, false); }; EventBus.prototype.triggerAsync = function (event, data) { return this.trigger(event, data, true); }; EventBus.inject = function (obj, args) { args = args || {}; var squid = new EventBus(args); obj.subscribe = function (listener, event) { squid.subscribe(listener, event); }; obj.unsubscribe = function (listener, event) { squid.unsubscribe(listener, event); }; obj.once = function (listener, event) { squid.once(listener, event); }; obj.trigger = function (event, data, async) { async = (typeof async !== "undefined" && async === false) ? false : true; squid.trigger(event, data, async); }; obj.triggerSync = squid.triggerSync.bind(squid); obj.triggerAsync = squid.triggerAsync.bind(squid); obj.subscribe("destroyed", function () { squid.callbacks = []; }); }; return EventBus; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, module, window */ (function MO5ExceptionBootstrap () { if (typeof using === "function") { using().define("MO5.Exception", MO5ExceptionModule); } else if (typeof window !== "undefined") { window.MO5 = window.MO5 || {}; window.MO5.Exception = MO5ExceptionModule(); } else { module.exports = MO5ExceptionModule(); } function MO5ExceptionModule () { function Exception (msg) { var e = Error.apply(null, arguments), key; // we need to copy the properties manually since // Javascript's Error constructor ignores the first // parameter used with .call()... for (key in e) { this[key] = e[key]; } this.message = msg; this.name = "MO5.Exception"; } Exception.prototype = new Error(); Exception.prototype.constructor = Exception; return Exception; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, console, module */ (function MO5failBootstrap () { if (typeof using === "function") { using().define("MO5.fail", MO5failModule); } else if (typeof window !== "undefined") { window.MO5.fail = MO5failModule(); } else { module.exports = MO5failModule(); } function MO5failModule () { /** * A function to log errors with stack traces to the console. * Useful if you encounter some minor errors that are no show-stoppers * and should therefore not be thrown, but which can help * debug your code by looking at the console output. */ function fail (e) { if (console.error) { console.error(e.toString()); } else { console.log(e.toString()); } if (e.stack) { console.log(e.stack); } } return fail; } }()); /* global using, document */ using().define("MO5.globals.document", function () { return document; }); /* global using, window */ using().define("MO5.globals.window", function () { return window; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global MO5, window, require, module */ (function MO5ListBootstrap () { if (typeof using === "function") { using("MO5.CoreObject", "MO5.Queue", "MO5.types"). define("MO5.List", MO5ListModule); } else if (typeof window !== "undefined") { window.MO5.List = MO5ListModule(MO5.CoreObject, MO5.Queue, MO5.types); } else { module.exports = MO5ListModule( require("./CoreObject.js"), require("./Queue.js"), require("./types.js") ); } function MO5ListModule (CoreObject, Queue, types) { function List (items) { CoreObject.call(this); this.unsubscribers = {}; this.items = types.isArray(items) ? items : []; } List.prototype = new CoreObject(); List.prototype.length = function () { return this.items.length; }; List.prototype.append = function (value) { var self = this; function listener () { var i, len; for (i = 0, len = self.items.length; i < len; i += 1) { if (self.items[i] === value) { self.items.splice(i, 1); } } delete self.unsubscribers[value.id]; } function unsubscribe () { value.unsubscribe(listener, "destroyed"); } if (CoreObject.isCoreObject(value)) { this.unsubscribers[value.id] = unsubscribe; value.subscribe(listener, "destroyed"); value.subscribe("destroyed", function () {value = null;}); } this.items.push(value); return this; }; List.prototype.remove = function (i) { var val = this.items[i]; if (CoreObject.isCoreObject(val)) { this.unsubscribers[val.id](); delete this.unsubscribers[val.id]; } this.items.splice(i, 1); return this; }; List.prototype.clear = function () { var list = this; this.forEach(function (item, i) { list.remove(i); }); }; List.prototype.at = function (i) { return this.items[+i]; }; List.prototype.indexOf = function (item) { return this.items.indexOf(item); }; List.prototype.values = function () { var values = []; this.forEach(function (value) { values.push(value); }); return values; }; List.prototype.toQueue = function () { var q = new Queue(); this.items.forEach(function (item) { q.add(item); }); return q; }; List.prototype.forEach = function (fn) { this.items.forEach(fn); }; List.prototype.filter = function (fn) { return this.items.filter(fn); }; List.prototype.map = function (fn) { return this.items.map(fn); }; List.prototype.reduce = function (fn) { return this.items.reduce(fn); }; List.prototype.every = function (fn) { return this.items.every(fn); }; List.prototype.some = function (fn) { return this.items.some(fn); }; List.prototype.find = function (fn) { var i, numberOfItems = this.items.length; for (i = 0; i < numberOfItems; i += 1) { if (fn(this.items[i])) { return this.items[i]; } } return undefined; }; /** * Returns a list which is this list with all the items from another list * appended to it. */ List.prototype.combine = function (otherList) { return new List(this.items.slice().concat(otherList.items)); }; List.prototype.clone = function () { return new List(this.items.slice()); }; List.prototype.destroy = function () { if (this.destroyed) { return; } for (var i = 0; i < this.unsubscribers.length; i++) { this.unsubscribers[i](); delete this.unsubscribers[i]; }; CoreObject.prototype.destroy.apply(this, arguments); } return List; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, module, require, window */ (function MO5MapBootstrap () { if (typeof using === "function") { using("MO5.CoreObject", "MO5.Exception"). define("MO5.Map", MO5MapModule); } else if (typeof window !== "undefined") { window.MO5.Map = MO5MapModule(MO5.CoreObject, MO5.Exception); } else { module.exports = MO5MapModule( require("./CoreObject.js"), require("./Exception.js") ); } function MO5MapModule (CoreObject, Exception) { var prefix = "MO5Map"; function makeKey (k) { return prefix + k; } function revokeKey (k) { return k.replace(new RegExp(prefix), ""); } function Map (content) { var key; CoreObject.call(this); this.clear(); if (content) { for (key in content) { this.set(key, content[key]); } } } Map.prototype = new CoreObject(); Map.prototype.clear = function () { this.items = {}; this.unsubscribers = {}; this.count = 0; }; Map.prototype.length = function () { return this.count; }; Map.prototype.set = function (k, value) { var self = this, key = makeKey(k); function whenDestroyed () { if (self.has(k)) { self.remove(k); } } if (!k) { throw new Error("MO5.Map keys cannot be falsy."); } if (this.has(key)) { this.remove(key); } if (value && value instanceof CoreObject) { if (value.destroyed) { throw new Error("Trying to add an MO5.Object that has " + "already been destroyed."); } value.subscribe(whenDestroyed, "destroyed"); } if (k instanceof CoreObject) { if (k.destroyed) { throw new Error("Trying to use an MO5.Object as key that " + "has already been destroyed."); } k.subscribe(whenDestroyed, "destroyed"); } if (value && value instanceof CoreObject || k instanceof CoreObject) { this.unsubscribers[key] = function () { if (value instanceof CoreObject) { value.unsubscribe(whenDestroyed, "destroyed"); } if (k instanceof CoreObject) { k.unsubscribe(whenDestroyed, "destroyed"); } }; } this.items[key] = value; this.count += 1; this.trigger("updated", null, false); this.trigger("set", key, false); return this; }; Map.prototype.get = function (k) { var key = makeKey(k); if (!this.items.hasOwnProperty(key)) { return undefined; } return this.items[key]; }; /** * The same as .get(), but throws when the key doesn't exist. * This can be useful if you want to use a map as some sort of registry. */ Map.prototype.require = function (key) { if (!this.has(key)) { throw new Error("Required key '" + key + "' does not exist."); } return this.get(key); }; Map.prototype.remove = function (k) { var key = makeKey(k); if (!this.has(k)) { throw new Error("Trying to remove an unknown key from an MO5.Map."); } if (this.unsubscribers.hasOwnProperty(key)) { this.unsubscribers[key](); delete this.unsubscribers[key]; } delete this.items[key]; this.count -= 1; this.trigger("updated", null, false); this.trigger("removed", key, false); return this; }; Map.prototype.has = function (k) { var key = makeKey(k); return this.items.hasOwnProperty(key); }; Map.prototype.destroy = function () { for (var key in this.unsubscribers) { this.unsubscribers[key](); delete this.unsubscribers[key]; } CoreObject.prototype.destroy.call(this); }; Map.prototype.forEach = function (fn) { if (!fn || typeof fn !== "function") { throw new Error("Parameter 1 is expected to be of type function."); } for (var key in this.items) { fn(this.items[key], revokeKey(key), this); } return this; }; Map.prototype.filter = function (fn) { var matches = new Map(); this.forEach(function (item, key, all) { if (fn(item, key, all)) { matches.set(key, item); } }); return matches; }; Map.prototype.find = function (fn) { var value, valueFound = false; this.forEach(function (item, key, all) { if (!valueFound && fn(item, key, all)) { value = item; valueFound = true; } }); return value; }; Map.prototype.map = function (fn) { var mapped = new Map(); this.forEach(function (item, key, all) { mapped.set(key, fn(item, key, all)); }); return mapped; }; Map.prototype.reduce = function (fn, initialValue) { var result = initialValue; this.forEach(function (item, key, all) { result = fn(result, item, key, all); }); return result; }; Map.prototype.every = function (fn) { return this.reduce(function (last, item, key, all) { return last && fn(item, key, all); }, true); }; Map.prototype.some = function (fn) { var matchFound = false; this.forEach(function (item, key, all) { if (!matchFound && fn(item, key, all)) { matchFound = true; } }); return matchFound; }; Map.prototype.keys = function () { var keys = []; this.forEach(function (item, key) { keys.push(key); }); return keys; }; /** * Returns the map's values in an array. */ Map.prototype.values = function () { var values = []; this.forEach(function (item) { values.push(item); }); return values; }; Map.prototype.toObject = function () { var jsObject = {}; this.forEach(function (item, key) { jsObject[key] = item; }); return jsObject; }; Map.prototype.clone = function () { var clone = new Map(); this.forEach(function (item, key) { clone.set(key, item); }); return clone; }; /** * Adds the content of another map to this map's content. * @param otherMap Another MO5.Map. */ Map.prototype.addMap = function (otherMap) { var self = this; otherMap.forEach(function (item, key) { self.set(key, item); }); return this; }; /** * Returns a new map which is the result of joining this map * with another map. This map isn't changed in the process. * The keys from otherMap will replace any keys from this map that * are the same. * @param otherMap A map to join with this map. */ Map.prototype.join = function (otherMap) { return this.clone().addMap(otherMap); }; return Map; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using */ using().define("MO5.Point", function () { function Point (x, y) { this.x = x; this.y = y; } Point.prototype.getDistance = function (otherPoint) { var dx = this.x - otherPoint.x, dy = this.y - otherPoint.y, dist = Math.squrt(dx * dx + dy * dy); return dist; }; return Point; }); /* global global, window, process, document, using, Promise, module */ (function() { var define, requireModule, require, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = require = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }()); (function MO5PromiseBootstrap () { if (typeof using === "function") { using().define("MO5.Promise", MO5PromiseModule); } else if (typeof window !== "undefined") { window.MO5.Promise = MO5PromiseModule(); } else { module.exports = MO5PromiseModule(); } function MO5PromiseModule () { function MO5Promise (fn) { var success, failure, promise = new Promise(function (resolve, reject) { success = function (value) { resolve(value); return promise; }; failure = function (reason) { reject(reason); return promise; }; }); promise.success = success; promise.failure = failure; promise.resolve = success; promise.reject = failure; if (typeof fn === "function") { fn(success, failure); } return promise; } MO5Promise.resolve = Promise.resolve; MO5Promise.reject = Promise.reject; MO5Promise.all = Promise.all; MO5Promise.race = Promise.race; MO5Promise.consolify = function (promise) { promise. then(console.log.bind(console)). catch(function (error) { console.error(error); console.log(error.stack); }); }; return MO5Promise; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global MO5, require, module, window */ (function MO5QueueBootstrap () { if (typeof using === "function") { using("MO5.Exception", "MO5.CoreObject"). define("MO5.Queue", MO5QueueModule); } else if (typeof window !== "undefined") { window.MO5.Queue = MO5QueueModule(MO5.Exception, MO5.CoreObject); } else { module.exports = MO5QueueModule( require("./Exception.js"), require("./CoreObject.js") ); } function MO5QueueModule (Exception, CoreObject) { function Queue (arr) { CoreObject.call(this); if (arr && !(arr instanceof Array)) { throw new Exception("Parameter 1 is expected to be of type Array."); } this.arr = arr || []; } Queue.prototype = new CoreObject(); Queue.prototype.constructor = Queue; Queue.prototype.length = function () { return this.arr.length; }; /** * Adds an item to the back of the queue. */ Queue.prototype.add = function (val) { var self = this, index = this.arr.length; if (val instanceof CoreObject) { if (val.destroyed) { throw new Exception("Trying to add an MO5.Object that has " + "already been destroyed."); } val.once(function () { if (!self.destroyed) { self.arr.splice(index, 1); } }, "destroyed"); } this.arr.push(val); this.trigger("updated"); this.trigger("added", val); return this; }; /** * Replaces all items of the queue with the items in the first parameter. * @param arr An array containing the new items. */ Queue.prototype.replace = function (arr) { if (!(arr instanceof Array)) { throw new Exception("Parameter 1 is expected to be of type Array."); } this.arr = arr; this.trigger("updated"); this.trigger("replaced", arr); return this; }; /** * Removes the front of the queue and returns it. */ Queue.prototype.next = function () { if (!this.hasNext()) { throw new Exception("Calling next() on empty queue."); } var ret = this.arr.shift(); this.trigger("updated"); this.trigger("next"); if (this.arr.length < 1) { this.trigger("emptied"); } return ret; }; /** * Returns the front item of the queue without removing it. */ Queue.prototype.peak = function () { return this.isEmpty() ? undefined : this.arr[0]; }; Queue.prototype.isEmpty = function () { return !this.hasNext(); }; Queue.prototype.hasNext = function () { return this.arr.length > 0; }; /** * Removes all items from the queue. */ Queue.prototype.clear = function () { this.arr = []; this.trigger("updated"); this.trigger("cleared"); return this; }; /** * Reverses the queue's order so that the first item becomes the last. */ Queue.prototype.reverse = function () { var q = new Queue(), len = this.length(), i = len - 1; while (i >= 0) { q.add(this.arr[i]); i -= 1; } return q; }; /** * Returns a shallow copy of the queue. */ Queue.prototype.clone = function () { return new Queue(this.arr.slice()); }; return Queue; } }()); /* global MO5, window, module */ (function MO5rangeBootstrap () { if (typeof using === "function") { using().define("MO5.range", MO5rangeModule); } else if (typeof window !== "undefined") { window.MO5.range = MO5rangeModule(); } else { module.exports = MO5rangeModule(); } function MO5rangeModule () { function range (first, last) { var bag = [], i; for (i = first; i <= last; i += 1) { bag.push(i); } return bag; } return range; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, setTimeout, module, require, process, console */ (function MO5ResultBootstrap () { console.warn("MO5.Result is deprecated - use MO5.Promise instead!"); if (typeof using === "function") { using("MO5.CoreObject", "MO5.Queue", "MO5.Exception", "MO5.fail"). define("MO5.Result", MO5ResultModule); } else if (typeof window !== "undefined") { window.MO5.CoreObject = MO5ResultModule( MO5.CoreObject, MO5.Queue, MO5.Exception, MO5.fail ); } else { module.exports = MO5ResultModule( require("./CoreObject.js"), require("./Queue.js"), require("./Exception.js"), require("./fail.js") ); } function MO5ResultModule (CoreObject, Queue, Exception, fail) { var setImmediate; if (typeof window !== "undefined" && window.setImmediate) { setImmediate = window.setImmediate; } else if (typeof process !== "undefined") { setImmediate = function (fn) { process.nextTick(fn); }; } else { setImmediate = function (fn) { setTimeout(fn, 0); }; } function resolve (queue, value) { while (queue.hasNext()) { setImmediate((function (cur) { return function () { cur(value); }; }(queue.next()))); } } function addToQueue (type, queue, cb, action) { if (typeof cb === "function") { queue.add(function (value) { var nextValue; try { nextValue = cb(value); if (nextValue && nextValue instanceof Promise) { nextValue.then(action.success, action.failure); } else { action.success(nextValue); } } catch (e) { action.failure(e); } return nextValue; }); } else { queue.add(function (value) { action[type](value); }); } } function Result () { CoreObject.call(this); this.successQueue = new Queue(); this.failureQueue = new Queue(); this.value = undefined; this.status = Result.STATUS_PENDING; this.promise = new Promise(this); } Result.STATUS_PENDING = 1; Result.STATUS_FAILURE = 2; Result.STATUS_SUCCESS = 3; Result.getFulfilledPromise = function () { return new Result().success().promise; }; Result.getBrokenPromise = function () { return new Result().failure().promise; }; Result.prototype = new CoreObject(); Result.prototype.isPending = function () { return this.status === Result.STATUS_PENDING; }; Result.prototype.failure = function (reason) { if (this.status !== Result.STATUS_PENDING) { fail(new Exception("The result of the action has already been determined.")); return; } this.value = reason; this.status = Result.STATUS_FAILURE; resolve(this.failureQueue, reason); this.successQueue.clear(); this.failureQueue.clear(); return this; }; Result.prototype.success = function (value) { if (this.status !== Result.STATUS_PENDING) { fail(new Exception("The result of the action has already been determined.")); return; } this.value = value; this.status = Result.STATUS_SUCCESS; resolve(this.successQueue, value); this.successQueue.clear(); this.failureQueue.clear(); return this; }; Result.addToQueue = addToQueue; Result.resolve = resolve; function Promise (result) { CoreObject.call(this); this.then = function (success, failure) { var newResult = new Result(); switch (result.status) { case Result.STATUS_PENDING: Result.addToQueue("success", result.successQueue, success, newResult); Result.addToQueue("failure", result.failureQueue, failure, newResult); break; case Result.STATUS_SUCCESS: Result.addToQueue("success", result.successQueue, success, newResult); Result.resolve(result.successQueue, result.value); break; case Result.STATUS_FAILURE: Result.addToQueue("failure", result.failureQueue, failure, newResult); Result.resolve(result.failureQueue, result.value); break; } return newResult.promise; }; } Promise.prototype = new CoreObject(); return Result; } }()); /* global using, module, require, window */ (function MO5SetBootstrap () { if (typeof using === "function") { using("MO5.CoreObject", "MO5.types"). define("MO5.Set", MO5SetModule); } else if (typeof window !== "undefined") { window.MO5.Set = MO5SetModule(MO5.CoreObject, MO5.types); } else { module.exports = MO5SetModule(require("./CoreObject.js"), require("./types.js")); } function MO5SetModule (CoreObject, types) { var KEY_PREFIX = "MO5Set_"; /** * A set implementation that is similar to the ES6 Set, but knows about CoreObjects. * * @type void|[any] -> Set * @param items Optional array or other .forEach()-implementing object with items to add. */ function Set (items) { CoreObject.call(this); // We need to hold onto CoreObject listeners to unsubscribe them // when the item gets deleted from the set: this._unsubscribers = {}; // An object where the keys are "hashes" for simple values or CoreObject IDs: this._stringItems = {}; // An array that holds non-"hashable" items, that is arrays and non-CoreObject objects: this._items = []; if (items && types.hasForEach(items)) { this.addMany(items); } } Set.fromRange = function (first, last) { var set = new Set(), i; for (i = first; i <= last; i += 1) { set.add(i); } return set; }; Set.prototype = new CoreObject(); /** * Checks whether an item is contained in the set. * * @type any -> boolean * @param item The item to check. * @return Is the item contained in the set? */ Set.prototype.has = function (item) { var i, length; if (canBeConvertedToKey(item)) { return (toKey(item) in this._stringItems); } else { for (i = 0, length = this._items.length; i < length; i += 1) { if (this._items[i] === item) { return true; } } return false; } }; /** * Adds an item to the set. * * @type any -> Set * @param item The item to add. * @return The Set object. */ Set.prototype.add = function (item) { var key; if (this.has(item)) { return this; } if (canBeConvertedToKey(item)) { key = toKey(item); this._stringItems[key] = item; if (CoreObject.isCoreObject(item)) { this._unsubscribers[key] = this.delete.bind(this, item); item.subscribe("destroyed", this._unsubscribers[key]); } } else { this._items.push(item); } return this; }; /** * Removes an item from the set. * * @type any -> boolean * @param item The item to remove. * @return Has the item been deleted? */ Set.prototype.delete = function (item) { var key; if (!this.has(item)) { return false; } if (canBeConvertedToKey(item)) { key = toKey(item); delete this._stringItems[key]; if (CoreObject.isCoreObject(item)) { item.unsubscribe("destroyed", this._unsubscribers[key]); delete this._unsubscribers[key]; } } else { this._items.splice(this._items.indexOf(item), 1); } return true; }; /** * Removes all items from the set. * * @type void -> undefined */ Set.prototype.clear = function () { this._items.forEach(this.delete.bind(this)); this._items = []; this._stringItems = {}; this._unsubscribers = {}; }; /** * Calls a callback for each of the items in the set with the following arguments: * 1) the item * 2) the index - this should be in the order in which the items have been added * 3) the set itself * * @type function -> undefined * @param fn A callback function. */ Set.prototype.forEach = function (fn) { var key, i = 0; for (key in this._stringItems) { fn(this._stringItems[key], i, this); i += 1; } this._items.forEach(function (item) { fn(item, i, this); i += 1; }.bind(this)); }; /** * Returns all items in the set as an array. * * @type void -> [any] */ Set.prototype.values = function () { var values = []; this.forEach(function (item) { values.push(item); }); return values; }; Set.prototype.keys = Set.prototype.values; /** * Adds many items to the set at once. * * @type [any] -> Set * @param items An array or other iterable object with a .forEach() method. * @return The Set object. */ Set.prototype.addMany = function (items) { items.forEach(this.add.bind(this)); return this; }; Set.prototype.intersection = function (otherSet) { var result = new Set(); otherSet.forEach(function (item) { if (this.has(item)) { result.add(item); } }.bind(this)); return result; }; Set.prototype.difference = function (otherSet) { var result = new Set(this.values()); otherSet.forEach(function (item) { if (result.has(item)) { result.delete(item); } else { result.add(item); } }); return result; }; Set.prototype.size = function () { var length = this._items.length, key; for (key in this._stringItems) { length += 1; } return length; }; return Set; /** * Checks whether an item can be converted to string in some form to be used as a key. * * @type any -> boolean * @param item The item to check. * @return Can the item be converted to key? */ function canBeConvertedToKey (item) { if (types.isObject(item)) { if (types.isNumber(item.id)) { return true; } return false; } return true; } /** * Converts an item to a key that can be used as a primitive "hash" to identifiy * the object inside the set. * * @type any -> string * @param item The item to convert to key. * @return The key as a string. */ function toKey (item) { if (types.isObject(item)) { return KEY_PREFIX + "MO5CoreObject_" + item.id; } return KEY_PREFIX + "SimpleValue_" + JSON.stringify(item); } } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modular HTML5 and Node.js Apps Copyright (c) 2014 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using */ using().define("MO5.Size", function () { function Size (width, height) { this.width = width || 0; this.height = height || 0; } return Size; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, module, require */ (function MO5TimerBootstrap () { if (typeof using === "function") { using("MO5.Exception", "MO5.CoreObject", "MO5.fail", "MO5.Promise"). define("MO5.Timer", MO5TimerModule); } else if (typeof window !== "undefined") { window.MO5.Timer = MO5TimerModule(MO5.Exception, MO5.CoreObject, MO5.fail, MO5.Promise); } else { module.exports = MO5TimerModule( require("./Exception.js"), require("./CoreObject.js"), require("./fail.js"), require("./Promise.js") ); } function MO5TimerModule (Exception, CoreObject, fail, Promise) { function TimerError (msg) { Exception.call(this); this.message = msg; this.name = "MO5.TimerError"; } TimerError.prototype = new Exception(); /** * A Timer object is returned by the transform() function. * It can be used to control the transformation during its * execution and it can also be used to obtain information * about the state of a transformation, e.g. whether it's * still ongoing. */ function Timer () { CoreObject.call(this); this.running = false; this.paused = false; this.canceled = false; this.startTime = +(new Date()); this.timeElapsed = 0; this.pauseTimeElapsed = 0; this.pauseStartTime = this.startTime; } Timer.prototype = new CoreObject(); Timer.prototype.constructor = Timer; Timer.prototype.start = function () { this.startTime = +(new Date()); this.running = true; this.trigger("started", null, false); return this; }; Timer.prototype.stop = function () { this.running = false; this.paused = false; this.trigger("stopped", null, false); return this; }; Timer.prototype.cancel = function () { if (!this.running) { fail(new TimerError("Trying to cancel a Timer that isn't running.")); } this.elapsed(); this.canceled = true; this.running = false; this.paused = false; this.trigger("canceled", null, false); return this; }; Timer.prototype.isRunning = function () { return this.running; }; Timer.prototype.isCanceled = function () { return this.canceled; }; Timer.prototype.isPaused = function () { return this.paused; }; Timer.prototype.pause = function () { this.paused = true; this.pauseStartTime = +(new Date()); this.trigger("paused", null, false); }; Timer.prototype.resume = function () { if (!this.paused) { fail(new TimerError("Trying to resume a timer that isn't paused.")); } this.paused = false; this.pauseTimeElapsed += +(new Date()) - this.pauseStartTime; this.trigger("resumed", null, false); }; /** * Returns the number of milliseconds since the call of start(). If the * Timer's already been stopped, then the number of milliseconds between * start() and stop() is returned. The number of milliseconds does not * include the times between pause() and resume()! */ Timer.prototype.elapsed = function () { if (this.running && !this.paused) { this.timeElapsed = ((+(new Date()) - this.startTime) - this.pauseTimeElapsed); } return this.timeElapsed; }; /** * Returns a capability object that can be given to other objects * by those owning a reference to the Timer. It is read only so that * the receiver of the capability object can only obtain information * about the Timer's state, but not modify it. */ Timer.prototype.getReadOnlyCapability = function () { var self = this; return { isRunning: function () { return self.running; }, isCanceled: function () { return self.canceled; }, isPaused: function () { return self.paused; }, elapsed: function () { return self.elapsed(); } }; }; Timer.prototype.promise = function () { var promise = new Promise(), self = this; this.once( function () { promise.resolve(self); }, "stopped" ); this.once( function () { promise.reject(self); }, "canceled" ); this.once( function () { promise.reject(self); }, "destroyed" ); return promise; }; return Timer; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, module, require */ (function MO5TimerWatcherBootstrap () { if (typeof using === "function") { using("MO5.Exception", "MO5.CoreObject", "MO5.fail", "MO5.Timer"). define("MO5.TimerWatcher", MO5TimerWatcherModule); } else if (typeof window !== "undefined") { window.MO5.TimerWatcher = MO5TimerWatcherModule( MO5.Exception, MO5.CoreObject, MO5.fail, MO5.Timer ); } else { module.exports = MO5TimerWatcherModule( require("./Exception.js"), require("./CoreObject.js"), require("./fail.js"), require("./Timer.js") ); } function MO5TimerWatcherModule (Exception, CoreObject, fail, Timer) { /** * A TimerWatcher object can be used to bundle MO5.Timer objects * together and observe them. The TimerWatcher object emits the * same events as a Timer does and has almost the same API, so that * in most cases, a TimerWatcher object can be used as if it was a Timer. * * A TimerWatcher extends MO5.Object. * * @type Constructor * * @event added(MO5.Timer) * @event canceled() * @event created(MO5.Timer) * @event pause() * @event resume() * @event started() * @event stopped() */ function TimerWatcher (timers) { var self; CoreObject.call(this); if (timers && !(timers instanceof Array)) { throw new Exception("Parameter 1 is expected to be of type Array.").log(); } timers = timers || []; self = this; this.timers = {}; this.count = 0; timers.forEach(function (t) { self.addTimer(t); }); } TimerWatcher.prototype = new CoreObject(); TimerWatcher.prototype.constructor = TimerWatcher; TimerWatcher.prototype.addTimer = function (timer) { var fn, self = this; if (this.timers[+timer]) { throw new Exception( "A timer with ID '" + timer + "' has already been added to the watcher."); } this.count += 1; fn = function () { self.count -= 1; if (self.count < 1) { self.trigger("stopped", null, false); } }; this.timers[+timer] = { timer: timer, unsubscribe: function () { timer.unsubscribe(fn, "stopped"); } }; timer.subscribe(fn, "stopped"); this.trigger("added", timer, false); return this; }; /** * Creates and returns a Timer that is already added to * the TimerWatcher when it's returned to the caller. */ TimerWatcher.prototype.createTimer = function () { var timer = new Timer(); this.trigger("created", timer, false); this.addTimer(timer); return timer; }; TimerWatcher.prototype.removeTimer = function (timer) { if (!this.timers[+timer]) { fail(new Exception("Trying to remove a timer that is unknown to the watcher.")); return this; } this.timers[+timer].unsubscribe(); delete this.timers[+timer]; this.trigger("removed", timer, false); return this; }; TimerWatcher.prototype.forAll = function (what) { var key, cur; for (key in this.timers) { if (!(this.timers.hasOwnProperty(key))) { continue; } cur = this.timers[key].timer; if (cur instanceof TimerWatcher) { this.timers[key].timer.forAll(what); } else { this.timers[key].timer[what](); } } return this; }; TimerWatcher.prototype.cancel = function () { this.forAll("cancel"); this.trigger("canceled", null, false); return this; }; TimerWatcher.prototype.pause = function () { this.forAll("pause"); this.trigger("paused", null, false); return this; }; TimerWatcher.prototype.resume = function () { this.forAll("resume"); this.trigger("resumed", null, false); return this; }; TimerWatcher.prototype.stop = function () { return this.forAll("stop"); }; TimerWatcher.prototype.start = function () { this.forAll("start"); this.trigger("started", null, false); return this; }; TimerWatcher.prototype.promise = function () { return Timer.prototype.promise.call(this); }; return TimerWatcher; } }()); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, window, document, console */ using().define("MO5.tools", function () { var tools = {}; /** * Returns a unique ID for MO5 objects. * @return [Number] The unique ID. */ tools.getUniqueId = (function () { var n = 0; return function () { return n++; }; }()); /** * Returns the window's width and height. * @return Object An object with a width and a height property. */ tools.getWindowDimensions = function () { var e = window, a = 'inner'; if (!('innerWidth' in e)) { a = 'client'; e = document.documentElement || document.body; } return { width: e[a + 'Width'], height: e[a + 'Height'] }; }; /** * Scales an element to fit the window using CSS transforms. * @param el The DOM element to scale. * @param w The normal width of the element. * @param h The normal height of the element. */ tools.fitToWindow = function (el, w, h) { var dim, ratio, sw, sh, ratioW, ratioH; dim = tools.getWindowDimensions(); sw = dim.width; // - (dim.width * 0.01); sh = dim.height; // - (dim.height * 0.01); ratioW = sw / w; ratioH = sh / h; ratio = ratioW > ratioH ? ratioH : ratioW; el.setAttribute('style', el.getAttribute('style') + ' -moz-transform: scale(' + ratio + ',' + ratio + ') rotate(0.01deg);' + ' -ms-transform: scale(' + ratio + ',' + ratio + ');' + ' -o-transform: scale(' + ratio + ',' + ratio + ');' + ' -webkit-transform: scale(' + ratio + ',' + ratio + ');' + ' transform: scale(' + ratio + ',' + ratio + ');'); }; tools.timeoutInspector = (function () { var oldSetTimeout, oldSetInterval, oldClearTimeout; var oldClearInterval, oldRequestAnimationFrame; var activeIntervals = {}, timeoutCalls = 0, intervalCalls = 0, animationFrameRequests = 0; oldSetTimeout = window.setTimeout; oldSetInterval = window.setInterval; oldClearTimeout = window.clearTimeout; oldClearInterval = window.clearInterval; oldRequestAnimationFrame = window.requestAnimationFrame; return { logAnimationFrameRequests: false, logTimeouts: false, logIntervals: false, enable: function () { window.setTimeout = function (f, t) { var h = oldSetTimeout(f, t); timeoutCalls += 1; if (this.logTimeouts) { console.log("Setting timeout: ", {callback: f.toString(), time: t}, h); } return h; }; window.setInterval = function (f, t) { var h = oldSetInterval(f, t); intervalCalls += 1; activeIntervals[h] = true; if (this.logIntervals) { console.log("Setting interval: ", {callback: f.toString(), time: t}, h); } return h; }; window.clearTimeout = function (h) { console.log("Clearing timeout: ", h); return oldClearTimeout(h); }; window.clearInterval = function (h) { console.log("Clearing interval: ", h); if (!(h in activeIntervals)) { console.log("Warning: Interval " + h + " doesn't exist."); } else { delete activeIntervals[h]; } return oldClearInterval(h); }; window.requestAnimationFrame = function (f) { animationFrameRequests += 1; if (this.logAnimationFrameRequests) { console.log("Requesting animation frame: ", {callback: f.toString()}); } return oldRequestAnimationFrame(f); }; }, disable: function () { window.setTimeout = oldSetTimeout; window.setInterval = oldSetInterval; window.clearTimeout = oldClearTimeout; window.clearInterval = oldClearInterval; window.requestAnimationFrame = oldRequestAnimationFrame; }, getActiveIntervals: function () { var key, handles = []; for (key in this.activeIntervals) { handles.push(key); } return handles; }, totalTimeoutCalls: function () { return timeoutCalls; }, totalIntervalCalls: function () { return intervalCalls; }, totalRequestAnimationFrameCalls: function () { return animationFrameRequests; } }; }()); return tools; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, requestAnimationFrame, console */ using("MO5.Exception", "MO5.Timer", "MO5.easing"). define("MO5.transform", function (Exception, Timer, easing) { /** * * [Function] MO5.transform * ======================== * * The main tween function for animations. Calculates values between * a start and an end value using either a sine function or a user * defined function and feeds them into a callback function. * * * Parameters * ---------- * * 1. callback: * [Function] The callback function. It takes one * argument, which is the current calculated value. Use this * callback function to set the value(s) you want to transform. * * 2. from: * [Number] The start value. * * 3. to: * [Number] The end value. * * 4. args: * [Object] (optional) Arguments object. * * The options are: * * * duration: * [Number] How long the transformation shall take * (in milliseconds). Default: 1000 * * * log: * [Boolean] Log each calculated value to the browser's * console? * * * easing: * [Function] The function to actually calculate the values. * It must conform to this signature [Number] function(d, t) * where d is the full duration of the transformation and * t is the time the transformation took up to that point. * Default: MO5.easing.sineEaseOut * * * onFinish: * [Function] Callback that gets executed once the * transformation is finished. * * * timer: * [MO5.Timer] A timer to use instead of creating a new one. * This can be useful if you want to use one timer for multiple * transformations. * * * Return value * ------------ * * [MO5.Timer] A timer to control the transformation or see if it's still running. * When stop() is called on the timer, the transformation is immediately finished. * Calling cancel() on the timer stops the transformation at the current value. * Calling pause() pauses the transformation until resume() is called. * * */ function transform (callback, from, to, args) { args = args || {}; if (typeof callback === "undefined" || !callback) { throw new Exception("MO5.transform expects parameter callback to be a function."); } var dur = typeof args.duration !== "undefined" && args.duration >= 0 ? args.duration : 500, f, func, cv = from, timer = args.timer || new Timer(), diff = to - from, doLog = args.log || false, c = 0, // number of times func get's executed lastExecution = 0, fps = args.fps || 60; f = args.easing || easing.sineEaseOut; func = function () { var dt, tElapsed; if ((Date.now() - lastExecution) > (1000 / fps)) { if (timer.canceled) { return; } if (timer.paused) { timer.once(func, "resumed"); return; } c += 1; tElapsed = timer.elapsed(); if (tElapsed > dur || timer.stopped) { cv = from + diff; callback(to); if (!timer.stopped) { timer.stop(); } return; } cv = f(dur, tElapsed) * diff + from; callback(cv); dt = timer.elapsed() - tElapsed; if (doLog === true) { console.log("Current value: " + cv + "; c: " + c + "; Exec time: " + dt); } lastExecution = Date.now(); } requestAnimationFrame(func); }; timer.start(); requestAnimationFrame(func); return timer; } return transform; }); /* global using, window, module */ (function MO5typesBootstrap () { if (typeof using === "function") { using().define("MO5.types", MO5typesModule); } else if (typeof window !== "undefined") { window.MO5.types = MO5typesModule(); } else { module.exports = MO5typesModule(); } function MO5typesModule () { var types = {}; types.isObject = function (thing) { return (typeof thing === "object" && thing !== null); }; types.isString = function (thing) { return typeof thing === "string"; }; types.isNumber = function (thing) { return typeof thing === "number"; }; types.isFunction = function (thing) { return typeof thing === "function"; }; types.isArray = function (thing) { if (Array.isArray) { return Array.isArray(thing); } if (!types.isObject(thing)) { return false; } return thing instanceof Array; }; types.hasForEach = function (thing) { return types.isObject(thing) && types.isFunction(thing.forEach); }; return types; } }()); /* global using */ using( "WSE.assets.Animation", "WSE.assets.Audio", "WSE.assets.Background", "WSE.assets.Character", "WSE.assets.Curtain", "WSE.assets.Imagepack", "WSE.assets.Textbox", "WSE.assets.Composite" ). define("WSE.assets", function ( AnimationAsset, AudioAsset, BackgroundAsset, CharacterAsset, CurtainAsset, ImagepackAsset, TextboxAsset, CompositeAsset ) { var assets = { Animation: AnimationAsset, Audio: AudioAsset, Background: BackgroundAsset, Character: CharacterAsset, Curtain: CurtainAsset, Imagepack: ImagepackAsset, Textbox: TextboxAsset, Composite: CompositeAsset }; return assets; }); /* global using */ using( "WSE.commands.alert", "WSE.commands.break", "WSE.commands.choice", "WSE.commands.confirm", "WSE.commands.do", "WSE.commands.fn", "WSE.commands.global", "WSE.commands.globalize", "WSE.commands.goto", "WSE.commands.line", "WSE.commands.localize", "WSE.commands.prompt", "WSE.commands.restart", "WSE.commands.set_vars", "WSE.commands.sub", "WSE.commands.trigger", "WSE.commands.var", "WSE.commands.wait", "WSE.commands.while", "WSE.commands.with" ). define("WSE.commands", function ( alertCommand, breakCommand, choiceCommand, confirmCommand, doCommand, fnCommand, globalCommand, globalizeCommand, gotoCommand, lineCommand, localizeCommand, promptCommand, restartCommand, setVarsCommand, subCommand, triggerCommand, varCommand, waitCommand, whileCommand, withCommand ) { "use strict"; var commands = { "alert": alertCommand, "break": breakCommand, "choice": choiceCommand, "confirm": confirmCommand, "do": doCommand, "fn": fnCommand, "global": globalCommand, "globalize": globalizeCommand, "goto": gotoCommand, "line": lineCommand, "localize": localizeCommand, "prompt": promptCommand, "restart": restartCommand, "set_vars": setVarsCommand, "sub": subCommand, "trigger": triggerCommand, "var": varCommand, "wait": waitCommand, "while": whileCommand, "with": withCommand }; return commands; }); /* global using */ using().define("WSE.functions", function () { "use strict"; var functions = { savegames: function (interpreter) { interpreter.toggleSavegameMenu(); }, stageclick_disable: function (interpreter) { interpreter.game.unsubscribeListeners(); }, stageclick_enable: function (interpreter) { interpreter.game.subscribeListeners(); } }; return functions; }); /* global using */ using("WSE.dataSources.LocalStorage"). define("WSE.dataSources", function (LocalStorageDataSource) { var dataSources = { LocalStorage: LocalStorageDataSource }; return dataSources; }); /* global using */ using("databus", "WSE.assets", "WSE.commands", "WSE.dataSources", "WSE.functions"). define("WSE", function (DataBus, assets, commands, dataSources, functions) { "use strict"; var WSE = {}, version = "2016.7.1-final.1608060015"; DataBus.inject(WSE); WSE.instances = []; WSE.dataSources = dataSources; WSE.assets = assets; WSE.commands = commands; WSE.functions = functions; WSE.getVersion = function () { return version; }; return WSE; }); /* global using */ using().define("WSE.Keys", function () { /** @module WSE.Keys [Constructor] WSE.Keys ============================ A simple object to handle key press events. Has a number of handy pseudo constants which can be used to identify keys. If there's a key identifier missing, you can add your own by defining a plain object literal with a kc property for the keycode and an optional which property for the event type. Parameters ---------- 1. args: [Object] An object to configure the instance's behaviour. Has the following properties: * element: [DOMElement] The HTML element to bind the listeners to. Default: window * log: [Boolean] Log the captured events to the console? Default: false. Properties ---------- * keys: [Object] An object with 'constants' for easier key identification. The property names are the names of the keys and the values are objects with a "kc" property for the KeyCode and optionally a "which" property for the event type. The property names are all UPPERCASE. Examples: * SPACE * ENTER * TAB * CTRL * ALT * SHIFT * LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW * A to Z * NUM_0 to NUM_9 * NUMPAD_0 to NUMPAD_9 * F1 to F12 * ADD, SUBSTRACT, MULTIPLY, DIVIDE, EQUALS * PERIOD * COMMA */ function Keys (args) { args = args || {}; this.keys = {}; this.keys.BACKSPACE = {kc: 8}; this.keys.TAB = {kc: 9}; this.keys.ENTER = {kc: 13, which: 13}; this.keys.SHIFT = {kc: 16}; this.keys.CTRL = {kc: 17}; this.keys.ALT = {kc: 18}; this.keys.PAUSE = {kc: 19}; this.keys.CAPS_LOCK = {kc: 20}; this.keys.ESCAPE = {kc: 27}; this.keys.SPACE = {kc: 32}; this.keys.PAGE_UP = {kc: 33}; this.keys.PAGE_DOWN = {kc: 20}; this.keys.END = {kc: 20}; this.keys.HOME = {kc: 20}; this.keys.LEFT_ARROW = {kc: 37}; this.keys.UP_ARROW = {kc: 38}; this.keys.RIGHT_ARROW = {kc: 39}; this.keys.DOWN_ARROW = {kc: 40}; this.keys.INSERT = {kc: 45}; this.keys.DELETE = {kc: 46}; this.keys.NUM_0 = {kc: 48}; this.keys.NUM_1 = {kc: 49}; this.keys.NUM_2 = {kc: 50}; this.keys.NUM_3 = {kc: 51}; this.keys.NUM_4 = {kc: 52}; this.keys.NUM_5 = {kc: 53}; this.keys.NUM_6 = {kc: 54}; this.keys.NUM_7 = {kc: 55}; this.keys.NUM_8 = {kc: 56}; this.keys.NUM_9 = {kc: 57}; this.keys.A = {kc: 65}; this.keys.B = {kc: 66}; this.keys.C = {kc: 67}; this.keys.D = {kc: 68}; this.keys.E = {kc: 69}; this.keys.F = {kc: 70}; this.keys.G = {kc: 71}; this.keys.H = {kc: 72}; this.keys.I = {kc: 73}; this.keys.J = {kc: 74}; this.keys.K = {kc: 75}; this.keys.L = {kc: 76}; this.keys.M = {kc: 77}; this.keys.N = {kc: 78}; this.keys.O = {kc: 79}; this.keys.P = {kc: 80}; this.keys.Q = {kc: 81}; this.keys.R = {kc: 82}; this.keys.S = {kc: 83}; this.keys.T = {kc: 84}; this.keys.U = {kc: 85}; this.keys.V = {kc: 86}; this.keys.W = {kc: 87}; this.keys.X = {kc: 88}; this.keys.Y = {kc: 89}; this.keys.Z = {kc: 90}; this.keys.LEFT_WIN = {kc: 91}; this.keys.RIGHT_WIN = {kc: 92}; this.keys.SELECT = {kc: 93}; this.keys.NUMPAD_0 = {kc: 96}; this.keys.NUMPAD_1 = {kc: 97}; this.keys.NUMPAD_2 = {kc: 98}; this.keys.NUMPAD_3 = {kc: 99}; this.keys.NUMPAD_4 = {kc: 100}; this.keys.NUMPAD_5 = {kc: 101}; this.keys.NUMPAD_6 = {kc: 102}; this.keys.NUMPAD_7 = {kc: 103}; this.keys.NUMPAD_8 = {kc: 104}; this.keys.NUMPAD_9 = {kc: 105}; this.keys.MULTIPLY = {kc: 106}; this.keys.ADD = {kc: 107}; this.keys.SUBSTRACT = {kc: 109}; this.keys.DECIMAL_POINT = {kc: 110}; this.keys.DIVIDE = {kc: 111}; this.keys.F1 = {kc: 112}; this.keys.F2 = {kc: 113}; this.keys.F3 = {kc: 114}; this.keys.F4 = {kc: 115}; this.keys.F5 = {kc: 116}; this.keys.F6 = {kc: 117}; this.keys.F7 = {kc: 118}; this.keys.F8 = {kc: 119}; this.keys.F9 = {kc: 120}; this.keys.F10 = {kc: 121}; this.keys.F11 = {kc: 122}; this.keys.F12 = {kc: 123}; this.keys.NUM_LOCK = {kc: 144}; this.keys.SCROLL_LOCK = {kc: 145}; this.keys.SEMI_COLON = {kc: 186}; this.keys.EQUALS = {kc: 187}; this.keys.COMMA = {kc: 188}; this.keys.DASH = {kc: 189}; this.keys.PERIOD = {kc: 190}; this.keys.SLASH = {kc: 191}; this.keys.GRAVE = {kc: 192}; this.keys.OPEN_BRACKET = {kc: 219}; this.keys.BACK_SLASH = {kc: 220}; this.keys.CLOSE_BRACKET = {kc: 221}; this.keys.SINGLE_QUOTE = {kc: 222}; this.listeners = []; var attach, capture, captureUp, captureDown, capturePress, examineEvent, logEvents = args.log || false, element = args.element || window, self = this; attach = function(elem) { if (elem == null || typeof elem == 'undefined') { return; } if (elem.addEventListener) { elem.addEventListener("keyup", captureUp, false); elem.addEventListener("keydown", captureDown, false); elem.addEventListener("keypress", capturePress, false); if (logEvents === true) { elem.addEventListener("keyup", examineEvent, false); elem.addEventListener("keydown", examineEvent, false); elem.addEventListener("keypress", examineEvent, false); } } else if (elem.attachEvent) { elem.attachEvent("onkeyup", captureUp); elem.attachEvent("onkeydown", captureDown); elem.attachEvent("onkeypress", capturePress); if (logEvents === true) { elem.attachEvent("onkeyup", examineEvent); elem.attachEvent("onkeydown", examineEvent); elem.attachEvent("onkeypress", examineEvent); } } }; capture = function (event, type) { var len = self.listeners.length, cur, i, kc, which; for (i = 0; i < len; ++i) { cur = self.listeners[i]; if (typeof cur == 'undefined' || cur.type != type) { continue; } cur.key = cur.key || {}; kc = cur.key.kc || null; which = cur.key.which || null; if (event.which == which || event.keyCode == kc) { cur.callback(event); } } }; captureUp = function (event) { capture(event, "up"); }; captureDown = function (event) { capture(event, "down"); }; capturePress = function (event) { capture(event, "press"); }; examineEvent = function (event) { /* eslint-disable no-console */ console.log(event); /* eslint-enable no-console */ }; attach(element); } /** @module WSE.Keys [Function] WSE.Keys.addListener ===================================== Binds a new callback to a key. Parameters ---------- 1. key: [Object] One of the WSE.Keys pseudo constants. 2. callback: [Function] The callback to execute once the key has been pressed. 3. type: [String] The event type to use. One of: * "up" for "keyup", * "down" for "keydown", * "press" for "keypress" Default: "up" Errors ------ Throws an Error when the type parameter is not recognized. */ Keys.prototype.addListener = function(key, callback, type) { type = type || "up"; if (type !== "up" && type !== "down" && type !== "press") { throw new Error("Event type not recognized."); } this.listeners.push({ key: key, callback: callback, type: type }); }; /** @module WSE.Keys [Function] WSE.Keys.removeListener ======================================== Removes the event listeners for a key. Parameters ---------- 1. key: [Object] One of WSE.Keys pseudo constants. */ Keys.prototype.removeListener = function (key, callback, type) { var len = this.listeners.length; var cur; type = type || null; for (var i = 0; i < len; ++i) { cur = this.listeners[i]; if (type !== null && cur.type != type) { continue; } if (typeof cur !== 'undefined' && cur.key === key && cur.callback === callback) { delete this.listeners[i]; } } }; /** @module WSE.Keys [Function] WSE.Keys.forAll ================================ Executes a callback for any key event that occurs. Parameters ---------- 1. callback: [Function] A callback function to be executed when a keyboard event occurs. 2. type: [String] The keyboard event type to use. One of: * "up" for "keyup", * "down" for "keydown", * "press" for "keypress" Default: "up" Errors ------ Throws an Error when the type parameter is not recognized. */ Keys.prototype.forAll = function (callback, type) { type = type || "up"; if (type !== "up" && type !== "down" && type !== "press") { throw new Error("Event type not recognized."); } for (var key in this.keys) { if (!this.keys.hasOwnProperty(key)) { continue; } this.addListener(this.keys[key], callback, type); } }; return Keys; }); /* global using */ using("MO5.Timer").define("WSE.tools", function (Timer) { "use strict"; var tools = {}; /** * Attaches a DOM Event to a DOM Element. * * FIXME: Is this even needed? Supported browsers should all * have .addEventListener()... */ tools.attachEventListener = function (elem, type, listener) { if (elem === null || typeof elem === "undefined") { return; } if (elem.addEventListener) { elem.addEventListener(type, listener, false); } else if (elem.attachEvent) { elem.attachEvent("on" + type, listener); } }; /** * Sets the x and y units on an asset object according * to it's definition in the WebStory. * @param obj The JavaScript object asset. * @param asset The XML Element with the asset's information. */ tools.applyAssetUnits = function (obj, asset) { var x, y; x = asset.getAttribute('x') || ""; y = asset.getAttribute('y') || ""; obj.xUnit = x.replace(/^.*(px|%)$/, '$1'); obj.xUnit = obj.xUnit || 'px'; obj.yUnit = y.replace(/^.*(px|%)$/, '$1'); obj.yUnit = obj.yUnit || 'px'; if (obj.xUnit !== "px" && obj.xUnit !== "%") { obj.xUnit = "px"; } if (obj.yUnit !== "px" && obj.yUnit !== "%") { obj.yUnit = "px"; } }; /** * Removes a DOM Event from a DOM Element. */ tools.removeEventListener = function (elem, type, listener) { if (typeof elem === "undefined" || elem === null) { return; } elem.removeEventListener(type, listener, false); }; /** * Function that replaces the names of variables in a string * with their respective values. * * @param text [string] The text that contains variables. * @param interpreter [WSE.Interpreter] The interpreter instance. * @return [string] The text with the inserted variable values. */ tools.replaceVariables = function (text, interpreter) { var f1, f2; if (text === null) { return text; } if (typeof text !== "string") { interpreter.bus.trigger("wse.interpreter.error", { message: "Argument supplied to the replaceVariables function must be a string." }); text = ""; } f1 = function () { var name = arguments[1]; if (interpreter.globalVars.has(name)) { return "" + interpreter.globalVars.get(name); } return ""; }; f2 = function () { var name = arguments[1]; if (name in interpreter.runVars) { return "" + interpreter.runVars[name]; } return ""; }; // insert values of global variables ($$var): text = text.replace(/\{\$\$([a-zA-Z0-9_]+)\}/g, f1); // insert values of local variables ($var): text = text.replace(/\{\$([a-zA-Z0-9_]+)\}/g, f2); return text; }; tools.getSerializedNodes = function (element) { var ser = new XMLSerializer(), nodes = element.childNodes, i, len; var text = ''; for (i = 0, len = nodes.length; i < len; i += 1) { text += ser.serializeToString(nodes[i]); } return text; }; tools.getParsedAttribute = function (element, attributeName, interpreter, defaultValue) { var value; if (arguments.length < 3) { defaultValue = ""; } value = element.getAttribute(attributeName) || ("" + defaultValue); return tools.replaceVariables(value, interpreter); }; /** * Replaces { and } to < and > for making it HTML. * Optionally replaces newlines with <break> elements. * * @param text [string] The text to convert to HTML. * @param nltobr [bool] Should newlines be converted to breaks? Default: false. */ tools.textToHtml = function (text, nltobr) { nltobr = nltobr || false; if (!(String.prototype.trim)) { text = text.replace(/^\n/, ""); text = text.replace(/\n$/, ""); } else { text = text.trim(); } text = nltobr === true ? text.replace(/\n/g, "<br />") : text; text = text.replace(/\{/g, "<"); text = text.replace(/\}/g, ">"); return text; }; /** * Generates a unique ID. Used by assets to identify their own stuff * in savegames and the DOM of the stage. * * @return [number] The unique ID. */ tools.getUniqueId = (function () { var uniqueIdCount = 0; return function () { uniqueIdCount += 1; return uniqueIdCount; }; }()); /** * Converts the first character in a string to upper case. * * @param input [string] The string to transform. * @return [string] The transformed string. */ tools.firstLetterUppercase = function (input) { if (input.length < 1) { return ""; } return "" + input.charAt(0).toUpperCase() + input.replace(/^.{1}/, ""); }; tools.mixin = function (source, target) { var key; for (key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } }; tools.extractUnit = function (numberString) { return typeof numberString !== "string" ? "" : numberString.replace(/^(-){0,1}[0-9]*/, ""); }; tools.calculateValueWithAnchor = function (oldValue, anchor, maxValue) { var value = 0, anchorUnit = "px"; if (!anchor) { return oldValue; } anchorUnit = tools.extractUnit(anchor); anchor = parseInt(anchor, 10); if (anchorUnit === "%") { value = oldValue - ((maxValue / 100) * anchor); } else { value = oldValue - anchor; } return value; }; tools.createTimer = function (duration) { var timer = new Timer(); duration = duration || 0; duration = duration < 0 ? 0 : duration; timer.start(); setTimeout(timer.stop.bind(timer), duration); return timer; }; tools.getWindowDimensions = function () { var e = window, a = 'inner'; if (!('innerWidth' in e)) { a = 'client'; e = document.documentElement || document.body; } return { width: e[a + 'Width'], height: e[a + 'Height'] }; }; tools.fitToWindow = function (el, w, h) { var dim, ratio, sw, sh, ratioW, ratioH; dim = tools.getWindowDimensions(); sw = dim.width; // - (dim.width * 0.01); sh = dim.height; // - (dim.height * 0.01); ratioW = sw / w; ratioH = sh / h; ratio = ratioW > ratioH ? ratioH : ratioW; //ratio = parseInt(ratio * 100) / 100; el.setAttribute('style', el.getAttribute('style') + ' -moz-transform: scale(' + ratio + ',' + ratio + ') rotate(0.01deg);' + ' -ms-transform: scale(' + ratio + ',' + ratio + ');' + ' -o-transform: scale(' + ratio + ',' + ratio + ');' + ' -webkit-transform: scale(' + ratio + ',' + ratio + ');' + ' transform: scale(' + ratio + ',' + ratio + ');'); }; tools.log = function (bus, message) { tools.trigger(bus, "wse.interpreter.message", message); }; tools.warn = function (bus, message, element) { tools.trigger(bus, "wse.interpreter.warning", message, element); }; tools.logError = function (bus, message, element) { tools.trigger(bus, "wse.interpreter.error", message, element); }; tools.trigger = function (bus, channel, message, element) { bus.trigger(channel, { element: element || null, message: message }); }; return tools; }); /* global using */ using("easy-ajax", "WSE.tools.compile::compile"). define("WSE.loader", function (ajax, compile) { function generateGameFile (mainFilePath, then) { compileFile(mainFilePath, function (mainFile) { generateGameFileFromString(mainFile, then); }); } function generateGameFileFromString (text, then) { var gameDocument = parseXml(text); var fileDefinitions = getFileDefinitions(gameDocument); compileFiles(fileDefinitions, function (files) { files.forEach(function (file, i) { var type = fileDefinitions[i].type; var parent = gameDocument.getElementsByTagName(type)[0]; if (!parent) { parent = gameDocument.createElement(type); gameDocument.documentElement.appendChild(parent); } parent.innerHTML += "\n" + file + "\n"; }); then(gameDocument); }); } function generateFromString (text, then) { generateGameFileFromString(compile(text), then); } function compileFiles (fileDefinitions, then) { var loaded = 0; var count = fileDefinitions.length; var files = []; fileDefinitions.forEach(function (definition, i) { compileFile(definition.url, function (file) { files[i] = file; loaded += 1; if (loaded >= count) { then(files); } }); }); if (count < 1) { then(files); } } function compileFile (path, then) { ajax.get(path + "?random=" + Math.random(), function (error, obj) { if (error) { console.error(error); return; } then(compile(obj.responseText)); }); } function parseXml (text) { return new DOMParser().parseFromString(text, "application/xml"); } function getFileDefinitions (xml) { var elements = xml.getElementsByTagName("file"); return [].map.call(elements, function (element) { return { type: element.getAttribute("type"), url: element.getAttribute("url") }; }); } return { generateGameFile: generateGameFile, generateFromString: generateFromString }; }); /* global using */ using("string-dict").define("WSE.dataSources.LocalStorage", function (Dict) { "use strict"; var testKey = "___wse_storage_test"; var localStorageEnabled = false; var data; try { localStorage.setItem(testKey, "works"); if (localStorage.getItem(testKey) === "works") { localStorageEnabled = true; } } catch (error) { console.error("LocalStorage not available, using JS object as fallback."); data = new Dict(); } function LocalStorageDataSource () {} LocalStorageDataSource.prototype.set = function (key, value) { if (!localStorageEnabled) { data.set(key, value); } else { localStorage.setItem(key, value); } }; LocalStorageDataSource.prototype.get = function (key) { if (!localStorageEnabled) { if (!data.has(key)) { return null; } return data.get(key); } return localStorage.getItem(key); }; LocalStorageDataSource.prototype.remove = function (key) { if (!localStorageEnabled) { if (!data.has(key)) { return; } return data.remove(key); } return localStorage.removeItem(key); }; return LocalStorageDataSource; }); /* global using */ using("WSE.commands", "WSE.functions", "WSE.tools::warn"). define("WSE.Trigger", function (commands, functions, warn) { "use strict"; function Trigger (trigger, interpreter) { var self = this, fn; this.name = trigger.getAttribute("name") || null; this.event = trigger.getAttribute("event") || null; this.special = trigger.getAttribute("special") || null; this.fnName = trigger.getAttribute("function") || null; this.scene = trigger.getAttribute("scene") || null; this.interpreter = interpreter; this.isSubscribed = false; if (this.name === null) { warn(interpreter.bus, "No 'name' attribute specified on 'trigger' element.", trigger); return; } if (this.event === null) { warn(interpreter.bus, "No 'event' attribute specified on 'trigger' element '" + this.name + "'.", trigger); return; } if (this.special === null && this.fnName === null && this.scene === null) { warn(interpreter.bus, "No suitable action or function found for trigger element '" + this.name + "'.", trigger); return; } if (this.scene) { fn = function () { commands.sub(trigger, interpreter); interpreter.index = 0; interpreter.currentElement = 0; interpreter.next(); }; } this.isKeyEvent = false; this.key = null; if (this.special !== null && this.special !== "next") { warn(interpreter.bus, "Unknown special specified on trigger element '" + this.name + "'.", trigger); return; } if (this.special === "next") { fn = function () { if (self.interpreter.state === "pause" || self.interpreter.waitCounter > 0) { return; } self.interpreter.next(); }; } if (this.fnName !== null) { if (typeof functions[this.fnName] !== "function") { warn(interpreter.bus, "Unknown function specified on trigger element '" + this.name + "'.", trigger); return; } fn = function () { functions[self.fnName](self.interpreter, trigger); }; } switch (this.event) { case "keyup": case "keydown": case "keypress": this.isKeyEvent = true; this.key = trigger.getAttribute("key") || null; if (this.key === null) { warn(interpreter.bus, "No 'key' attribute specified on trigger element '" + this.name + "'.", trigger); return; } if ( typeof interpreter.game.keys.keys[this.key] === "undefined" || interpreter.game.keys.keys[this.key] === null ) { warn(interpreter.bus, "Unknown key '" + this.key + "' specified on trigger " + "element '" + this.name + "'.", trigger); return; } this.fn = function (data) { if (data.keys[self.key].kc !== data.event.keyCode) { return; } if (interpreter.keysDisabled > 0) { return; } fn(); }; return; default: this.fn = fn; } } Trigger.prototype.activate = function () { if (this.isSubscribed === true) { return; } this.interpreter.bus.subscribe(this.fn, this.event); this.isSubscribed = true; }; Trigger.prototype.deactivate = function () { if (this.isSubscribed === false) { return; } this.interpreter.bus.unsubscribe(this.fn, this.event); this.isSubscribed = false; }; return Trigger; }); /* global using */ /* eslint no-console: off */ using( "databus", "easy-ajax", "WSE.Keys", "WSE.Interpreter", "WSE.tools", "WSE", "WSE.loader" ). define("WSE.Game", function (DataBus, ajax, Keys, Interpreter, tools, WSE, loader) { "use strict"; /** * Constructor used to create instances of games. * * You can configure the game instance using the config object * that can be supplied as a parameter to the constructor function. * * The options are: * - url: [string] The URL of the WebStory file. * - debug: [bool] Should the game be run in debug mode? (not used yet) * - host: [object] The HOST object for the LocalContainer * version. Optional. * * @event [email protected] * @param args A config object. See above for details. */ function Game (args) { var host; WSE.instances.push(this); WSE.trigger("wse.game.constructor", {args: args, game: this}); args = args || {}; this.bus = new DataBus(); this.url = args.url || "game.xml"; this.gameId = args.gameId || null; this.ws = null; this.debug = args.debug === true ? true : false; host = args.host || false; this.host = host; if (this.gameId) { loader.generateFromString( document.getElementById(this.gameId).innerHTML, this.load.bind(this) ); } else { if (host) { loader.generateFromString(host.get(this.url), this.load.bind(this)); } else { loader.generateGameFile(this.url, this.load.bind(this)); } } this.interpreter = new Interpreter(this); this.keys = new Keys(); this.listenersSubscribed = false; //console.log("this.interpreter: ", this.interpreter); this.bus.subscribe( function (data) { console.log("Message: " + data); }, "wse.interpreter.message" ); this.bus.subscribe( function (data) { console.log("Error: " + data.message); }, "wse.interpreter.error" ); this.bus.subscribe( function (data) { console.log("Warning: " + data.message, data.element); }, "wse.interpreter.warning" ); } /** * Loads the WebStory file using the AJAX function and triggers * the game initialization. */ Game.prototype.load = function (gameDocument) { this.ws = gameDocument; this.init(); }; Game.prototype.loadFromUrl = function (url) { //console.log("Loading game file..."); var fn, self; this.url = url || this.url; self = this; fn = function (obj) { self.ws = obj.responseXML; //console.log("Response XML: " + obj.responseXML); self.init(); }; ajax.get(this.url, null, fn); }; /** * Initializes the game instance. */ Game.prototype.init = function () { var ws, stage, stageElements, stageInfo, width, height, id, alignFn, resizeFn; ws = this.ws; (function () { var parseErrors = ws.getElementsByTagName("parsererror"); console.log("parsererror:", parseErrors); if (parseErrors.length) { document.body.innerHTML = "" + '<div class="parseError">'+ "<h1>Cannot parse WebStory file!</h3>" + "<p>Your WebStory file is mal-formed XML and contains these errors:</p>" + '<pre class="errors">' + parseErrors[0].innerHTML + '</pre>' + '</div>'; throw new Error("Can't parse game file, not well-formed XML:", parseErrors[0]); } }()); try { stageElements = ws.getElementsByTagName("stage"); } catch (e) { console.log(e); } width = "800px"; height = "480px"; id = "Stage"; if (!stageElements || stageElements.length < 1) { throw new Error("No stage definition found!"); } stageInfo = stageElements[0]; width = stageInfo.getAttribute("width") || width; height = stageInfo.getAttribute("height") || height; id = stageInfo.getAttribute("id") || id; // Create the stage element or inject into existing one? if (stageInfo.getAttribute("create") === "yes") { stage = document.createElement("div"); stage.setAttribute("id", id); document.body.appendChild(stage); } else { stage = document.getElementById(id); } stage.setAttribute("class", "WSEStage"); stage.style.width = width; stage.style.height = height; // Aligns the stage to be always in the center of the browser window. // Must be specified in the game file. alignFn = function () { var dim = tools.getWindowDimensions(); stage.style.left = (dim.width / 2) - (parseInt(width, 10) / 2) + 'px'; stage.style.top = (dim.height / 2) - (parseInt(height, 10) / 2) + 'px'; }; if (stageInfo.getAttribute("center") === "yes") { tools.attachEventListener(window, 'resize', alignFn); alignFn(); } // Resizes the stage to fit the browser window dimensions. Must be // specified in the game file. resizeFn = function () { console.log("Resizing..."); tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10)); }; if (stageInfo.getAttribute("resize") === "yes") { tools.attachEventListener(window, 'resize', resizeFn); resizeFn(); } this.stage = stage; // stage.onclick = function() { self.interpreter.next(); }; this.applySettings(); // This section only applies when the engine is used inside // the local container app. if (this.host) { this.host.window.width = parseInt(width, 10); this.host.window.height = parseInt(height, 10); (function (self) { var doResize = self.getSetting("host.stage.resize") === "true" ? true : false; if (!doResize) { return; } window.addEventListener("resize", function () { console.log("Resizing..."); tools.fitToWindow(stage, parseInt(width, 10), parseInt(height, 10)); }); }(this)); } }; /** * Returns the value of a setting as specified in the WebStory file. * @param name [string] The name of the setting. * @return [mixed] The value of the setting or null. */ Game.prototype.getSetting = function (name) { var ret, settings, i, len, cur, curName; settings = this.ws.getElementsByTagName("setting"); for (i = 0, len = settings.length; i < len; i += 1) { cur = settings[i]; curName = cur.getAttribute("name") || null; if (curName !== null && curName === name) { ret = cur.getAttribute("value") || null; return ret; } } return null; }; // FIXME: implement... Game.prototype.applySettings = function () { this.webInspectorEnabled = this.getSetting("host.inspector.enable") === "true" ? true : false; if (this.host) { if (this.webInspectorEnabled === true) { this.host.inspector.show(); } } }; /** * Use this method to start the game. The WebStory file must have * been successfully loaded for this to work. */ Game.prototype.start = function () { var fn, contextmenu_proxy, self; self = this; if (this.ws === null) { return setTimeout( function () { self.start(); } ); } // Listener that sets the interpreter's state machine to the next state // if the current state is not pause or wait mode. // This function gets executed when a user clicks on the stage. fn = function () { if (self.interpreter.state === "pause" || self.interpreter.waitCounter > 0) { return; } //console.log("Next triggered by user..."); self.interpreter.next(true); }; contextmenu_proxy = function (e) { self.bus.trigger("contextmenu", {}); // let's try to prevent real context menu showing if (e && typeof e.preventDefault === "function") { e.preventDefault(); } return false; }; this.subscribeListeners = function () { tools.attachEventListener(this.stage, 'contextmenu', contextmenu_proxy); tools.attachEventListener(this.stage, 'click', fn); this.listenersSubscribed = true; }; this.unsubscribeListeners = function () { tools.removeEventListener(this.stage, 'contextmenu', contextmenu_proxy); tools.removeEventListener(this.stage, 'click', fn); this.listenersSubscribed = false; }; this.interpreter.start(); }; return Game; }); /* global using */ /* eslint no-console: off */ using( "WSE.dataSources.LocalStorage", "WSE.Trigger", "WSE.tools", "WSE.tools.ui", "WSE", "WSE.tools::logError", "WSE.tools::warn", "WSE.LoadingScreen", "WSE.tools::getSerializedNodes", "enjoy-core::each", "enjoy-core::find", "enjoy-typechecks::isUndefined", "enjoy-typechecks::isNull", "WSE.savegames" ). define("WSE.Interpreter", function ( LocalStorageSource, Trigger, tools, ui, WSE, logError, warn, LoadingScreen, getSerializedNodes, each, find, isUndefined, isNull, savegames ) { "use strict"; /** * Constructor to create an instance of the engine's interpreter. * Each game has it's own interpreter instance. The interpreter * reads the information in the WebStory file and triggers the execution * of the appropriate commands. * * @event * @param game [object] The WSE.Game instance the interpreter belongs to. */ function Interpreter (game) { var datasource, key; WSE.trigger("wse.interpreter.constructor", {game: game, interpreter: this}); this.game = game; this.assets = {}; /** @var Index of the currently examined element inside the active scene. */ this.index = 0; this.visitedScenes = []; /** @var A text log of everything that has been shown on text boxes. */ this.log = []; this.waitForTimer = false; /** @var Number of assets that are currently being fetched from the server. */ this.assetsLoading = 0; /** @var Total number of assets to load. */ this.assetsLoadingMax = 0; /** @var Number of assets already fetched from the server. */ this.assetsLoaded = 0; /** @var The timestamp from when the game starts. Used for savegames. */ this.startTime = 0; /** @var Holds 'normal' variables. These are only remembered for the current route. */ this.runVars = {}; /** @var The call stack for sub scenes. */ this.callStack = []; this.keysDisabled = 0; // if this is > 0, key triggers should be disabled /** @var The current state of the interpreter's state machine. * 'listen' means that clicking on the stage or going to the next line * is possible. */ this.state = "listen"; /** @var All functions that require the interpreter's state machine * to wait. The game will only continue when this is set to 0. * This can be used to prevent e.g. that the story continues in * the background while a dialog is displayed in the foreground. */ this.waitCounter = 0; /** @var Should the game be run in debug mode? */ this.debug = game.debug === true ? true : false; // The datasource to use for saving games and global variables. // Hardcoded to localStorage for now. datasource = new LocalStorageSource(); this.datasource = datasource; // Each game must have it's own unique storage key so that multiple // games can be run on the same web page. key = "wse_globals_" + location.pathname + "_" + this.game.url + "_"; /** @var Stores global variables. That is, variables that will * be remembered independently of the current state of the game. * Can be used for unlocking hidden features after the first * playthrough etc. */ this.globalVars = { set: function (name, value) { datasource.set(key + name, value); }, get: function (name) { return datasource.get(key + name); }, has: function (name) { if (isNull(datasource.get(key + name))) { return false; } return true; } }; this._loadingScreen = new LoadingScreen(); if (this.debug === true) { this.game.bus.debug = true; } } Interpreter.prototype.start = function () { var self, fn, makeKeyFn, bus, startTime = Date.now(); this.story = this.game.ws; this.stage = this.game.stage; this.bus = this.game.bus; this.index = 0; this.currentElement = 0; this.sceneId = null; this.scenePath = []; this.currentCommands = []; this.wait = false; this.startTime = Math.round(+new Date() / 1000); this.stopped = false; self = this; bus = this.bus; this._startLoadingScreen(); // Adds location info to warnings and errors. fn = function (data) { var section, element, msg; data = data || {}; element = data.element || null; section = null; if (element !== null) { try { section = data.element.tagName === "asset" ? "assets" : null; section = data.element.parent.tagName === "settings" ? "settings" : null; } catch (e) { // do nothing } } section = section || "scenes"; switch (section) { case "assets": msg = " Encountered in section 'assets'."; break; case "settings": msg = " Encountered in section 'settings'."; break; default: msg = " Encountered in scene '" + self.sceneId + "', element " + self.currentElement + "."; } console.log(msg); }; bus.subscribe(fn, "wse.interpreter.error"); bus.subscribe(fn, "wse.interpreter.warning"); bus.subscribe(fn, "wse.interpreter.message"); bus.subscribe( function () { console.log("Game over."); }, "wse.interpreter.end" ); bus.subscribe( function () { self.numberOfFunctionsToWaitFor += 1; }, "wse.interpreter.numberOfFunctionsToWaitFor.increase" ); bus.subscribe( function () { self.numberOfFunctionsToWaitFor -= 1; }, "wse.interpreter.numberOfFunctionsToWaitFor.decrease" ); bus.subscribe( this._loadingScreen.addItem.bind(this._loadingScreen), "wse.assets.loading.increase" ); bus.subscribe( this._loadingScreen.itemLoaded.bind(this._loadingScreen), "wse.assets.loading.decrease" ); this.buildAssets(); this.createTriggers(); makeKeyFn = function (type) { return function (ev) { bus.trigger( type, { event: ev, keys: self.game.keys.keys } ); }; }; this.game.keys.forAll(makeKeyFn("keyup"), "up"); this.game.keys.forAll(makeKeyFn("keydown"), "down"); this.game.keys.forAll(makeKeyFn("keypress"), "press"); this.game.subscribeListeners(); this._assetsLoaded = false; this._loadingScreen.subscribe("finished", function () { var time = Date.now() - startTime; if (self._assetsLoaded) { return; } self._assetsLoaded = true; self.callOnLoad(); if (time < 1000) { setTimeout(self.runStory.bind(self), 1000 - time); } else { self.runStory(); } }); if (this._loadingScreen.count() < 1) { this._assetsLoaded = true; this.runStory(); } }; Interpreter.prototype.callOnLoad = function () { each(function (asset) { if (typeof asset.onLoad === "function") { asset.onLoad(); } }, this.assets); }; Interpreter.prototype.runStory = function () { if (this.assetsLoading > 0) { setTimeout(this.runStory.bind(this), 100); return; } this.bus.trigger("wse.assets.loading.finished"); this._loadingScreen.hide(); this.startTime = Math.round(+new Date() / 1000); this.changeScene(this.getFirstScene()); }; Interpreter.prototype.getFirstScene = function () { var scenes, len, startScene; scenes = this.story.getElementsByTagName("scene"); this.scenes = scenes; len = scenes.length; startScene = this.getSceneById("start"); if (startScene !== null) { return startScene; } if (len < 1) { logError(this.bus, "No scenes found!"); return null; } return scenes[0]; }; Interpreter.prototype.changeScene = function (scene) { this.changeSceneNoNext(scene); this.next(); }; Interpreter.prototype.changeSceneNoNext = function (scene) { var len, id, bus = this.bus; bus.trigger( "wse.interpreter.changescene.before", { scene: scene, interpreter: this }, false ); if (isUndefined(scene) || isNull(scene)) { logError(bus, "Scene does not exist."); return; } id = scene.getAttribute("id"); this.visitedScenes.push(id); if (isNull(id)) { logError(bus, "Encountered scene without id attribute."); return; } bus.trigger("wse.interpreter.message", "Entering scene '" + id + "'."); while (this.scenePath.length > 0) { this.popFromCallStack(); } this.currentCommands = scene.childNodes; len = this.currentCommands.length; this.index = 0; this.sceneId = id; this.scenePath = []; this.currentElement = 0; if (len < 1) { warn(bus, "Scene '" + id + "' is empty.", scene); return; } this.numberOfFunctionsToWaitFor = 0; bus.trigger( "wse.interpreter.changescene.after", { scene: scene, interpreter: this }, false ); }; Interpreter.prototype.pushToCallStack = function () { var obj = {}; obj.index = this.index; obj.sceneId = this.sceneId; obj.scenePath = this.scenePath.slice(); obj.currentElement = this.currentElement; this.callStack.push(obj); }; Interpreter.prototype.popFromCallStack = function () { var top = this.callStack.pop(), scenePath = top.scenePath.slice(); this.bus.trigger( "wse.interpreter.message", "Returning from sub scene '" + this.sceneId + "' to scene '" + top.sceneId + "'...", false ); this.index = top.index + 1; this.sceneId = top.sceneId; this.scenePath = top.scenePath; this.currentScene = this.getSceneById(top.sceneId); this.currentElement = top.currentElement; this.currentCommands = this.currentScene.childNodes; while (scenePath.length > 0) { this.currentCommands = this.currentCommands[scenePath.shift()].childNodes; } }; Interpreter.prototype.getSceneById = function (sceneName) { var scene = find(function (current) { return current.getAttribute("id") === sceneName; }, this.scenes); if (isNull(scene)) { warn(this.bus, "Scene '" + sceneName + "' not found!"); } return scene; }; Interpreter.prototype.next = function (triggeredByUser) { var nodeName, command, check, self, stopObj, bus = this.bus; stopObj = { stop: false }; triggeredByUser = triggeredByUser === true ? true : false; bus.trigger("wse.interpreter.next.before", this, false); if (triggeredByUser === true) { bus.trigger("wse.interpreter.next.user", stopObj, false); } if (stopObj.stop === true) { return; } self = this; if (this.state === "pause") { return; } if (this.waitForTimer === true || (this.wait === true && this.waitCounter > 0)) { setTimeout(function () { self.next(); }, 0); return; } if (this.wait === true && this.numberOfFunctionsToWaitFor < 1) { this.wait = false; } this.stopped = false; if (this.cancelCharAnimation) { this.cancelCharAnimation(); this.cancelCharAnimation = null; return; } if (this.index >= this.currentCommands.length) { if (this.callStack.length > 0) { this.popFromCallStack(); setTimeout(function () { self.next(); }, 0); return; } bus.trigger("wse.interpreter.next.after.end", this, false); bus.trigger("wse.interpreter.end", this); return; } command = this.currentCommands[this.index]; nodeName = command.nodeName; // ignore text and comment nodes: if (nodeName === "#text" || nodeName === "#comment") { this.index += 1; setTimeout(function () { self.next(); }, 0); bus.trigger("wse.interpreter.next.ignore", this, false); return; } bus.trigger("wse.interpreter.next.command", command); this.currentElement += 1; check = this.runCommand(this.currentCommands[this.index]); check = check || {}; check.doNext = check.doNext === false ? false : true; check.wait = check.wait === true ? true : false; check.changeScene = check.changeScene || null; if (check.wait === true) { this.wait = true; } this.index += 1; if (check.changeScene !== null) { this.changeScene(check.changeScene); return; } if (check.doNext === true) { setTimeout(function () { self.next(); }, 0); bus.trigger("wse.interpreter.next.after.donext", this, false); return; } this.stopped = true; bus.trigger("wse.interpreter.next.after.nonext", this, false); }; Interpreter.prototype.checkIfvar = function (command) { var ifvar, ifval, ifnot, varContainer, bus = this.bus; ifvar = command.getAttribute("ifvar") || null; ifval = command.getAttribute("ifvalue"); ifnot = command.getAttribute("ifnot"); if (ifvar !== null || ifval !== null || ifnot !== null) { varContainer = this.runVars; if (!(ifvar in varContainer)) { warn(bus, "Unknown variable '" + ifvar + "' used in condition. Ignoring command.", command); bus.trigger( "wse.interpreter.runcommand.after.condition.error.key", { interpreter: this, command: command }, false ); return false; } if (ifnot !== null && ("" + varContainer[ifvar] === "" + ifnot)) { bus.trigger( "wse.interpreter.message", "Conidition not met. " + ifvar + "==" + ifnot); bus.trigger( "wse.interpreter.runcommand.after.condition.false", { interpreter: this, command: command }, false ); return false; } else if (ifval !== null && ("" + varContainer[ifvar]) !== "" + ifval) { bus.trigger("wse.interpreter.message", "Conidition not met."); bus.trigger( "wse.interpreter.runcommand.after.condition.false", { interpreter: this, command: command }, false ); return false; } bus.trigger( "wse.interpreter.runcommand.condition.met", { interpreter: this, command: command }, false ); bus.trigger("wse.interpreter.message", "Conidition met."); } return true; }; Interpreter.prototype.runCommand = function (command) { var tagName, assetName, bus = this.bus; this.bus.trigger( "wse.interpreter.runcommand.before", { interpreter: this, command: command }, false ); tagName = command.tagName; assetName = command.getAttribute("asset") || null; if (!this.checkIfvar(command)) { return { doNext: true }; } if (tagName in WSE.commands) { bus.trigger( "wse.interpreter.runcommand.after.command", { interpreter: this, command: command }, false ); bus.trigger('game.commands.' + tagName); return WSE.commands[tagName](command, this); } else if ( assetName !== null && assetName in this.assets && typeof this.assets[assetName][tagName] === "function" && tagName.match(/(show|hide|clear|flicker|flash|play|start|stop|pause|move|shake|set|tag)/) ) { bus.trigger('game.assets.' + assetName + '.' + tagName); return this.assets[assetName][tagName](command, this); } else { warn(bus, "Unknown element '" + tagName + "'.", command); bus.trigger( "wse.interpreter.runcommand.after.error", { interpreter: this, command: command }, false ); return { doNext: true }; } }; Interpreter.prototype.createTriggers = function () { var triggers, curName, curTrigger, bus = this.bus; var interpreter = this; bus.trigger("wse.interpreter.triggers.create", this, false); this.triggers = {}; try { triggers = this.game.ws.getElementsByTagName("triggers")[0]. getElementsByTagName("trigger"); } catch (e) { console.log(e); return; } each(function (cur) { curName = cur.getAttribute("name") || null; if (curName === null) { warn(bus, "No name specified for trigger.", cur); return; } if (typeof interpreter.triggers[curName] !== "undefined" && interpreter.triggers[curName] !== null) { warn(bus, "A trigger with the name '" + curName + "' already exists.", cur); return; } curTrigger = new Trigger(cur, interpreter); if (typeof curTrigger.fn === "function") { interpreter.triggers[curName] = curTrigger; } }, triggers); }; Interpreter.prototype.buildAssets = function () { var assets, bus = this.bus; bus.trigger("wse.assets.loading.started"); try { assets = this.story.getElementsByTagName("assets")[0].childNodes; } catch (e) { logError(bus, "Error while creating assets: " + e.getMessage()); } each(function (asset) { if (asset.nodeType !== 1) { return; } this.createAsset(asset); }.bind(this), assets); }; Interpreter.prototype.createAsset = function (asset) { var name, assetType, bus = this.bus; bus.trigger( "wse.interpreter.createasset", { interpreter: this, asset: asset }, false ); name = asset.getAttribute("name"); assetType = asset.tagName; if (name === null) { logError(bus, "Expected attribute 'name'.", asset); return; } if (assetType === null) { warn(bus, "Expected attribute 'type' on asset '" + name + "'.", asset); return; } if (typeof this.assets[name] !== "undefined") { warn(bus, "Trying to override existing asset '" + name + "'.", asset); } assetType = tools.firstLetterUppercase(assetType); if (assetType in WSE.assets) { this.assets[name] = new WSE.assets[assetType](asset, this); return; } else { warn(bus, "Unknown asset type '" + assetType + "'.", asset); return; } }; Interpreter.prototype.toggleSavegameMenu = function () { var menu, deleteButton, loadButton, saveButton, self; var saves, buttonPanel, resumeButton, id, sgList; var curEl, listenerStatus, curElapsed, oldState; self = this; id = "WSESaveGameMenu_" + this.game.url; listenerStatus = this.game.listenersSubscribed; menu = document.getElementById(id) || null; if (menu !== null) { try { listenerStatus = menu.getAttribute("data-wse-listener-status") === "true" ? true : false; this.stage.removeChild(menu); } catch (e) { console.log(e); } if (listenerStatus === true) { this.savegameMenuVisible = false; } this.state = this.oldStateInSavegameMenu; this.waitCounter -= 1; return; } if (this.stopped !== true) { setTimeout(function () { self.toggleSavegameMenu(); }, 20); return; } oldState = this.state; this.oldStateInSavegameMenu = oldState; this.state = "pause"; this.waitCounter += 1; this.savegameMenuVisible = true; menu = document.createElement("div"); menu.innerHTML = ""; menu.setAttribute("id", id); menu.setAttribute("class", "WSESavegameMenu"); menu.setAttribute("data-wse-remove", "true"); menu.setAttribute("data-wse-listener-status", listenerStatus); menu.style.zIndex = 100000; menu.style.position = "absolute"; saves = savegames.getSavegameList(this, true); deleteButton = document.createElement("input"); deleteButton.setAttribute("class", "button delete"); deleteButton.setAttribute("type", "button"); deleteButton.value = "Delete"; deleteButton.addEventListener( "click", function (ev) { var active, savegameName; ev.stopPropagation(); ev.preventDefault(); active = menu.querySelector(".active") || null; if (active === null) { return; } savegameName = active.getAttribute("data-wse-savegame-name"); function fn (decision) { if (decision === false) { return; } savegames.remove(self, savegameName); self.toggleSavegameMenu(); self.toggleSavegameMenu(); } ui.confirm( self, { title: "Delete game?", message: "Do you really want to delete savegame '" + savegameName + "'?", callback: fn } ); }, false ); saveButton = document.createElement("input"); saveButton.setAttribute("class", "button save"); saveButton.setAttribute("type", "button"); saveButton.value = "Save"; saveButton.addEventListener( "click", function (ev) { var active, savegameName; ev.stopPropagation(); ev.preventDefault(); active = menu.querySelector(".active") || null; if (active === null) { ui.prompt( self, { title: "New savegame", message: "Please enter a name for the savegame:", callback: function (data) { if (data === null) { return; } if (!data) { ui.alert( self, { title: "Error", message: "The savegame name cannot be empty!" } ); return; } self.toggleSavegameMenu(); self.game.listenersSubscribed = listenerStatus; savegames.save(self, data); self.toggleSavegameMenu(); self.game.listenersSubscribed = false; ui.alert( self, { title: "Game saved", message: "Your game has been saved." } ); } } ); return; } savegameName = active.getAttribute("data-wse-savegame-name"); ui.confirm( self, { title: "Overwrite savegame?", message: "You are about to overwrite an old savegame. Are you sure?", trueText: "Yes", falseText: "No", callback: function (decision) { if (decision === false) { return; } self.toggleSavegameMenu(); savegames.save(self, savegameName); self.toggleSavegameMenu(); ui.alert( self, { title: "Game saved", message: "Your game has been saved." } ); } } ); }, false ); loadButton = document.createElement("input"); loadButton.setAttribute("class", "button load"); loadButton.setAttribute("type", "button"); loadButton.setAttribute("tabindex", 1); loadButton.value = "Load"; loadButton.addEventListener( "click", function (ev) { var active, savegameName, fn; ev.stopPropagation(); ev.preventDefault(); active = menu.querySelector(".active") || null; if (active === null) { return; } savegameName = active.getAttribute("data-wse-savegame-name"); fn = function (decision) { if (decision === false) { return; } self.stage.removeChild(document.getElementById(id)); self.savegameMenuVisible = false; self.waitCounter -= 1; self.state = oldState; savegames.load(self, savegameName); }; ui.confirm( self, { title: "Load game?", message: "Loading a savegame will discard all unsaved progress. Continue?", callback: fn } ); }, false ); buttonPanel = document.createElement("div"); buttonPanel.setAttribute("class", "panel"); resumeButton = document.createElement("input"); resumeButton.setAttribute("class", "button resume"); resumeButton.setAttribute("type", "button"); resumeButton.value = "Resume"; resumeButton.addEventListener( "click", function (ev) { ev.stopPropagation(); ev.preventDefault(); self.stage.removeChild(document.getElementById(id)); self.bus.trigger( "wse.interpreter.numberOfFunctionsToWaitFor.decrease", null, false ); self.savegameMenuVisible = false; self.waitCounter -= 1; self.state = oldState; }, false ); sgList = document.createElement("div"); sgList.setAttribute("class", "list"); buttonPanel.appendChild(loadButton); buttonPanel.appendChild(saveButton); buttonPanel.appendChild(deleteButton); buttonPanel.appendChild(resumeButton); menu.appendChild(buttonPanel); function makeClickFn (curEl) { return function (event) { var old; event.stopPropagation(); event.preventDefault(); try { old = sgList.querySelector(".active") || null; if (old !== null) { old.setAttribute("class", old.getAttribute("class").replace(/active/, "")); } } catch (e) { console.log(e); } curEl.setAttribute("class", curEl.getAttribute("class") + " active"); loadButton.focus(); }; } curEl = document.createElement("div"); curEl.setAttribute("class", "button"); each(function (cur) { curEl = document.createElement("div"); curElapsed = cur.saveTime - cur.startTime; curEl.setAttribute("class", "button"); curEl.setAttribute("data-wse-savegame-name", cur.name); curEl.innerHTML = '' + '<p class="name">' + cur.name + '</p>' + '<p class="description">' + '<span class="elapsed">' + parseInt((curElapsed / 60) / 60, 10) + 'h ' + parseInt((curElapsed / 60) % 60, 10) + 'm ' + parseInt(curElapsed % 60, 10) + 's' + '</span>' + '<span class="date">' + new Date(cur.saveTime * 1000).toUTCString() + '</span>' + '</p>'; curEl.addEventListener("click", makeClickFn(curEl, cur), false); sgList.appendChild(curEl); }, saves); menu.addEventListener( "click", function (ev) { var active; ev.stopPropagation(); ev.preventDefault(); active = menu.querySelector(".active") || null; if (active === null) { return; } active.setAttribute("class", active.getAttribute("class").replace(/active/, "")); }, false ); menu.appendChild(sgList); this.stage.appendChild(menu); }; Interpreter.prototype._startLoadingScreen = function () { var template = this.story.querySelector("loadingScreen"); if (template) { this._loadingScreen.setTemplate(getSerializedNodes(template)); } this._loadingScreen.show(this.stage); }; return Interpreter; }); /* global using */ using("transform-js::transform", "databus"). define("WSE.LoadingScreen", function (transform, DataBus) { function LoadingScreen () { DataBus.inject(this); this._loading = 0; this._loaded = 0; this._max = 0; this._finished = false; this._template = '' + '<div class="container">' + '<div class="logo">' + '<img src="assets/images/logo.png"' + 'onerror="this.style.display=\'none\'"/>' + '</div>' + '<div class="heading">' + '<span id="WSELoadingScreenPercentage">{$progress}%</span>' + 'Loading...' + '</div>' + '<div class="progressBar">' + '<div class="progress" id="WSELoadingScreenProgress" ' + 'style="width: {$progress}%;">' + '</div>' + '</div>' + '</div>'; this._container = document.createElement("div"); this._container.setAttribute("id", "WSELoadingScreen"); this._container.style.zIndex = 10000; this._container.style.width = "100%"; this._container.style.height = "100%"; } LoadingScreen.prototype.setTemplate = function (template) { this._template = template; }; LoadingScreen.prototype.addItem = function () { if (this._finished) { return; } this._loading += 1; this._max += 1; this.update(); }; LoadingScreen.prototype.count = function () { return this._max; }; LoadingScreen.prototype.itemLoaded = function () { if (this._finished) { return; } if (this._loaded === this._max) { return; } this._loading -= 1; this._loaded += 1; if (this._loaded === this._max) { this._finished = true; this.trigger("finished"); } this.update(); }; LoadingScreen.prototype.update = function () { var progress; if (this._loaded > this._max) { this._loaded = this._max; } progress = parseInt((this._loaded / this._max) * 100, 10); if (this._max < 1) { progress = 0; } this._container.innerHTML = render(this._template, { all: this._max, remaining: this._max - this._loaded, loaded: this._loaded, progress: progress }); }; LoadingScreen.prototype.show = function (parent) { this._container.style.display = ""; parent.appendChild(this._container); this.update(); }; LoadingScreen.prototype.hide = function () { var self = this; function valFn (v) { self._container.style.opacity = v; } function finishFn () { self._container.style.display = "none"; self._container.parentNode.removeChild(self._container); } transform(1, 0, valFn, { duration: 500, onFinish: finishFn }); this._container.style.display = "none"; }; return LoadingScreen; function render (template, vars) { for (var key in vars) { template = insertVar(template, key, vars[key]); } return template; } function insertVar (template, name, value) { return ("" + template).split("{$" + name + "}").join("" + value); } }); /* global using */ using( "WSE.tools::warn", "WSE.tools::replaceVariables" ).define("WSE.tools.ui", function (warn, replaceVars) { "use strict"; var KEYCODE_ENTER = 13; var KEYCODE_ESCAPE = 27; var ui = { confirm: function (interpreter, args) { var title, message, trueText, falseText, callback, root, dialog; var tEl, mEl, yesEl, noEl, container, pause, oldState, doNext; interpreter.waitCounter += 1; args = args || {}; title = args.title || "Confirm?"; message = args.message || "Do you want to proceed?"; trueText = args.trueText || "Yes"; falseText = args.falseText || "No"; callback = typeof args.callback === "function" ? args.callback : function () {}; root = args.parent || interpreter.stage; pause = args.pause === true ? true : false; oldState = interpreter.state; doNext = args.doNext === true ? true : false; if (pause === true) { interpreter.state = "pause"; } container = document.createElement("div"); container.setAttribute("class", "WSEUIContainer"); container.setAttribute("data-wse-remove", "true"); dialog = document.createElement("div"); dialog.setAttribute("class", "WSEUIDialog WSEUIConfirm"); tEl = document.createElement("div"); tEl.innerHTML = title; tEl.setAttribute("class", "title"); mEl = document.createElement("div"); mEl.innerHTML = message; mEl.setAttribute("class", "message"); yesEl = document.createElement("input"); yesEl.setAttribute("value", trueText); yesEl.value = trueText; yesEl.setAttribute("class", "true button"); yesEl.setAttribute("type", "button"); yesEl.addEventListener("click", function (ev) { ev.stopPropagation(); ev.preventDefault(); root.removeChild(container); interpreter.waitCounter -= 1; // interpreter.keysDisabled -= 1; if (pause === true) { interpreter.state = oldState; } callback(true); if (doNext === true) { setTimeout(function () { interpreter.next(); }, 0); } }); noEl = document.createElement("input"); noEl.setAttribute("value", falseText); noEl.value = falseText; noEl.setAttribute("class", "false button"); noEl.setAttribute("type", "button"); noEl.addEventListener("click", function (ev) { ev.stopPropagation(); ev.preventDefault(); root.removeChild(container); interpreter.waitCounter -= 1; if (pause === true) { interpreter.state = oldState; } callback(false); if (doNext === true) { setTimeout(function () { interpreter.next(); }, 0); } }); dialog.appendChild(tEl); dialog.appendChild(mEl); dialog.appendChild(yesEl); dialog.appendChild(noEl); container.appendChild(dialog); root.appendChild(container); yesEl.focus(); }, alert: function (interpreter, args) { var title, message, okText, callback, root, dialog; var tEl, mEl, buttonEl, container, pause, oldState, doNext; interpreter.waitCounter += 1; args = args || {}; title = args.title || "Alert!"; message = args.message || "Please take notice of this!"; okText = args.okText || "OK"; callback = typeof args.callback === "function" ? args.callback : function () {}; root = args.parent || interpreter.stage; pause = args.pause === true ? true : false; oldState = interpreter.state; doNext = args.doNext === true ? true : false; if (pause === true) { interpreter.state = "pause"; } container = document.createElement("div"); container.setAttribute("class", "WSEUIContainer"); container.setAttribute("data-wse-remove", "true"); dialog = document.createElement("div"); dialog.setAttribute("class", "WSEUIDialog WSEUIConfirm"); tEl = document.createElement("div"); tEl.innerHTML = title; tEl.setAttribute("class", "title"); mEl = document.createElement("div"); mEl.innerHTML = message; mEl.setAttribute("class", "message"); buttonEl = document.createElement("input"); buttonEl.setAttribute("value", okText); buttonEl.value = okText; buttonEl.setAttribute("class", "true button"); buttonEl.setAttribute("type", "button"); buttonEl.addEventListener("click", function (ev) { ev.stopPropagation(); ev.preventDefault(); root.removeChild(container); interpreter.waitCounter -= 1; if (pause === true) { interpreter.state = oldState; } callback(true); if (doNext === true) { setTimeout(function () { interpreter.next(); }, 0); } }); dialog.appendChild(tEl); dialog.appendChild(mEl); dialog.appendChild(buttonEl); container.appendChild(dialog); root.appendChild(container); buttonEl.focus(); }, prompt: function (interpreter, args) { var title, message, submitText, cancelText, callback, root, dialog, oldState; var tEl, mEl, buttonEl, cancelEl, inputEl, container, pause, doNext; var allowEmptyInput, hideCancelButton, prefill; interpreter.waitCounter += 1; args = args || {}; title = args.title || "Input required"; message = args.message || "Please enter something:"; submitText = args.submitText || "Submit"; cancelText = args.cancelText || "Cancel"; callback = typeof args.callback === "function" ? args.callback : function () {}; root = args.parent || interpreter.stage; pause = args.pause === true ? true : false; oldState = interpreter.state; doNext = args.doNext === true ? true : false; allowEmptyInput = args.allowEmptyInput; hideCancelButton = args.hideCancelButton; prefill = args.prefill || ""; if (pause === true) { interpreter.state = "pause"; } container = document.createElement("div"); container.setAttribute("class", "WSEUIContainer"); container.setAttribute("data-wse-remove", "true"); dialog = document.createElement("div"); dialog.setAttribute("class", "WSEUIDialog WSEUIPrompt"); tEl = document.createElement("div"); tEl.innerHTML = title; tEl.setAttribute("class", "title"); mEl = document.createElement("div"); mEl.innerHTML = message; mEl.setAttribute("class", "message"); inputEl = document.createElement("input"); inputEl.setAttribute("value", prefill); inputEl.value = prefill; inputEl.setAttribute("class", "input text"); inputEl.setAttribute("type", "text"); inputEl.addEventListener("keyup", function (event) { if (cancelOnEscape()) { return; } if (allowEmptyInput) { submitOnEnter(); return; } if (inputEl.value) { buttonEl.disabled = false; submitOnEnter(); } else { buttonEl.disabled = true; } function submitOnEnter () { if (event.keyCode === KEYCODE_ENTER) { buttonEl.click(); } } function cancelOnEscape () { if (event.keyCode === KEYCODE_ESCAPE && !hideCancelButton) { cancelEl.click(); return true; } return false; } }); buttonEl = document.createElement("input"); buttonEl.setAttribute("value", submitText); buttonEl.value = submitText; buttonEl.setAttribute("class", "submit button"); buttonEl.setAttribute("type", "button"); if (!allowEmptyInput && !prefill) { buttonEl.disabled = true; } buttonEl.addEventListener("click", function (ev) { var val = inputEl.value; if (!allowEmptyInput && !val) { return; } ev.stopPropagation(); ev.preventDefault(); root.removeChild(container); interpreter.waitCounter -= 1; if (pause === true) { interpreter.state = oldState; } callback(val); if (doNext === true) { setTimeout(function () { interpreter.next(); }, 0); } }); cancelEl = document.createElement("input"); cancelEl.setAttribute("value", cancelText); cancelEl.value = cancelText; cancelEl.setAttribute("class", "cancel button"); cancelEl.setAttribute("type", "button"); cancelEl.addEventListener("click", function (ev) { ev.stopPropagation(); ev.preventDefault(); root.removeChild(container); interpreter.waitCounter -= 1; if (pause === true) { interpreter.state = oldState; } callback(null); if (doNext === true) { setTimeout(function () { interpreter.next(); }, 0); } }); dialog.appendChild(tEl); dialog.appendChild(mEl); dialog.appendChild(inputEl); dialog.appendChild(buttonEl); if (!hideCancelButton) { dialog.appendChild(cancelEl); } container.appendChild(dialog); root.appendChild(container); inputEl.focus(); } }; ui.makeInputFn = function (type) { return function (command, interpreter) { var title, message, container, key, doNext, hideCancelButton, allowEmptyInput; var submitText, cancelText, prefill; title = command.getAttribute("title") || "Input required..."; message = command.getAttribute("message") || "Your input is required:"; key = command.getAttribute("var") || null; submitText = command.getAttribute("submitText") || ""; cancelText = command.getAttribute("cancelText") || ""; prefill = command.getAttribute("prefill") || ""; allowEmptyInput = replaceVars(command.getAttribute("allowEmptyInput") || "", interpreter) === "no" ? false : true; hideCancelButton = replaceVars(command.getAttribute("hideCancelButton") || "", interpreter) === "yes" ? true : false; doNext = replaceVars(command.getAttribute("next") || "", interpreter) === "false" ? false : true; if (key !== null) { key = replaceVars(key, interpreter); } title = replaceVars(title, interpreter); message = replaceVars(message, interpreter); cancelText = replaceVars(cancelText, interpreter); submitText = replaceVars(submitText, interpreter); prefill = replaceVars(prefill, interpreter); interpreter.bus.trigger("wse.interpreter.commands." + type, command); if (key === null) { warn(interpreter.bus, "No 'var' attribute defined on " + type + " command. Command ignored.", command); return { doNext: true }; } container = interpreter.runVars; ui[type]( interpreter, { title: title, message: message, pause: true, doNext: doNext, callback: function (decision) { container[key] = "" + decision; }, allowEmptyInput: allowEmptyInput, hideCancelButton: hideCancelButton, submitText: submitText, cancelText: cancelText, prefill: prefill } ); return { doNext: true }; }; }; return ui; }); /*///////////////////////////////////////////////////////////////////////////////// MO5.js - JavaScript Library For Building Modern DOM And Canvas Applications Copyright (c) 2013 Jonathan Steinbeck All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name MO5.js nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. /////////////////////////////////////////////////////////////////////////////////*/ /* global using, setTimeout */ using("transform-js::transform").define("WSE.tools.reveal", function (transform) { function reveal (element, args) { args = args || {}; markCharacters(element); hideCharacters(element); return revealCharacters(element, args.speed || 50, args.onFinish || null); } return reveal; function revealCharacters (element, speed, then) { var chars = element.querySelectorAll(".Char"); var offset = 1000 / (speed || 40); var stop = false; var timeouts = []; var left = chars.length; then = then || function () {}; [].forEach.call(chars, function (char, i) { var id = setTimeout(function () { // Workaround for strange move.js behaviour: // Sometimes the last .end() callback doesn't get called, so // we set another timeout to correct this mistake if it happens. var called = false; var duration = 10 * offset; if (stop) { return; } transform(0, 1, setOpacity, {duration: duration}, end); setTimeout(end, duration + 2000); function setOpacity (v) { char.style.opacity = v; } function end () { if (called) { return; } called = true; left -= 1; if (stop) { return; } if (left <= 0) { then(); } } }, i * offset); timeouts.push(id); }); function cancel () { if (stop || left <= 0) { return false; } stop = true; timeouts.forEach(function (id) { clearTimeout(id); }); [].forEach.call(chars, function (char) { char.style.opacity = "1"; }); then(); return true; } return { cancel: cancel }; } function hideCharacters (element) { var chars = element.querySelectorAll(".Char"); [].forEach.call(chars, function (char) { char.style.opacity = 0; }); } function markCharacters (element, offset) { var TEXT_NODE = 3; var ELEMENT = 1; offset = offset || 0; [].forEach.call(element.childNodes, function (child) { var text = "", newNode; if (child.nodeType === TEXT_NODE) { [].forEach.call(child.textContent, function (char) { text += '<span class="Char" data-char="' + offset + '">' + char + '</span>'; offset += 1; }); newNode = document.createElement("span"); newNode.setAttribute("class", "CharContainer"); newNode.innerHTML = text; child.parentNode.replaceChild(newNode, child); } else if (child.nodeType === ELEMENT) { offset = markCharacters(child, offset); } }); return offset; } }); // // A module containing functions for compiling a simple command language to the old // WSE command elements. // /* global using */ using("xmugly").define("WSE.tools.compile", function (xmugly) { // // Compiles the new WSE command language to XML elements. // function compile (text) { text = xmugly.compile(text, [ { identifier: "@", attribute: "asset", value: "_" }, { identifier: ":", attribute: "duration", value: "_" }, { identifier: "+", attribute: "_", value: "yes" }, { identifier: "-", attribute: "_", value: "no" }, { identifier: "#", attribute: "id", value: "_" }, { identifier: "~", attribute: "name", value: "_" } ]); text = compileSpeech(text); return text; } return { compile: compile }; // // Compiles "(( c: I say something ))" to <line s="c">I say something</line>''. // function compileSpeech (text) { return text.replace( /([\s]*)\(\([\s]*([a-zA-Z0-9_-]+):[\s]*((.|[\s])*?)([\s]*)\)\)/g, '$1<line s="$2">$3</line>$5' ); } }); /* global using */ using( "enjoy-core::each", "WSE.tools::warn", "enjoy-typechecks::isNull", "enjoy-typechecks::isUndefined", "WSE" ). define("WSE.savegames", function (each, warn, isNull, isUndefined, WSE) { function load (interpreter, name) { var ds, savegame, scene, sceneId, scenePath, scenes; var savegameId, bus = interpreter.bus; savegameId = buildSavegameId(interpreter, name); ds = interpreter.datasource; savegame = ds.get(savegameId); bus.trigger( "wse.interpreter.load.before", { interpreter: interpreter, savegame: savegame }, false ); if (!savegame) { warn(bus, "Could not load savegame '" + savegameId + "'!"); return false; } savegame = JSON.parse(savegame); interpreter.stage.innerHTML = savegame.screenContents; restoreSavegame(interpreter, savegame.saves); interpreter.startTime = savegame.startTime; interpreter.runVars = savegame.runVars; interpreter.log = savegame.log; interpreter.visitedScenes = savegame.visitedScenes; interpreter.index = savegame.index; interpreter.wait = savegame.wait; interpreter.waitForTimer = savegame.waitForTimer; interpreter.currentElement = savegame.currentElement; interpreter.callStack = savegame.callStack; interpreter.waitCounter = savegame.waitCounter; interpreter.state = "listen"; sceneId = savegame.sceneId; interpreter.sceneId = sceneId; scenes = interpreter.story.getElementsByTagName("scene"); interpreter.scenes = scenes; scene = find(function (scene) { return scene.getAttribute("id") === sceneId; }, interpreter.scenes); if (!scene) { bus.trigger( "wse.interpreter.error", { message: "Loading savegame '" + savegameId + "' failed: Scene not found!" } ); return false; } scenePath = savegame.scenePath; interpreter.scenePath = scenePath.slice(); interpreter.currentCommands = scene.childNodes; while (scenePath.length > 0) { interpreter.currentCommands = interpreter.currentCommands[scenePath.shift()].childNodes; } // Re-insert choice menu to get back the DOM events associated with it: // Remove savegame menu on load: (function (interpreter) { var index, wseType, com, rem; each(function (cur) { if (isUndefined(cur) || isNull(cur)) { return; } wseType = cur.getAttribute("data-wse-type") || ""; rem = cur.getAttribute("data-wse-remove") === "true" ? true : false; if (rem === true) { interpreter.stage.removeChild(cur); } if (wseType !== "choice") { return; } index = parseInt(cur.getAttribute("data-wse-index"), 10) || null; if (index === null) { warn(interpreter.bus, "No data-wse-index found on element."); return; } com = interpreter.currentCommands[index]; if (com.nodeName === "#text" || com.nodeName === "#comment") { return; } interpreter.stage.removeChild(cur); WSE.commands.choice(com, interpreter); interpreter.waitCounter -= 1; }, interpreter.stage.getElementsByTagName("*")); }(interpreter)); bus.trigger( "wse.interpreter.load.after", { interpreter: interpreter, savegame: savegame }, false ); return true; } function save (interpreter, name) { name = name || "no name"; var savegame, json, key, savegameList, listKey, lastKey, bus = interpreter.bus; savegame = {}; bus.trigger( "wse.interpreter.save.before", { interpreter: interpreter, savegame: savegame }, false ); savegame.saves = createSavegame(interpreter); savegame.startTime = interpreter.startTime; savegame.saveTime = Math.round(Date.now() / 1000); savegame.screenContents = interpreter.stage.innerHTML; savegame.runVars = interpreter.runVars; savegame.name = name; savegame.log = interpreter.log; savegame.visitedScenes = interpreter.visitedScenes; savegame.gameUrl = interpreter.game.url; savegame.index = interpreter.index; savegame.wait = interpreter.wait; savegame.waitForTimer = interpreter.waitForTimer; savegame.currentElement = interpreter.currentElement; savegame.sceneId = interpreter.sceneId; savegame.scenePath = interpreter.scenePath; savegame.listenersSubscribed = interpreter.game.listenersSubscribed; savegame.callStack = interpreter.callStack; savegame.waitCounter = interpreter.waitCounter; savegame.pathname = location.pathname; key = buildSavegameId(interpreter, name); json = JSON.stringify(savegame); listKey = "wse_" + savegame.pathname + "_" + savegame.gameUrl + "_savegames_list"; savegameList = JSON.parse(interpreter.datasource.get(listKey)); savegameList = savegameList || []; lastKey = savegameList.indexOf(key); if (lastKey >= 0) { savegameList.splice(lastKey, 1); } savegameList.push(key); try { interpreter.datasource.set(key, json); interpreter.datasource.set(listKey, JSON.stringify(savegameList)); } catch (e) { warn(bus, "Savegame could not be created!"); bus.trigger( "wse.interpreter.save.after.error", { interpreter: interpreter, savegame: savegame }, false ); return false; } bus.trigger( "wse.interpreter.save.after.success", { interpreter: interpreter, savegame: savegame } ); return true; } function createSavegame (interpreter) { var saves = {}; each(function (asset, key) { try { saves[key] = asset.save(); } catch (e) { console.error("WSE Internal Error: Asset '" + key + "' does not have a 'save' method!"); } }, interpreter.assets); return saves; } function restoreSavegame (interpreter, saves) { each(function (asset, key) { try { asset.restore(saves[key]); } catch (e) { console.error(e); warn(interpreter.bus, "Could not restore asset state for asset '" + key + "'!"); } }, interpreter.assets); } function buildSavegameId (interpreter, name) { var vars = {}; vars.name = name; vars.id = "wse_" + location.pathname + "_" + interpreter.game.url + "_savegame_" + name; interpreter.bus.trigger( "wse.interpreter.save.before", { interpreter: interpreter, vars: vars }, false ); return vars.id; } function getSavegameList (interpreter, reversed) { var names; var out = []; var key = "wse_" + location.pathname + "_" + interpreter.game.url + "_savegames_list"; var json = interpreter.datasource.get(key); if (json === null) { return out; } names = JSON.parse(json); out = []; each(function (name) { if (reversed === true) { out.unshift(JSON.parse(interpreter.datasource.get(name))); } else { out.push(JSON.parse(interpreter.datasource.get(name))); } }, names); interpreter.bus.trigger( "wse.interpreter.getsavegamelist", { interpreter: interpreter, list: out, names: names }, false ); return out; } function remove (interpreter, name) { var sgs, key, index, json, id; key = "wse_" + location.pathname + "_" + interpreter.game.url + "_savegames_list"; json = interpreter.datasource.get(key); if (json === null) { return false; } sgs = JSON.parse(json); id = buildSavegameId(interpreter, name); index = sgs.indexOf(id); if (index >= 0) { sgs.splice(index, 1); interpreter.datasource.set( "wse_" + location.pathname + "_" + interpreter.game.url + "_savegames_list", JSON.stringify(sgs) ); interpreter.datasource.remove(id); return true; } return false; } return { save: save, load: load, remove: remove, getSavegameList: getSavegameList }; }); /* global using */ using( "transform-js::transform", "eases", "WSE.tools", "WSE.tools::warn", "WSE.tools::applyAssetUnits", "WSE.tools::extractUnit", "WSE.tools::calculateValueWithAnchor" ). define("WSE.DisplayObject", function ( transform, easing, tools, warn, applyUnits, extractUnit, anchoredValue ) { // // The prototype for all displayable assets. // // Set ._boxSizeSelectors to an array containing CSS selectors in your // asset if you want the initial position of the asset to be calculated // depending on some of its element's children instead of the element's // .offsetWidth and .offsetHeight. This can be necessary for assets such // as ImagePacks because the asset's element will not have a size until // at least some of its children are shown. // function DisplayObject (asset, interpreter) { this.stage = interpreter.stage; this.bus = interpreter.bus; this.name = asset.getAttribute("name"); this.cssid = asset.getAttribute("cssid") || "wse_imagepack_" + this.name; this.interpreter = interpreter; this.x = asset.getAttribute("x") || 0; this.y = asset.getAttribute("y") || 0; this.z = asset.getAttribute("z") || this.z || 0; this.xAnchor = asset.getAttribute("xAnchor"); this.yAnchor = asset.getAttribute("yAnchor"); this.width = asset.getAttribute("width") || this.width; this.height = asset.getAttribute("height") || this.height; this._createElement(); applyUnits(this, asset); } DisplayObject.prototype.onLoad = function () { this._calculateBoxSize(); this._moveToPosition(); }; DisplayObject.prototype.flash = function flash (command, args) { var self, duration, element, isAnimation, maxOpacity; var visible, parse = tools.getParsedAttribute; args = args || {}; self = this; duration = +parse(command, "duration", this.interpreter, 500); maxOpacity = +parse(command, "opacity", this.interpreter, 1); element = args.element || document.getElementById(this.cssid); if (!element) { warn(this.bus, "DOM Element for asset is missing!", command); return; } isAnimation = args.animation === true ? true : false; visible = (+(element.style.opacity.replace(/[^0-9\.]/, ""))) > 0 ? true : false; if (!isAnimation) { self.interpreter.waitCounter += 1; } transform( visible ? maxOpacity : 0, visible ? 0 : maxOpacity, function (v) { element.style.opacity = v; }, { duration: duration / 3, easing: easing.cubicIn }, function () { var argsObj; function tranformFn (v) { element.style.opacity = v; } function finishFn () { if (isAnimation) { return; } self.interpreter.waitCounter -= 1; } argsObj = { duration: (duration / 3) * 2, easing: easing.cubicOut }; transform( visible ? 0 : maxOpacity, visible ? maxOpacity : 0, tranformFn, argsObj, finishFn ); } ); return { doNext: true }; }; DisplayObject.prototype.flicker = function (command, args) { var self, duration, times, step, element; var isAnimation, fn, iteration, maxOpacity, val1, val2, dur1, dur2; args = args || {}; self = this; duration = command.getAttribute("duration") || 500; times = command.getAttribute("times") || 10; maxOpacity = command.getAttribute("opacity") || 1; element = args.element || document.getElementById(this.cssid); step = duration / times; iteration = 0; if (!element) { warn(this.bus, "DOM Element for asset is missing!", command); return; } if (!(parseInt(element.style.opacity, 10))) { val1 = 0; val2 = maxOpacity; dur1 = step / 3; dur2 = dur1 * 2; } else { val2 = 0; val1 = maxOpacity; dur2 = step / 3; dur1 = dur2 * 2; } isAnimation = args.animation === true ? true : false; if (!isAnimation) { self.interpreter.waitCounter += 1; } fn = function () { iteration += 1; transform( val1, val2, function (v) { element.style.opacity = v; }, { duration: dur1, easing: easing.quadIn }, function () { transform( val2, val1, function (v) { element.style.opacity = v; }, { duration: dur2, easing: easing.quadIn }, function () { if (iteration <= times) { setTimeout(fn, 0); return; } if (!isAnimation) { self.interpreter.waitCounter -= 1; } } ); } ); }; fn(); return { doNext: true }; }; DisplayObject.prototype.hide = function (command, args) { var self, duration, effect, direction, offsetWidth, offsetHeight; var ox, oy, to, prop, isAnimation, element, easingType, easingFn, stage; var xUnit, yUnit; var parse = tools.getParsedAttribute; args = args || {}; self = this; duration = parse(command, "duration", this.interpreter, 500); effect = parse(command, "effect", this.interpreter, "fade"); direction = parse(command, "direction", this.interpreter, "left"); isAnimation = args.animation === true ? true : false; element = document.getElementById(this.cssid); easingType = parse(command, "easing", this.interpreter, "sineEaseOut"); easingFn = (easing[easingType]) ? easing[easingType] : easing.sineOut; stage = this.stage; xUnit = this.xUnit || 'px'; yUnit = this.yUnit || 'px'; if (effect === "slide") { element.style.opacity = 1; if (xUnit === '%') { ox = element.offsetLeft / (stage.offsetWidth / 100); offsetWidth = 100; } else { ox = element.offsetLeft; offsetWidth = stage.offsetWidth; } if (yUnit === '%') { oy = element.offsetTop / (stage.offsetHeight / 100); offsetHeight = 100; } else { oy = element.offsetTop; offsetHeight = stage.offsetHeight; } switch (direction) { case "left": to = ox - offsetWidth; prop = "left"; break; case "right": to = ox + offsetWidth; prop = "left"; break; case "top": to = oy - offsetHeight; prop = "top"; break; case "bottom": to = oy + offsetHeight; prop = "top"; break; default: to = ox - offsetWidth; prop = "left"; } if (!isAnimation) { self.interpreter.waitCounter += 1; } (function () { var valFn, from, finishFn, options; valFn = function (v) { element.style[prop] = v + (prop === 'left' ? xUnit : yUnit); }; from = (prop === "left" ? ox : oy); finishFn = function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } element.style.opacity = 0; switch (direction) { case "left": case "right": element.style.left = ox + xUnit; prop = "left"; break; case "top": case "bottom": element.style.top = oy + yUnit; prop = "top"; break; default: element.style.left = ox + xUnit; prop = "left"; } }; options = { duration: duration, easing: easingFn }; transform(from, to, valFn, options, finishFn); }()); } else { if (!isAnimation) { self.interpreter.waitCounter += 1; } (function () { var valFn, options, finishFn; valFn = function (v) { element.style.opacity = v; }; finishFn = function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } element.style.opacity = 0; }; options = { duration: duration, easing: easingFn }; transform(1, 0, valFn, options, finishFn); }()); } return { doNext: true }; }; DisplayObject.prototype.move = function (command, args) { var x, y, z, element, self, xUnit, yUnit, duration, easingType; var easingFn, isAnimation, ox, oy, stage; var xAnchor, yAnchor, interpreter = this.interpreter; var offsetLeft, offsetTop, oldElementDisplayStyle; args = args || {}; self = this; element = document.getElementById(this.cssid); x = command.getAttribute("x"); y = command.getAttribute("y"); z = command.getAttribute("z"); xAnchor = command.getAttribute("xAnchor") || "0"; yAnchor = command.getAttribute("yAnchor") || "0"; if (xAnchor === null && this.xAnchor !== null) { xAnchor = this.xAnchor; } if (yAnchor === null && this.yAnchor !== null) { yAnchor = this.yAnchor; } x = tools.replaceVariables(x, this.interpreter); y = tools.replaceVariables(y, this.interpreter); z = tools.replaceVariables(z, this.interpreter); xAnchor = tools.replaceVariables(xAnchor, this.interpreter); yAnchor = tools.replaceVariables(yAnchor, this.interpreter); duration = tools.getParsedAttribute(command, "duration", interpreter, 500); easingType = tools.getParsedAttribute(command, "easing", interpreter, "sineEaseOut"); easingFn = (easing[easingType]) ? easing[easingType] : easing.sineOut; isAnimation = args.animation === true ? true : false; stage = this.interpreter.stage; offsetLeft = element.offsetLeft; offsetTop = element.offsetTop; if (x !== null) { xUnit = tools.extractUnit(x) || "px"; x = parseInt(x, 10); } if (y !== null) { yUnit = tools.extractUnit(y) || "px"; y = parseInt(y, 10); } oldElementDisplayStyle = element.style.display; element.style.display = ""; if (xUnit === "%") { x = (stage.offsetWidth / 100) * x; xUnit = "px"; } if (yUnit === "%") { y = (stage.offsetHeight / 100) * y; yUnit = "px"; } x = tools.calculateValueWithAnchor(x, xAnchor, element.offsetWidth); y = tools.calculateValueWithAnchor(y, yAnchor, element.offsetHeight); element.style.display = oldElementDisplayStyle; if (x === null && y === null && z === null) { warn(this.bus, "Can't apply command 'move' to asset '" + this.name + "' because no x, y or z position " + "has been supplied.", command); } if (x !== null) { if (xUnit === '%') { ox = offsetLeft / (stage.offsetWidth / 100); } else { ox = offsetLeft; } if (!isAnimation) { self.interpreter.waitCounter += 1; } transform( ox, x, function (v) { element.style.left = v + xUnit; }, { duration: duration, easing: easingFn }, function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } } ); } if (y !== null) { if (yUnit === '%') { oy = offsetTop / (stage.offsetHeight / 100); } else { oy = offsetTop; } if (!isAnimation) { self.interpreter.waitCounter += 1; } transform( oy, y, function (v) { element.style.top = v + yUnit; }, { duration: duration, easing: easingFn }, function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } } ); } if (z !== null) { if (!isAnimation) { self.interpreter.waitCounter += 1; } transform( element.style.zIndex || 0, parseInt(z, 10), function (v) { element.style.zIndex = v; }, { duration: duration, easing: easingFn }, function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } } ); } this.bus.trigger("wse.assets.mixins.move", this); return { doNext: true }; }; DisplayObject.prototype.shake = function (command) { var dx, dy, element, self, xUnit, yUnit, duration, period; var ox, oy, stage; self = this; element = document.getElementById(this.cssid); dx = command.getAttribute("dx"); dy = command.getAttribute("dy"); period = command.getAttribute("period") || 50; duration = command.getAttribute("duration") || 275; stage = this.interpreter.stage; if (dx === null && dy === null) { dy = "-10px"; } if (dx !== null) { xUnit = tools.extractUnit(dx); dx = parseInt(dx, 10); } if (dy !== null) { yUnit = tools.extractUnit(dy); dy = parseInt(dy, 10); } function easing (d, t) { var x = t / period; while (x > 2.0) { x -= 2.0; } if (x > 1.0) { x = 2.0 - x; } return x; } if (dx !== null) { if (xUnit === '%') { ox = element.offsetLeft / (stage.offsetWidth / 100); } else { ox = element.offsetLeft; } self.interpreter.waitCounter += 1; transform( ox - dx, ox + dx, function (v) { element.style.left = v + xUnit; }, { duration: duration, easing: easing } ). then(function () { element.style.left = ox + xUnit; self.interpreter.waitCounter -= 1; }); } if (dy !== null) { if (yUnit === '%') { oy = element.offsetTop / (stage.offsetHeight / 100); } else { oy = element.offsetTop; } self.interpreter.waitCounter += 1; transform( oy - dy, oy + dy, function (v) { element.style.top = v + yUnit; }, { duration: duration, easing: easing }, function () { element.style.top = oy + yUnit; self.interpreter.waitCounter -= 1; } ); } this.bus.trigger("wse.assets.mixins.shake", this); return { doNext: true }; }; DisplayObject.prototype.show = function (command, args) { var duration, effect, direction, ox, oy, prop, xUnit, yUnit; var stage, element, isAnimation, easingFn, easingType, interpreter; var offsetWidth, offsetHeight, startX, startY; var parse = tools.getParsedAttribute; args = args || {}; duration = parse(command, "duration", this.interpreter, 500); effect = parse(command, "effect", this.interpreter, "fade"); direction = parse(command, "direction", this.interpreter, "right"); element = args.element || document.getElementById(this.cssid); xUnit = this.xUnit || 'px'; yUnit = this.yUnit || 'px'; if (!element) { warn(this.bus, "DOM Element for asset is missing!", command); return; } interpreter = args.interpreter || this.interpreter; stage = args.stage || this.stage; easingType = parse(command, "easing", this.interpreter, "sineOut"); easingFn = (easing[easingType]) ? easing[easingType] : easing.sineOut; isAnimation = args.animation === true ? true : false; if (effect === "slide") { if (xUnit === '%') { ox = element.offsetLeft / (stage.offsetWidth / 100); offsetWidth = 100; } else { ox = element.offsetLeft; offsetWidth = stage.offsetWidth; } if (yUnit === '%') { oy = element.offsetTop / (stage.offsetHeight / 100); offsetHeight = 100; } else { oy = element.offsetTop; offsetHeight = stage.offsetHeight; } switch (direction) { case "left": element.style.left = ox + offsetWidth + xUnit; prop = "left"; break; case "right": element.style.left = ox - offsetWidth + xUnit; prop = "left"; break; case "top": element.style.top = oy + offsetHeight + yUnit; prop = "top"; break; case "bottom": element.style.top = oy - offsetHeight + yUnit; prop = "top"; break; default: element.style.left = ox - offsetWidth + xUnit; prop = "left"; break; } element.style.opacity = 1; if (!isAnimation) { interpreter.waitCounter += 1; } if (xUnit === '%') { startX = element.offsetLeft / (stage.offsetWidth / 100); } else { startX = element.offsetLeft; } if (yUnit === '%') { startY = element.offsetTop / (stage.offsetHeight / 100); } else { startY = element.offsetTop; } transform( (prop === "left" ? startX : startY), (prop === "left" ? ox : oy), function (v) { element.style[prop] = v + (prop === 'left' ? xUnit : yUnit); }, { duration: duration, easing: easingFn }, function () { if (!isAnimation) { interpreter.waitCounter -= 1; } } ); } else { if (!isAnimation) { interpreter.waitCounter += 1; } transform( 0, 1, function (v) { element.style.opacity = v; }, { duration: duration, easing: easingFn }, function () { if (!isAnimation) { interpreter.waitCounter -= 1; } } ); } return { doNext: true }; }; DisplayObject.prototype._createElement = function () { this.element = document.createElement(this.elementType || "div"); this.element.style.opacity = 0; this.element.draggable = false; this.element.setAttribute("class", "asset"); this.element.setAttribute("id", this.cssid); this.element.setAttribute("data-wse-asset-name", this.name); this.element.style.position = "absolute"; this.element.style.zIndex = this.z; this.element.style.width = this.width; this.element.style.height = this.height; this.stage.appendChild(this.element); }; DisplayObject.prototype._moveToPosition = function () { var x, y, xUnit, yUnit; var element = this.element; x = parseInt(this.x, 10); y = parseInt(this.y, 10); xUnit = extractUnit(this.x) || "px"; yUnit = extractUnit(this.y) || "px"; if (xUnit === "%") { x = (this.stage.offsetWidth / 100) * x; } if (yUnit === "%") { y = (this.stage.offsetHeight / 100) * y; } x = anchoredValue(x, this.xAnchor, this.boxWidth || this.element.offsetWidth); y = anchoredValue(y, this.yAnchor, this.boxHeight || this.element.offsetHeight); if (xUnit === "%") { x = x / (this.stage.offsetWidth / 100); } if (yUnit === "%") { y = y / (this.stage.offsetHeight / 100); } element.style.left = "" + x + xUnit; element.style.top = "" + y + yUnit; }; // // Calculates .boxWidth and .boxHeight by finding the highest width and height // of the element's children depending on the selectors in ._boxSizeSelectors. // DisplayObject.prototype._calculateBoxSize = function () { var width = 0; var height = 0; var element = this.element; if (!Array.isArray(this._boxSizeSelectors)) { return; } this._boxSizeSelectors.forEach(function (selector) { [].forEach.call(element.querySelectorAll(selector), function (img) { if (img.offsetWidth > width) { width = img.offsetWidth; } if (img.offsetHeight > height) { height = img.offsetHeight; } }); }); this.boxWidth = width; this.boxHeight = height; }; return DisplayObject; }); /* global using */ using( "transform-js::transform", "eases", "MO5.Animation", "MO5.TimerWatcher", "WSE.commands", "WSE.tools::createTimer", "WSE.tools::warn" ). define("WSE.assets.Animation", function ( transform, easing, MO5Animation, TimerWatcher, commands, createTimer, warn ) { "use strict"; function Animation (asset, interpreter) { var groups, i, len, current, transformations, jlen; var self, doElements; this.stage = interpreter.stage; this.bus = interpreter.bus; this.asset = asset; this.name = asset.getAttribute("name"); this.cbs = []; this.assets = interpreter.assets; this.isRunning = false; self = this; groups = this.asset.getElementsByTagName("group"); len = groups.length; if (len < 1) { warn(this.bus, "Animation asset '" + this.name + "' is empty.", asset); return { doNext: true }; } function createTransformFn (as, f, t, pn, u, opt) { return transform(f, t, function (v) { as.style[pn] = v + u; }, opt); } function runDoCommandFn (del, watcher) { var curDur, curDoEl; curDoEl = del; curDur = curDoEl.getAttribute("duration"); commands["do"](curDoEl, interpreter, { animation: true }); if (curDur !== null) { watcher.addTimer(createTimer(curDur)); } } function loopFn (transf, doEls) { var dlen; dlen = doEls.length; jlen = transformations.length; self.cbs.push(function () { var from, to, unit, curTr, curAs, curAsName; var dur, propName, j, easingType, opt, di, watcher; watcher = new TimerWatcher(); for (j = 0; j < jlen; j += 1) { curTr = transf[j]; if (typeof curTr === "undefined" || curTr === null) { continue; } curAsName = curTr.getAttribute("asset"); try { curAs = document.getElementById(self.assets[curAsName].cssid) || self.stage; } catch (e) { continue; } easingType = curTr.getAttribute("easing"); from = parseInt(curTr.getAttribute("from"), 10); to = parseInt(curTr.getAttribute("to"), 10); unit = curTr.getAttribute("unit") || ""; dur = curTr.getAttribute("duration") || 500; propName = curTr.getAttribute("property"); opt = {}; opt.duration = dur; if (easingType !== null && typeof easing[easingType] !== "undefined" && easing[easingType] !== null) { opt.easing = easing[easingType]; } watcher.addTimer(createTransformFn(curAs, from, to, propName, unit, opt)); } for (di = 0; di < dlen; di += 1) { runDoCommandFn(doEls[di], watcher); } return watcher; }); } for (i = 0; i < len; i += 1) { current = groups[i]; transformations = current.getElementsByTagName("transform"); doElements = current.getElementsByTagName("do"); loopFn(transformations, doElements); } this.anim = new MO5Animation(); this.cbs.forEach(function (cb) { this.anim.addStep(cb); }.bind(this)); this.bus.trigger("wse.assets.animation.constructor", this); (function () { function fn () { self.stop(); } self.bus.subscribe(fn, "wse.interpreter.restart"); self.bus.subscribe(fn, "wse.interpreter.end"); self.bus.subscribe(fn, "wse.interpreter.load.before"); }()); } Animation.prototype.start = function () { this.anim.start(); this.isRunning = true; this.bus.trigger("wse.assets.animation.started", this); }; Animation.prototype.stop = function () { if (this.anim.isRunning()) { this.anim.stop(); } this.isRunning = false; this.bus.trigger("wse.assets.animation.stopped", this); }; Animation.prototype.save = function () { var obj = { assetType: "Animation", isRunning: this.isRunning, index: this.anim.index }; this.bus.trigger( "wse.assets.animation.save", { subject: this, saves: obj } ); return obj; }; Animation.prototype.restore = function (obj) { this.isRunning = obj.isRunning; if (this.isRunning === true) { this.anim.index = obj.index; this.start(); } this.bus.trigger( "wse.assets.animation.restore", { subject: this, saves: obj } ); }; return Animation; }); /* global using */ using("WSE.tools::warn", "howler::Howl"). define("WSE.assets.Audio", function (warn, Howl) { "use strict"; /** * Constructor for the <audio> asset. * * @param asset [XML DOM Element] The asset definition. * @param interpreter [object] The interpreter instance. * @trigger wse.interpreter.warning@interpreter * @trigger wse.assets.audio.constructor@interpreter */ function Audio (asset, interpreter) { var sources, i, len, j, jlen, current, track, trackName; var trackFiles, href, type, source, tracks, bus, trackSettings; bus = interpreter.bus; this.interpreter = interpreter; this.bus = bus; this.name = asset.getAttribute("name"); this.tracks = {}; this.autopause = asset.getAttribute("autopause") === "true" ? true : false; this.loop = asset.getAttribute("loop") === "true" ? true : false; this.fade = asset.getAttribute("fade") === "true" ? true : false; this.fadeinDuration = parseInt(asset.getAttribute("fadein")) || 1000; this.fadeoutDuration = parseInt(asset.getAttribute("fadeout")) || 1000; this._playing = false; tracks = asset.getElementsByTagName("track"); len = tracks.length; if (len < 1) { warn(this.bus, "No tracks defined for audio element '" + this.name + "'.", asset); return { doNext: true }; } // check all sources and create Howl instances: for (i = 0; i < len; i += 1) { current = tracks[i]; trackName = current.getAttribute("title"); if (trackName === null) { warn(this.bus, "No title defined for track '" + trackName + "' in audio element '" + this.name + "'.", asset); continue; } sources = current.getElementsByTagName("source"); jlen = sources.length; if (jlen < 1) { warn(this.bus, "No sources defined for track '" + trackName + "' in audio element '" + this.name + "'.", asset); continue; } trackSettings = { urls: [], autoplay: false, loop: this.loop || false, onload: this.bus.trigger.bind(this.bus, "wse.assets.loading.decrease") }; trackFiles = {}; for (j = 0; j < jlen; j += 1) { source = sources[j]; href = source.getAttribute("href"); type = source.getAttribute("type"); if (href === null) { warn(this.bus, "No href defined for source in track '" + trackName + "' in audio element '" + this.name + "'.", asset); continue; } if (type === null) { warn(this.bus, "No type defined for source in track '" + trackName + "' in audio element '" + this.name + "'.", asset); continue; } trackFiles[type] = href; trackSettings.urls.push(href); } this.bus.trigger("wse.assets.loading.increase"); track = new Howl(trackSettings); this.tracks[trackName] = track; } /** * Starts playing the current track. * * @param command [XML DOM Element] The command as written in the WebStory. * @return [object] Object that determines the next state of the interpreter. */ this.play = function (command) { var fadeDuration; if (this._playing) { return { doNext: true }; } this._playing = true; this._paused = false; if (command.getAttribute("fadein")) { this.interpreter.waitCounter += 1; fadeDuration = +command.getAttribute("fadein"); this.tracks[this._currentTrack].volume(0); this.tracks[this._currentTrack].play(); this.tracks[this._currentTrack].fade(0, 1, fadeDuration, function () { this.interpreter.waitCounter -= 1; }.bind(this)); } else { this.tracks[this._currentTrack].play(); } return { doNext: true }; }; /** * Stops playing the current track. * * @param command [XML DOM Element] The command as written in the WebStory. * @return [object] Object that determines the next state of the interpreter. */ this.stop = function (command) { var fadeDuration; if (!this._currentTrack) { return { doNext: true }; } this._playing = false; this._paused = false; if (command && command.getAttribute("fadeout")) { this.interpreter.waitCounter += 1; fadeDuration = +command.getAttribute("fadeout"); this.tracks[this._currentTrack].fade(1, 0, fadeDuration, function () { this.tracks[this._currentTrack].stop(); this.interpreter.waitCounter -= 1; }.bind(this)); } else { this.tracks[this._currentTrack].stop(); } this.bus.trigger("wse.assets.audio.stop", this); return { doNext: true }; }; /** * Pauses playing the curren track. * * @return [object] Object that determines the next state of the interpreter. */ this.pause = function () { if (!this._currentTrack || !this._playing) { return { doNext: true }; } this._paused = true; this.tracks[this._currentTrack].pause(); return { doNext: true }; }; this.bus.trigger("wse.assets.audio.constructor", this); this.bus.subscribe("wse.interpreter.restart", function () { this.stop(); }.bind(this)); window.addEventListener("blur", function () { if (this._playing) { this.tracks[this._currentTrack].fade(1, 0, 200); } }.bind(this)); window.addEventListener("focus", function () { if (this._playing) { this.tracks[this._currentTrack].fade(0, 1, 200); } }.bind(this)); } /** * Changes the currently active track. * * @param command [DOM Element] The command as specified in the WebStory. * @trigger wse.interpreter.warning@interpreter * @trigger wse.assets.audio.set@interpreter */ Audio.prototype.set = function (command) { var wasPlaying = false; if (this._playing) { wasPlaying = true; } this.stop(); this._currentTrack = command.getAttribute("track"); if (wasPlaying) { this.play(command); } return { doNext: true }; }; /** * Gathers the data to put into a savegame. * * @param obj [object] The savegame object. */ Audio.prototype.save = function () { var obj = { currentTrack: this._currentTrack, playing: this._playing, paused: this._paused }; this.bus.trigger("wse.assets.audio.save", this); return obj; }; /** * Restore function for loading the state from a savegame. * * @param obj [object] The savegame data. * @trigger wse.assets.audio.restore@interpreter */ Audio.prototype.restore = function (vals) { var key; this._playing = vals.playing; this._paused = vals.paused; this._currentTrack = vals.currentTrack; for (key in this.tracks) { this.tracks[key].stop(); } if (this._playing && !this._paused) { this.tracks[this._currentTrack].play(); } this.bus.trigger("wse.assets.audio.restore", this); }; return Audio; }); /* global using */ using().define("WSE.assets.Character", function () { "use strict"; function Character (asset, interpreter) { this.asset = asset; this.stage = interpreter.stage; this.bus = interpreter.bus; this.name = asset.getAttribute('name'); this.bus.trigger("wse.assets.character.constructor", this); } Character.prototype.setTextbox = function (command) { this.asset.setAttribute("textbox", command.getAttribute("textbox")); this.bus.trigger("wse.assets.character.settextbox", this); }; Character.prototype.save = function () { var obj = { assetType: "Character", textboxName: this.asset.getAttribute("textbox") }; this.bus.trigger( "wse.assets.character.save", { subject: this, saves: obj } ); return obj; }; Character.prototype.restore = function (obj) { this.asset.setAttribute("textbox", obj.textboxName); this.bus.trigger( "wse.assets.character.restore", { subject: this, saves: obj } ); }; return Character; }); /* global using */ using("WSE.DisplayObject", "WSE.tools::warn"). define("WSE.assets.Curtain", function (DisplayObject, warn) { "use strict"; function Curtain (asset) { DisplayObject.apply(this, arguments); this.asset = asset; this.color = asset.getAttribute("color") || "black"; this.z = asset.getAttribute("z") || 20000; this.cssid = this.cssid || "WSECurtain_" + this.id; this.element.setAttribute("class", "asset WSECurtain"); this.element.style.left = 0; this.element.style.top = 0; this.element.style.width = this.stage.offsetWidth + "px"; this.element.style.height = this.stage.offsetHeight + "px"; this.element.style.opacity = 0; this.element.style.backgroundColor = this.color; } Curtain.prototype = Object.create(DisplayObject.prototype); Curtain.prototype.set = function (asset) { this.color = asset.getAttribute("color") || "black"; this.element.style.backgroundColor = this.color; }; Curtain.prototype.save = function () { return { color: this.color, cssid: this.cssid, z: this.z }; }; Curtain.prototype.restore = function (obj) { this.color = obj.color; this.cssid = obj.cssid; this.z = obj.z; try { this.element = document.getElementById(this.cssid); } catch (e) { warn(this.bus, "Element with CSS ID '" + this.cssid + "' could not be found."); return; } this.element.style.backgroundColor = this.color; this.element.style.zIndex = this.z; }; return Curtain; }); /* global using, console */ using( "transform-js::transform", "eases", "WSE.DisplayObject", "WSE.tools::applyAssetUnits", "WSE.tools::attachEventListener", "WSE.tools::extractUnit", "WSE.tools::calculateValueWithAnchor", "WSE.tools::warn" ). define("WSE.assets.Imagepack", function ( transform, easing, DisplayObject, applyUnits, attachListener, extractUnit, anchoredValue, warn ) { "use strict"; /** * Constructor function for ImagePacks. * * @param asset [DOM Element] The asset definition. * @param interpreter [WSE.Interpreter] The interpreter object. */ function Imagepack (asset) { var images, children, i, len, current, name; var src, image, self, triggerDecreaseFn, width, height; this._boxSizeSelectors = ["img"]; DisplayObject.apply(this, arguments); this.cssid = this.cssid || "wse_imagepack_" + this.name; self = this; images = {}; width = asset.getAttribute('width'); height = asset.getAttribute('height'); this.element.setAttribute("class", "asset imagepack"); children = asset.getElementsByTagName("image"); triggerDecreaseFn = self.bus.trigger.bind(self.bus, "wse.assets.loading.decrease", null, false); for (i = 0, len = children.length; i < len; i += 1) { current = children[i]; name = current.getAttribute("name"); src = current.getAttribute("src"); if (name === null) { warn(this.bus, "Image without name in imagepack '" + this.name + "'.", asset); continue; } if (src === null) { warn(this.bus, "Image without src in imagepack '" + this.name + "'.", asset); continue; } image = new Image(); this.bus.trigger("wse.assets.loading.increase", null, false); attachListener(image, 'load', triggerDecreaseFn); image.src = src; image.style.opacity = 0; image.style.position = "absolute"; image.draggable = false; image.setAttribute("data-wse-asset-image-name", name); if (width !== null) { image.setAttribute('width', width); } if (height !== null) { image.setAttribute('height', height); } images[name] = this.cssid + "_" + name; image.setAttribute("id", images[name]); this.element.appendChild(image); } this.images = images; this.current = null; } Imagepack.prototype = Object.create(DisplayObject.prototype); Imagepack.prototype.set = function (command, args) { var image, name, self, old, duration, isAnimation, bus = this.bus, element; args = args || {}; self = this; name = command.getAttribute("image"); duration = command.getAttribute("duration") || 400; isAnimation = args.animation === true ? true : false; if (name === null) { warn(bus, "Missing attribute 'image' on 'do' element " + "referencing imagepack '" + this.name + "'.", command); return { doNext: true }; } try { image = document.getElementById(this.images[name]); } catch (e) { console.error("DOM Element for Image " + name + " on Imagepack " + this.name + " not found!", e); } if (typeof image === "undefined" || image === null) { warn(bus, "Unknown image name on 'do' element referencing " + "imagepack '" + this.name + "'.", command); return { doNext: true }; } old = this.current; for (var key in this.images) { if (this.images.hasOwnProperty(key)) { if (key !== name) { continue; } if (key === old) { warn(bus, "Trying to set the image that is already set on imagepack '" + this.name + "'.", command); return { doNext: true }; } } } if (!isAnimation) { self.interpreter.waitCounter += 1; } element = document.getElementById(this.cssid); element.style.width = image.offsetWidth + "px"; element.style.height = image.offsetHeight + "px"; (function () { var valFn, finishFn, options; valFn = function (v) { image.style.opacity = v; }; finishFn = function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } }; options = { duration: duration, easing: easing.cubicOut }; transform(0, 1, valFn, options, finishFn); }()); if (this.current !== null) { if (!isAnimation) { self.interpreter.waitCounter += 1; } (function () { var timeoutFn; timeoutFn = function() { var oldEl, valFn, finishFn, options; oldEl = document.getElementById(self.images[old]); valFn = function (v) { oldEl.style.opacity = v; }; finishFn = function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } }; options = { duration: duration, easing: easing.cubicIn }; transform(1, 0, valFn, options, finishFn); }; timeoutFn(); }()); } this.current = name; return { doNext: true }; }; Imagepack.prototype.save = function () { var cur, images, obj; images = this.images; cur = this.current || null; obj = { assetType: "Imagepack", current: cur, cssid: this.cssid, images: images, xAnchor: this.xAnchor, yAnchor: this.yAnchor, z: this.z }; this.bus.trigger( "wse.assets.imagepack.save", { subject: this, saves: obj } ); return obj; }; Imagepack.prototype.restore = function (save) { var name; name = save.current; this.cssid = save.cssid; this.z = save.z; this.current = name; this.xAnchor = save.xAnchor; this.yAnchor = save.yAnchor; document.getElementById(this.cssid).style.zIndex = this.z; this.bus.trigger( "wse.assets.imagepack.restore", { subject: this, saves: save } ); }; return Imagepack; }); /* global using */ using( "transform-js::transform", "WSE.tools.reveal", "class-manipulator::list", "WSE.DisplayObject", "WSE.tools::applyAssetUnits", "WSE.tools::replaceVariables" ). define("WSE.assets.Textbox", function ( transform, reveal, classes, DisplayObject, applyUnits, replaceVars ) { "use strict"; function Textbox (asset) { this.z = 1000; DisplayObject.apply(this, arguments); var element, nameElement, textElement; this.type = asset.getAttribute("behaviour") || "adv"; this.showNames = asset.getAttribute("namebox") === "yes" ? true : false; this.nltobr = asset.getAttribute("nltobr") === "true" ? true : false; this.cssid = this.cssid || "wse_textbox_" + this.name; this.effectType = asset.getAttribute("effect") || "typewriter"; this.speed = asset.getAttribute("speed") || 0; this.speed = parseInt(this.speed, 10); this.fadeDuration = asset.getAttribute("fadeDuration") || 0; (function (ctx) { var el, i, len, elms; try { elms = asset.childNodes; for (i = 0, len = elms.length; i < len; i += 1) { if (elms[i].nodeType === 1 && elms[i].tagName === 'nameTemplate') { el = elms[i]; break; } } if (!el) { throw new Error('No nameTemplate found.'); } ctx.nameTemplate = new XMLSerializer().serializeToString(el); } catch (e) { ctx.nameTemplate = '{name}: '; } }(this)); if (this.type === "nvl") { this.showNames = false; } element = this.element; nameElement = document.createElement("div"); textElement = document.createElement("div"); element.setAttribute("class", "asset textbox"); textElement.setAttribute("class", "text"); nameElement.setAttribute("class", "name"); element.appendChild(nameElement); element.appendChild(textElement); if (this.showNames === false) { nameElement.style.display = "none"; } nameElement.setAttribute("id", this.cssid + "_name"); textElement.setAttribute("id", this.cssid + "_text"); this.nameElement = this.cssid + "_name"; this.textElement = this.cssid + "_text"; element.style.opacity = 0; this.bus.trigger("wse.assets.textbox.constructor", this); } Textbox.prototype = Object.create(DisplayObject.prototype); Textbox.prototype.put = function (text, name, speakerId) { var textElement, nameElement, namePart, self, cssClass = "wse_no_character", element; name = name || null; speakerId = speakerId || "_no_one"; self = this; textElement = document.getElementById(this.textElement); nameElement = document.getElementById(this.nameElement); element = document.getElementById(this.cssid); text = replaceVars(text, this.interpreter); self.interpreter.waitCounter += 1; namePart = ""; if (this.showNames === false && !(!name)) { namePart = this.nameTemplate.replace(/\{name\}/g, name); } if (name === null) { if (this.showNames) { nameElement.style.display = "none"; } name = ""; } else { if (this.showNames) { nameElement.style.display = ""; } cssClass = "wse_character_" + speakerId.split(" ").join("_"); } if (this._lastCssClass) { classes(element).remove(this._lastCssClass).apply(); } this._lastCssClass = cssClass; classes(element).add(cssClass).apply(); if (this.speed < 1) { if (this.fadeDuration > 0) { self.interpreter.waitCounter += 1; (function () { var valFn, finishFn, options; valFn = function (v) { textElement.style.opacity = v; }; finishFn = function () { self.interpreter.waitCounter -= 1; }; options = { duration: self.fadeDuration }; transform(1, 0, valFn, options, finishFn); }()); } else { putText(); } } if (this.speed > 0) { if (self.type === 'adv') { textElement.innerHTML = ""; } (function () { var container; container = document.createElement('div'); container.setAttribute('class', 'line'); textElement.appendChild(container); container.innerHTML = namePart + text; nameElement.innerHTML = self.nameTemplate.replace(/\{name\}/g, name); //self.interpreter.waitCounter += 1; self.interpreter.cancelCharAnimation = reveal( container, { speed: self.speed, onFinish: function () { //self.interpreter.waitCounter -= 1; self.interpreter.cancelCharAnimation = null; } } ).cancel; }()); } else if (this.fadeDuration > 0) { self.interpreter.waitCounter += 1; setTimeout( function () { putText(); if (self.type === 'nvl') { textElement.innerHTML = '<div>' + textElement.innerHTML + '</div>'; } transform( 0, 1, function (v) { textElement.style.opacity = v; }, { duration: self.fadeDuration, onFinish: function () { self.interpreter.waitCounter -= 1; } } ); }, self.fadeDuration ); } this.bus.trigger("wse.assets.textbox.put", this, false); self.interpreter.waitCounter -= 1; return { doNext: false }; function putText () { if (self.type === 'adv') { textElement.innerHTML = ""; } textElement.innerHTML += namePart + text; nameElement.innerHTML = self.nameTemplate.replace(/\{name\}/g, name); } }; Textbox.prototype.clear = function () { document.getElementById(this.textElement).innerHTML = ""; document.getElementById(this.nameElement).innerHTML = ""; this.bus.trigger("wse.assets.textbox.clear", this); return { doNext: true }; }; Textbox.prototype.save = function () { return { assetType: "Textbox", type: this.type, showNames: this.showNames, nltobr: this.nltobr, cssid: this.cssid, nameElement: this.nameElement, textElement: this.textElement, z: this.z }; }; Textbox.prototype.restore = function (save) { this.type = save.type; this.showNames = save.showNames; this.nltobr = save.nltobr; this.cssid = save.cssid; this.nameElement = save.nameElement; this.textElement = save.textElement; this.z = save.z; document.getElementById(this.cssid).style.zIndex = this.z; }; return Textbox; }); /* global using */ using("WSE.tools::applyAssetUnits", "WSE.DisplayObject", "WSE.tools::warn"). define("WSE.assets.Background", function (applyUnits, DisplayObject, warn) { "use strict"; function resize (self) { self.element.setAttribute("width", self.stage.offsetWidth); self.element.setAttribute("height", self.stage.offsetHeight); } function styleElement (self) { var s = self.element.style; self.element.setAttribute("id", self.cssid); self.element.setAttribute("class", "WSEBackground"); self.element.style.position = "absolute"; self.element.draggable = false; s.left = 0; s.top = 0; s.opacity = 0; s.zIndex = self.z; } function Background (asset) { this.elementType = "img"; DisplayObject.apply(this, arguments); var self = this; this.asset = asset; this.cssid = this.cssid || "WSEBackground_" + this.id; this.src = asset.getAttribute('src'); if (!this.src) { warn(this.bus, 'No source defined on background asset.', asset); return; } this.element.setAttribute('src', this.src); styleElement(this); resize(this); window.addEventListener('resize', function () { resize(self); }); } Background.prototype = Object.create(DisplayObject.prototype); Background.prototype.save = function () { return { cssid: this.cssid, z: this.z }; }; Background.prototype.restore = function (obj) { this.cssid = obj.cssid; this.z = obj.z; try { this.element = document.getElementById(this.cssid); } catch (e) { warn(this.bus, "Element with CSS ID '" + this.cssid + "' could not be found."); return; } }; return Background; }); /* global using */ using( "transform-js::transform", "eases", "WSE.DisplayObject", "WSE.tools::applyAssetUnits", "WSE.tools::attachEventListener", "WSE.tools::extractUnit", "WSE.tools::calculateValueWithAnchor", "WSE.tools::warn" ). define("WSE.assets.Composite", function ( transform, easing, DisplayObject, applyUnits, attachListener, extractUnit, anchoredValue, warn ) { "use strict"; /** * Constructor function for Composites. * * @param asset [DOM Element] The asset definition. * @param interpreter [WSE.Interpreter] The interpreter object. */ function Composite (asset) { var element, children; var self, triggerDecreaseFn, width, height; this._boxSizeSelectors = ["img"]; DisplayObject.apply(this, arguments); this.cssid = this.cssid || "wse_composite_" + this.name; self = this; element = this.element; width = this.width; height = this.height; element.setAttribute("class", "asset composite"); children = asset.getElementsByTagName("image"); triggerDecreaseFn = self.bus.trigger.bind(self.bus, "wse.assets.loading.decrease", null, false); [].forEach.call(children, function (current) { var tags, src, image; tags = current.getAttribute("tags"); src = current.getAttribute("src"); if (tags === null) { warn(self.bus, "Image without tags in composite '" + self.name + "'.", asset); return; } if (src === null) { warn(self.bus, "Image without src in composite '" + self.name + "'.", asset); return; } image = new Image(); self.bus.trigger("wse.assets.loading.increase", null, false); attachListener(image, 'load', triggerDecreaseFn); image.src = src; image.style.opacity = 0; image.style.position = "absolute"; image.draggable = false; image.setAttribute("data-wse-tags", tags); if (width !== null) { image.setAttribute('width', width); } if (height !== null) { image.setAttribute('height', height); } element.appendChild(image); }); this.current = []; } Composite.prototype = Object.create(DisplayObject.prototype); Composite.prototype.tag = function (command, args) { var self, old, duration, isAnimation, bus = this.bus, element; var toAdd, toRemove, imagesByTags, oldImages, newImages; args = args || {}; self = this; toAdd = extractTags(command.getAttribute("add") || ""); toRemove = extractTags(command.getAttribute("remove") || ""); duration = command.getAttribute("duration") || 400; isAnimation = args.animation === true ? true : false; if (!toAdd.length && !toRemove.length) { warn(bus, "No attribute 'add' or 'remove' on element " + "referencing composite '" + this.name + "'. Expected at least one.", command); return { doNext: true }; } old = this.current; if (toRemove.length && toRemove[0] === "*") { this.current = toAdd.slice(); } else { this.current = old.filter(function (tag) { return toRemove.indexOf(tag) < 0; }); toAdd.forEach(function (tag) { if (self.current.indexOf(tag) < 0) { self.current.push(tag); } }); } imagesByTags = getImagesByTags(this); oldImages = []; newImages = []; old.forEach(function (tag) { if (imagesByTags[tag]) { imagesByTags[tag].forEach(function (image) { if (oldImages.indexOf(image) < 0) { oldImages.push(image); } }); } }); this.current.forEach(function (tag) { if (imagesByTags[tag]) { imagesByTags[tag].forEach(function (image) { if (newImages.indexOf(image) < 0) { newImages.push(image); } }); } }); newImages = newImages.filter(function (image) { if (oldImages.indexOf(image) >= 0) { oldImages.splice(oldImages.indexOf(image), 1); return false; } return true; }); if (!isAnimation) { self.interpreter.waitCounter += 1; } element = document.getElementById(this.cssid); element.style.width = highest(newImages, "offsetWidth") + "px"; element.style.height = highest(newImages, "offsetHeight") + "px"; (function () { var valFn, finishFn, options; valFn = function (v) { newImages.forEach(function (image) { image.style.opacity = v; }); }; finishFn = function () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } }; options = { duration: duration, easing: easing.cubicOut }; transform(0, 1, valFn, options, finishFn); }()); if (this.current !== null) { if (!isAnimation) { self.interpreter.waitCounter += 1; } (function () { function timeoutFn () { var options; function valFn (v) { oldImages.forEach(function (image) { image.style.opacity = v; }); } function finishFn () { if (!isAnimation) { self.interpreter.waitCounter -= 1; } } options = { duration: duration, easing: easing.cubicIn }; transform(1, 0, valFn, options, finishFn); } timeoutFn(); }()); } return { doNext: true }; }; Composite.prototype.save = function () { var cur, obj; cur = this.current || []; obj = { assetType: "Composite", current: cur, cssid: this.cssid, xAnchor: this.xAnchor, yAnchor: this.yAnchor, z: this.z }; this.bus.trigger( "wse.assets.composite.save", { subject: this, saves: obj } ); return obj; }; Composite.prototype.restore = function (save) { this.cssid = save.cssid; this.z = save.z; this.current = save.current.slice(); this.xAnchor = save.xAnchor; this.yAnchor = save.yAnchor; this.element = document.getElementById(this.cssid); this.element.style.zIndex = this.z; this.bus.trigger( "wse.assets.composite.restore", { subject: this, saves: save } ); }; return Composite; function getImagesByTags (self) { var images, imagesByTag; images = document.getElementById(self.cssid).getElementsByTagName("img"); imagesByTag = {}; [].forEach.call(images, function (image) { var tags = extractTags(image.getAttribute("data-wse-tags") || ""); tags.forEach(function (tag) { if (!Array.isArray(imagesByTag[tag])) { imagesByTag[tag] = []; } imagesByTag[tag].push(image); }); }); return imagesByTag; } function extractTags (raw) { return raw.split(",").map(function (rawTag) { return rawTag.trim(); }); } function highest (all, key) { var biggest = 0; all.forEach(function (item) { if (item[key] > biggest) { biggest = item[key]; } }); return biggest; } }); /* global using */ using( "WSE.tools.ui", "WSE.tools", "WSE.tools::replaceVariables" ).define("WSE.commands.alert", function (ui, tools, replaceVars) { function alert (command, interpreter) { var title, message, doNext; title = command.getAttribute("title") || "Alert!"; message = command.getAttribute("message") || "Alert!"; doNext = replaceVars(command.getAttribute("next") || "", interpreter) === "false" ? false : true; message = replaceVars(message, interpreter); title = replaceVars(title, interpreter); message = tools.textToHtml(message); interpreter.bus.trigger("wse.interpreter.commands.alert", command); ui.alert( interpreter, { title: title, message: message, pause: true, doNext: doNext } ); return { doNext: true }; } return alert; }); /* global using */ using().define("WSE.commands.break", function () { "use strict"; function breakFn (command, interpreter) { interpreter.bus.trigger( "wse.interpreter.commands.break", { interpreter: interpreter, command: command }, false ); return { doNext: false, wait: true }; } return breakFn; }); /* global using */ using("WSE.tools", "WSE.DisplayObject"). define("WSE.commands.choice", function (tools, DisplayObject) { "use strict"; function choice (command, interpreter) { var menuElement, buttons, children, len, i, current; var currentButton, scenes, self, sceneName; var makeButtonClickFn, oldState, cssid; interpreter.bus.trigger( "wse.interpreter.commands.choice", { interpreter: interpreter, command: command }, false ); oldState = interpreter.state; interpreter.state = "pause"; buttons = []; scenes = []; self = interpreter; children = command.childNodes; len = children.length; cssid = command.getAttribute("cssid") || "WSEChoiceMenu"; makeButtonClickFn = function (cur, me, sc, idx) { sc = sc || null; return function (ev) { ev.stopPropagation(); ev.preventDefault(); setTimeout( function () { var childrenLen = cur.childNodes ? cur.childNodes.length : 0; var oldIndex = interpreter.index; var oldSceneId = interpreter.sceneId; var oldScenePath = interpreter.scenePath.slice(); var oldCurrentScene = interpreter.currentScene; if (sc !== null) { self.changeSceneNoNext(sc); } if (childrenLen > 0) { interpreter.pushToCallStack(); interpreter.currentCommands = cur.childNodes; interpreter.sceneId = oldSceneId; interpreter.scenePath = oldScenePath; interpreter.scenePath.push(oldIndex-1); interpreter.scenePath.push(idx); interpreter.index = 0; interpreter.currentScene = oldCurrentScene; interpreter.currentElement = 0; } self.next(); }, 0 ); self.stage.removeChild(me); interpreter.waitCounter -= 1; interpreter.state = oldState; }; }; if (len < 1) { interpreter.bus.trigger( "wse.interpreter.warning", { element: command, message: "Element 'choice' is empty. Expected at " + "least one 'option' element." } ); } menuElement = document.createElement("div"); menuElement.setAttribute("class", "menu"); menuElement.setAttribute("id", cssid); // associate HTML element with XML element; used when loading savegames: menuElement.setAttribute("data-wse-index", interpreter.index); menuElement.setAttribute("data-wse-scene-id", interpreter.sceneId); menuElement.setAttribute("data-wse-game", interpreter.game.url); menuElement.setAttribute("data-wse-type", "choice"); for (i = 0; i < len; i += 1) { current = children[i]; if (!current.tagName || current.tagName !== "option" || !interpreter.checkIfvar(current)) { continue; } currentButton = document.createElement("input"); currentButton.setAttribute("class", "button"); currentButton.setAttribute("type", "button"); currentButton.setAttribute("tabindex", i + 1); currentButton.setAttribute("value", current.getAttribute("label")); currentButton.value = tools.replaceVariables( current.getAttribute("label"), interpreter ); sceneName = current.getAttribute("scene") || null; scenes[i] = sceneName ? interpreter.getSceneById(sceneName) : null; tools.attachEventListener( currentButton, 'click', makeButtonClickFn(current, menuElement, scenes[i], i) ); buttons.push(currentButton); menuElement.appendChild(currentButton); } menuElement.style.opacity = 0; interpreter.stage.appendChild(menuElement); DisplayObject.prototype.show.call( undefined, command, { element: menuElement, bus: interpreter.bus, stage: interpreter.stage, interpreter: interpreter } ); interpreter.waitCounter += 1; return { doNext: false, wait: true }; } return choice; }); /* global using */ using("WSE.tools.ui").define("WSE.commands.confirm", function (ui) { return ui.makeInputFn("confirm"); }); /* global using */ using("WSE.tools::warn").define("WSE.commands.do", function (warn) { "use strict"; function doCommand (command, interpreter, args) { var assetName, action, bus = interpreter.bus, assets = interpreter.assets; args = args || {}; bus.trigger( "wse.interpreter.commands.do", { interpreter: interpreter, command: command }, false ); assetName = command.getAttribute("asset"); action = command.getAttribute("action"); if (assetName === null) { warn(bus, "Element of type 'do' must have an attribute 'asset'. " + "Element ignored.", command); return; } if (action === null) { warn(bus, "Element of type 'do' must have an attribute 'action'." + " Element ignored.", command); return; } if (typeof assets[assetName] === "undefined" || assets[assetName] === null) { warn(bus, "Reference to unknown asset '" + assetName + "'.", command); return { doNext: true }; } if (typeof assets[assetName][action] === "undefined") { warn(bus, "Action '" + action + "' is not defined for asset '" + assetName + "'.", command); return { doNext: true }; } return assets[assetName][action](command, args); } return doCommand; }); /* global using */ using("WSE.functions", "WSE.tools::warn").define("WSE.commands.fn", function (functions, warn) { "use strict"; function fn (command, interpreter) { var name, varName, ret; name = command.getAttribute("name") || null; varName = command.getAttribute("tovar") || null; if (typeof functions[name] !== "function") { warn(interpreter.bus, "No name supplied on fn element.", command); return { doNext: true }; } if (typeof functions[name] !== "function") { warn(interpreter.bus, "Unknown function '" + name + "'.", command); return { doNext: true }; } ret = functions[name](interpreter); if (varName !== null){ interpreter.runVars[varName] = "" + ret; } return { doNext: true }; } return fn; }); /* global using */ using("WSE.tools::warn").define("WSE.commands.global", function (warn) { "use strict"; function global (command, interpreter) { var name, value, next; name = command.getAttribute("name") || null; value = command.getAttribute("value") || null; next = {doNext: true}; if (name === null) { warn(interpreter.bus, "No name defined on element 'global'.", command); return next; } if (value === null) { warn(interpreter.bus, "No value defined on element 'global'.", command); return next; } interpreter.globalVars.set(name, value); return next; } return global; }); /* global using */ using("WSE.tools::warn").define("WSE.commands.globalize", function (warn) { "use strict"; function globalize (command, interpreter) { var key, next; key = command.getAttribute("name") || null; next = {doNext: true}; if (key === null) { warn(interpreter.bus, "No variable name defined on globalize element.", command); return next; } if (typeof interpreter.runVars[key] === "undefined" || interpreter.runVars[key] === null) { warn(interpreter.bus, "Undefined local variable.", command); return next; } interpreter.globalVars.set(key, interpreter.runVars[key]); return next; } return globalize; }); /* global using */ using( "WSE.tools::replaceVariables", "WSE.tools::logError" ). define("WSE.commands.goto", function (replaceVars, logError) { "use strict"; function gotoCommand (command, interpreter) { var scene, sceneName, bus = interpreter.bus; bus.trigger( "wse.interpreter.commands.goto", { interpreter: interpreter, command: command }, false ); sceneName = command.getAttribute("scene"); if (sceneName === null) { logError(bus, "Element 'goto' misses attribute 'scene'."); } sceneName = replaceVars(sceneName, interpreter); scene = interpreter.getSceneById(sceneName); if (scene === null) { logError(bus, "Unknown scene '" + sceneName + "'."); return; } return { changeScene: scene }; } return gotoCommand; }); /* global using */ using("WSE.tools::getSerializedNodes", "WSE.tools::warn"). define("WSE.commands.line", function (getSerializedNodes, warn) { "use strict"; function line (command, interpreter) { var speakerId, speakerName, textboxName, i, len, current; var assetElements, text, doNext, bus = interpreter.bus, next; next = {doNext: true}; bus.trigger( "wse.interpreter.commands.line", { interpreter: interpreter, command: command }, false ); speakerId = command.getAttribute("s"); doNext = command.getAttribute("stop") === "false" ? true : false; if (speakerId === null) { warn(bus, "Element 'line' requires attribute 's'.", command); return next; } assetElements = interpreter.story.getElementsByTagName("character"); len = assetElements.length; for (i = 0; i < len; i += 1) { current = assetElements[i]; if (current.getAttribute("name") === speakerId) { textboxName = current.getAttribute("textbox"); if (typeof textboxName === "undefined" || textboxName === null) { warn(bus, "No textbox defined for character '" + speakerId + "'.", command); return next; } try { speakerName = getSerializedNodes(current.getElementsByTagName("displayname")[0]).trim(); } catch (e) {} break; } } if (typeof interpreter.assets[textboxName] === "undefined") { warn(bus, "Trying to use an unknown textbox or character.", command); return next; } text = getSerializedNodes(command); interpreter.log.push({speaker: speakerId, text: text}); interpreter.assets[textboxName].put(text, speakerName, speakerId); return { doNext: doNext, wait: true }; } return line; }); /* global using */ using("WSE.tools::warn").define("WSE.commands.localize", function (warn) { "use strict"; function localize (command, interpreter) { var key, next; next = {doNext: true}; key = command.getAttribute("name") || null; if (key === null) { warn(interpreter.bus, "No variable name defined on localize element.", command); return next; } if (!interpreter.globalVars.has(key)) { warn(interpreter.bus, "Undefined global variable.", command); return next; } interpreter.runVars[key] = interpreter.globalVars.get(key); return next; } return localize; }); /* global using */ using("WSE.tools.ui").define("WSE.commands.prompt", function (ui) { return ui.makeInputFn("prompt"); }); /* global using */ using().define("WSE.commands.restart", function () { "use strict"; function restart (command, interpreter) { interpreter.bus.trigger( "wse.interpreter.commands.restart", { interpreter: interpreter, command: command }, false ); interpreter.bus.trigger("wse.interpreter.message", "Restarting game...", false); interpreter.bus.trigger("wse.interpreter.restart", interpreter, false); interpreter.runVars = {}; interpreter.log = []; interpreter.visitedScenes = []; interpreter.startTime = Math.round(+new Date() / 1000); interpreter.waitCounter = 0; interpreter.state = "listen"; interpreter.stage.innerHTML = ""; interpreter.assets = {}; interpreter.buildAssets(); interpreter.callOnLoad(); while (interpreter.callStack.length > 0) { interpreter.callStack.shift(); } return { doNext: true, changeScene: interpreter.getFirstScene() }; } return restart; }); /* global using */ using( "WSE.tools::replaceVariables", "WSE.commands.set_vars", "WSE.tools::warn", "WSE.tools::logError", "WSE.tools::log" ). define("WSE.commands.sub", function (replaceVars, setVars, warn, logError, log) { "use strict"; function sub (command, interpreter) { var sceneId, scene, doNext, next; interpreter.bus.trigger( "wse.interpreter.commands.sub", { interpreter: interpreter, command: command }, false ); next = {doNext: true}; sceneId = command.getAttribute("scene") || null; doNext = command.getAttribute("next") === false ? false : true; if (sceneId === null) { warn(interpreter.bus, "Missing 'scene' attribute on 'sub' command!", command); return next; } sceneId = replaceVars(sceneId, interpreter); scene = interpreter.getSceneById(sceneId); if (!scene) { logError(interpreter.bus, "No such scene '" + sceneId + "'!", command); return next; } log(interpreter.bus, "Entering sub scene '" + sceneId + "'..."); interpreter.pushToCallStack(); interpreter.currentCommands = scene.childNodes; interpreter.index = -1; interpreter.sceneId = sceneId; interpreter.scenePath = []; interpreter.currentElement = -1; if (command.getAttribute("names")) { setVars(command, interpreter); } return { doNext: doNext }; } return sub; }); /* global using */ using("WSE.tools::warn").define("WSE.commands.trigger", function (warn) { "use strict"; function trigger (command, interpreter) { var triggerName, action, next; next = {doNext: true}; interpreter.bus.trigger( "wse.interpreter.commands.trigger", { interpreter: interpreter, command: command }, false ); triggerName = command.getAttribute("name") || null; action = command.getAttribute("action") || null; if (triggerName === null) { warn(interpreter.bus, "No name specified on trigger command.", command); return next; } if (action === null) { warn(interpreter.bus, "No action specified on trigger command " + "referencing trigger '" + triggerName + "'.", command); return next; } if ( typeof interpreter.triggers[triggerName] === "undefined" || interpreter.triggers[triggerName] === null ) { warn(interpreter.bus, "Reference to unknown trigger '" + triggerName + "'.", command); return next; } if (typeof interpreter.triggers[triggerName][action] !== "function") { warn(interpreter.bus, "Unknown action '" + action + "' on trigger command referencing trigger '" + triggerName + "'.", command); return next; } interpreter.triggers[triggerName][action](command); return next; } return trigger; }); /* global using */ using("WSE.tools::replaceVariables", "WSE.tools::warn", "WSE.tools::log"). define("WSE.commands.var", function (replaceVars, warn, log) { "use strict"; function varCommand (command, interpreter) { var key, val, lval, action, container, next; next = {doNext: true}; interpreter.bus.trigger( "wse.interpreter.commands.var", { interpreter: interpreter, command: command }, false ); key = command.getAttribute("name") || null; val = command.getAttribute("value") || "1"; action = command.getAttribute("action") || "set"; if (key === null) { warn(interpreter.bus, "Command 'var' must have a 'name' attribute.", command); return next; } container = interpreter.runVars; if (action !== "set" && !(key in container || command.getAttribute("lvalue"))) { warn(interpreter.bus, "Undefined variable.", command); return next; } val = replaceVars(val, interpreter); if (action === "set") { container[key] = "" + val; return next; } lval = command.getAttribute("lvalue") || container[key]; lval = replaceVars(lval, interpreter); switch (action) { case "delete": delete container[key]; break; case "increase": container[key] = "" + (parseFloat(lval) + parseFloat(val)); break; case "decrease": container[key] = "" + (parseFloat(lval) - parseFloat(val)); break; case "multiply": container[key] = "" + (parseFloat(lval) * parseFloat(val)); break; case "divide": container[key] = "" + (parseFloat(lval) / parseFloat(val)); break; case "modulus": container[key] = "" + (parseFloat(lval) % parseFloat(val)); break; case "and": container[key] = "" + (parseFloat(lval) && parseFloat(val)); break; case "or": container[key] = "" + (parseFloat(lval) || parseFloat(val)); break; case "not": container[key] = parseFloat(lval) ? "0" : "1"; break; case "is_greater": container[key] = parseFloat(lval) > parseFloat(val) ? "1" : "0"; break; case "is_less": container[key] = parseFloat(lval) < parseFloat(val) ? "1" : "0"; break; case "is_equal": container[key] = parseFloat(lval) === parseFloat(val) ? "1" : "0"; break; case "not_greater": container[key] = parseFloat(lval) <= parseFloat(val) ? "1" : "0"; break; case "not_less": container[key] = parseFloat(lval) >= parseFloat(val) ? "1" : "0"; break; case "not_equal": container[key] = parseFloat(lval) !== parseFloat(val) ? "1" : "0"; break; case "print": log(interpreter.bus, "Variable '" + key + "' is: " + container[key]); break; default: warn(interpreter.bus, "Unknown action '" + action + "' defined on 'var' command.", command); } return next; } return varCommand; }); /* global using */ using("WSE.tools::logError").define("WSE.commands.set_vars", function (logError) { "use strict"; function setVars (command, interpreter) { var container = interpreter.runVars, keys, values, next; next = {doNext: true}; keys = (command.getAttribute("names") || "").split(","); values = (command.getAttribute("values") || "").split(","); if (keys.length !== values.length) { logError(interpreter.bus, "Number of names does not match number of values " + "in <set_vars> command."); return next; } keys.forEach(function (key, i) { container[key.trim()] = "" + values[i].trim(); }); return next; } return setVars; }); /* global using */ using().define("WSE.commands.wait", function () { "use strict"; function wait (command, interpreter) { var duration, self; interpreter.bus.trigger( "wse.interpreter.commands.wait", { interpreter: interpreter, command: command }, false ); self = interpreter; duration = command.getAttribute("duration"); if (duration !== null) { duration = parseInt(duration, 10); interpreter.waitForTimer = true; setTimeout( function () { self.waitForTimer = false; }, duration ); return { doNext: true, wait: false }; } return { doNext: true, wait: true }; } return wait; }); /* global using */ using("WSE.tools::getParsedAttribute", "WSE.tools::warn"). define("WSE.commands.with", function (getParsedAttribute, warn) { "use strict"; function withCommand (command, interpreter) { var container = interpreter.runVars; var children = command.childNodes; var variableName = getParsedAttribute(command, "var", interpreter); var i, numberOfChildren = children.length, current; for (i = 0; i < numberOfChildren; i += 1) { current = children[i]; if (shouldBeSkipped(current, interpreter)) { continue; } if (isWhen(current) && !hasCondition(current)) { warn(interpreter.bus, "Element 'when' without a condition. Ignored.", command); } if (isElse(current) && hasCondition(current)) { warn(interpreter.bus, "Element 'else' with a condition. Ignored.", command); } if (isElse(current) || isWhen(current) && hasCondition(current) && getParsedAttribute(current, "is") === container[variableName]) { interpreter.pushToCallStack(); interpreter.currentCommands = current.childNodes; interpreter.scenePath.push(interpreter.index); interpreter.scenePath.push(i); interpreter.index = -1; interpreter.currentElement = -1; break; } } return { doNext: true }; } return withCommand; function shouldBeSkipped (element, interpreter) { return !element.tagName || !interpreter.checkIfvar(element) || (element.tagName !== "when" && element.tagName !== "else"); } function isWhen (element) { return tagNameIs(element, "when"); } function isElse (element) { return tagNameIs(element, "else"); } function tagNameIs (element, name) { return element.tagName === name; } function hasCondition (element) { return element.hasAttribute("is"); } }); /* global using */ using().define("WSE.commands.while", function () { "use strict"; function whileCommand (command, interpreter) { interpreter.index -= 1; interpreter.currentElement -= 1; interpreter.pushToCallStack(); interpreter.currentCommands = command.childNodes; interpreter.scenePath.push(interpreter.index+1); interpreter.index = -1; interpreter.currentElement = -1; return { doNext: true }; } return whileCommand; });
jsteinbeck/WebStory-Engine
build/WebStoryEngine.js
JavaScript
bsd-3-clause
517,692
var appBase = require("../app_base/app"); var config = { host: "192.168.1.35", port: 8080 }; appBase.init(config);
B4U/TSKL
examples/demo/app1/app.js
JavaScript
bsd-3-clause
119
var RS = new RemoteScripting(); function RemoteScripting() { this.pool = new Array(); this.poolSize = 0; this.maxPoolSize = 1000; this.usePOST = false; this.debug = false; // Sniff the browser if (document.layers) this.browser = "NS"; else if (document.all) { var agent = navigator.userAgent.toLowerCase(); if (agent.indexOf("opera") != -1) this.browser = "OPR"; else if (agent.indexOf("konqueror") != -1) this.browser = "KONQ"; else this.browser = "IE"; } else if (document.getElementById) this.browser = "MOZ"; else this.browser = "OTHER"; } RemoteScripting.prototype.Execute = function(url, method) { var call = this.getAvailableCall(); var args = RemoteScripting.prototype.Execute.arguments; var len = RemoteScripting.prototype.Execute.arguments.length; var methodArgs = new Array(); for (var i = 2; i < len; i++) { if (typeof(args[i]) == 'function') { call.callback = args[i++]; if (i < len && typeof(args[i]) == 'function') call.callbackForError = args[i++]; var ca = 0; for (; i < len; i++) call.callbackArgs[ca++] = args[i]; break; } methodArgs[i - 2] = args[i]; } call.showIfDebugging(); if (this.usePOST && ((this.browser == 'IE') || (this.browser == 'MOZ'))) call.POST(url, method, methodArgs); else call.GET(url, method, methodArgs); return this.id; } RemoteScripting.prototype.PopupDebugInfo = function() { var doc = window.open().document; doc.open(); doc.write('<html><body>Pool Size: ' + this.poolSize + '<br><font face = "arial" size = "2"><b>'); for (var i = 0; i < this.pool; i++) { var call = this.pool[i]; doc.write('<hr>' + call.id + ' : ' + (call.busy ? 'busy' : 'available') + '<br>'); doc.write(call.container.document.location.pathname + '<br>'); doc.write(call.container.document.location.search + '<br>'); doc.write('<table border = "1"><tr><td>' + call.container.document.body.innerHTML + '</td></tr></table>'); } doc.write('</table></body></html>'); doc.close(); return false; } RemoteScripting.prototype.ReplaceOptions = function(element, optionsHTML) { // Remove any existing options while (element.options.length > 0) element.options[0] = null; // Create an array of each item for the dropdown var options = optionsHTML.split("</option>"); var selectIndex = 0; var quote = (optionsHTML.indexOf("\"") > 0 ? "\"" : "'"); // Fill 'er up for (var i = 0; i < options.length - 1; i++) { aValueText = options[i].split(">"); option = new Option; option.text = aValueText[aValueText.length - 1]; // Account for the possibility of a value containing a > for (var e = 1; e < aValueText.length - 1; e++) aValueText[0] += ">" + aValueText[e]; // Extract the value var firstQuote = aValueText[0].indexOf(quote); var lastQuote = aValueText[0].lastIndexOf(quote); if (firstQuote > 0 && lastQuote > firstQuote + 1) option.value = aValueText[0].substring(firstQuote + 1, lastQuote); // Check if it's selected if (aValueText[0].indexOf('selected') > 0) selectIndex = i; element.options[element.options.length] = option; } element.options[selectIndex].selected = true; } RemoteScripting.prototype.ReplaceOptions2 = function(optionsHTML, element) { RS.ReplaceOptions(element, optionsHTML); window.status = ""; } RemoteScripting.prototype.getAvailableCall = function() { for (var i = 0; i < this.poolSize; i++) { var call = this.pool['C' + (i + 1)]; if (!call.busy) { call.busy = true; return this.pool[call.id]; } } // If we got here, there are no existing free calls if (this.poolSize <= this.maxPoolSize) { var callID = "C" + (this.poolSize + 1); this.pool[callID] = new RemoteScriptingCall(callID); this.poolSize++; return this.pool[callID]; } alert("RemoteScripting Error: Call pool is full (no more than 1000 calls can be made simultaneously)."); return null; } function RemoteScriptingCall(callID) { this.id = callID; this.busy = true; this.callback = null; this.callbackForError = null; this.callbackArgs = new Array(); switch (RS.browser) { case 'IE': document.body.insertAdjacentHTML("afterBegin", '<span id = "SPAN' + callID + '"></span>'); this.span = document.all("SPAN" + callID); var html = '<iframe style = "width:800px" name = "' + callID + '" src = "./"></iframe>'; this.span.innerHTML = html; this.span.style.display = 'none'; this.container = window.frames[callID]; break; case 'NS': this.container = new Layer(100); this.container.name = callID; this.container.visibility = 'hidden'; this.container.clip.width = 100; this.container.clip.height = 100; break; case 'MOZ': this.span = document.createElement('SPAN'); this.span.id = "SPAN" + callID; document.body.appendChild(this.span); var iframe = document.createElement('IFRAME'); iframe.id = callID; iframe.name = callID; iframe.style.width = 800; iframe.style.height = 200; this.span.appendChild(iframe); this.container = iframe; break; case 'OPR': this.span = document.createElement('SPAN'); this.span.id = "SPAN" + callID; document.body.appendChild(this.span); var iframe = document.createElement('IFRAME'); iframe.id = callID; iframe.name = callID; iframe.style.width = 800; iframe.style.height = 200; this.span.appendChild(iframe); this.container = iframe; break; case 'KONQ': default: this.span = document.createElement('SPAN'); this.span.id = "SPAN" + callID; document.body.appendChild(this.span); var iframe = document.createElement('IFRAME'); iframe.id = callID; iframe.name = callID; iframe.style.width = 800; iframe.style.height = 200; this.span.appendChild(iframe); this.container = iframe; // Needs to be hidden for Konqueror, otherwise it'll appear on the page this.span.style.display = none; iframe.style.display = none; iframe.style.visibility = hidden; iframe.height = 0; iframe.width = 0; } } RemoteScriptingCall.prototype.POST = function(url, method, args) { var d = new Date(); var unique = d.getTime() + '' + Math.floor(1000 * Math.random()); var doc = (RS.browser == "IE") ? this.container.document : this.container.contentDocument; var paramSep = (url.lastIndexOf('?') < 0 ? '?' : '&'); doc.open(); doc.write('<html><body>'); doc.write('<form name="rsForm" method="post" target=""'); doc.write('action="' + url + paramSep + 'U=' + unique + '">'); doc.write('<input type="hidden" name="RC" value="' + this.id + '">'); // func and args are optional if (method != null) { doc.write('<input type = "hidden" name = "M" value = "' + method + '">'); if (args != null) { if (typeof(args) == "string") { // single parameter doc.write('<input type = "hidden" name = "P0" ' + 'value = "[' + this.escapeParam(args) + ']">'); } else { // assume args is array of strings for (var i = 0; i < args.length; i++) { doc.write('<input type = "hidden" name = "P' + i + '" ' + 'value = "[' + this.escapeParam(args[i]) + ']">'); } } // parm type } // args } // method doc.write('</form></body></html>'); doc.close(); doc.forms['rsForm'].submit(); } RemoteScriptingCall.prototype.GET = function(url, method, args) { // build URL to call var URL = url; var paramSep = (url.lastIndexOf('?') < 0 ? '?' : '&'); // always send call URL += paramSep + "RC=" + this.id; // method and args are optional if (method != null) { URL += "&M=" + escape(method); if (args != null) { if (typeof(args) == "string") { // single parameter URL += "&P0=[" + escape(args + '') + "]"; } else { // assume args is array of strings for (var i = 0; i < args.length; i++) { URL += "&P" + i + "=[" + escape(args[i] + '') + "]"; } } // parm type } // args } // method // unique string to defeat cache var d = new Date(); URL += "&U=" + d.getTime(); // make the call switch (RS.browser) { case 'IE': this.container.document.location.replace(URL); break; case 'NS': this.container.src = URL; break; case 'MOZ': case 'OPR': case 'KONQ': default: this.container.src = ''; this.container.src = URL; break; } } RemoteScriptingCall.prototype.setResult = function(result) { var argsCount = this.callbackArgs.length; if (result == true) { if (this.callback != null) this.callback(this.unescape(this.getPayload()), argsCount > 0 ? this.callbackArgs[0] : null, argsCount > 1 ? this.callbackArgs[1] : null, argsCount > 2 ? this.callbackArgs[2] : null); } else { if (this.callbackForError == null) alert(this.unescape(this.getPayload())); else this.callbackForError(this.unescape(this.getPayload()), argsCount > 0 ? this.callbackArgs[0] : null, argsCount > 1 ? this.callbackArgs[1] : null, argsCount > 2 ? this.callbackArgs[2] : null); } this.callback = null; this.callbackForError = null; this.callbackArgs = new Array(); this.busy = false; } RemoteScriptingCall.prototype.getPayload = function() { switch (RS.browser) { case 'IE': return this.container.document.forms['rsForm']['rsPayload'].value; case 'NS': return this.container.document.forms['rsForm'].elements['rsPayload'].value; case 'MOZ': return window.frames[this.container.name].document.forms['rsForm']['rsPayload'].value; case 'OPR': return window.frames[this.container.name].document.forms['rsForm']['rsPayload'].value; case 'KONQ': default: return window.frames[this.container.name].document.getElementById("rsPayload").value; } } RemoteScriptingCall.prototype.showIfDebugging = function() { var vis = (RS.debug == true); switch (RS.browser) { case 'IE': document.all("SPAN" + this.id).style.display = (vis) ? '' : 'none'; break; case 'NS': this.container.visibility = (vis) ? 'show' : 'hidden'; break; case 'MOZ': case 'OPR': case 'KONQ': default: document.getElementById("SPAN" + this.id).style.visibility = (vis) ? '' : 'hidden'; this.container.width = (vis) ? 250 : 0; this.container.height = (vis) ? 100 : 0; break; } } RemoteScriptingCall.prototype.escapeParam = function(str) { return str.replace(/'"'/g, '\\"'); } RemoteScriptingCall.prototype.unescape = function(str) { return str.replace(/\\\//g, "/"); }
BackupTheBerlios/wc3o-svn
web/trunk/Game/Scripts/RemoteScripting.js
JavaScript
bsd-3-clause
10,815
provided_data = {{ provided_data|safe }}; function loadAdditionalData(adata) { $.ajax({ method: "GET", url: "{% url 'device-details-json' device_id %}", }).done(function(data) { if (data.formatted_entries) { adata.provided_data = data.formatted_entries; } if (data.raw_entries) { adata.raw_provided_data = data.raw_entries; } }).fail(function() { }); } function deviceDetail() { return { provided_data: provided_data, raw_provided_data: [], onLoad() { loadAdditionalData(this); }, storedAt() { if (this.provided_data && this.provided_data.length > 0) { return this.provided_data[0].stored_at; } else { return ""; } } } }
MPIB/Lagerregal
templates/devices/detail/device_detail.js
JavaScript
bsd-3-clause
883
/* * Copyright (c) 2014 Jesse van den Kieboom. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var utils = require('../utils/utils'); /** * Render an object from a geometry buffer. A RendeGroup is a wrapper * around an element array buffer, containing element indices into * an existing Geometry. * * @param ctx the context. * @param geometry a Geometry. * @param indices the indices in the geometry to render. * @param options optional options, defaults to <binding:gl.STATIC_DRAW, type:gl.TRIANGLES>. */ function RenderGroup(ctx, geometry, indices, options) { this._ibo = null; this._geometry = null; this.update(ctx, geometry, indices, options); } /** * Update the render group. * * @param ctx the context. * @param geometry a Geometry. * @param indices the indices in the geometry to render. * @param options optional options, defaults to <binding:gl.STATIC_DRAW, type:gl.TRIANGLES>. */ RenderGroup.prototype.update = function(ctx, geometry, indices, options) { var gl = ctx.gl; this.geometry = geometry; this.indices = indices; var opts = utils.merge({ binding: gl.STATIC_DRAW, type: gl.TRIANGLES, aabbox: null }, options); this.type = opts.type; this.aabbox = opts.aabbox; if (this._ibo) { gl.deleteBuffer(this._ibo); } if (indices && (typeof indices !== 'object' || Object.getPrototypeOf(indices) !== Uint16Array.prototype)) { indices = new Uint16Array(indices); } this._ibo = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._ibo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, opts.binding); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); this.length = indices.length; }; /** * Get all render parts of the render group. Note that this just returns * an array with a single element, this. */ RenderGroup.prototype.renderParts = function() { if (this.length === 0) { return []; } return [this]; }; /** * Bind the render group in the given context. * * @param ctx the context. */ RenderGroup.prototype.bind = function(ctx) { var gl = ctx.gl; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._ibo); }; /** * Unbind the render group from the given context. * * @param ctx the context. */ RenderGroup.prototype.unbind = function(ctx) { var gl = ctx.gl; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); }; /** * Render the render group. * * @param ctx the context. */ RenderGroup.prototype.render = function(ctx) { var gl = ctx.gl; this.bind(ctx); ctx._renderedSomething = true; gl.drawElements(this.type, this.length, gl.UNSIGNED_SHORT, 0); this.unbind(ctx); }; module.exports = RenderGroup; // vi:ts=4:et
jessevdk/webgl-play
js/models/rendergroup.js
JavaScript
bsd-3-clause
4,245
define([ 'jquery', ], function( $ ) { var ConsoleBlock = function(class_name) { this.console_blocks = $(class_name); this.init(); }; ConsoleBlock.prototype = { init: function(){ var self = this; $(document).ready(function () { $(".c-tab-unix").on("click", function() { $("section.c-content-unix").show(); $("section.c-content-win").hide(); $(".c-tab-unix").prop("checked", true); }); $(".c-tab-win").on("click", function() { $("section.c-content-win").show(); $("section.c-content-unix").hide(); $(".c-tab-win").prop("checked", true); }); }); } }; // Export a single instance of our module: return new ConsoleBlock('.console-block'); });
django/djangoproject.com
djangoproject/static/js/mod/console-tabs.js
JavaScript
bsd-3-clause
921
/** * Import success pane * * Displays success messages if import went fine :) * * - It needs a model to know what happened with the import. * * new cdb.admin.ImportSuccessPane({ model: state_model }); * */ cdb.admin.ImportSuccessPane = cdb.core.View.extend({ className: 'create-success', initialize: function() { this.template = cdb.templates.getTemplate(this.options.template || 'common/views/import/import_success'); this._initBinds(); this.render(); }, render: function() { var service = this.model.get("upload") && this.model.get('option') || ""; var tweets_cost = this.model.get("upload") && this.model.get('upload').tweets_cost || 0; var tweets_overquota = this.model.get("upload") && this.model.get('upload').tweets_overquota || false; var tweets_georeferenced = this.model.get("upload") && cdb.Utils.formatNumber(this.model.get('upload').tweets_georeferenced) || 0; var table_name = this.model.get("upload") && this.model.get('upload').table_name; var tweets_left = this.model.get("upload") && cdb.Utils.formatNumber(this.model.get('upload').tweets_left) || 0; var d = { service: service, tweets_cost: tweets_cost, tweets_overquota: tweets_overquota, tweets_georeferenced: tweets_georeferenced, table_name: table_name, tweets_left: tweets_left }; this.$el.html(this.template(d)); return this; }, _initBinds: function() { this.model.bind('change', this.render, this); } });
comilla/map
lib/assets/javascripts/cartodb/common/import/import_success_pane.js
JavaScript
bsd-3-clause
1,643
$(document).ready(function() { var link = '<a href="#" class="prompt-toggle">Toggle Prompt</a><br /><br />'; $(link).prependTo( $("div.code.python,div.highlight-python > .highlight > pre") ); $(".prompt-toggle").click(function (e) { e.preventDefault(); $(this.parentElement).find("span.gp").toggle(); }); });
anacode/anacode-toolkit
docs/source/_static/js/toggable_prompt.js
JavaScript
bsd-3-clause
340
import glob from 'glob'; import fs from 'fs'; const fileExists = filePath => { try { return fs.statSync(filePath).isFile(); } catch (err) { return false; } }; const filesConverted = []; const filesRemaining = []; glob('**/*.js', { ignore: ['**/es6/**','**/node_modules/**', '**/bower_components/**'] }, (err, files) => { for(let file of files) { let es6File = file.replace(/(.*)\/(.*)/, "$1/es6/$2"); if (es6File.indexOf('/') === -1) es6File = 'es6/' + es6File; if (fileExists(es6File)) filesConverted.push(es6File); else filesRemaining.push(file); } const summary = () => { console.log('\n'); console.log('Total JS files: ', filesConverted.length + filesRemaining.length); console.log('Converted: ', filesConverted.length); console.log('Remaining: ', filesRemaining.length); console.log('% Completed: ', filesConverted.length/(filesConverted.length + filesRemaining.length)); console.log('\n'); }; summary(); console.log('Remaining:'); console.log(filesRemaining); console.log('\n'); console.log('Converted:'); console.log(filesConverted); summary(); });
openAgile/CommitStream.Web
src/app/es6/hitlist.js
JavaScript
bsd-3-clause
1,135
import * as actions from './v3_keystore_actions'; export default { actions, };
soundchain/soundchain-frontend
src/js/keystoreTypes/v3/index.js
JavaScript
bsd-3-clause
82
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* jshint newcap: false */ var _ = require('lodash'); var domready = require('domready'); var React = require('react'); var ReactDOM = require('react-dom'); var dom = require('./dom'); var Sidebar = React.createFactory(require('./sidebar')); var Toc = React.createFactory(require('./toc')); domready(function() { var sidebarEl = dom.find('.sidebar'); if (sidebarEl) { ReactDOM.render(Sidebar({ subsite: sidebarEl.dataset.subsite, items: parseSidebarProps(dom.find('.sidebar-data')) }), sidebarEl); // Menu toggle, for small screens. var obfuscatorEl = dom.element('div'); obfuscatorEl.classList.add('mdl-layout__obfuscator'); dom.find('body').appendChild(obfuscatorEl); function showSidebar() { sidebarEl.classList.add('is-visible'); obfuscatorEl.classList.add('is-visible'); } function hideSidebar() { sidebarEl.classList.remove('is-visible'); obfuscatorEl.classList.remove('is-visible'); } obfuscatorEl.addEventListener('click', hideSidebar); dom.find('header .icon').addEventListener('click', showSidebar); } // Render table of contents if requested and there are headings. var el = dom.find('.toc'); if (el) { var props = parseTocProps(); if ((props.headings || []).length > 0) { ReactDOM.render(Toc(props), el); } else { el.parentNode.removeChild(el); } } // Init syntax highlighting. require('./highlight')(); // Add copy-to-clipboard buttons to code blocks, but only for certain sections // of the site. var pathname = window.location.pathname; if (pathname.match(/(tutorials|installation|contributing|syncbase)/)) { require('./clipboard')(); } // Run the scroll listener on landing page only. Other pages have the header // fixed. if (pathname === '/' || pathname === '/index.html') { var body = document.body; function onScroll() { if(body.scrollTop < 15) { body.classList.add('not-scrolled'); } else { body.classList.remove('not-scrolled'); } } onScroll(); document.addEventListener('scroll', onScroll); } // Update img elements to display alt text in a figcaption. dom.all('main img').forEach(function(img) { var a = dom.element('a'); a.setAttribute('href', img.src); a.setAttribute('target', '_blank'); a.appendChild(img.cloneNode()); var caption = dom.element('figcaption', img.alt); var figure = dom.element('figure'); figure.appendChild(a); figure.appendChild(caption); img.parentNode.replaceChild(figure, img); }); // Open external links in a new tab. var links = document.links; for (var i = 0; i < links.length; i++) { if (links[i].hostname !== window.location.hostname) { links[i].target = '_blank'; } } }); function parseSidebarProps(el) { return _.map(_.filter(dom.all(el, 'a'), function(a) { return a.parentNode === el; }), function(a) { var text = a.innerText; if (a.className !== 'nav') { return {text: text, href: a.href}; } var nav = a.nextElementSibling; console.assert(nav.tagName === 'NAV'); return {text: text, items: parseSidebarProps(nav)}; }); } function parseTocProps() { // Note, we ignore nested headers such as those inside info boxes. var hs = dom.all('main > h1, main > h2, main > h3, main > h4'); var titleEl = _.find(hs, function(el) { return el.classList.contains('title'); }); var headings = []; _.forEach(hs, function(el) { if (el === titleEl || !el.id) { return; } headings.push({ id: el.id, text: el.innerText, level: parseInt(el.tagName.split('')[1]), isAboveWindow: function() { return el.getBoundingClientRect().top < 0; }, isBelowWindow: function() { return el.getBoundingClientRect().bottom > window.innerHeight; } }); }); return { title: titleEl.innerText, headings: headings }; }
vanadium/website
browser/index.js
JavaScript
bsd-3-clause
4,154
define( { "id": 1, "testSpecs": { "name": "Test 1", "description": "Test 1", "items": 300, "maxOmissions": 0, "duration": 5 }, "testItems": { "instructions": [ { "id": 1, "testletId": 1, "title": "Titolo istruzioni testlet 1", "text": "<b>Istruzioni testlet 1</b>: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non arcu vel mi pulvinar congue eget id dolor. Praesent ullamcorper gravida iaculis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ullamcorper placerat vestibulum. Mauris at sagittis metus. Integer ligula odio, semper a eros consequat, maximus viverra lacus. Integer pharetra mauris ex, ut vehicula nunc iaculis ut. Vivamus ac euismod justo. Sed at lacinia lacus. Nullam rhoncus aliquam orci et auctor. In porttitor felis nec sem dapibus ultrices. Praesent in maximus libero. Aliquam ultricies eu odio id interdum. Nullam turpis magna, tristique sollicitudin cursus ac, luctus quis metus. Ut pretium ligula vitae nisl facilisis, sit amet feugiat arcu gravida.", "media": { "files": [ ], "audio": [ ], "videos": [ ], "images": [ "tests/1/images/img1.png", "tests/1/images/img2.png" ] } }, { "id": 2, "testletId": 1, "title": "Titolo istruzioni testlet 2", "text": "<b>Istruzioni testlet 2</b>: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non arcu vel mi pulvinar congue eget id dolor. Praesent ullamcorper gravida iaculis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ullamcorper placerat vestibulum. Mauris at sagittis metus. Integer ligula odio, semper a eros consequat, maximus viverra lacus. Integer pharetra mauris ex, ut vehicula nunc iaculis ut. Vivamus ac euismod justo. Sed at lacinia lacus. Nullam rhoncus aliquam orci et auctor. In porttitor felis nec sem dapibus ultrices. Praesent in maximus libero. Aliquam ultricies eu odio id interdum. Nullam turpis magna, tristique sollicitudin cursus ac, luctus quis metus. Ut pretium ligula vitae nisl facilisis, sit amet feugiat arcu gravida.", "media": { "files": [ ], "audio": [ ], "videos": [ ], "images": [ "tests/1/images/img1.png", "tests/1/images/img2.png" ] } } ], "items": [ { "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }, { "id": 5 }, { "id": 6 }, { "id": 7 }, { "id": 8 }, { "id": 9 }, { "id": 10 }, { "id": 11 }, { "id": 12 }, { "id": 13 }, { "id": 14 }, { "id": 15 }, { "id": 16 }, { "id": 17 }, { "id": 18 }, { "id": 19 }, { "id": 20 }, { "id": 21 }, { "id": 22 }, { "id": 23 }, { "id": 24 }, { "id": 25 }, { "id": 26 }, { "id": 27 }, { "id": 28 }, { "id": 29 }, { "id": 30 }, { "id": 31 }, { "id": 32 }, { "id": 33 }, { "id": 34 }, { "id": 35 }, { "id": 36 }, { "id": 37 }, { "id": 38 }, { "id": 39 }, { "id": 40 }, { "id": 41 }, { "id": 42 }, { "id": 43 }, { "id": 44 }, { "id": 45 }, { "id": 46 }, { "id": 47 }, { "id": 48 }, { "id": 49 }, { "id": 50 }, { "id": 51 }, { "id": 52 }, { "id": 53 }, { "id": 54 }, { "id": 55 }, { "id": 56 }, { "id": 57 }, { "id": 58 }, { "id": 59 }, { "id": 60 }, { "id": 61 }, { "id": 62 }, { "id": 63 }, { "id": 64 }, { "id": 65 }, { "id": 66 }, { "id": 67 }, { "id": 68 }, { "id": 69 }, { "id": 70 }, { "id": 71 }, { "id": 72 }, { "id": 73 }, { "id": 74 }, { "id": 75 }, { "id": 76 }, { "id": 77 }, { "id": 78 }, { "id": 79 }, { "id": 80 }, { "id": 81 }, { "id": 82 }, { "id": 83 }, { "id": 84 }, { "id": 85 }, { "id": 86 }, { "id": 87 }, { "id": 88 }, { "id": 89 }, { "id": 90 }, { "id": 91 }, { "id": 92 }, { "id": 93 }, { "id": 94 }, { "id": 95 }, { "id": 96 }, { "id": 97 }, { "id": 98 }, { "id": 99 }, { "id": 100 }, { "id": 101 }, { "id": 102 }, { "id": 103 }, { "id": 104 }, { "id": 105 }, { "id": 106 }, { "id": 107 }, { "id": 108 }, { "id": 109 }, { "id": 110 }, { "id": 111 }, { "id": 112 }, { "id": 113 }, { "id": 114 }, { "id": 115 }, { "id": 116 }, { "id": 117 }, { "id": 118 }, { "id": 119 }, { "id": 120 }, { "id": 121 }, { "id": 122 }, { "id": 123 }, { "id": 124 }, { "id": 125 }, { "id": 126 }, { "id": 127 }, { "id": 128 }, { "id": 129 }, { "id": 130 }, { "id": 131 }, { "id": 132 }, { "id": 133 }, { "id": 134 }, { "id": 135 }, { "id": 136 }, { "id": 137 }, { "id": 138 }, { "id": 139 }, { "id": 140 }, { "id": 141 }, { "id": 142 }, { "id": 143 }, { "id": 144 }, { "id": 145 }, { "id": 146 }, { "id": 147 }, { "id": 148 }, { "id": 149 }, { "id": 150 }, { "id": 151 }, { "id": 152 }, { "id": 153 }, { "id": 154 }, { "id": 155 }, { "id": 156 }, { "id": 157 }, { "id": 158 }, { "id": 159 }, { "id": 160 }, { "id": 161 }, { "id": 162 }, { "id": 163 }, { "id": 164 }, { "id": 165 }, { "id": 166 }, { "id": 167 }, { "id": 168 }, { "id": 169 }, { "id": 170 }, { "id": 171 }, { "id": 172 }, { "id": 173 }, { "id": 174 }, { "id": 175 }, { "id": 176 }, { "id": 177 }, { "id": 178 }, { "id": 179 }, { "id": 180 }, { "id": 181 }, { "id": 182 }, { "id": 183 }, { "id": 184 }, { "id": 185 }, { "id": 186 }, { "id": 187 }, { "id": 188 }, { "id": 189 }, { "id": 190 }, { "id": 191 }, { "id": 192 }, { "id": 193 }, { "id": 194 }, { "id": 195 }, { "id": 196 }, { "id": 197 }, { "id": 198 }, { "id": 199 }, { "id": 200 }, { "id": 201 }, { "id": 202 }, { "id": 203 }, { "id": 204 }, { "id": 205 }, { "id": 206 }, { "id": 207 }, { "id": 208 }, { "id": 209 }, { "id": 210 }, { "id": 211 }, { "id": 212 }, { "id": 213 }, { "id": 214 }, { "id": 215 }, { "id": 216 }, { "id": 217 }, { "id": 218 }, { "id": 219 }, { "id": 220 }, { "id": 221 }, { "id": 222 }, { "id": 223 }, { "id": 224 }, { "id": 225 }, { "id": 226 }, { "id": 227 }, { "id": 228 }, { "id": 229 }, { "id": 230 }, { "id": 231 }, { "id": 232 }, { "id": 233 }, { "id": 234 }, { "id": 235 }, { "id": 236 }, { "id": 237 }, { "id": 238 }, { "id": 239 }, { "id": 240 }, { "id": 241 }, { "id": 242 }, { "id": 243 }, { "id": 244 }, { "id": 245 }, { "id": 246 }, { "id": 247 }, { "id": 248 }, { "id": 249 }, { "id": 250 }, { "id": 251 }, { "id": 252 }, { "id": 253 }, { "id": 254 }, { "id": 255 }, { "id": 256 }, { "id": 257 }, { "id": 258 }, { "id": 259 }, { "id": 260 }, { "id": 261 }, { "id": 262 }, { "id": 263 }, { "id": 264 }, { "id": 265 }, { "id": 266 }, { "id": 267 }, { "id": 268 }, { "id": 269 }, { "id": 270 }, { "id": 271 }, { "id": 272 }, { "id": 273 }, { "id": 274 }, { "id": 275 }, { "id": 276 }, { "id": 277 }, { "id": 278 }, { "id": 279 }, { "id": 280 }, { "id": 281 }, { "id": 282 }, { "id": 283 }, { "id": 284 }, { "id": 285 }, { "id": 286 }, { "id": 287 }, { "id": 288 }, { "id": 289 }, { "id": 290 }, { "id": 291 }, { "id": 292 }, { "id": 293 }, { "id": 294 }, { "id": 295 }, { "id": 296 }, { "id": 297 }, { "id": 298 }, { "id": 299 }, { "id": 300 } ] }, "testLayout": { "results": { "dom": "#testContainer", "subViews": { "result": { "dom": "#results" } } }, "test": { "dom": "#testContainer", "subViews": { "itemsList": { "dom": "#itemsList", "itemsPerPage": 50 } } }, "instructions": { "dom": "#testContainer", "subViews": { "instructionsList": { "dom": "#instructionsList" } } } }, "testResults": { } } );
alkaest2002/gzts-lab
web/app/assets/js/app/data/tests/1/testData.js
JavaScript
bsd-3-clause
23,986
/** * Inline development version. Only to be used while developing since it uses document.write to load scripts. */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports) { "use strict"; var html = "", baseDir; var modules = {}, exposedModules = [], moduleCount = 0; var scripts = document.getElementsByTagName('script'); for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; if (src.indexOf('/plugin.dev.js') != -1) { baseDir = src.substring(0, src.lastIndexOf('/')); } } function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function register(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); if (--moduleCount === 0) { for (var i = 0; i < exposedModules.length; i++) { register(exposedModules[i]); } } } function expose(ids) { exposedModules = ids; } function writeScripts() { document.write(html); } function load(path) { html += '<script type="text/javascript" src="' + baseDir + '/' + path + '"></script>\n'; moduleCount++; } // Expose globally exports.define = define; exports.require = require; expose(["tinymce/spellcheckerplugin/DomTextMatcher"]); load('classes/DomTextMatcher.js'); load('classes/Plugin.js'); writeScripts(); })(this); // $hash: 60f97835fac35e947a55814ab4ed7f51
killer-djon/dev-v2.web2book.ru
public/mixins/javascripts/tinymce4/plugins/spellchecker/plugin.dev.js
JavaScript
bsd-3-clause
2,587
var path = require('path'), User = require(path.resolve('models/User')); module.exports = function(app, rootUrl) { app.get(rootUrl + '/users/:id', function(req,res) { var id = req.params.id; if (id == 'me') id = req.user.id; User.findById(id, function(err, user) { if (err) return res.send(500); if (user === null) return res.send(404); res.send(200, user); }); }); };
calvinDN/portfolio_webapp
routes/admin/users.js
JavaScript
bsd-3-clause
499
container: "paypal-container", singleUse: <%= payment_method.preferred_store_payments_in_vault.eql?('do_not_store') %>, amount: <%= @order.total %>, currency: "<%= current_currency %>", locale: "en_us", displayName: "<%= payment_method.preferred_paypal_display_name %>", enableShippingAddress: true, shippingAddressOverride: { recipientName: '<%= "#{shipping_address.firstname} #{shipping_address.lastname}" %>', streetAddress: '<%= shipping_address.address1 %>', extendedAddress: '<%= shipping_address.address2 %>', locality: '<%= shipping_address.city %>', countryCodeAlpha2: '<%= shipping_address.country.try(:iso) %>', postalCode: '<%= shipping_address.zipcode %>', region: '<%= shipping_address.state.try(:abbr) %>', phone: '<%= shipping_address.phone %>', editable: false }, onReady: function (integration) { if(!SpreeBraintreeVzero.admin) SpreeBraintreeVzero.deviceData = integration.deviceData; checkout = integration; }, headless: true, onPaymentMethodReceived: function (result) { var formId = "#" + checkoutFormId; if (result.nonce.length) { $(formId).append("<input type='hidden' name='order[payments_attributes][][braintree_nonce]' value=" + result.nonce + ">"); $(formId).append("<input type='hidden' name='paypal_email' value=" + result.details.email + ">"); paymentMethodSelect = $("#order_payments_attributes__braintree_token") if(paymentMethodSelect.length) paymentMethodSelect.val(""); $(formId)[0].submit(); } else { $(errorMessagesContainer).prepend("<div class='alert alert-error'><%= I18n.t(:gateway_error, scope: 'braintree.error') %>></div>") } }
muzykabart/spree_braintree_vzero
app/views/spree/shared/braintree_vzero/_paypal.js
JavaScript
bsd-3-clause
1,633
/*globals namespace, ursa, xsd, rdf, rdfs, owl, hydra, shacl, guid */ (function(namespace) { "use strict"; var parseDate = function(dateTime) { var timeZone = null; var position; if ((position = dateTime.lastIndexOf("+")) !== -1) { timeZone = dateTime.substr(position + 1); dateTime = dateTime.substr(0, position); } else if ((position = dateTime.lastIndexOf("Z")) !== -1) { timeZone = "00:00"; dateTime = dateTime.substr(0, position); } var date; var time = "00:00:00.000"; if ((position = dateTime.indexOf("T")) !== -1) { date = dateTime.substr(0, position); time = dateTime.substr(position + 1); } else { date = dateTime; } date = date.split("-"); time = time.split(":"); var result = new Date(parseInt(date[0]), parseInt(date[1] - 1), parseInt(date[2]), parseInt(time[0]), parseInt(time[1]), (time.length > 2 ? parseInt(time[2].split(".")[0]) : 0), ((time.length > 2) && (time[2].indexOf(".") !== -1) ? time[2].split(".")[1] : 0)); if (timeZone !== null) { timeZone = timeZone.split(":"); result.setTime(result.getTime() + (parseInt(timeZone[0]) * 60 * 1000) + (parseInt(timeZone[1]) * 1000)); } return result; }; var parseValue = function(type) { if ((this === null) || (typeof(this) !== "string")) { return null; } if ((this === "") && (type === xsd.string)) { return ""; } switch (type) { case xsd.boolean: return ((this === "") || (this === "false") ? false : true); case xsd.byte: case xsd.unsignedByte: case xsd.short: case xsd.unsignedShort: case xsd.int: case xsd.unsignedInt: case xsd.long: case xsd.unsignedLong: case xsd.integer: case xsd.nonPositiveInteger: case xsd.nonNegativeInteger: case xsd.negativeInteger: case xsd.positiveInteger: case xsd.gYear: case xsd.gMonth: case xsd.gDay: return (this === "" ? 0 : parseInt(this)); case xsd.float: case xsd.double: case xsd.decimal: return (this === "" ? 0 : parseFloat(this)); case xsd.dateTime: return (this === "" ? new Date(0, 1, 1, 0, 0, 0) : parseDate(this)); } return this; }; var getValue = function (property) { if ((!this[property]) || (this[property].length === 0)) { return null; } var result = (this[property][0]["@value"] !== undefined ? this[property][0]["@value"] : this[property][0]["@id"]); if (this[property][0]["@type"] === undefined) { return result; } if ((this[property][0]["@type"] !== xsd.string) && (typeof (result) === "string")) { result = parseValue.call(result, this[property][0]["@type"]); } return result; }; var getValues = function (property) { var result = []; if (this[property]) { for (var index = 0; index < this[property].length; index++) { var value = this[property][index]["@value"] || this[property][index]["@id"]; if ((this[property][index]["@type"] !== undefined) && (this[property][index]["@type"] !== xsd.string) && (typeof (value) === "string")) { value = parseValue.call(value, this[property][index]["@type"]); } if (value !== null) { result.push(value); } } } return result; }; var isBlankNode = function(resource) { return ((resource ? resource["@id"] : this).indexOf("_:") === 0); }; var canOverrideSuperClassId = function(superClassId) { return (superClassId === null) || ((superClassId === hydra.Collection) && (this["@id"] === rdf.List)) || ((isBlankNode.call(superClassId)) && (!isBlankNode(this))); }; var isRestriction = function(resource) { return !!((resource[owl.onProperty]) || (resource[owl.allValuesFrom])); }; var composeClass = function($class, graph, levels, level) { levels = levels || []; level = level || 0; var superClasses = []; var superClassId = ((this["@id"]) && (this["@id"].indexOf("_:") === 0) ? this["@id"] : null); for (var property in $class) { if (!$class.hasOwnProperty(property)) { continue; } switch (property) { case "@id": if (!this["@id"]) { this["@id"] = $class["@id"]; } if ((canOverrideSuperClassId.call($class, superClassId)) && (!isBlankNode($class)) && (!isRestriction($class)) && (this["@id"] !== $class["@id"])) { superClassId = $class["@id"]; } break; case "@type": if (!this["@type"]) { this["@type"] = $class["@type"]; } else { for (var typeIndex = 0; typeIndex < $class["@type"].length; typeIndex++) { this["@type"].push($class["@type"][typeIndex]); } } break; case rdfs.subClassOf: superClasses = $class[rdfs.subClassOf]; break; default: if ((!this[property]) || ((this[property]) && (levels[property]) && (levels[property] > level))) { this[property] = $class[property]; levels[property] = level; } break; } } for (var index = 0; index < superClasses.length; index++) { var superSuperClassId = composeClass.call(this, graph.getById(superClasses[index]["@id"]), graph, levels, level + 1); if ((superClassId === null) || ((superSuperClassId === hydra.Collection) && (superClassId !== rdf.List)) || (superSuperClassId === rdf.List)) { superClassId = superSuperClassId; } } return superClassId; }; var getClass = function(owner, graph) { var $class = {}; var targetClass = $class; var superClassId = composeClass.call($class, this, graph); var isEnumerable = false; var isList = false; if (superClassId !== null) { switch (superClassId) { case hydra.Collection: isEnumerable = true; targetClass = graph.getById($class[owl.allValuesFrom][0]["@id"]); break; case rdf.List: isEnumerable = isList = true; targetClass = graph.getById($class[owl.allValuesFrom][0]["@id"]); break; default: targetClass = graph.getById(superClassId); break; } } var result = owner.apiDocumentation.knownTypes.getById(targetClass["@id"]); if (result === null) { var Ctor = ((targetClass["@id"].indexOf(xsd) === -1) && (targetClass["@id"].indexOf(guid) === -1) ? ursa.model.Class : ursa.model.DataType); result = new Ctor(owner.apiDocumentation || owner, targetClass, graph); } if ($class === targetClass) { return result; } result = result.subClass($class["@id"]); ursa.model.Type.prototype.constructor.call(result, owner, $class, graph); result.maxOccurances = (isEnumerable ? Number.MAX_VALUE : result.maxOccurances); result.isList = isList; return result; }; var getOperations = function(resource, graph, predicate) { if (predicate === undefined) { predicate = hydra.supportedOperation; } var index; if (resource[predicate]) { for (index = 0; index < resource[predicate].length; index++) { var supportedOperation = graph.getById(resource[predicate][index]["@id"]); this.supportedOperations.push(new ursa.model.Operation(this, supportedOperation, null, graph)); } } for (var propertyName in resource) { if ((resource.hasOwnProperty(propertyName)) && (propertyName.match(/^[a-zA-Z][a-zA-Z0-9\+\-\.]*:/) !== null) && (propertyName.indexOf(xsd) === -1) && (propertyName.indexOf(rdf) === -1) && (propertyName.indexOf(rdfs) === -1) && (propertyName.indexOf(owl) === -1) && (propertyName.indexOf(guid) === -1) && (propertyName.indexOf(hydra) === -1) && (propertyName.indexOf(shacl) === -1) && (propertyName.indexOf(ursa) === -1)) { var property = graph.getById(propertyName); if ((!property) || (property["@type"].indexOf(hydra.TemplatedLink) === -1) || (!property[hydra.supportedOperation])) { continue; } var operation = graph.getById(property[hydra.supportedOperation][0]["@id"]); var templates = resource[propertyName]; for (index = 0; index < templates.length; index++) { var template = graph.getById(templates[index]["@id"]); if (template["@type"].indexOf(hydra.IriTemplate) !== -1) { this.supportedOperations.push(new ursa.model.Operation(this, operation, template, graph)); } } } } }; Object.defineProperty(namespace, "getValue", { enumerable: false, configurable: false, writable: true, value: getValue }); Object.defineProperty(namespace, "getValues", { enumerable: false, configurable: false, writable: true, value: getValues }); Object.defineProperty(namespace, "isBlankNode", { enumerable: false, configurable: false, writable: true, value: isBlankNode }); Object.defineProperty(namespace, "composeClass", { enumerable: false, configurable: false, writable: true, value: composeClass }); Object.defineProperty(namespace, "getClass", { enumerable: false, configurable: false, writable: true, value: getClass }); Object.defineProperty(namespace, "getOperations", { enumerable: false, configurable: false, writable: true, value: getOperations }); }(namespace("ursa.model")));
alien-mcl/URSA
URSA.Client/app/scripts/ursa/model/helpers.js
JavaScript
bsd-3-clause
10,750
// Copyright (c) 2019 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. function getParentRect(element) { var parent = element.parentElement; var parentRect = parent.getClientRects()[0]; return parentRect; } function getInViewPoint(element) { var rectangles = element.getClientRects(); if (rectangles.length === 0) { return false; } var rect = rectangles[0]; var left = Math.max(0, rect.left); var right = Math.min(window.innerWidth, rect.right); var top = Math.max(0, rect.top); var bottom = Math.min(window.innerHeight, rect.bottom); // Find the view boundary of the element by checking itself and all of its // ancestor's boundary. while (element.parentElement != null && element.parentElement != document.body && element.parentElement.getClientRects().length > 0) { var parentStyle = window.getComputedStyle(element.parentElement); var overflow = parentStyle.getPropertyValue("overflow"); var overflowX = parentStyle.getPropertyValue("overflow-x"); var overflowY = parentStyle.getPropertyValue("overflow-y"); var parentRect = getParentRect(element); // Only consider about overflow cases when the parent area overlaps with // the element's area. if (parentRect.right > left && parentRect.bottom > top && right > parentRect.left && bottom > parentRect.top) { if (overflow == "auto" || overflow == "scroll" || overflow == "hidden") { left = Math.max(left, parentRect.left); right = Math.min(right, parentRect.right); top = Math.max(top, parentRect.top); bottom = Math.min(bottom, parentRect.bottom); } else { if (overflowX == "auto" || overflowX == "scroll" || overflowX == "hidden") { left = Math.max(left, parentRect.left); right = Math.min(right, parentRect.right); } if (overflowY == "auto" || overflowY == "scroll" || overflowY == "hidden") { top = Math.max(top, parentRect.top); bottom = Math.min(bottom, parentRect.bottom); } } } element = element.parentElement; } var x = 0.5 * (left + right); var y = 0.5 * (top + bottom); return [x, y, left, top]; } function inView(element) { var elementPoint = getInViewPoint(element); if (elementPoint[0] <= 0 || elementPoint[1] <= 0 || elementPoint[0] >= window.innerWidth || elementPoint[1] >= window.innerHeight || !document.elementsFromPoint(elementPoint[0], elementPoint[1]) .includes(element)) { return false; } return true; } function getElementLocation(element, center) { // Check that node type is element. if (element.nodeType != 1) throw new Error(element + ' is not an element'); if (!inView(element)) { element.scrollIntoView({behavior: "instant", block: "end", inline: "nearest"}); } var clientRects = element.getClientRects(); if (clientRects.length === 0) { var e = new Error(element + ' has no size and location'); // errorCode 60: ElementNotInteractableException e.code = 60; throw e; } var elementPoint = getInViewPoint(element); if (center) { return { 'x': elementPoint[0], 'y': elementPoint[1] }; } else { return { 'x': elementPoint[2], 'y': elementPoint[3] }; } }
endlessm/chromium-browser
chrome/test/chromedriver/js/get_element_location.js
JavaScript
bsd-3-clause
3,490
import React from 'react'; import Relay from 'react-relay'; import 'babel/polyfill'; import './FacebookLoginButton.css'; class FacebookLoginButton extends React.Component { constructor(props) { super(props); } render() { return ( <a onClick={this.props.onClick} className="btn-auth btn-facebook large" href="#"> Sign in with <b>Facebook</b> </a> ); } } export default FacebookLoginButton;
xuorig/form-check-app
js/components/shared/Buttons/FacebookLoginButton.js
JavaScript
bsd-3-clause
434
var path = require('path'); var port = 3000; var domain = 'http://127.0.0.1'; module.exports = module.exports || {}; module.exports.name = 'trending-food'; module.exports.port = port; module.exports.url = domain + ':' + port; module.exports.uploadDir = 'uploads'; module.exports.backupDir = 'backups'; /** * Database */ module.exports.db = { host: '127.0.0.1', port: '27017', name: 'trending-food' }; module.exports.meal = { amount: { default: 0, min: 0, max: 99 }, votes: { default: 0, min: 0 } }; module.exports.mealtime = { minutesBeforeLock : { default: 60 } }; module.exports.mealtimelimit = 24;
ICANS/trending-food
config/default.js
JavaScript
bsd-3-clause
694
var model = require('../models') , config = require('../config') var title = config.development.express.title; var subtitle = config.development.express.subtitle; exports.index = function(req, res){ res.render('index', { user: req.user, title: title, subtitle: subtitle }); }; exports.profile = function(req, res){ res.render('profile', { user: req.user, title: title, subtitle: subtitle }); console.log(req.user) };
Tzvayim/theArk
routes/index.js
JavaScript
bsd-3-clause
425
// Copyright 2015 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. // This Polymer element is used as a header for the media router interface. Polymer({ is: 'media-router-header', properties: { /** * The name of the icon used as the back button. This is set once, when * the |this| is ready. * @private {string} */ arrowDropIcon_: { type: String, value: '', }, /** * Whether or not the arrow drop icon should be disabled. * @type {boolean} */ arrowDropIconDisabled: { type: Boolean, value: false, }, /** * Title text for the back button. * @private {string} */ backButtonTitle_: { type: String, readOnly: true, value: function() { return loadTimeData.getString('backButtonTitle'); }, }, /** * Title text for the close button. * @private {string} */ closeButtonTitle_: { type: String, readOnly: true, value: function() { return loadTimeData.getString('closeButtonTitle'); }, }, /** * The header text to show. * @type {string} */ headingText: { type: String, value: '', }, /** * The height of the header when it shows the user email. * @private {number} */ headerWithEmailHeight_: { type: Number, readOnly: true, value: 62, }, /** * The height of the header when it doesn't show the user email. * @private {number} */ headerWithoutEmailHeight_: { type: Number, readOnly: true, value: 52, }, /** * Whether to show the user email in the header. * @type {boolean} */ showEmail: { type: Boolean, value: false, observer: 'maybeChangeHeaderHeight_', }, /** * The text to show in the tooltip. * @type {string} */ tooltip: { type: String, value: '', }, /** * The user email if they are signed in. * @type {string} */ userEmail: { type: String, value: '', }, /** * The current view that this header should reflect. * @type {?media_router.MediaRouterView} */ view: { type: String, value: null, observer: 'updateHeaderCursorStyle_', }, }, listeners: { 'focus': 'onFocus_', }, attached: function() { // isRTL() only works after i18n_template.js runs to set <html dir>. // Set the back button icon based on text direction. this.arrowDropIcon_ = isRTL() ? 'arrow-forward' : 'arrow-back'; }, /** * @param {?media_router.MediaRouterView} view The current view. * @return {string} The current arrow-drop-* icon to use. * @private */ computeArrowDropIcon_: function(view) { return view == media_router.MediaRouterView.CAST_MODE_LIST ? 'arrow-drop-up' : 'arrow-drop-down'; }, /** * @param {?media_router.MediaRouterView} view The current view. * @return {boolean} Whether or not the arrow drop icon should be hidden. * @private */ computeArrowDropIconHidden_: function(view) { return view != media_router.MediaRouterView.SINK_LIST && view != media_router.MediaRouterView.CAST_MODE_LIST; }, /** * @param {?media_router.MediaRouterView} view The current view. * @return {string} The title text for the arrow drop button. * @private */ computeArrowDropTitle_: function(view) { return view == media_router.MediaRouterView.CAST_MODE_LIST ? loadTimeData.getString('viewDeviceListButtonTitle') : loadTimeData.getString('viewCastModeListButtonTitle'); }, /** * @param {?media_router.MediaRouterView} view The current view. * @return {boolean} Whether or not the back button should be hidden. * @private */ computeBackButtonHidden_: function(view) { return view != media_router.MediaRouterView.ROUTE_DETAILS && view != media_router.MediaRouterView.FILTER; }, /** * Returns whether given string is undefined, null, empty, or whitespace only. * @param {?string} str String to be tested. * @return {boolean} |true| if the string is undefined, null, empty, or * whitespace. * @private */ isEmptyOrWhitespace_: function(str) { return str === undefined || str === null || (/^\s*$/).test(str); }, /** * Handles a click on the back button by firing a back-click event. * * @private */ onBackButtonClick_: function() { this.fire('back-click'); }, /** * Handles a click on the close button by firing a close-button-click event. * * @private */ onCloseButtonClick_: function() { this.fire('close-dialog', { pressEscToClose: false, }); }, /** * Handles a click on the arrow button by firing an arrow-click event. * * @private */ onHeaderOrArrowClick_: function() { if (this.view == media_router.MediaRouterView.SINK_LIST || this.view == media_router.MediaRouterView.CAST_MODE_LIST) { this.fire('header-or-arrow-click'); } }, /** * Updates header height to accomodate email text. This is called on changes * to |showEmail| and will return early if the value has not changed. * * @param {boolean} newValue The new value of |showEmail|. * @param {boolean} oldValue The previous value of |showEmail|. * @private */ maybeChangeHeaderHeight_: function(newValue, oldValue) { if (!!oldValue == !!newValue) { return; } // Ensures conditional templates are stamped. this.async(function() { var currentHeight = this.offsetHeight; this.$$('#header-toolbar').style.height = this.showEmail && !this.isEmptyOrWhitespace_(this.userEmail) ? this.headerWithEmailHeight_ + 'px' : this.headerWithoutEmailHeight_ + 'px'; // Only fire if height actually changed. if (currentHeight != this.offsetHeight) { this.fire('header-height-changed'); } }); }, /** * Updates the cursor style for the header text when the view changes. When * the drop arrow is also shown, the header text is also clickable. * * @param {?media_router.MediaRouterView} view The current view. * @private */ updateHeaderCursorStyle_: function(view) { this.$$('#header-text').style.cursor = view == media_router.MediaRouterView.SINK_LIST || view == media_router.MediaRouterView.CAST_MODE_LIST ? 'pointer' : 'auto'; }, });
was4444/chromium.src
chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js
JavaScript
bsd-3-clause
6,625
Ext.define('icc.controller.idatabase.Collection', { extend: 'Ext.app.Controller', models: ['idatabase.Collection', 'idatabase.Structure'], stores: ['idatabase.Collection', 'idatabase.Collection.Type', 'idatabase.Structure'], views: ['idatabase.Collection.Grid', 'idatabase.Collection.Add', 'idatabase.Collection.Edit', 'idatabase.Collection.TabPanel', 'idatabase.Collection.Password', 'idatabase.Collection.Dashboard'], controllerName: 'idatabaseCollection', plugin: false, __PLUGIN_ID__: '', actions: { add: '/idatabase/collection/add', edit: '/idatabase/collection/edit', remove: '/idatabase/collection/remove', save: '/idatabase/collection/save' }, refs: [{ ref: 'projectTabPanel', selector: 'idatabaseProjectTabPanel' }], collectionTabPanel: function() { return this.getProjectTabPanel().getActiveTab().down('idatabaseCollectionTabPanel'); }, getExpandedAccordion: function() { return this.getProjectTabPanel().getActiveTab().down('idatabaseCollectionAccordion').child("[collapsed=false]"); }, init: function() { var me = this; var controllerName = me.controllerName; if (controllerName == '') { Ext.Msg.alert('成功提示', '请设定controllerName'); return false; } me.addRef([{ ref: 'main', selector: me.controllerName + 'Main' }, { ref: 'list', selector: me.controllerName + 'Grid' }, { ref: 'add', selector: me.controllerName + 'Add' }, { ref: 'edit', selector: me.controllerName + 'Edit' }]); var listeners = {}; listeners[controllerName + 'Add button[action=submit]'] = { click: function(button) { var grid = me.getExpandedAccordion(); var store = grid.store; var form = button.up('form').getForm(); if (form.isValid()) { form.submit({ waitTitle: '系统提示', waitMsg: '系统处理中,请稍后……', success: function(form, action) { Ext.Msg.alert('成功提示', action.result.msg); form.reset(); store.load(); }, failure: function(form, action) { Ext.Msg.alert('失败提示', action.result.msg); } }); } else { Ext.Msg.alert('失败提示', '表单验证失败,请确认你填写的表单符合要求'); } } }; listeners[controllerName + 'Edit button[action=submit]'] = { click: function(button) { var grid = me.getExpandedAccordion(); var store = grid.store; var form = button.up('form').getForm(); if (form.isValid()) { form.submit({ waitTitle: '系统提示', waitMsg: '系统处理中,请稍后……', success: function(form, action) { Ext.Msg.alert('成功提示', action.result.msg); store.load(); }, failure: function(form, action) { Ext.Msg.alert('失败提示', action.result.msg); } }); } } }; listeners[controllerName + 'Grid button[action=add]'] = { click: function(button) { var grid = button.up('gridpanel'); var win = Ext.widget(controllerName + 'Add', { __PROJECT_ID__: grid.__PROJECT_ID__, plugin: grid.plugin, __PLUGIN_ID__: grid.__PLUGIN_ID__, orderBy: grid.store.getTotalCount() }); win.show(); } }; listeners[controllerName + 'Grid button[action=edit]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length > 0) { var win = Ext.widget(controllerName + 'Edit', { __PROJECT_ID__: grid.__PROJECT_ID__, plugin: grid.plugin, __PLUGIN_ID__: grid.__PLUGIN_ID__ }); var form = win.down('form').getForm(); form.loadRecord(selections[0]); win.show(); } else { Ext.Msg.alert('提示信息', '请选择你要编辑的项'); } } }; listeners[controllerName + 'Grid button[action=save]'] = { click: function(button) { var grid = button.up('gridpanel'); var store = grid.store; var records = grid.store.getUpdatedRecords(); var recordsNumber = records.length; if (recordsNumber == 0) { Ext.Msg.alert('提示信息', '很遗憾,未发现任何被修改的信息需要保存'); } var updateList = []; for (var i = 0; i < recordsNumber; i++) { record = records[i]; updateList.push(record.data); } Ext.Ajax.request({ url: me.actions.save, params: { updateInfos: Ext.encode(updateList), __PROJECT_ID__: grid.__PROJECT_ID__ }, scope: me, success: function(response) { var text = response.responseText; var json = Ext.decode(text); Ext.Msg.alert('提示信息', json.msg); if (json.success) { store.load(); } } }); } }; listeners[controllerName + 'Grid button[action=remove]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length > 0) { Ext.Msg.confirm('提示信息', '请确认是否要删除您选择的信息?', function(btn) { if (btn == 'yes') { var _id = []; for (var i = 0; i < selections.length; i++) { selection = selections[i]; grid.store.remove(selection); _id.push(selection.get('_id')); } Ext.Ajax.request({ url: me.actions.remove, params: { _id: Ext.encode(_id), __PROJECT_ID__: grid.__PROJECT_ID__, plugin: grid.plugin, __PLUGIN_ID__: grid.__PLUGIN_ID__ }, scope: me, success: function(response) { var text = response.responseText; var json = Ext.decode(text); Ext.Msg.alert('提示信息', json.msg); if (json.success) { grid.store.load(); } } }); } }, me); } else { Ext.Msg.alert('提示信息', '请选择您要删除的项'); } } }; listeners[controllerName + 'Grid'] = { selectionchange: function(selectionModel, selected, eOpts) { var grid = this.getExpandedAccordion(); if (selected.length > 1) { Ext.Msg.alert('提示信息', '请勿选择多项'); return false; } var record = selected[0]; if (record) { var panel = this.collectionTabPanel().getComponent(record.get('_id')); if (record.get('locked') && panel == null) { var win = Ext.widget(controllerName + 'Password', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), width: 320, height: 240, selectedRecord: record }); win.show(); } else { this.buildDataPanel(grid, this.collectionTabPanel(), record); } } return true; } }; listeners['idatabaseCollectionPassword button[action=submit]'] = { click: function(button) { var grid = this.getExpandedAccordion(); var form = button.up('form').getForm(); var win = button.up('window'); if (form.isValid()) { form.submit({ waitTitle: '系统提示', waitMsg: '系统处理中,请稍后……', success: function(form, action) { win.close(); me.buildDataPanel(grid, me.collectionTabPanel(), grid.getSelectionModel().getSelection()[0]); }, failure: function(form, action) { Ext.Msg.alert('失败提示', action.result.msg); } }); } } }; listeners[controllerName + 'Grid button[action=structure]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseStructureWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), plugin: grid.plugin, __PLUGIN_ID__: grid.__PLUGIN_ID__, __PLUGIN_COLLECTION_ID__: record.get('plugin_collection_id') }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=orderBy]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseCollectionOrderWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), plugin: grid.plugin, __PLUGIN_ID__: grid.__PLUGIN_ID__, __PLUGIN_COLLECTION_ID__: record.get('plugin_collection_id') }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=index]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseIndexWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), __PLUGIN_ID__: grid.__PLUGIN_ID__, plugin: grid.plugin, __PLUGIN_COLLECTION_ID__: record.get('plugin_collection_id') }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=mapping]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var __PROJECT_ID__ = grid.__PROJECT_ID__; var __COLLECTION_ID__ = record.get('_id'); var __PLUGIN_ID__ = grid.__PLUGIN_ID__; Ext.Ajax.request({ url: '/idatabase/mapping/index', params: { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: __COLLECTION_ID__, __PLUGIN_ID__: __PLUGIN_ID__ }, scope: me, success: function(response) { var text = response.responseText; var json = Ext.decode(text); var collection = ''; var database = 'ICCv1'; var cluster = 'default'; var active = false; if (json.total > 0) { collection = json.result[0].collection; database = json.result[0].database; cluster = json.result[0].cluster; active = json.result[0].active; } var win = Ext.widget('idatabaseMappingWindow', { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: __COLLECTION_ID__, collection: collection, database: database, cluster: cluster, active: active }); win.show(); } }); } else { Ext.Msg.alert('提示信息', '请选择一项您要添加映射关系的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=statistic]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseStatisticWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), __PLUGIN_ID__: grid.__PLUGIN_ID__, plugin: grid.plugin, __PLUGIN_COLLECTION_ID__: record.get('plugin_collection_id') }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要添加统计信息的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=lock]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseLockWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), __PLUGIN_ID__: grid.__PLUGIN_ID__ }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=dbimport]'] = { click: function(button) { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; var win = Ext.widget('idatabaseImportWindow', { __PROJECT_ID__: grid.__PROJECT_ID__, __COLLECTION_ID__: record.get('_id'), width: 480, height: 320 }); win.show(); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } return true; } }; listeners[controllerName + 'Grid button[action=sync]'] = { click: function(button) { Ext.Msg.confirm('提示信息', '请确认你要同步当前插件的集合或者文档结构?', function(btn) { if (btn == 'yes') { var grid = button.up('gridpanel'); Ext.Ajax.request({ url: '/idatabase/collection/sync', params: { __PROJECT_ID__: grid.__PROJECT_ID__, __PLUGIN_ID__: grid.__PLUGIN_ID__ }, scope: me, success: function(response) { var text = Ext.JSON.decode(response.responseText, true); Ext.Msg.alert('提示信息', text.msg); grid.store.load(); } }); } }, me); } }; listeners[controllerName + 'Grid button[action=hook]'] = { click: function(button) { Ext.Msg.confirm('提示信息', '请确认你要触发关联动作?', function(btn) { if (btn == 'yes') { var grid = button.up('gridpanel'); var selections = grid.getSelectionModel().getSelection(); if (selections.length == 1) { var record = selections[0]; Ext.Ajax.request({ url: '/idatabase/collection/hook', params: { __PROJECT_ID__: grid.__PROJECT_ID__, __PLUGIN_ID__: grid.__PLUGIN_ID__, __COLLECTION_ID__: record.get('_id') }, scope: me, success: function(response) { var text = Ext.JSON.decode(response.responseText, true); Ext.Msg.alert('提示信息', text.msg); } }); } else { Ext.Msg.alert('提示信息', '请选择一项您要编辑的集合'); } } }, me); } }; me.control(listeners); }, buildDataPanel: function(grid, tabpanel, record) { var __PROJECT_ID__ = grid.__PROJECT_ID__; var __PLUGIN_ID__ = grid.__PLUGIN_ID__; var __COLLECTION_ID__ = record.get('_id'); var __PLUGIN_COLLECTION_ID__ = record.get('plugin_collection_id'); var collection_name = record.get('name'); var isTree = Ext.isBoolean(record.get('isTree')) ? record.get('isTree') : false; var isRowExpander = Ext.isBoolean(record.get('isRowExpander')) ? record.get('isRowExpander') : false; var rowBodyTpl = record.get('rowExpanderTpl'); var me = this; var panel = tabpanel.getComponent(__COLLECTION_ID__); if (panel == null) { // model的fields动态创建 var modelFields = []; var searchFields = [{ xtype: 'hiddenfield', name: '__PROJECT_ID__', value: __PROJECT_ID__, allowBlank: false }, { xtype: 'hiddenfield', name: '__COLLECTION_ID__', value: __COLLECTION_ID__, allowBlank: false }]; var gridColumns = []; var structureStore = Ext.create('icc.store.idatabase.Structure'); structureStore.proxy.extraParams = { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: __COLLECTION_ID__, __PLUGIN_ID__: __PLUGIN_ID__, __PLUGIN_COLLECTION_ID__: __PLUGIN_COLLECTION_ID__ }; var treeField = ''; var treeLabel = ''; structureStore.load(function(records, operation, success) { // 存储下拉菜单模式的列 var gridComboboxColumns = []; var addOrEditFields = []; Ext.Array.forEach(records, function(record) { var isBoxSelect = Ext.isBoolean(record.get('isBoxSelect')) ? record.get('isBoxSelect') : false; var isLinkageMenu = Ext.isBoolean(record.get('isLinkageMenu')) ? record.get('isLinkageMenu') : false; var linkageClearValueField = Ext.isString(record.get('linkageClearValueField')) ? record.get('linkageClearValueField') : ''; var linkageSetValueField = Ext.isString(record.get('linkageSetValueField')) ? record.get('linkageSetValueField') : ''; var jsonSearch = Ext.isString(record.get('rshSearchCondition')) ? record.get('rshSearchCondition') : ''; var cdnUrl = Ext.isString(record.get('cdnUrl')) ? record.get('cdnUrl') : ''; var xTemplate = Ext.isString(record.get('xTemplate')) ? record.get('xTemplate') : ''; // 获取fatherField if (record.get('rshKey')) { treeField = record.get('field'); treeLabel = record.get('label'); } var convertDot = function(name) { return name.replace(/\./g, '__DOT__'); }; var convertToDot = function(name) { return name.replace(/__DOT__/g, '.'); }; var recordType = record.get('type'); var recordField = convertDot(record.get('field')); var recordLabel = record.get('label'); var allowBlank = !record.get('required'); // 创建添加和编辑的field表单开始 var addOrEditField = { xtype: recordType, fieldLabel: recordLabel, name: recordField, allowBlank: allowBlank }; switch (recordType) { case 'arrayfield': case 'documentfield': addOrEditField.xtype = 'textareafield'; addOrEditField.name = recordField; break; case 'boolfield': delete addOrEditField.name; addOrEditField.radioName = recordField; break; case 'filefield': addOrEditField = { xtype: 'filefield', name: recordField, fieldLabel: recordLabel, labelWidth: 100, msgTarget: 'side', allowBlank: true, anchor: '100%', buttonText: '浏览本地文件' }; break; case '2dfield': addOrEditField.title = recordLabel; addOrEditField.fieldName = recordField; break; case 'datefield': addOrEditField.format = 'Y-m-d H:i:s'; break; case 'numberfield': addOrEditField.decimalPrecision = 8; break; case 'htmleditor': addOrEditField.height = 300; break; }; var rshCollection = record.get('rshCollection'); if (rshCollection != '') { var rshCollectionModel = 'rshCollectionModel' + rshCollection; var convert = function(value) { if (Ext.isObject(value)) { if (value['$id'] != undefined) { return value['$id']; } else if (value['sec'] != undefined) { var date = new Date(); date.setTime(value['sec'] * 1000); return date; } } else if (Ext.isArray(value)) { return value.join(','); } return value; }; Ext.define(rshCollectionModel, { extend: 'icc.model.common.Model', fields: [{ name: record.get('rshCollectionDisplayField'), convert: convert }, { name: record.get('rshCollectionValueField'), convert: convert }] }); var comboboxStore = Ext.create('Ext.data.Store', { model: rshCollectionModel, autoLoad: false, pageSize: 20, proxy: { type: 'ajax', url: '/idatabase/data/index', extraParams: { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: record.get('rshCollection'), jsonSearch: jsonSearch }, reader: { type: 'json', root: 'result', totalProperty: 'total' } } }); if (isBoxSelect) { addOrEditField.xtype = 'boxselect'; addOrEditField.name = recordField + '[]'; addOrEditField.multiSelect = true; addOrEditField.valueParam = 'idbComboboxSelectedValue'; addOrEditField.delimiter = ','; } else { addOrEditField.xtype = 'combobox'; addOrEditField.name = recordField; addOrEditField.multiSelect = false; } addOrEditField.fieldLabel = recordLabel; addOrEditField.store = comboboxStore; addOrEditField.queryMode = 'remote'; addOrEditField.forceSelection = true; addOrEditField.editable = true; addOrEditField.minChars = 1; addOrEditField.pageSize = 20; addOrEditField.queryParam = 'search'; addOrEditField.typeAhead = false; addOrEditField.valueField = record.get('rshCollectionValueField'); addOrEditField.displayField = record.get('rshCollectionDisplayField'); addOrEditField.fatherField = record.get('rshCollectionFatherField'); addOrEditField.listeners = { select: function(combo, records, eOpts) { if (isLinkageMenu) { var value = []; if (records.length == 0 || linkageClearValueField == '' || linkageSetValueField == '') { return false; } Ext.Array.forEach(records, function(record) { value.push(record.get(combo.valueField)); }); var form = combo.up('form').getForm(); var clearValueFields = linkageClearValueField.split(','); Ext.Array.forEach(clearValueFields, function(field) { var formField = form.findField(field) == null ? form.findField(field + '[]') : form.findField(field); if (formField != null) { formField.clearValue(); } }); var setValueFields = linkageSetValueField.split(','); Ext.Array.forEach(setValueFields, function(field) { var formField = form.findField(field) == null ? form.findField(field + '[]') : form.findField(field); if (formField != null) { var store = formField.store; var extraParams = store.proxy.extraParams; var linkageSearch = {}; if (formField.fatherField != '') { linkageSearch[formField.fatherField] = { "$in": value }; extraParams.linkageSearch = Ext.JSON.encode(linkageSearch); } store.load(); } }); } return true; } }; } addOrEditFields.push(addOrEditField); // 创建添加和编辑的field表单结束 // 创建model的fields开始 var field = { name: convertToDot(recordField), type: 'string' }; switch (recordType) { case 'arrayfield': field.convert = function(value, record) { if (Ext.isArray(value)) { return Ext.JSON.encode(value); } else { return value; } }; break; case 'documentfield': field.convert = function(value, record) { if (Ext.isObject(value) || Ext.isArray(value)) { return Ext.JSON.encode(value); } else { return value; } }; break; case '2dfield': field.convert = function(value, record) { if (Ext.isArray(value)) { return value.join(','); } return value; }; break; case 'datefield': field.convert = function(value, record) { if (Ext.isObject(value) && value['sec'] != undefined) { var date = new Date(); date.setTime(value.sec * 1000); return date; } else { return value; } }; break; case 'numberfield': field.type = 'float'; break; case 'boolfield': field.type = 'boolean'; field.convert = function(value, record) { if (Ext.isBoolean(value)) { return value; } else if (Ext.isString(value)) { return value === 'true' || value === '√' ? true : false; } return value; }; break; } modelFields.push(field); // 绘制grid的column信息 if (record.get('main')) { var column = { text: recordLabel, dataIndex: convertToDot(recordField), flex: 1 }; if (xTemplate != '') { var column = { text: recordLabel, dataIndex: convertToDot(recordField), xtype: 'templatecolumn', tpl: xTemplate, flex: 1 }; } switch (recordType) { case 'boolfield': column.xtype = 'booleancolumn'; column.trueText = '√'; column.falseText = '×'; column.field = { xtype: 'commonComboboxBoolean' }; break; case '2dfield': column.align = 'center'; break; case 'datefield': column.xtype = 'datecolumn'; column.format = 'Y-m-d H:i:s'; column.align = 'center'; column.field = { xtype: 'datefield', allowBlank: allowBlank, format: 'Y-m-d H:i:s' }; break; case 'numberfield': column.format = '0,000.00'; column.align = 'right'; column.field = { xtype: 'numberfield', allowBlank: allowBlank }; break; case 'filefield': if (xTemplate != '') { if (record.get('showImage') != undefined && record.get('showImage') == true) { column.tpl = '<a href="' + cdnUrl + '{' + recordField + '}" target="_blank"><img src="' + cdnUrl + '{' + recordfield + '}?size=100x100" border="0" height="100" /></a>'; } else { column.tpl = column.tpl.replace('{cdnUrl}', cdnUrl); } } break; default: column.field = { xtype: 'textfield', allowBlank: allowBlank }; break; } // 存在关联集合数据,则直接采用combobox的方式进行显示 if (rshCollection != '' && !isBoxSelect) { column.field = { xtype: 'combobox', typeAhead: true, store: comboboxStore, allowBlank: allowBlank, displayField: record.get('rshCollectionDisplayField'), valueField: record.get('rshCollectionValueField'), queryParam: 'search', minChars: 1 }; column.renderer = function(value) { var rec = comboboxStore.findRecord(record.get('rshCollectionValueField'), value, 0, false, false, true); if (rec != null) { return rec.get(record.get('rshCollectionDisplayField')); } return ''; }; gridComboboxColumns.push(column); } gridColumns.push(column); } // 创建model的fields结束 // 创建条件检索form if (record.get('searchable') && recordType != 'filefield') { var rshCollection = record.get('rshCollection'); // $not操作 var exclusive = { fieldLabel: '非', name: 'exclusive__' + recordField, xtype: 'checkboxfield', width: 30, inputValue: true, checked: false }; // 开启精确匹配 var exactMatch = { fieldLabel: '等于', name: 'exactMatch__' + recordField, xtype: 'checkboxfield', width: 30 }; if (rshCollection != '') { var comboboxSearchStore = Ext.create('Ext.data.Store', { model: rshCollectionModel, autoLoad: false, pageSize: 20, proxy: { type: 'ajax', url: '/idatabase/data/index', extraParams: { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: record.get('rshCollection'), jsonSearch: jsonSearch }, reader: { type: 'json', root: 'result', totalProperty: 'total' } } }); comboboxSearchStore.addListener('load', function() { var rec = comboboxSearchStore.findRecord(record.get('rshCollectionValueField'), '', 0, false, false, true); if (rec == null) { var insertRecord = {}; insertRecord[record.get('rshCollectionDisplayField')] = '无'; insertRecord[record.get('rshCollectionValueField')] = ''; comboboxSearchStore.insert(0, Ext.create(rshCollectionModel, insertRecord)); } return true; }); searchFieldItem = { xtype: 'combobox', name: recordField, fieldLabel: recordLabel, typeAhead: true, store: comboboxSearchStore, displayField: record.get('rshCollectionDisplayField'), valueField: record.get('rshCollectionValueField'), queryParam: 'search', minChars: 1 }; searchField = { xtype: 'fieldset', layout: 'hbox', title: recordLabel, fieldDefaults: { labelAlign: 'top', labelSeparator: '' }, items: [exclusive, searchFieldItem] }; } else if (recordType == 'datefield') { searchField = { xtype: 'fieldset', layout: 'hbox', title: recordLabel, defaultType: 'datefield', fieldDefaults: { labelAlign: 'top', labelSeparator: '', format: 'Y-m-d H:i:s' }, items: [exclusive, { fieldLabel: '开始时间', name: recordField + '[start]' }, { fieldLabel: '截止时间', name: recordField + '[end]' }] }; } else if (recordType == 'numberfield') { searchField = { xtype: 'fieldset', layout: 'hbox', title: recordLabel, defaultType: 'numberfield', fieldDefaults: { labelAlign: 'top', labelSeparator: '' }, items: [exclusive, { fieldLabel: '最小值(>=)', name: recordField + '[min]' }, { fieldLabel: '最大值(<=)', name: recordField + '[max]' }] }; } else if (recordType == '2dfield') { searchField = { xtype: 'fieldset', layout: 'hbox', title: recordLabel, defaultType: 'numberfield', fieldDefaults: { labelAlign: 'top', labelSeparator: '' }, items: [{ name: recordField + '[lng]', fieldLabel: '经度' }, { name: recordField + '[lat]', fieldLabel: '维度' }, { name: recordField + '[distance]', fieldLabel: '附近范围(km)' }] }; } else if (recordType == 'boolfield') { searchField = { xtype: 'commonComboboxBoolean', fieldLabel: recordLabel, name: recordField }; } else { searchField = { xtype: 'fieldset', layout: 'hbox', title: recordLabel, defaultType: 'textfield', fieldDefaults: { labelAlign: 'top', labelSeparator: '' }, items: [exclusive, exactMatch, { name: recordField, fieldLabel: recordLabel }] }; } searchFields.push(searchField); } // 创建条件检索form结束 }); // 完善树状结构 gridColumns = Ext.Array.merge(gridColumns, [{ text: "_id", sortable: false, dataIndex: '_id', flex: 1, editor: 'textfield', hidden: true }, { xtype: 'datecolumn', format: 'Y-m-d H:i:s', text: "创建时间", sortable: false, flex: 1, dataIndex: '__CREATE_TIME__' }, { xtype: 'datecolumn', format: 'Y-m-d H:i:s', text: "修改时间", sortable: false, flex: 1, dataIndex: '__MODIFY_TIME__', hidden: true }]); // 创建数据的model var dataModelName = 'dataModel' + __COLLECTION_ID__; modelFields.push({ name: '__DOMAIN__', type: 'string', defaultValue : __DOMAIN__ }); modelFields.push({ name: '__PROJECT_ID__', type: 'string', defaultValue : __PROJECT_ID__ }); modelFields.push({ name: '__COLLECTION_ID__', type: 'string', defaultValue : __COLLECTION_ID__ }); var dataModel = Ext.define(dataModelName, { extend: 'icc.model.common.Model', fields: modelFields }); // 加载数据store if (isTree) { gridColumns = Ext.Array.merge({ xtype: 'treecolumn', text: treeLabel, flex: 2, sortable: false, dataIndex: treeField }, gridColumns); gridColumns = Ext.Array.filter(gridColumns, function(item, index, array) { if (item.xtype !== 'treecolumn' && item.dataIndex === treeField) { return false; } return true; }); var dataStore = Ext.create('Ext.data.TreeStore', { model: dataModelName, autoLoad: false, proxy: { type: 'ajax', url: '/idatabase/data/tree', extraParams: { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: __COLLECTION_ID__, __PLUGIN_ID__: __PLUGIN_ID__ } }, folderSort: true }); } else { var dataStore = Ext.create('Ext.data.Store', { model: dataModelName, autoLoad: false, pageSize: 20, proxy: { type: 'ajax', url: '/idatabase/data/index', extraParams: { __PROJECT_ID__: __PROJECT_ID__, __COLLECTION_ID__: __COLLECTION_ID__, __PLUGIN_ID__: __PLUGIN_ID__ }, reader: { type: 'json', root: 'result', totalProperty: 'total' } } }); } panel = Ext.widget('idatabaseDataMain', { id: __COLLECTION_ID__, name: collection_name, title: collection_name, __COLLECTION_ID__: __COLLECTION_ID__, __PROJECT_ID__: __PROJECT_ID__, __PLUGIN_ID__: __PLUGIN_ID__, gridColumns: gridColumns, gridStore: dataStore, isTree: isTree, searchFields: searchFields, addOrEditFields: addOrEditFields, isRowExpander: isRowExpander, rowBodyTpl: rowBodyTpl }); panel.on({ beforerender: function(panel) { var grid = panel.down('grid') ? panel.down('grid') : panel.down('treepanel'); grid.store.on('load', function(store, records, success) { if (success) { var loop = gridComboboxColumns.length; if (loop > 0) { Ext.Array.forEach(gridComboboxColumns, function(gridComboboxColumn) { var ids = []; for (var index = 0; index < records.length; index++) { ids.push(records[index].get(gridComboboxColumn.dataIndex)); } ids = Ext.Array.unique(ids); var store = gridComboboxColumn.field.store; if (isTree) { store.proxy.extraParams.limit = 10000; } else { store.proxy.extraParams.idbComboboxSelectedValue = ids.join(','); } store.load(function() { loop -= 1; if (loop == 0) { grid.getView().refresh(); } }); }); } else { grid.getView().refresh(); } } }); if (!isTree) { grid.store.load(); } } }); tabpanel.add(panel); tabpanel.setActiveTab(__COLLECTION_ID__); }); } else { tabpanel.setActiveTab(__COLLECTION_ID__); } // grid.getSelectionModel().deselectAll(); } });
shanghaiyangming/iCC
public/js/app/controller/idatabase/Collection.js
JavaScript
bsd-3-clause
35,128
/*jslint nomen: true */ /*global define, window, history*/ define(["dojo/_base/lang", "dojo/_base/declare", "dapp/Controller", "dapp/utils/hash", "dojo/topic"], function (lang, declare, Controller, hash, topic) { "use strict"; // module: // dapp/tests/mediaQuery3ColumnApp/controllers/CustomHistory // summary: // This CustomHistory controller will manage the history stack so that if you return to a view target which // is in the history stack already, it will update the history stack to go to that previous view in the stack. // Using dapp/controllers/History means you can use the browser back/forward buttons to retrace all of your // steps even if, for example if you select "Main Option 1" multiple times. // // Using CustomHistory without setting customHistoryStackKey in the config means it will check to see if the current url // has been used already, and if it has it will remove the things from the history stack back to the point it was // last used. So for example if you start the application in a new tab, and select "Main Option 1", then // you select other options, (like "Main Option 2" and "Main Option 3") and then select // "Main Option 1" again, doing a browser back after selecting "Main Option 1" the last time will take you // back to the initial default page instead of the last thing before you last went to "Main Option 1". // // Using CustomHistory and setting customHistoryStackKey to "target" in the config means it will check to see if the // current target has been used already, and if it has it will remove the things from the history stack back to the // point it was last used. So for example if you start the application in a new tab, and select "Main Option 1", then // you select other options, (like "Main Option 2" and "Main Option 3") and then select // "Main Option 1" again, doing a browser back after selecting "Main Option 1" the last time will take you // back to the initial default page instead of the last thing before you last went to "Main Option 1". // The difference caused by using "target" can be seen when selecting "Last Option 1", 2 or 3, and then using the // browser back button, when using "target" you will not go back through those selections, but without "target" // you will go through those options because those options are set in the url, but not in the target. // Bind "app-domNode" event on dapp application instance. // Bind "startTransition" event on dapp application domNode. // Bind "popstate" event on window object. // Maintain history by HTML5 "pushState" method and "popstate" event. return declare("dapp/tests/mediaQuery3ColumnApp/controllers/CustomHistory", Controller, { // _currentPosition: Integer // Persistent variable which indicates the current position/index in the history // (so as to be able to figure out whether the popState event was triggerd by // a backward or forward action). _currentPosition: 0, // currentState: Object // Current state currentState: {}, // currentStack: Array // Array with the history used to look for targets already in the stack currentStack: [], // currentStackKey: string // boolean is true when the currentStack is being updated because the view target was already in the stack currentStackKey: "url", // set "customHistoryStackKey" : "target" in the config if you want to key off of the target instead of the url // currentStackUpdating: boolean // boolean is true when the currentStack is being updated because the view target was already in the stack currentStackUpdating: false, constructor: function () { // summary: // Bind "app-domNode" event on dapp application instance. // Bind "startTransition" event on dapp application domNode. // Bind "popstate" event on window object. // this.events = { "app-domNode": this.onDomNodeChange }; if (this.app.domNode) { this.onDomNodeChange({oldNode: null, newNode: this.app.domNode}); } this.bind(window, "popstate", lang.hitch(this, this.onPopState)); this.currentStackKey = this.app.customHistoryStackKey || this.currentStackKey; }, onDomNodeChange: function (evt) { if (evt.oldNode !== null) { this.unbind(evt.oldNode, "startTransition"); } this.bind(evt.newNode, "startTransition", lang.hitch(this, this.onStartTransition)); }, onStartTransition: function (evt) { // summary: // Response to dapp "startTransition" event. // // example: // Use "dojox/mobile/TransitionEvent" to trigger "startTransition" event, and this function will response the event. For example: // | var transOpts = { // | title:"List", // | target:"items,list", // | url: "#items,list", // | params: {"param1":"p1value"} // | }; // | new TransitionEvent(domNode, transOpts, e).dispatch(); // // evt: Object // Transition options parameter var currentHash = window.location.hash, currentView = hash.getTarget(currentHash, this.app.defaultView), currentParams = hash.getParams(currentHash), _detail = lang.clone(evt.detail), newUrl, testStackKey, idx, len, i; _detail.target = _detail.title = currentView; _detail.url = currentHash; _detail.params = currentParams; _detail.id = this._currentPosition; // Create initial state if necessary if (history.length === 1) { history.pushState(_detail, _detail.href, currentHash); } // Update the current state _detail.bwdTransition = _detail.transition; lang.mixin(this.currentState, _detail); history.replaceState(this.currentState, this.currentState.href, currentHash); // Create a new "current state" history entry this._currentPosition += 1; newUrl = evt.detail.url || "#" + evt.detail.target; // move up above if (evt.detail.params) { newUrl = hash.buildWithParams(newUrl, evt.detail.params); } //check to see if the hash or target based upon currentStackKey is already in the list testStackKey = this.currentStackKey === "target" ? evt.detail.target : newUrl; idx = this.currentStack.indexOf(testStackKey); if (idx > -1) { // the target is in the list // found the target in the list, so backup to that entry this.currentStackUpdating = true; len = this.currentStack.length - idx; this._currentPosition -= len; history.go(-len); for (i = 0; i < len; i = i + 1) { this.currentStack.pop(); } } evt.detail.id = this._currentPosition; evt.detail.fwdTransition = evt.detail.transition; history.pushState(evt.detail, evt.detail.href, newUrl); if (this.currentStackKey === "target") { this.currentStack.push(evt.detail.target); } else { this.currentStack.push(newUrl); } this.currentState = lang.clone(evt.detail); // Finally: Publish pushState topic topic.publish("/app/history/pushState", evt.detail.target); }, onPopState: function (evt) { // summary: // Response to dapp "popstate" event. // // evt: Object // Transition options parameter var opts, backward; // Clean browser's cache and refresh the current page will trigger popState event, // but in this situation the application has not started and throws an error. // So we need to check application status, if application not STARTED, do nothing. if ((this.app.getStatus() !== this.app.lifecycle.STARTED) || !evt.state || this.currentStackUpdating) { this.currentStackUpdating = false; return; } // Get direction of navigation and update _currentPosition accordingly backward = evt.state.id < this._currentPosition; if (backward) { this._currentPosition -= 1; } else { this._currentPosition += 1; } if (backward) { this.currentStack.pop(); // keep currentStack up to date } else { if (this.currentStackKey === "target") { this.currentStack.push(evt.state.target); } else { this.currentStack.push(evt.state.url); } } // Publish popState topic and transition to the target view. Important: Use correct transition. // Reverse transitionDir only if the user navigates backwards. opts = lang.mixin({reverse: backward ? true : false}, evt.state); opts.transition = backward ? opts.bwdTransition : opts.fwdTransition; this.app.emit("app-transition", { viewId: evt.state.target, opts: opts }); topic.publish("/app/history/popState", evt.state.target); } }); });
kfbishop/dworklight-testapp
apps/DWorklightApp/common/app/controllers/CustomHistory.js
JavaScript
bsd-3-clause
10,200
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/when', 'dojo/Deferred', 'dojo/Stateful', 'dijit/registry', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'dojox/mvc/_InlineTemplateMixin', 'dojox/mvc/at', '../computed', 'dojox/mvc/Element', './TodoEscape', './TodoFocus' ], function (declare, lang, when, Deferred, Stateful, registry, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, _InlineTemplateMixin, at, computed) { // To use Dojo's super call method, inherited() /*jshint strict:false*/ /** * Todo item, which does the following: * - instantiate the template * - expose the model for use in the template * - provide event handlers * @class Todo */ return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, _InlineTemplateMixin], { startup: function () { this.inherited(arguments); if (!this.todosWidget) { throw new Error('this.todosWidget property should be there before this widgets starts up: ' + this); } this.own(computed(this, 'isEditing', function (editedTodo) { return editedTodo === this.target; }, at(this.todosWidget, 'editedTodo'))); }, editTodo: function () { this.set('originalTitle', this.target.get('title')); this.todosWidget.set('editedTodo', this.target); }, invokeSaveEdits: function () { // For handling input's blur event, make sure change event has been fired var dfd = new Deferred(); setTimeout(lang.hitch(this, function () { when(this.saveEdits(), function (data) { dfd.resolve(data); }, function (e) { dfd.reject(e); }); }), 0); return dfd.promise; }, saveEdits: function (event) { var progress; var originalTitle = this.get('originalTitle'); var newTitle = lang.trim(this.target.get('title')); var goAhead = this.get('isEditing') && newTitle !== originalTitle; var blur = !event; if (blur || goAhead) { this.target.set('title', newTitle); } if (goAhead) { if (newTitle) { progress = this.todosWidget.saveTodo(this.target, originalTitle, this.target.get('completed')); } else { progress = this.removeTodo(); } } if (blur || goAhead) { progress = when(progress, lang.hitch(this, function () { this.todosWidget.set('editedTodo', null); }), lang.hitch(this, function (e) { this.todosWidget.set('editedTodo', null); throw e; })); } if (event && event.type === 'submit') { event.preventDefault(); } return progress; }, revertEdits: function () { if (this.get('isEditing')) { this.todosWidget.set('editedTodo', null); this.todosWidget.replaceTodo(this.target, new Stateful({ id: this.target.get('id'), title: this.get('originalTitle'), completed: this.target.get('completed') })); this.destroyRecursive(); } }, toggleCompleted: function () { this.todosWidget.saveTodo(this.target, this.target.get('title'), !this.target.get('completed')); }, removeTodo: function () { return when(this.todosWidget.removeTodo(this.target), lang.hitch(this, this.destroyRecursive)); } }); });
gabrielmancini/interactor
src/demo/dojo/js/todo/widgets/Todo.js
JavaScript
bsd-2-clause
3,146
const test = require('tape') const sinon = require('sinon') const helpers = require('../test/helpers') const bindFunc = helpers.bindFunc const isFunction = require('../core/isFunction') const unit = require('../core/_unit') const constant = x => () => x const compareWith = require('./compareWith') test('compareWith pointfree', t => { const f = bindFunc(compareWith) const x = 'result' const m = { compareWith: sinon.spy(constant(x)) } t.ok(isFunction(compareWith), 'is a function') const err = /compareWith: Equiv required for third argument/ t.throws(f(13, 13, undefined), err, 'throws if passed undefined') t.throws(f(13, 13, null), err, 'throws if passed null') t.throws(f(13, 13, 0), err, 'throws if passed a falsey number') t.throws(f(13, 13, 1), err, 'throws if passed a truthy number') t.throws(f(13, 13, ''), err, 'throws if passed a falsey string') t.throws(f(13, 13, 'string'), err, 'throws if passed a truthy string') t.throws(f(13, 13, false), err, 'throws if passed false') t.throws(f(13, 13, true), err, 'throws if passed true') t.throws(f(13, 13, []), err, 'throws if passed an array') t.throws(f(13, 13, {}), err, 'throws if passed an object') t.throws(f(13, 13, unit), err, 'throws if passed a function') const result = compareWith(23)(23)(m) t.ok(m.compareWith.called, 'calls compareWith on the passed container') t.equal(result, x, 'returns the result of calling m.compareWith') t.end() })
evilsoft/crocks
src/pointfree/compareWith.spec.js
JavaScript
isc
1,462
/** * * DASH4 configuration * https://github.com/smollweide/dash4 * */ const { PluginTerminal } = require('@dash4/plugin-terminal'); const { PluginReadme } = require('@dash4/plugin-readme'); const { PluginNpmScripts } = require('@dash4/plugin-npm-scripts'); const { PluginActions } = require('@dash4/plugin-actions'); async function getConfig() { return { port: 4444, tabs: [ { title: 'START', rows: [ [new PluginReadme({ file: 'readme.md' })], [ new PluginTerminal({ title: 'Development Mode', cmd: 'npm run dev', dark: true, autostart: false, }), new PluginTerminal({ title: 'Cypress Mode', cmd: 'npm run cypress-test', dark: true, autostart: false, }), new PluginTerminal({ title: 'Production Mode', cmd: 'npm run prod', dark: true, autostart: false, }), ], [ new PluginNpmScripts({ scripts: [ { title: 'Run Linting', cmd: 'npm run lint' }, { title: 'Run Tests', cmd: 'npm run test' }, { title: 'Run Visual Tests', cmd: 'npm run visual-test' }, { title: 'Get Lighthouse Score', cmd: 'npm run lighthouse-test' }, ], }), new PluginNpmScripts({ scripts: [ { title: 'Run Prettier', cmd: 'npm run prettier' }, { title: 'Update Dependencies', cmd: 'npm run update-dependencies' }, { title: 'Clean', cmd: 'npm run clean' }, ], }), ], [ new PluginActions({ title: 'Links', actions: [ { type: 'link', href: 'https://nitro-project-test.netlify.app/', title: 'Proto Server', }, ], }), ], ], }, { title: 'READMES', rows: [ [new PluginReadme({ file: 'project/docs/nitro.md' })], [ new PluginReadme({ file: 'project/docs/nitro-config.md' }), new PluginReadme({ file: 'project/docs/nitro-webpack.md' }), new PluginReadme({ file: 'project/docs/nitro-exporter.md' }), ], ], }, ], }; } module.exports = getConfig;
namics/generator-nitro
packages/project-nitro-typescript/dash4.config.js
JavaScript
mit
2,124
const express = require('express'), path = require('path'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), mongoose = require('mongoose'), passport = require('passport'), session = require('express-session'), cel = require('connect-ensure-login'), count = require('./server/routes/count'), auth = require('./server/routes/auth'), index = require('./server/routes/index'), users = require('./server/routes/users'), posts = require('./server/routes/posts') MongoStore = require('connect-mongo')(session) require('dotenv').load(); require('./passport')(passport) mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGO_URI); let app = express() app.use(express.static(path.join(__dirname, './dist'))) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(session({ secret: 'toro-net', resave: false, saveUninitialized: false, cookie: { httpOnly: true, maxAge: 2495000000 }, store: new MongoStore({ url: process.env.MONGO_URI }) })) app.use(cookieParser('test-secret')) app.use(passport.initialize()) app.use(passport.session()) app.use('/users', users), app.use('/auth', auth), app.use('/count', count), app.use('/posts', posts), app.use('/', index) /* Catch all errors and log them. */ app.use(function(err, req, res, next) { console.log(err) }) const port = process.env.PORT || 3000; app.listen(port, () => console.log('Running on localhost:', port))
ErnestUrzua/csc583-midterm
server.js
JavaScript
mit
1,528
var asyncLoop = function asyncLoop(arr, funk, exit){ var index = 0; var loop = { next:function(){ if (index < arr.length) { funk(arr[index++], loop); } else { exit(); } }, break:function(){ exit(); } }; loop.next(); return loop; }; exports.asyncLoop = asyncLoop;
zackehh/redis-scanner
util/util.js
JavaScript
mit
395
'use strict'; var _ = require('lodash'); var Domain = require('../base/Domain'); var V1 = require('./monitor/V1'); /* jshint ignore:start */ /** * Initialize monitor domain * * @constructor Twilio.Monitor * * @property {Twilio.Monitor.V1} v1 - v1 version * @property {Twilio.Monitor.V1.AlertList} alerts - alerts resource * @property {Twilio.Monitor.V1.EventList} events - events resource * * @param {Twilio} twilio - The twilio client */ /* jshint ignore:end */ function Monitor(twilio) { Domain.prototype.constructor.call(this, twilio, 'https://monitor.twilio.com'); // Versions this._v1 = undefined; } _.extend(Monitor.prototype, Domain.prototype); Monitor.prototype.constructor = Monitor; Object.defineProperty(Monitor.prototype, 'v1', { get: function() { this._v1 = this._v1 || new V1(this); return this._v1; }, }); Object.defineProperty(Monitor.prototype, 'alerts', { get: function() { return this.v1.alerts; }, }); Object.defineProperty(Monitor.prototype, 'events', { get: function() { return this.v1.events; }, }); module.exports = Monitor;
sagnew/floppy-bird-demo
twilio-temp/lib/rest/Monitor.js
JavaScript
mit
1,108
describe('Lock/Unlock methods ', function () { var Context = { syncemitted: 0, syncLastValue: 0 }; var Stream = Warden.Stream(function(trigger){ this.sync = function(value){ trigger(value); } this.async = function(time, value){ setTimeout(function(){ trigger(value); }, time); } }, Context); it('-- locking and unlocking simple listened bus', function (done) { Stream.listen(function(x){ Context.syncemitted++ Context.syncLastValue = x; }); Context.sync(10); Context.sync(10); Context.sync(20); Stream.lock(); Context.sync(10); Context.sync(10); Context.sync(30); expect(Context.syncemitted).toBe(3); expect(Context.syncLastValue).toBe(20); Stream.unlock(); Context.sync(10); Context.sync(10); Context.sync(10); expect(Context.syncemitted).toBe(6); expect(Context.syncLastValue).toBe(10); done(); }); it('-- locking and unlocking difference buses', function (done) { var bus1 = Stream.stream(), bus2 = Stream.stream(); var b1 = {t: 0,v: 0}, b2 = {t: 0,v: 0} bus1.listen(function(x){ b1.t++ b1.v = x; }); bus2.listen(function(x){ b2.t++ b2.v = x; }); Context.sync(10); Context.sync(10); Context.sync(20); expect(b1.t).toBe(3); expect(b1.v).toBe(20); expect(b2.t).toBe(3); expect(b2.v).toBe(20); bus1.lock(); Context.sync(10); Context.sync(10); Context.sync(30); expect(b1.t).toBe(3); expect(b1.v).toBe(20); expect(b2.t).toBe(6); expect(b2.v).toBe(30); bus2.lock(); Context.sync(10); Context.sync(10); Context.sync(10); expect(b1.t).toBe(3); expect(b1.v).toBe(20); expect(b2.t).toBe(6); expect(b2.v).toBe(30); bus1.unlock(); Context.sync(10); Context.sync(10); Context.sync('test'); expect(b1.t).toBe(6); expect(b1.v).toBe('test'); expect(b2.t).toBe(6); expect(b2.v).toBe(30); bus2.unlock(); Context.sync(10); Context.sync(10); Context.sync('10'); expect(b1.t).toBe(9); expect(b1.v).toBe('10'); expect(b2.t).toBe(9); expect(b2.v).toBe('10'); bus1.lock(); bus2.lock(); done(); }); });
xgrommx/Warden.js
test/src/specs/common/lockunlock.js
JavaScript
mit
2,113
// @flow declare module 'http-status-codes' { /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 * * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. */ declare var ACCEPTED : 202; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 * * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. */ declare var BAD_GATEWAY : 502; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 * * This response means that server could not understand the request due to invalid syntax. */ declare var BAD_REQUEST : 400; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 * * This response is sent when a request conflicts with the current state of the server. */ declare var CONFLICT : 409; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 * * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. */ declare var CONTINUE : 100; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 * * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. */ declare var CREATED : 201; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 * * This response code means the expectation indicated by the Expect request header field can't be met by the server. */ declare var EXPECTATION_FAILED : 417; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 * * The request failed due to failure of a previous request. */ declare var FAILED_DEPENDENCY : 424; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 * * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. */ declare var FORBIDDEN : 403; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 * * This error response is given when the server is acting as a gateway and cannot get a response in time. */ declare var GATEWAY_TIMEOUT : 504; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 * * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. */ declare var GONE : 410; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 * * The HTTP version used in the request is not supported by the server. */ declare var HTTP_VERSION_NOT_SUPPORTED : 505; /** * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 * * Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. */ declare var IM_A_TEAPOT : 418; /** * UNOFFICIAL w/ NO DOCS */ declare var INSUFFICIENT_SPACE_ON_RESOURCE : 419; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 * * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. */ declare var INSUFFICIENT_STORAGE : 507; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 * * The server has encountered a situation it doesn't know how to handle. */ declare var INTERNAL_SERVER_ERROR : 500; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 * * Server rejected the request because the Content-Length header field is not defined and the server requires it. */ declare var LENGTH_REQUIRED : 411; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 * * The resource that is being accessed is locked. */ declare var LOCKED : 423; /** * @deprecated * A deprecated response used by the Spring Framework when a method has failed. */ declare var METHOD_FAILURE : 420; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 * * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. */ declare var METHOD_NOT_ALLOWED : 405; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 * * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. */ declare var MOVED_PERMANENTLY : 301; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 * * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. */ declare var MOVED_TEMPORARILY : 302; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 * * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. */ declare var MULTI_STATUS : 207; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 * * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses. */ declare var MULTIPLE_CHOICES : 300; /** * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 * * The 511 status code indicates that the client needs to authenticate to gain network access. */ declare var NETWORK_AUTHENTICATION_REQUIRED : 511; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 * * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. */ declare var NO_CONTENT : 204; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response. */ declare var NON_AUTHORITATIVE_INFORMATION : 203; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 * * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent. */ declare var NOT_ACCEPTABLE : 406; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 * * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. */ declare var NOT_FOUND : 404; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 * * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. */ declare var NOT_IMPLEMENTED : 501; /** * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 * * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response. */ declare var NOT_MODIFIED : 304; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 * * The request has succeeded. The meaning of a success varies depending on the HTTP method: * GET: The resource has been fetched and is transmitted in the message body. * HEAD: The entity headers are in the message body. * POST: The resource describing the result of the action is transmitted in the message body. * TRACE: The message body contains the request message as received by the server */ declare var OK : 200; /** * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 * * This response code is used because of range header sent by the client to separate download into multiple streams. */ declare var PARTIAL_CONTENT : 206; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 * * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently. */ declare var PAYMENT_REQUIRED : 402; /** * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 * * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. */ declare var PERMANENT_REDIRECT : 308; /** * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 * * The client has indicated preconditions in its headers which the server does not meet. */ declare var PRECONDITION_FAILED : 412; /** * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 * * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. */ declare var PRECONDITION_REQUIRED : 428; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 * * This code indicates that the server has received and is processing the request, but no response is available yet. */ declare var PROCESSING : 102; /** * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 * * This is similar to 401 but authentication is needed to be done by a proxy. */ declare var PROXY_AUTHENTICATION_REQUIRED : 407; /** * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 * * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. */ declare var REQUEST_HEADER_FIELDS_TOO_LARGE : 431; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 * * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. */ declare var REQUEST_TIMEOUT : 408; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 * * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. */ declare var REQUEST_TOO_LONG : 413; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 * * The URI requested by the client is longer than the server is willing to interpret. */ declare var REQUEST_URI_TOO_LONG : 414; /** * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 * * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data. */ declare var REQUESTED_RANGE_NOT_SATISFIABLE : 416; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 * * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. */ declare var RESET_CONTENT : 205; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 * * Server sent this response to directing client to get requested resource to another URI with an GET request. */ declare var SEE_OTHER : 303; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 * * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. */ declare var SERVICE_UNAVAILABLE : 503; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 * * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. */ declare var SWITCHING_PROTOCOLS : 101; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 * * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. */ declare var TEMPORARY_REDIRECT : 307; /** * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 * * The user has sent too many requests in a given amount of time ("rate limiting"). */ declare var TOO_MANY_REQUESTS : 429; /** * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 * * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. */ declare var UNAUTHORIZED : 401; /** * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 * * The request was well-formed but was unable to be followed due to semantic errors. */ declare var UNPROCESSABLE_ENTITY : 422; /** * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 * * The media format of the requested data is not supported by the server, so the server is rejecting the request. */ declare var UNSUPPORTED_MEDIA_TYPE : 415; /** * @deprecated * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 * * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. */ declare var USE_PROXY : 305; /** * Convert the numeric status code to its appropriate title. * @param statusCode One of the available status codes in this package * @returns {String} The associated title of the passed status code */ declare function getStatusText(statusCode: number): string; /** * Convert the status reason phrase to its appropriate numeric value * @param reasonPhrase One of the available reason phrases in this package * @returns {Number} The associated status code of the passed reason phrase * @throws {Error} The reason phrase does not exist */ declare function getStatusCode(reasonPhrase: string): number; }
flowtype/flow-typed
definitions/npm/http-status-codes_v1.x.x/flow_v0.25.0-/http-status-codes_v1.x.x.js
JavaScript
mit
17,389
/** * Created by kiran on 12/16/15. */ 'use strict'; module.exports = function(sequelize, DataTypes) { var ProductVendor = sequelize.define('ProductVendor', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: DataTypes.INTEGER }, ProductId:{ type:DataTypes.INTEGER, allowNull:false }, VendorId:{ type:DataTypes.INTEGER, allowNull:false }, isprimary:{ type:DataTypes.INTEGER, allowNull:false, defaultValue:0 }, isdeleted:{ type:DataTypes.INTEGER, allowNull:false, defaultValue:0 }, }, { classMethods: { associate: function(models) { ProductVendor.belongsTo(models.Vendor); ProductVendor.belongsTo(models.Product); } } }); return ProductVendor; };
freshcarton/freshcarton
server/models/productvendor.js
JavaScript
mit
835
define(["require", "exports"], function (require, exports) { /** * @name Browser * @author Mient-jan Stelling * @description a replacement of the mootools Browser static class, gives you crossplatform Xhr request. Browser name, version, platform * @todo add type of device like iphone, tablet, andriod phone, tablet */ var Browser = (function () { function Browser() { } Browser.empty = function () { }; Browser.getXhr = function () { if (!Browser._xhr) { var XMLHTTP = function () { return new XMLHttpRequest(); }; var MSXML2 = function () { return new ActiveXObject('MSXML2.XMLHTTP'); }; var MSXML = function () { return new ActiveXObject('Microsoft.XMLHTTP'); }; try { XMLHTTP(); this._xhr = XMLHTTP; } catch (e) { try { MSXML2(); this._xhr = MSXML2; } catch (e) { try { MSXML(); this._xhr = MSXML; } catch (e) { throw 'XMLHttpRequest not available'; } } } } return Browser._xhr(); }; // // Flash detection // // var version = (Function.attempt(function(){ // return navigator.plugins['Shockwave Flash'].description; // }, function(){ // return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); // }) || '0 r0').match(/\d+/g); // // Browser.Plugins.Flash = { // version: Number(version[0] || '0.' + version[1]) || 0, // build: Number(version[2]) || 0 // }; // String scripts Browser.exec = function (text) { if (!text) return text; if (window.execScript) { window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.text = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; Browser.ua = navigator.userAgent.toLowerCase(); Browser.platform = navigator.platform.toLowerCase(); Browser.UA = Browser.ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0]; Browser.mode = Browser.UA[1] == 'ie' && document.documentMode; // public static extend = Function.prototype.extend; Browser.name = (Browser.UA[1] == 'version' ? Browser.UA[3] : Browser.UA[1]); Browser.version = Browser.mode || parseFloat((Browser.UA[1] == 'opera' && Browser.UA[4]) ? Browser.UA[4] : Browser.UA[2]); Browser.versionNumber = parseInt(Browser.version, 10); Browser.Platform = { name: Browser.ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (Browser.ua.match(/(?:webos|android)/) || Browser.platform.match(/mac|win|linux/) || ['other'])[0] }; Browser.Plugins = {}; Browser.Features = { xpath: !!(document['evaluate']), air: !!(window['runtime']), query: !!(document.querySelector), json: !!(window['JSON']), xhr: !!(Browser.getXhr()) }; return Browser; })(); return Browser; });
ThaNarie/AutoListing
source/inc/script/lib/temple/utils/Browser.js
JavaScript
mit
3,842
import Init from './_init'; import parseHTML from './parsehtml'; import on from './on'; import off from './off'; import add from './add'; import assign from '../../_helpers/assign'; // tiny jQuery replacement for Seemple export default function mq(selector, context) { return new Init(selector, context); } mq.parseHTML = parseHTML; assign(Init.prototype, { on, off, add });
matreshkajs/matreshka
packages/seemple/src/_dom/mq/index.js
JavaScript
mit
386
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 7v2.99s-1.99.01-2 0V7h-3s.01-1.99 0-2h3V2h2v3h3v2h-3zm-3 4V8h-3V5H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-8h-3zM5 19l3-4 2 3 3-4 4 5H5z" /> , 'AddPhotoAlternate');
callemall/material-ui
packages/material-ui-icons/src/AddPhotoAlternate.js
JavaScript
mit
307
import { FS } from 'grind-support' const path = require('path') export async function DetectPackagesProvider(app) { app.packages = [] if (!(await FS.exists(app.paths.bootstrap))) { return } const bootstrap = (await FS.readFile(app.paths.bootstrap)).toString() const info = require(app.paths.packageInfo) const packages = new Set([ 'grind-cli', 'grind-http', ...Object.keys(info.dependencies || {}), ...Object.keys(info.devDependencies || {}), ...((info.grind || {}).packages || []), ]) bootstrap.replace(/require\s*\(\s*["'`](.+?)["'`]\s*\)/g, (_, pkg) => packages.add(pkg)) bootstrap.replace(/from\s+["'`](.+?)["'`]/g, (_, pkg) => packages.add(pkg)) return Promise.all( Array.from(packages) .filter(pkg => !/^[./]/.test(pkg)) .map(async pkg => { const packagePath = app.paths.packages(pkg.includes('/') ? path.dirname(pkg) : pkg) const packageInfoPath = path.join(packagePath, 'package.json') if (!(await FS.exists(packageInfoPath))) { return } const { grind } = require(packageInfoPath) if (grind === null || typeof grind !== 'object') { return } app.packages.push({ name: pkg, path: packagePath, config: grind, }) }), ) } DetectPackagesProvider.priority = -100
shnhrrsn/grind-framework
packages/toolkit/app/Providers/DetectPackagesProvider.js
JavaScript
mit
1,270
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h10v4h8v10z" /></g></React.Fragment> , 'TabOutlined');
allanalexandre/material-ui
packages/material-ui-icons/src/TabOutlined.js
JavaScript
mit
359
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M10.83 5L9.36 6.47 17 14.11V5zM7 9.79V19h9.23z" opacity=".3" /><path d="M10.83 5H17v9.11l2 2V5c0-1.1-.9-2-2-2h-7L7.94 5.06l1.42 1.42L10.83 5zM21.26 21.21L3.79 3.74 2.38 5.15 5 7.77V19c0 1.11.9 2 2 2h11.23l1.62 1.62 1.41-1.41zM7 19V9.79L16.23 19H7z" /></g></React.Fragment> , 'SignalCellularNoSimTwoTone');
allanalexandre/material-ui
packages/material-ui-icons/src/SignalCellularNoSimTwoTone.js
JavaScript
mit
485
layoutManager.setWallSize= function(runtime, container) { var totalRow = runtime.totalRow; var totalCol = runtime.totalCol; var gutterY = runtime.gutterY; var gutterX = runtime.gutterX; var cellH = runtime.cellH; var cellW = runtime.cellW; var totalWidth = Math.max(0, cellW * totalCol - gutterX); var totalHeight = Math.max(0, cellH * totalRow - gutterY); container.attr({ 'data-total-col': totalCol, 'data-total-row': totalRow, 'data-wall-width': Math.ceil(totalWidth), 'data-wall-height': Math.ceil(totalHeight) }); if (runtime.limitCol < runtime.limitRow) { // do not set height with nesting grid; !container.attr("data-height") && container.height(Math.ceil(totalHeight)); } }
iraycd/brickwork
src/layout_manager/set-wallsize.js
JavaScript
mit
783
var Scroll = {}; Scroll.positions = {}; var ease = { outSine: function(t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, outQuint: function(t, b, c, d) { t /= d; t--; return c*(t*t*t*t*t + 1) + b; }, outQuad: function(t, b, c, d) { t /= d; return -c * t*(t-2) + b; }, outExpo: function(t, b, c, d) { return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b; }, outQuart: function(t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, outCirc: function (t, b, c, d) { t /= d; t--; return c * Math.sqrt(1 - t*t) + b; } }; Scroll.smoothScrollBy = function(x, y) { var isVertical = (y) ? true : false, easeFunc = ease.outExpo, i = 0, delta = 0; this.isScrolling = true; if (document.body) { if (document.body.scrollTop + y < 0) { y = -document.body.scrollTop - 5; } else if (document.body.scrollTop + window.innerHeight + y > document.body.scrollHeight) { y = document.body.scrollHeight - window.innerHeight - document.body.scrollTop + 5; } } function animLoop() { if (isVertical) { window.scrollBy(0, Math.round(easeFunc(i, 0, y, settings.scrollduration) - delta)); } else { window.scrollBy(Math.round(easeFunc(i, 0, x, settings.scrollduration) - delta), 0); } if (i < settings.scrollduration) { window.requestAnimationFrame(animLoop); } else { Scroll.isScrolling = false; } delta = easeFunc(i, 0, (x || y), settings.scrollduration); i += 1; } animLoop(); }; Scroll.scroll = function(type, repeats) { var stepSize = settings ? settings.scrollstep : 60; if (document.body) { this.lastPosition = [document.body.scrollLeft, document.body.scrollTop]; } if (settings && settings.smoothscroll) { switch (type) { case 'down': Scroll.smoothScrollBy(0, repeats * stepSize); break; case 'up': Scroll.smoothScrollBy(0, -repeats * stepSize); break; case 'pageDown': Scroll.smoothScrollBy(0, repeats * window.innerHeight / 2); break; case 'fullPageDown': Scroll.smoothScrollBy(0, repeats * window.innerHeight * (settings.fullpagescrollpercent / 100 || 0.85)); break; case 'pageUp': Scroll.smoothScrollBy(0, -repeats * window.innerHeight / 2); break; case 'fullPageUp': Scroll.smoothScrollBy(0, -repeats * window.innerHeight * (settings.fullpagescrollpercent / 100 || 0.85)); break; case 'top': Scroll.smoothScrollBy(0, -document.body.scrollTop - 10); break; case 'bottom': Scroll.smoothScrollBy(0, document.body.scrollHeight - document.body.scrollTop - window.innerHeight + 10); break; case 'left': Scroll.smoothScrollBy(repeats * -stepSize / 2, 0); break; case 'right': Scroll.smoothScrollBy(repeats * stepSize / 2, 0); break; case 'leftmost': Scroll.smoothScrollBy(-document.body.scrollLeft - 10, 0); break; case 'rightmost': Scroll.smoothScrollBy(document.body.scrollWidth - document.body.scrollLeft - window.innerWidth + 20, 0); break; default: break; } } else { switch (type) { case 'down': scrollBy(0, repeats * stepSize); break; case 'up': scrollBy(0, -repeats * stepSize); break; case 'pageDown': scrollBy(0, repeats * window.innerHeight / 2); break; case 'fullPageDown': scrollBy(0, repeats * window.innerHeight * (settings.fullpagescrollpercent / 100 || 0.85)); break; case 'pageUp': scrollBy(0, -repeats * window.innerHeight / 2); break; case 'fullPageUp': scrollBy(0, -repeats * window.innerHeight * (settings.fullpagescrollpercent / 100 || 0.85)); break; case 'top': scrollTo(0, 0); break; case 'bottom': scrollTo(0, document.body.scrollHeight); break; case 'left': scrollBy(-repeats * stepSize, 0); break; case 'right': scrollBy(repeats * stepSize, 0); break; case 'leftmost': scrollTo(0, document.body.scrollTop); break; case 'rightmost': scrollTo(document.body.scrollWidth - document.documentElement.offsetWidth, document.body.scrollTop); break; default: break; } } };
mohitleo9/chromium-vim
content_scripts/scroll.js
JavaScript
mit
4,462
var config = require('../config') var gulp = require('gulp') var gulpSequence = require('gulp-sequence') var getEnabledTasks = require('../lib/getEnabledTasks') var productionTask = function(cb) { var tasks = getEnabledTasks('production') gulpSequence('clean', tasks.codeTasks, 'favicons', 'optimize', 'uglifyJs', cb) } gulp.task('production', productionTask) module.exports = productionTask
youonlyliveonce/24-1.studio
gulpfile.js/tasks/production.js
JavaScript
mit
412