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
// Karma configuration // Generated on Sun Jun 01 2014 13:42:43 GMT+0900 (JST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'requirejs', 'chai'], // list of files / patterns to load in the browser files: [ 'test-main.js', {pattern: 'js/*.js', included: false}, {pattern: 'test/*.js', included: false}, {pattern: 'test/resources/*', included: false} ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
takasan989/karma-requirejs-example
karma.conf.js
JavaScript
mit
1,746
import { NativeModules, NativeEventEmitter } from 'react-native'; import { LOCATION_SERVICES_STATUS_AUTHORIZED, // startScanningForBeacons, updateWayfindingStatus, startScanningSuccessful, startScanningFailure, detectedBeacons, } from '../actions/wayfinding'; export default class WayfindingActor { constructor(store) { this.BeaconManager = NativeModules.CMSBeaconManager; this.BeaconManagerObserver = new NativeEventEmitter(this.BeaconManager); this.dispatch = store.dispatch; this.store = store; this.listeningForBeaconPings = false; this.startListening(); } startListening() { const { BluetoothStatusChanged, LocationServicesAllowedChanged } = this.BeaconManager.Events; this.BeaconManagerObserver.addListener(BluetoothStatusChanged, (body) => { const bluetoothOn = body.bluetoothOn; this.handleWayfindingChanges({ bluetoothOn }); }); this.BeaconManagerObserver.addListener(LocationServicesAllowedChanged, (body) => { const locationServicesStatus = body.locationServicesStatus; this.handleWayfindingChanges({ locationServicesStatus }); }); this.BeaconManager.beginBluetoothAndLocationServicesEvents(); this.listening = true; } handleWayfindingChanges(newState) { const state = this.retrieveState(); const { rangingUUID, rangingIdentifier } = state; let bluetoothOn; if (newState.bluetoothOn != null) { bluetoothOn = newState.bluetoothOn; } else { bluetoothOn = state.bluetoothOn; } let locationServicesStatus; if (newState.locationServicesStatus != null) { locationServicesStatus = newState.locationServicesStatus; } else { locationServicesStatus = state.locationServicesStatus; } this.dispatch(updateWayfindingStatus(bluetoothOn, locationServicesStatus)); if (bluetoothOn && locationServicesStatus === LOCATION_SERVICES_STATUS_AUTHORIZED) { this.startScanningForBeacons(rangingUUID, rangingIdentifier); } else { this.stopListeningForBeaconPings(); } } async startScanningForBeacons(rangingUUID, rangingIdentifier) { try { await this.BeaconManager.startTracking(rangingUUID, rangingIdentifier); this.dispatch(startScanningSuccessful(rangingUUID, rangingIdentifier)); this.listenForBeaconPings(); } catch (e) { console.log(e); this.dispatch(startScanningFailure(e)); this.stopListeningForBeaconPings(); } } stopListeningForBeaconPings() { const { BeaconManagerBeaconPing } = this.BeaconManager.Events; this.BeaconManagerObserver.removeAllListeners(BeaconManagerBeaconPing); this.listeningForBeaconPings = false; } listenForBeaconPings() { if (this.listeningForBeaconPings) { return; } this.listeningForBeaconPings = true; let update = true; let updateTimer; const UPDATE_INTERVAL = 500; // milliseconds const { BeaconManagerBeaconPing } = this.BeaconManager.Events; this.BeaconManagerObserver.addListener(BeaconManagerBeaconPing, (beacons) => { if (update) { updateTimer = null; update = false; this.dispatch(detectedBeacons(beacons)); } else if (updateTimer == null) { updateTimer = setTimeout(() => { update = true; }, UPDATE_INTERVAL); } }); } retrieveState() { const state = this.store.getState(); return { bluetoothOn: state.wayfinding.bluetoothOn, locationServicesStatus: state.wayfinding.locationServicesStatus, rangingUUID: state.wayfinding.rangingUUID, rangingIdentifier: state.wayfinding.rangingIdentifier, }; } }
CMP-Studio/BeaconDeploymentTool
src/actors/wayfindingActor.js
JavaScript
mit
3,664
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Segment, Dimmer, Loader, Container, Message, Modal, Button, Header } from 'semantic-ui-react'; import { showUserPage } from './UserActions'; class UserPage extends Component { componentDidMount() { this.props.dispatch(showUserPage(this.props.match.params.id)); } render() { const { isFetch, redirect, message, error, authentication, user } = this.props; if (isFetch) { return ( <Dimmer inverted active> <Loader size='massive' inverted content="Загрузка" /> </Dimmer> ); } if (error) { return ( <Container text> <Message negative icon='warning sign' header={message} /> </Container> ); } if (!authentication && redirect) { return ( <Modal size="tiny" open onClose={() => { this.props.history.push('/'); }}> <Modal.Header> У вас нет прав для просмотра страницы <span>Профиля</span> </Modal.Header> <Modal.Content> <p>Пожалуйста, авторизируйтесь или создайте учетную запись. Спасибо!</p> </Modal.Content> <Modal.Actions> <Button inverted color='green' onClick={() => { this.props.history.push('/register'); }} content='Зарегистрироваться' /> <Button color='green' onClick={() => { this.props.history.push('/login'); }}> Войти </Button> </Modal.Actions> </Modal> ); } return ( <Segment basic padded='very'> <Header as='h2'>Личный кабинет</Header> { user && Object.keys(user).map(key => <div key={key}>{key} : {user[key]}</div>) } </Segment> ); } } export default connect( store => ({ user: store.user.user, isFetch: store.user.isFetch, authentication: store.user.authentication, message: store.user.message, error: store.user.error, redirect: store.user.redirect }), dispatch => ({dispatch}) )(UserPage);
kvago36/graphql-relay
client/src/modules/UserPage/UserPage.js
JavaScript
mit
2,229
/* jshint node: true */ 'use strict' module.exports = { name: 'ember-ambitious-table' }
dough-com/ember-ambitious-table
index.js
JavaScript
mit
91
define(["require", "exports", "tslib", "../aurelia"], function (require, exports, tslib_1, au) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var MdCarousel = /** @class */ (function () { function MdCarousel(element, taskQueue) { this.element = element; this.taskQueue = taskQueue; this.indicators = true; this.fullWidth = false; this.items = []; } MdCarousel.prototype.itemsChanged = function () { this.refresh(); }; MdCarousel.prototype.attached = function () { if (this.fullWidth) { this.element.classList.add("carousel-slider"); } }; MdCarousel.prototype.detached = function () { if (this.instance) { this.instance.destroy(); } }; MdCarousel.prototype.refresh = function () { var _this = this; if (!this.items.length) { return; } var options = { fullWidth: this.fullWidth, indicators: this.indicators, dist: this.dist, duration: this.duration, noWrap: this.noWrap, numVisible: this.numVisible, padding: this.padding, shift: this.shift, onCycleTo: function (current, dragged) { return au.fireMaterializeEvent(_this.element, "cycle-to", { current: current, dragged: dragged }); } }; au.cleanOptions(options); this.taskQueue.queueTask(function () { _this.detached(); _this.instance = new M.Carousel(_this.element, options); }); }; MdCarousel.prototype.next = function (n) { this.instance.next(n); }; MdCarousel.prototype.prev = function (n) { this.instance.prev(n); }; MdCarousel.prototype.set = function (n) { this.instance.set(n); }; tslib_1.__decorate([ au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Boolean) ], MdCarousel.prototype, "indicators", void 0); tslib_1.__decorate([ au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Boolean) ], MdCarousel.prototype, "fullWidth", void 0); tslib_1.__decorate([ au.ato.bindable.numberMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Number) ], MdCarousel.prototype, "duration", void 0); tslib_1.__decorate([ au.ato.bindable.numberMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Number) ], MdCarousel.prototype, "dist", void 0); tslib_1.__decorate([ au.ato.bindable.numberMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Number) ], MdCarousel.prototype, "shift", void 0); tslib_1.__decorate([ au.ato.bindable.numberMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Number) ], MdCarousel.prototype, "padding", void 0); tslib_1.__decorate([ au.ato.bindable.numberMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Number) ], MdCarousel.prototype, "numVisible", void 0); tslib_1.__decorate([ au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }), tslib_1.__metadata("design:type", Boolean) ], MdCarousel.prototype, "noWrap", void 0); tslib_1.__decorate([ au.children("md-carousel-item"), tslib_1.__metadata("design:type", Array) ], MdCarousel.prototype, "items", void 0); MdCarousel = tslib_1.__decorate([ au.customElement("md-carousel"), au.autoinject, tslib_1.__metadata("design:paramtypes", [Element, au.TaskQueue]) ], MdCarousel); return MdCarousel; }()); exports.MdCarousel = MdCarousel; }); //# sourceMappingURL=carousel.js.map
aurelia-ui-toolkits/aurelia-materialize-bridge
dist/amd/carousel/carousel.js
JavaScript
mit
4,477
'use strict'; window.angular.module('demoModule',['NgStorageModule']).config(function(localStorageServiceProvider){ localStorageServiceProvider.setPrefix('demoPrefix'); //localStorageServiceProvider.setStorageCookieDomain('example.com'); //localStorageServiceProvider.setStorageType('sessionStorage'); }).controller('DemoCtrl', function($scope,localStorageService){ $scope.ngStorageDemo = localStorageService.get('ngStorageDemo'); $scope.$watch('ngStorageDemo',function(value){ localStorageService.set('ngStorageDemo',value); $scope.ngStorageDemoValue = localStorageService.get('ngStorageDemo'); }); $scope.storageType = 'Local storage'; if (localStorageService.getStorageType().indexOf('session')>=0){ $scope.storageType = 'Session storage'; } if (!localStorageService.isSupported){ $scope.storageType = 'Cookie'; } $scope.$watch(function(){ return localStorageService.get('ngStorageDemo'); },function(value){ $scope.ngStorageDemo = value; }); $scope.clearAll = localStorageService.clearAll; } );
andreschait/ng-storage
demo/demo-app.js
JavaScript
mit
1,048
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = { extends: '@looker/stylelint-config', }
looker-open-source/components
.stylelintrc.js
JavaScript
mit
1,170
/* Server entry point */ // Only explicity set here . All other modules down the require chain use // the babel.js strict transformer. 'use strict'; if (!process.getuid()) throw new Error("Refusing to run as root."); const config = require('../config'), opts = require('./opts'), winston = require('winston'); // Read command line arguments. Modifies ../config, so loaded right after it. opts.parse_args(); // Some config defaults for backwards compatibility. // TODO: Centralised config defaulting in a later version if (!config.link_boards) config.link_boards = []; // Build an object of all possible board-like link targets const targets = config.link_targets = {}; for (let board of config.BOARDS) { targets[board] = `../${board}/`; } for (let board of config.PSUEDO_BOARDS.concat(config.link_boards)) { targets[board[0]] = board[1]; } // More verbose logging if (config.DEBUG) { winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {level: 'verbose'}); winston.warn("Running in (insecure) debug mode."); winston.warn("Do not use on the public internet."); } // For production else { winston.remove(winston.transports.Console); winston.add(winston.transports.File, { level: 'error', filename: 'error.log', handleExceptions: true }); } // Detect major version and add extra transformers as needed const tranformers = ['es6.destructuring', 'es6.parameters', 'strict'], version = +process.version[1] const features = { 5: 'es6.spread', 4: 'es6.arrowFunctions', 3: 'es6.properties.computed' } for (let i = version; i >= 3; i--) { if (version === i) break; tranformers.push(features[i]) } // ES6 transpiler require hook. We only enable some not yet implemented // feature transformers and rely on natives for others. require('babel/register')({ // Babel has trouble with hot.js, so we ignore the config module ignore: /node_modules|config/, sourceMaps: config.DEBUG && 'inline', // Stack traces should at least have the exact line numbers displayed // correctly retainLines: true, whitelist: tranformers }); // Require the actual server require('./server');
reiclone/doushio
server/index.js
JavaScript
mit
2,136
// All code points in the `Khmer` script as per Unicode v6.0.0: [ 0x1780, 0x1781, 0x1782, 0x1783, 0x1784, 0x1785, 0x1786, 0x1787, 0x1788, 0x1789, 0x178A, 0x178B, 0x178C, 0x178D, 0x178E, 0x178F, 0x1790, 0x1791, 0x1792, 0x1793, 0x1794, 0x1795, 0x1796, 0x1797, 0x1798, 0x1799, 0x179A, 0x179B, 0x179C, 0x179D, 0x179E, 0x179F, 0x17A0, 0x17A1, 0x17A2, 0x17A3, 0x17A4, 0x17A5, 0x17A6, 0x17A7, 0x17A8, 0x17A9, 0x17AA, 0x17AB, 0x17AC, 0x17AD, 0x17AE, 0x17AF, 0x17B0, 0x17B1, 0x17B2, 0x17B3, 0x17B4, 0x17B5, 0x17B6, 0x17B7, 0x17B8, 0x17B9, 0x17BA, 0x17BB, 0x17BC, 0x17BD, 0x17BE, 0x17BF, 0x17C0, 0x17C1, 0x17C2, 0x17C3, 0x17C4, 0x17C5, 0x17C6, 0x17C7, 0x17C8, 0x17C9, 0x17CA, 0x17CB, 0x17CC, 0x17CD, 0x17CE, 0x17CF, 0x17D0, 0x17D1, 0x17D2, 0x17D3, 0x17D4, 0x17D5, 0x17D6, 0x17D7, 0x17D8, 0x17D9, 0x17DA, 0x17DB, 0x17DC, 0x17DD, 0x17E0, 0x17E1, 0x17E2, 0x17E3, 0x17E4, 0x17E5, 0x17E6, 0x17E7, 0x17E8, 0x17E9, 0x17F0, 0x17F1, 0x17F2, 0x17F3, 0x17F4, 0x17F5, 0x17F6, 0x17F7, 0x17F8, 0x17F9, 0x19E0, 0x19E1, 0x19E2, 0x19E3, 0x19E4, 0x19E5, 0x19E6, 0x19E7, 0x19E8, 0x19E9, 0x19EA, 0x19EB, 0x19EC, 0x19ED, 0x19EE, 0x19EF, 0x19F0, 0x19F1, 0x19F2, 0x19F3, 0x19F4, 0x19F5, 0x19F6, 0x19F7, 0x19F8, 0x19F9, 0x19FA, 0x19FB, 0x19FC, 0x19FD, 0x19FE, 0x19FF ];
mathiasbynens/unicode-data
6.0.0/scripts/Khmer-code-points.js
JavaScript
mit
1,381
define([ ], function () { /** * Helper for use the requestAnimationFrame function (along with cancelling). Some older browsers that we still * support require prefixes therefore this helper acts as a helper for determining which one to use. * * @exports get-animation-frame * * @public */ function getAnimationFrame (win) { win = win || window; var obj = { request: win.requestAnimationFrame, cancel: win.cancelAnimationFrame || win.cancelRequestAnimationFrame }, methods = { request: 'requestAnimationFrame', cancel: 'cancelAnimationFrame' }, vendors = ['ms', 'moz', 'webkit', 'o']; // Loop through the list of vendors if the basic non-vendor function doesn't already exist. for (var x = 0; x < vendors.length && !obj.request; ++x) { var vendor = vendors[x], request = vendor + 'RequestAnimationFrame', cancel = vendor + 'CancelAnimationFrame'; obj.request = win[request]; methods.request = request; if (win[cancel]) { obj.cancel = win[cancel]; methods.cancel = cancel; } else { cancel = vendor + 'CancelRequestAnimationFrame'; obj.cancel = win[cancel]; methods.cancel = cancel; } } return methods; } return getAnimationFrame; });
rockabox/Auxilium.js
src/get-animation-frame.js
JavaScript
mit
1,534
import Router from 'koa-router'; import koaBody from 'koa-body'; import usersSvc from "../services/usersSvc"; import showPage from "../controllers/showPage"; import getLogger from "../lib/log"; const logger = getLogger(module); const log = logger.debug; const { createUser, getAllUsers, getUserByName, checkPassword } = usersSvc; const router = new Router(); router // Get all users .get("/users", async (ctx) => { ctx.body = await getAllUsers(); }) // Get user by name .get('/users/:name', async (ctx) => { const userData = await getUserByName(ctx.params.name); if (userData) { ctx.body = { id: userData._id, username: userData.username, email: userData.email, created: userData.created, } } else { ctx.status = 204 } }) // Create User .post("/user/create", koaBody(), async (ctx, next) => { const { username, email, password } = ctx.request.body; if (!username || !email || !password) { return next(new Error("all data are required")); } try { const newUser = await createUser(username, email, password ); ctx.body = { user: newUser.get("username"), email: newUser.get("email") }; } catch (err) { return next(err); } // TODO: don't need return return ctx.body; }) .post("/user/login", koaBody(), async (ctx, next) => { const { username, password } = ctx.request.body; try { const userData = await checkPassword(username, password); ctx.body = userData; } catch (err) { return next(err); } return { user: username }; // Log in via cookie // req.session.user = user._id; // res.cookie("access", "AOK"); // res.redirect("dashboard"); }); /* Home page */ // router.get("/", function(req, res) { // res.redirect("/home"); // }); /* Login page */ // router.get("/account/login", async (...args) => { // await showPage("login", {title: "Log In"}, ...args); // }); // router.post("/login", loginController); // // /* Registration page */ // router.get("/account/create", async (...args) => { // await showPage("registration", {title: "Registration"}, ...args); // }); // // router.post("/account/create", require("./signup").post); // // /* Log Out */ // // router.get("/logout", require("./logout").post); // // /* Dashboard page */ // router.get("/dashboard", /* checkAccess, */async (...args) => { // await showPage("dashboard", {title: "Dashboard"}, ...args); // }); export function routes() { return router.routes() } export function allowedMethods() { return router.allowedMethods() } /* check Auth via cookie */ // function checkAccess(req, res, next) { // if (!req.cookies || !req.cookies.access || req.cookies.access !== "AOK") { // res.redirect("/login"); // } else { // next(); // } // }
kkrisstoff/micro-auth-mongo
src/middleware/routes.js
JavaScript
mit
2,850
(function(HTML) { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module("stringify"); test('API', function() { ok(HTML._.fn.stringify); }); }(HTML));
nbubna/HTML
test/stringify.js
JavaScript
mit
752
var _und = require("../node_modules/underscore/underscore-min.js"); var db = require('../db_config.js'); exports.list = function(callback){ db.ListaCompra.find({},function(error,listaCompras){ if(error){ callback({error: 'Não foi possivel retornar as listas de compras.'}); }else{ callback(listaCompras); } }); }; exports.listaCompraById = function(id,callback){ db.ListaCompra.findById(id, function(error, listaCompra){ if(error){ callback({error: 'Não foi possivel retornar a lista de compra'}); return; } if(!listaCompra){ callback({error: 'Não existe o lista de compra com esse id.'}); } else{ callback(listaCompra); } }); }; exports.save = function(descricao,itens,callback){ var _listaCompra = new db.ListaCompra ({ 'descricao': descricao, 'itens':itens }); _listaCompra.save(function(error,listaCompra){ if(error){ callback({error: 'Não foi possivel salvar a lista de Compra.'}); }else{ callback(listaCompra); } }); }; exports.update = function(id,descricao,itens,callback){ db.ListaCompra.findById(id,function(error,listaCompra){ if(descricao){ listaCompra.descricao = descricao; } if(itens){ listaCompra.itens = itens; } listaCompra.save(function(error,listaCompra){ if(error){ callback({error: 'Não foi possivel atualizar a lista de compras'}); }else{ callback(listaCompra); } }); }); }; exports.removeItem = function(idLista,idItem,callback){ db.ListaCompra.findOneAndUpdate({_id : idLista}, {$pull: {itens: {_id: idItem }}}, function(error,listaCompra){ if(!error){ callback({response:'Item de compra excluído com sucesso.'}); } } ); } exports.delete = function(id,callback){ db.ListaCompra.findById(id,function(error, listaCompra){ if(error){ callback({error: 'Não foi possivel excluir a lista de compra.'}); } else if(listaCompra == null) { callback({error: 'Não existe lista de compra com esse id.'}); } else { listaCompra.remove(function(error,listaCompra){ if(!error){ callback({response:'Lista de compra excluído com sucesso.'}); } }); } }); };
CarlosPanarello/ListaCompra
controller/listaCompraController.js
JavaScript
mit
2,165
module.exports = Helper; var path = require('path'); function Helper(basePath, isolate) { this.basePath = basePath || '/'; this.isolate = isolate === undefined ? true : !!isolate; } Helper.prototype._prepareRelative = _prepareRelative; Helper.prototype.absolutePath = absolutePath; Helper.prototype.relativePath = relativePath; function absolutePath(_path) { _path = path.join(this.basePath, _path); var rel = this._prepareRelative(_path, this.basePath), abs = rel === null ? null : path.join(this.basePath, rel); return abs; } function relativePath(_path) { var rel = this._prepareRelative(_path); return rel; } function _prepareRelative(_path) { _path = path.normalize(_path); var rel = path.relative(this.basePath, _path), relArr = rel.split(path.sep); if (this.isolate && relArr[0] === '..') { return null; } return rel; }
Kroid/explorer
src/pathHelper.js
JavaScript
mit
883
module.exports = props => { const body = props && props.body ? props.body : ""; const template = ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <title>draft-js-markdown-plugin Demo</title> <link rel="stylesheet" href="./css/normalize.css"/> <link rel="stylesheet" href="./css/base.css"/> <link rel="stylesheet" href="./css/Draft.css"/> <link rel="stylesheet" href="./css/prism.css"/> <link rel="stylesheet" href="./css/CheckableListItem.css"/> <link rel="stylesheet" href="./app.css"/> <link href="https://fonts.googleapis.com/css?family=Open+Sans:700,300,700i,300i" rel="stylesheet" type="text/css"/> <link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'> <!-- ${new Date()} --> </head> <body> <div id="root">${body}</div> <script src="./app.js"></script> </body> </html>`.trim(); return template.trim(); };
withspectrum/draft-js-markdown-plugin
demo/index.html.js
JavaScript
mit
1,153
define([], function () { function hasFont(className, fontFamily) { var span = document.createElement('span'); span.className = className; span.style.display = 'none'; document.body.insertBefore(span, document.body.firstChild); if (window.getComputedStyle(span, null).getPropertyValue('font-family') === fontFamily) { document.body.removeChild(span); return true; } document.body.removeChild(span); return false; } window.AutomizySidebar = window.$AS = new AutomizyProject({ variables: { groups:[], inners:[], tabs:[] }, plugins: [ { name: 'fontawesome', skipCondition: function(){return hasFont('fa', 'FontAwesome')}, css: "vendor/fontawesome/css/font-awesome.min.css" }, { name: 'automizy-js', skipCondition: typeof AutomizyJs !== 'undefined', css: "vendor/automizy-js/automizy.css", js: [ "vendor/automizy-js/languages/en_US.js", "vendor/automizy-js/automizy.js" ], complete: function () { $A.setTranslate(window.I18N || {}); } }, { name: 'automizy-js-api', skipCondition: typeof AutomizyJsApi !== 'undefined', js: "vendor/automizy-js-api/automizy.api.js", requiredPlugins: [ 'automizy-js' ] } ] }); });
Automizy/Automizy-Sidebar
src/js/init/init.js
JavaScript
mit
1,670
// ==UserScript== // @name Github: Back button's back, all right! // @namespace http://github.com/carols10cents/github-back-button // @description Restores the functionality of the back button on github pull requests when navigating to the commits/files tabs. // @include http://github.com/* // @include https://github.com/* // @include http://www.github.com/* // @include https://www.github.com/* // @version 1 // @grant none // ==/UserScript== $(".js-pull-request-tab").removeClass("js-pull-request-tab"); $(window).on('pjax:end', function(e) { $(".js-pull-request-tab").removeClass("js-pull-request-tab"); });
carols10cents/github-back-button
github-back-button.user.js
JavaScript
mit
652
/** @babel */ /** @jsx etch.dom */ import { CompositeDisposable } from 'atom'; import { FitAddon } from 'xterm-addon-fit'; import etch from 'etch'; import ThemeMatcher from './theme-matcher'; const TERMINAL_PADDING = 5; export default class TerminalView { constructor(session) { this.disposables = new CompositeDisposable(); this.session = session; // Load the Fit Addon this.fitAddon = new FitAddon(); this.session.xterm.loadAddon(this.fitAddon); this.disposables.add(this.fitAddon); // // Observe the Session to know when it is destroyed so that we can // clean up our state (i.e. remove event observers). // this.session.onDidDestroy(this.destroy.bind(this)); // TODO: Documentation says this should be set for Atom... Research! etch.setScheduler(atom.views); etch.initialize(this); this.observeResizeEvents(); } render() { // TODO: Convert to <div class="terminal-view"> return ( <terminal-view attributes={{tabindex: -1}} on={{focus: this.didFocus}} /> ); } update() { return etch.update(this); } destroy() { this.resizeObserver.disconnect(); this.disposables.dispose(); etch.destroy(this); } // // Attach the Xterm instance from the session to this view's element, then // focus and resize it to fit its viewport. // openTerminal() { this.session.xterm.open(this.element); this.session.xterm.focus(); this.observeAndApplyThemeStyles(); this.observeAndApplyTypeSettings(); } // // Observe for resize events so that we can instruct the Xterm instance // to recalculate rows and columns to fit into its viewport when it // changes. // observeResizeEvents() { this.resizeObserver = new ResizeObserver(this.didResize.bind(this)); this.resizeObserver.observe(this.element); } resizeTerminalToFitContainer() { if (!this.session && !this.session.pty && !this.session.xterm) { return; } // Set padding and resize the terminal to fit its container (as best as possible) this.session.xterm.element.style.padding = `${TERMINAL_PADDING}px`; try { this.fitAddon.fit()} catch(error) { } // TODO: Yuck // Check the new size and add additional padding to the top of the // terminal so that it fills all available space. // TODO: Extract this into a new calculatePadding() or something... const elementStyles = getComputedStyle(this.element); const xtermElementStyles = getComputedStyle(this.session.xterm.element); const elementHeight = parseInt(elementStyles.height, 10); const xtermHeight = parseInt(xtermElementStyles.height, 10); const newHeight = elementHeight - xtermHeight + TERMINAL_PADDING; if (!isNaN(newHeight)) { this.fitAddon.fit(); this.session.xterm.element.style.paddingBottom = `${newHeight}px`; } // Update Pseudoterminal Process w/New Dimensions this.session.pty.resize(this.session.xterm.cols, this.session.xterm.rows); } // // Resizes the terminal instance to fit its parent container. Once the new // dimensions are established, the calculated columns and rows are passed to // the pseudoterminal (pty) to remain consistent. // didResize() { if (!this.session.xterm.element) { this.openTerminal(); } this.resizeTerminalToFitContainer(); } // // Transfer focus to the Xterm instance when the element is focused. When // switching between tabs, Atom will send a focus event to the element, // which makes it easy for us to delegate focus to the Xterm instance, whose // element we are managing in our view. // didFocus(/* event */) { this.session.xterm.focus(); } // // Observe for changes to the matchTheme configuration directive and apply // the styles when the value changes. This will also apply them when called // for the first time. // observeAndApplyThemeStyles() { if (this.isObservingThemeSettings) return; this.disposables.add(atom.config.onDidChange('terminal-tab.matchTheme', this.applyThemeStyles.bind(this))); this.disposables.add(atom.themes.onDidChangeActiveThemes(this.applyThemeStyles.bind(this))); this.isObservingThemeSettings = true; this.applyThemeStyles(); } // // Observe for changes to the Editor configuration for Atom and apply // the type settings when the values we are interested in change. This // will also apply them when called for the first time. // observeAndApplyTypeSettings() { if (this.isObservingTypeSettings) return; this.disposables.add(atom.config.onDidChange('terminal-tab.fontFamily', this.applyTypeSettings.bind(this))); this.disposables.add(atom.config.onDidChange('editor.fontFamily', this.applyTypeSettings.bind(this))); this.disposables.add(atom.config.onDidChange('editor.fontSize', this.applyTypeSettings.bind(this))); this.disposables.add(atom.config.onDidChange('editor.lineHeight', this.applyTypeSettings.bind(this))); this.isObservingTypeSettings = true; this.applyTypeSettings(); } // // Attempts to match the Xterm instance with the current Atom theme colors. // // TODO: This should take advantage of update() // TODO: This doesn't undo the font settings when the theme is disabled... // applyThemeStyles() { // Bail out if the user has not requested to match the theme styles if (!atom.config.get('terminal-tab.matchTheme')) { this.session.xterm.setOption('theme', {}); return; } // Parse the Atom theme styles and configure the Xterm to match. const themeStyles = ThemeMatcher.parseThemeStyles(); this.session.xterm.setOption('theme', themeStyles); } // // Attempts to match the Atom type settings (font family, size and line height) with // Xterm. // applyTypeSettings() { // // Set the font family in Xterm to match Atom. // const fontFamily = atom.config.get('terminal-tab.fontFamily') || atom.config.get('editor.fontFamily') || 'Menlo, Consolas, "DejaVu Sans Mono", monospace'; // Atom default (as of 1.25.0) this.session.xterm.setOption('fontFamily', fontFamily); // // Set the font size in Xterm to match Atom. // const fontSize = atom.config.get('editor.fontSize'); this.session.xterm.setOption('fontSize', fontSize); // // Set the line height in Xterm to match Atom. // // TODO: This is disabled, because the line height as specified in // Atom is not the same as what Xterm is using to render its // lines (i.e. 1.5 in Atom is more like 2x in Xterm). Need to // figure out the correct conversion or fix the bug, if there // is one. // // const lineHeight = atom.config.get('editor.lineHeight'); // this.session.xterm.setOption('lineHeight', lineHeight); // // Changing the font size and/or line height requires that we // recalcuate the size of the Xterm instance. // // TODO: Call the renamed method (i.e. resizeTerminalToFitContainer()) // this.didResize(); } }
jsmecham/atom-terminal-tab
lib/terminal-view.js
JavaScript
mit
7,071
import difference from 'lodash.difference'; class EventHandler { constructor(owner, filename, persistent, recursive) { this.owner = owner; this.filename = filename; this.persistent = persistent; this.recursive = recursive; } } let handlers = []; export default class EventHandlers { static add(owner, filename, persistent, recursive) { handlers.push(new EventHandler(owner, filename, persistent, recursive)); } static remove(owner) { handlers = handlers.filter((handler) => handler.owner !== owner); } static emit(event, path) { let emitHandlers = handlers.filter((handler) => handler.recursive ? !handler.filename.startsWith(path) : handler.filename === path); emitHandlers.forEach((handler) => handler.owner.onChange(0, event, path)); // remove single time handlers emitHandlers = emitHandlers.filter((handler) => !handler.persistent); if (emitHandlers.length) { handlers = difference(handlers, emitHandlers); emitHandlers.forEach((handler) => handler.owner.close()); } } }
kmalakoff/fs-memory
src/memory-file-system/lib/event-handlers.js
JavaScript
mit
1,058
import angular from 'angular'; import AppCore from './core/core.module'; import service from './app.service'; import component from './app.component'; import constants from './app.constants'; import config from './app.config'; import AppHeader from './features/appHeader/appHeader.module'; import AppBody from './features/appBody/appBody.module'; /** * App module */ const appModule = angular.module('app', [ AppCore.name, AppBody.name, AppHeader.name, ]) .config(config) .constant('SEARCHAPI', constants) .service('AppService', service) .component('app', component); export default appModule;
debatanu-thakur/music-search
src/app/app.module.js
JavaScript
mit
608
import React from 'react'; import PropTypes from 'prop-types'; const ArtistList = props => { return ( <div> {props.data} </div> ); }; ArtistList.propTypes = { data: PropTypes.array.isRequired }; export default ArtistList;
kmcarter/karaoke-song-lister
src/components/common/ArtistList.js
JavaScript
mit
244
version https://git-lfs.github.com/spec/v1 oid sha256:2383b51b91d99eafd99a672c098cf3da83592f5cbb5b4fd5f558e7c72e2926da size 5129
yogeshsaroya/new-cdnjs
ajax/libs/extjs/4.2.1/src/form/action/DirectSubmit.js
JavaScript
mit
129
/** * Created by unsad on 2017/3/29. */ const webpackMerge = require('webpack-merge'); // 合并webpack配置 const base = require('./base'); const path = require('path'); module.exports = webpackMerge(base, { // specific config output: { filename: '[name].bundle.js' }, resolve: { alias: { config: path.resolve(__dirname, './../config/dev.js') } }, devtool: 'eval-source-map', module: { rules: [ { test: /\.stylus$/, exclude: [/node_modules/], use: [ 'vue-style-loader', { loader: 'css-loader', options: { sourceMap: true } }, 'postcss-loader', { loader: 'stylus-loader', options: { sourceMap: true } } ] }, { test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { sourceMap: true } }, 'postcss-loader' ] } ] } });
unsad/Reading-App
webpack-config/dev.js
JavaScript
mit
1,109
import React from 'react' import EmailPreferences from './index' export default { title: 'pages/EmailPreferences', component: EmailPreferences, } export const Default = () => <EmailPreferences />
KissKissBankBank/kitten
assets/javascripts/kitten/karl/pages/email-preferences/stories.js
JavaScript
mit
202
/* Copyright (c) 2015 Paul McKay * * This file is part of the 'dry-layers' package for Node.js and is subject to * the terms of the MIT License. If a copy of the license was not distributed * with this file, you can get one at: * https://raw.githubusercontent.com/pmckay/dry-layers/master/LICENSE. */ var express = require('express'); var mongodb = require('mongodb'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var ObjectID = mongodb.ObjectID; var Registry = require('./registry.js'); var Renderer = require('./renderer.js'); var MeetingService = function () { var self = this; this.createRouter = function () { var router = express.Router(); router.get('/sign_in/meeting', function (req, res) { if (!req.query.url) { res.send(400); rese.send("Bad request"); return; } var html = Renderer.render('views/meeting_sign_in.jade', { title : 'Meeting Sign In', url : req.query.url }); res.send(html); }); router.post('/sign_in/meeting', function (req, res, next) { passport.authenticate('meeting', function (err, user, info) { if (err) { } if (!user) { res.status(401); res.send('Unauthorized'); return; } req.logIn(user, function (err) { if (err) { } res.json({}); }); })(req, res, next); }); return router; } this.createStrategy = function () { return new LocalStrategy({ usernameField : 'meeting', passwordField : 'password', passReqToCallback : true }, function (req, meeting, password, done) { process.nextTick(function () { var meetings = Registry.getCollection('meeting'); meetings.findOne({ _id: meeting }, function (err, meeting) { if (err) { return done(err); } if (!meeting) { return done(null, false, { message: 'Unknown meeting ' + meeting }); } if (meeting.password != password) { return done(null, false, { message: 'Invalid password' }); } user = self.createUser(); if (!meeting.users) { meeting.users = []; } meeting.users.push(user); meetings.update({ _id : meeting._id }, { $set : meeting }, function (err, result) { if (err) { return done(null, false, { message: 'Cannot update meeting' }); } return done(null, { user : user, meeting : meeting }); }); }); }); }); } this.createUser = function () { return { _id : (new ObjectID()).toString(), username : '', roles : ['User'] } } if (MeetingService.caller != MeetingService.getInstance) { throw new Error('') } } MeetingService.getInstance = function () { if (this.instance == null) { this.instance = new MeetingService(); } return this.instance; } MeetingService.instance = null; module.exports = MeetingService.getInstance();
pmckay/dry-layers
lib/meeting_service.js
JavaScript
mit
2,936
var _ = require('underscore'); module.exports = ObjectDecorator; /** * @constructor */ function ObjectDecorator() { 'use strict'; this.decorations = []; } /** * @param arguments - One or more decoration objects */ ObjectDecorator.prototype.addDecoration = function () { 'use strict'; _.each(arguments, function (decoration) { this.decorations.push(decoration); }, this); }; /** * @param object {Object} - Object to be decorated */ ObjectDecorator.prototype.decorate = function (object) { 'use strict'; _.each(this.decorations, function (decoration) { decoration.decorate(object); }); };
DyslexicChris/Folio
lib/decorators/ObjectDecorator.js
JavaScript
mit
648
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var film = exports.film = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M0 2v12h16v-12h-16zM3 13h-2v-2h2v2zM3 9h-2v-2h2v2zM3 5h-2v-2h2v2zM12 13h-8v-10h8v10zM15 13h-2v-2h2v2zM15 9h-2v-2h2v2zM15 5h-2v-2h2v2zM6 5v6l4-3z" } }] };
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/icomoon/film.js
JavaScript
mit
354
/** * 账户登录 */ var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; var logger = require('log4js').getLogger(path.relative(process.cwd(), __filename)); var captchaParser = require('../../captcha'); // var trainDataMap = captchaParser.loadTrainDataSync(); module.exports = exports = function(options, done){ options = options || {}; var trunks = []; var child = spawn( 'casperjs', [ '../casper/login.casper.js', '--ignore-ssl-errors=true', '--tempdir=' + path.resolve(options['cwd'], options['tempdir']), '--release=' + (options['release'] || false), //** 默认按开发模式运行 '--user=' + options['user'], '--pass=' + options['pass'], '--provid=' + options['provid'], ],{ cwd: __dirname, } ); child.on('error', function(err){ logger.debug(err); done(err); }); child.stderr.on('data', function(err){ logger.debug(err); done(err); }); child.stdout.on('data', function(data){ //** 请求输入验证码 if(/please input captcha verifyCode/.test(data.toString())){ console.log(data.toString()); //** 解析验证码 var captchaImageFile = path.join(options.cwd, options.tempdir, '/' + options['user'] + '_captcha.jpg'); if(fs.existsSync(captchaImageFile)){ // captchaParser.getAllOcr(captchaImageFile, trainDataMap, function(err, result){ captchaParser.getAllOcrSimple(captchaImageFile, function(err, result){ if(err){ logger.error(err); //** 虽然错误,但是继续流程,输入空验证码,保证phantomjs正确关闭 //** 未识别出验证码,输入空验证码 child.stdin.write(''); child.stdin.write('\n'); return; } console.log('captcha text: ' + result); //** 输入验证码 child.stdin.write(result); child.stdin.write('\n'); }); }else{ done('验证码文件不存在,分析验证码不能执行。'); } }else if(/do you confirm, yes or no/.test(data.toString())){ console.log(data.toString()); //** 确认输入验证码 child.stdin.write('yes'); child.stdin.write('\n'); child.stdin.end(); } trunks.push(data); }); child.on('close', function(code){ if(code != 0) return done('login() 非正常退出 code: ' + code); var data = trunks.join('').toString().replace(/(\t|\r|\n)/g,''); logger.debug('自动登录程序返回内容: ' + data); var responseJson = (data.match(/<response>(.*?)<\/response>/) || [])[1]; var response = {}; try{ response = JSON.parse(responseJson || '{}'); }catch(e){}; done(null, response); }); child.stdout.pipe(process.stdout); }
williambai/beyond-webapp
unicom/libs/cbss/lib/login.js
JavaScript
mit
2,652
module.exports = { parser: "@typescript-eslint/parser", // Specifies the ESLint parser extends: [ "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended", "plugin:react/recommended", "prettier", "prettier/@typescript-eslint", "prettier/react", ], plugins: ["react", "@typescript-eslint", "prettier"], parserOptions: { project: "./tsconfig.json", }, settings: { react: { pragma: "React", version: "detect", }, }, env: { browser: true, jasmine: true, jest: true, }, overrides: [ { files: ["*.ts"], rules: { camelcase: [2, { properties: "never" }], }, }, ], };
scottdurow/RibbonWorkbench
SmartButtonsUCI/SmartButtons.ClientHooks/.eslintrc.js
JavaScript
mit
759
initSidebarItems({"constant":[["DIGITS",""],["EPSILON",""],["INFINITY",""],["MANTISSA_DIGITS",""],["MAX","Largest finite f64 value"],["MAX_10_EXP",""],["MAX_EXP",""],["MAX_VALUE","Largest finite f64 value"],["MIN","Smallest finite f64 value"],["MIN_10_EXP",""],["MIN_EXP",""],["MIN_POSITIVE","Smallest positive, normalized f64 value"],["MIN_POS_VALUE","Smallest positive, normalized f64 value"],["MIN_VALUE","Smallest finite f64 value"],["NAN",""],["NEG_INFINITY",""],["RADIX",""]],"mod":[["consts","Various useful constants."]]});
ArcherSys/ArcherSys
Rust/share/doc/rust/html/core/f64/sidebar-items.js
JavaScript
mit
531
const Storage = { set(key,value,expiration=8640000000){//default expiration time is 100 days var data = { data:value, expiration:(new Date()).getTime()+expiration } window.localStorage.setItem(key, JSON.stringify(data)) }, get(key){ var value = window.localStorage.getItem(key); if(value){ value = JSON.parse(value) if(value.expiration > (new Date()).getTime()){ return value.data; }else{ window.localStorage.removeItem(key); return null; } } else{ return null; } } } export default Storage
summerstream/react-practise
src/lib/storage.js
JavaScript
mit
703
import expect from 'expect-legacy'; import range from 'lodash/fp/range'; import { applyMiddleware, createStore } from 'redux'; import { createLogic, createLogicMiddleware } from '../src/index'; describe('createLogicMiddleware-many-logic', () => { describe('with validate and process', () => { const NUM_LOGICS = 200; // 230 with cancel optimization let mw; let store; beforeEach(() => { const arrLogic = range(0, NUM_LOGICS).map(() => createLogic({ type: 'foo', validate({ action }, allow) { allow({ ...action, validates: action.validates + 1 }); }, process({ action }, dispatch, done) { dispatch({ type: 'foo-success' }); done(); } }) ); mw = createLogicMiddleware(arrLogic); const reducer = (state = { validates: 0, processes: 0 }, action) => { switch (action.type) { case 'foo': return { ...state, validates: state.validates + action.validates }; case 'foo-success': return { ...state, processes: state.processes + 1 }; default: return state; } }; store = createStore(reducer, undefined, applyMiddleware(mw)); store.dispatch({ type: 'foo', validates: 0 }); }); it('expect state to be updated', () => { expect(store.getState()).toEqual({ validates: NUM_LOGICS, processes: NUM_LOGICS }); }); }); describe('with validate', () => { const NUM_LOGICS = 300; // 370 with cancel optimization let mw; let store; beforeEach(() => { const arrLogic = range(0, NUM_LOGICS).map(() => createLogic({ type: 'foo', validate({ action }, allow) { allow({ ...action, validates: action.validates + 1 }); } }) ); mw = createLogicMiddleware(arrLogic); const reducer = (state = { validates: 0, processes: 0 }, action) => { switch (action.type) { case 'foo': return { ...state, validates: state.validates + action.validates }; default: return state; } }; store = createStore(reducer, undefined, applyMiddleware(mw)); store.dispatch({ type: 'foo', validates: 0 }); }); it('expect state to be updated', () => { expect(store.getState()).toEqual({ validates: NUM_LOGICS, processes: 0 }); }); }); describe('with process', () => { // single-test 240, with mergeMapOrTap 450 // full suite 350, with mergeMapOrTap 540 const NUM_LOGICS = 600; // 350 with optimizations let mw1; let mw2; let store; beforeEach(async () => { const arrLogic = range(0, NUM_LOGICS).map(() => createLogic({ type: 'foo', process({ action }, dispatch, done) { dispatch({ type: 'foo-success' }); done(); } }) ); mw1 = createLogicMiddleware(arrLogic.slice(0, 300)); mw2 = createLogicMiddleware(arrLogic.slice(300)); const reducer = (state = { validates: 0, processes: 0 }, action) => { switch (action.type) { case 'foo': return { ...state, validates: state.validates + action.validates }; case 'foo-success': return { ...state, processes: state.processes + 1 }; default: return state; } }; store = createStore(reducer, undefined, applyMiddleware(mw1, mw2)); store.dispatch({ type: 'foo', validates: 0 }); return Promise.all([mw1.whenComplete(), mw2.whenComplete()]); }); it('expect state to be updated', () => { expect(store.getState()).toEqual({ validates: 0, processes: NUM_LOGICS }); }); }); });
jeffbski/redux-logic
test/createLogicMiddleware-many-logic.spec.js
JavaScript
mit
4,048
/** * Tests the sensor class, mapping the input of the sensors to correct values */ var expect = require('chai').expect; var RxBotics = require('rxbotics'); describe('RxBotics.Sensor', function() { var sensor = new RxBotics.Sensor({ id: 'Test1', x : 0, y : 1, theta : 2, calibration : [ 42 ] }); it('should get initialised correctly', function() { expect(sensor.position.x).equals(0); expect(sensor.position.y).equals(1); expect(sensor.theta).equals(2); expect(sensor.currentReading()).equals(42); }); it('should return correct state', function() { expect(sensor.currentState()).deep.to.equal({ id : sensor.id, x : sensor.position.x, y : sensor.position.y, theta : sensor.theta, distance : sensor.calibration[0] }); }); });
eddspencer/rxbotics
test/rxbotics.sensor.test.js
JavaScript
mit
808
function CaseCtrl($scope, $rootScope, DarkBackground, MetadataService) { var vm = this; var title = 'Love is a roller coaster'; var description = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam interdum tortor augue.'; MetadataService.setMetadata({ title: 'Brand New Media | ' + title, description: description }); var act = new gigya.socialize.UserAction(); act.setTitle(title); act.setDescription(description); act.setLinkBack("http://brandnewmedia.com.au/our-flickbook/lifestyle-focused-digital-summit-proves-successful-acquiring-global-audience"); act.addMediaItem({ type: 'image', src: 'http://demo.gigya.com/images/recipe2.png', href: 'http://demo.gigya.com/recipe2.php' }); var showShareBarUI_params = { containerID: 'componentDiv', shareButtons: 'Facebook,Twitter,Linkedin,googleplus,Email,Print', iconsOnly: 'true', userAction: act, shareButtons: [ { // Facebook provider:'facebook', tooltip:'Recommend this on Facebook', iconImgUp:'images/icons/social-icons-facebook.png' }, { // Twitter provider:'Twitter', tooltip:'Tweet this', iconImgUp:'images/icons/social-icons-twitter.png' }, { // Linkedin provider:'Linkedin', tooltip:'Twitter', iconImgUp:'images/icons/social-icons-linkedin.png' }, { // Google+ provider:'googleplus', tooltip:'Share this on Google+', iconImgUp:'images/icons/social-icons-google.png' }, { // Email provider:'Email', tooltip:'Email this', iconImgUp:'images/icons/social-icons-email.png' }, { // Print provider:'Print', tooltip:'Print this page', iconImgUp:'images/icons/social-icons-print.png' } ], buttonWithCountTemplate: '<div class="gigya-icon" style="padding-right: 20px; padding-top: 10px; height: 26px;" onclick="$onClick"><img src="$iconImg" height="16"/></div>', buttonTemplate: '<div class="gigya-icon" style="padding-right: 20px; padding-top: 10px; height: 26px;" onclick="$onClick"><img src="$iconImg" height="16"/></div>', noButtonBorders: true } gigya.socialize.showShareBarUI(showShareBarUI_params); $rootScope.bodyclass = DarkBackground.bodyClass.data; $scope.intro = { 'title': title, 'description': 'Realising they were missing an online presence, Luna Park knew video content was needed to drive brand awareness through digital audiences. They wanted to engage people socially and activate peer-to-peer sharing, demonstrating they offer something for everyone.', 'link': 'https://www.youtube.com/watch?v=AB1PpQlRyds&list=PL9RaBFzxpPDBwpkCvMgNsvrNpZRKgM1Ey', 'linkTitle': 'Watch online', 'client': 'Luna Park Sydney', 'services': 'Content Production, Distribution & Amplification' } $scope.hero = { 'url': 'http://cdn.brandnewmedia.global/wp-content/uploads/2016/03/10125033/ChannelPLAY2-AU.mp4', 'thumbnail': 'images/AB1PpQlRyds.jpg' } $scope.lunaimage = { 'url': 'images/AB1PpQlRyds.jpg', 'alt': 'Here is some alt text' } $scope.lunagif = { 'url': 'images/ezgif-2280143617.gif', 'alt': 'Here is some alt text' } $scope.idea = { title: 'The idea', description: 'Praesent vel felis quis velit condimentum sodales. Proin ultrices justo at tempus fringilla. Proin vestibulum luctus sem eu sagittis. Duis non quam et orci volutpat bibendum sed et metus. Sed aliquet convallis ligula id cursus. Quisque et ornare ex. Nullam vulputate tellus elit. Morbi ornare consequat mi, in consequat dui gravida vitae. Maecenas id erat in mauris mattis vulputate in nec tortor. Pellentesque bibendum nisl ut lacus egestas finibus.' } $scope.solution = { title: 'The solution', description: 'Praesent vel felis quis velit condimentum sodales. Proin ultrices justo at tempus fringilla. Proin vestibulum luctus sem eu sagittis. Duis non quam et orci volutpat bibendum sed et metus. Sed aliquet convallis ligula id cursus. Quisque et ornare ex. Nullam vulputate tellus elit. Morbi ornare consequat mi, in consequat dui gravida vitae. Maecenas id erat in mauris mattis vulputate in nec tortor. Pellentesque bibendum nisl ut lacus egestas finibus.' } $scope.results = [ { number: '360,000', description: 'video views and still growing' }, { number: '50%', description: 'of video views were driven through earned media' }, { number: '30%', description: 'higher than average video retention rate' }, { number: '900,000', description: 'Facebook reach' }, ] } CaseCtrl.$inject = ["$scope", "$rootScope", "DarkBackground", "MetadataService"]; export default { name: 'CaseCtrl', fn: CaseCtrl };
bnmnjohnson/brandnewmedia-au
app/js/controllers/case.js
JavaScript
mit
5,177
var Conway = (function() { function Conway(width, height) { var width = width, height = height, data = new Array2(width, height, 'DEAD'); this.Colors = { DEAD: '#000000', ALIVE: '#00ff00' }; this.Neighbourhood = [ [ -1, -1 ], [ 0, -1 ], [ 1, -1 ], [ -1, 0 ], [ 1, 0 ], [ -1, 1 ], [ 0, 1 ], [ 1, 1 ] ]; this.randomize = function(p) { if (p === undefined) p = 0.5; data.apply(function(i, j, v) { return (Math.random() < p ? 'ALIVE' : 'DEAD'); }); }; function countAliveNeighbours(d, i, j, neighbourhood) { var count = 0; for (var n = 0; n < neighbourhood.length; ++n) { try { if (d.get(i + neighbourhood[n][0], j + neighbourhood[n][1]) == 'ALIVE') ++count; } catch (err) { } } return count; } this.step = function() { var old_data = data.clone(); var changed = false; for (var i = 0; i < width; ++i) { for (var j = 0; j < height; ++j) { var n = countAliveNeighbours(old_data, i, j, this.Neighbourhood); if (old_data.get(i, j) == 'ALIVE') { if (n < 2 || n > 3) { data.set(i, j, 'DEAD'); changed = true; } } else { // DEAD if (n == 3) { data.set(i, j, 'ALIVE'); changed = true; } } } } return changed; } this.render = function(canvas) { var dx = canvas.getAttribute('width') / width; var dy = canvas.getAttribute('height') / height; var ctx = canvas.getContext('2d'); for (var x = 0; x < width; ++x) { for (var y = 0; y < height; ++y) { ctx.fillStyle = this.Colors[data.get(x, y)]; ctx.fillRect(x * dx, y * dy, dx, dy); } } } this.getCellPos = function(canvas, mousePos) { var dx = canvas.getAttribute('width') / width; var dy = canvas.getAttribute('height') / height; return { x: Math.floor(mousePos.x / dx), y: Math.floor(mousePos.y / dy) }; } this.toggleCell = function(pos) { if (data.get(pos.x, pos.y) == 'DEAD') { data.set(pos.x, pos.y, 'ALIVE'); } else { data.set(pos.x, pos.y, 'DEAD'); } } this.getCell = function(pos) { return data.get(pos.x, pos.y) == 'ALIVE'; } this.setCell = function(pos, value) { data.set(pos.x, pos.y, value ? 'ALIVE' : 'DEAD'); } }; return Conway; } ());
dagothar/game-of-life-js
scripts/conway.js
JavaScript
mit
2,681
module.exports = { dist: { options: { modules: [{name: 'config'}], dir: '<%= config.dist %>/scripts', baseUrl: '<%= config.app %>/scripts', findNestedDependencies: true, // optimize: 'none', optimize: 'uglify2', // Supports generateSourceMaps preserveLicenseComments: false, useStrict: true, removeCombined: true, wrapShim: true, mainConfigFile: '<%= config.app %>/scripts/config.js', }, } };
rek/miniature-octo-lander
grunt/requirejs.js
JavaScript
mit
552
var x = 39.773845; //-34.397; var y = -86.176210; //150.644; var locations = new Array(); var titles = new Array(); locations[0] = new google.maps.LatLng(39.773845,-86.177074); titles[0] = "uni"; locations[1] = new google.maps.LatLng (39.774018,-86.172332); titles[1] = "street 1"; locations[2] = new google.maps.LatLng (39.774001,-86.170691); titles[2] = "street 2"; locations[3] = new google.maps.LatLng (39.773226,-86.173941); titles[3] = "building"; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{ document.write("Geolocation is not supported by this browser."); } function initialize() { var mapOptions = { center: new google.maps.LatLng(x, y), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); for (var i=0;i<locations.length;i++) { var marker = new google.maps.Marker( { position: locations[i], map: map, title: titles[i] }); addInfoWindow(marker, i); } var image = "https://www.firstpct.org/images/user.png"; var marker1 = new google.maps.Marker({ position: map.getCenter(), map: map, title: "you", icon: image }); // alert("here"); // I know where I am. :) } function addInfoWindow(marker, i) { var infowindow = new google.maps.InfoWindow( { content: titles[i] }); google.maps.event.addListener(marker, 'mouseover', function() { infowindow.open(marker.get('map'), marker); }); google.maps.event.addListener(marker, 'mouseout', function() { infowindow.close(); }); } function showPosition(position) { // x = position.coords.latitude; // y = position.coords.longitude; initialize(); } // google.maps.event.addDomListener(window, 'load', initialize);
hoosierEE/local-liquidator
old-demos/js/newMarkers.js
JavaScript
mit
1,837
module.exports = { "extends": "@hasaki-ui/eslint-config-hsk-kayle/node", rules: { // // 在实现函数重载时,需要对参数改变 // 'no-param-reassign': 'off', // // 跟wrap-iife 和 func-names起冲突 // 'no-extra-parens': 'off', // // 网上流行的一些正则表达式都通不过 // 'no-useless-escape': 'off', // 'complexity': ['warn', 20], // 'spaced-comment': ['error', 'always', { // exceptions: ['-', '+', '*', '@formatter:off', '@formatter:on'], // markers: ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!'] // }], // 'no-use-before-define': ['error', {"functions": false, "classes": true}], } };
HasakiUI/hsk-garen
.eslintrc.js
JavaScript
mit
752
'use strict' let config = {} config.port = 4000 config.apiUri = 'http://localhost:4000' module.exports = config
apolishch/react-article
config.js
JavaScript
mit
114
jQuery(function($){ // Create variables (in this scope) to hold the API and image size var jcrop_api, boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); var db_x = $('#x').val(); var db_y = $('#y').val(); var db_img_width = $('#x2').val(); var db_img_height = $('#y2').val(); $('#target').Jcrop({ bgFade: true, bgOpacity: .7, setSelect: [ db_x, db_y, db_img_width, db_img_height ], onChange: updatePreview, onSelect: updatePreview, aspectRatio: xsize / ysize },function(){ // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; /*************** to show previous image in preview section start *****************/ $('#target').Jcrop({onLoad: updatePreview}); /*************** to show previous image in preview section end *****************/ // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); function updatePreview(c) { //console.log(c.w); //console.log(c.x); if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $pimg.css({ width: Math.round(rx * boundx) + 'px', height: Math.round(ry * boundy) + 'px', marginLeft: '-' + Math.round(rx * c.x) + 'px', marginTop: '-' + Math.round(ry * c.y) + 'px' }); $('#x').val(c.x); $('#y').val(c.y); $('#x2').val(c.x2); $('#y2').val(c.y2); $('#img_width').val(c.w); $('#img_height').val(c.h); } }; });
dip712204123/kidskula
web/bundles/BundleAdmin/assets/custom/js/image_crop.js
JavaScript
mit
1,933
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /*global URI, Promise, ES6Promise, alert, confirm, console, XMLHttpRequest*/ /** * @class Provides base functionality of the SAP jQuery plugin as extension of the jQuery framework.<br/> * See also <a href="http://api.jquery.com/jQuery/">jQuery</a> for details.<br/> * Although these functions appear as static ones, they are meant to be used on jQuery instances.<br/> * If not stated differently, the functions follow the fluent interface paradigm and return the jQuery instance for chaining of statements. * * Example for usage of an instance method: * <pre> * var oRect = jQuery("#myDiv").rect(); * alert("Top Position: " + oRect.top); * </pre> * * @name jQuery * @static * @public */ (function() { if (!window.jQuery ) { throw new Error("SAPUI5 requires jQuery as a prerequisite (>= version 1.7)"); } // ensure not to initialize twice if (jQuery.sap) { return; } // Enable promise polyfill if native promise is not available if (!window.Promise) { ES6Promise.polyfill(); } /** * Window that the sap plugin has been initialized for. * @private */ var _window = window; // early logging support var _earlyLogs = []; function _earlyLog(sLevel, sMessage) { _earlyLogs.push({ level: sLevel, message: sMessage }); } var _sBootstrapUrl; // -------------------------- VERSION ------------------------------------- var rVersion = /^[0-9]+(?:\.([0-9]+)(?:\.([0-9]+))?)?(.*)$/; /** * Returns a Version instance created from the given parameters. * * This function can either be called as a constructor (using <code>new</code>) or as a normal function. * It always returns an immutable Version instance. * * The parts of the version number (major, minor, patch, suffix) can be provided in several ways: * <ul> * <li>Version("1.2.3-SNAPSHOT") - as a dot-separated string. Any non-numerical char or a dot followed by a non-numerical char starts the suffix portion. * Any missing major, minor or patch versions will be set to 0.</li> * <li>Version(1,2,3,"-SNAPSHOT") - as individual parameters. Major, minor and patch must be integer numbers or empty, suffix must be a string not starting with digits.</li> * <li>Version([1,2,3,"-SNAPSHOT"]) - as an array with the individual parts. The same type restrictions apply as before.</li> * <li>Version(otherVersion) - as a Version instance (cast operation). Returns the given instance instead of creating a new one.</li> * </ul> * * To keep the code size small, this implementation mainly validates the single string variant. * All other variants are only validated to some degree. It is the responsibility of the caller to * provide proper parts. * * @param {int|string|any[]|jQuery.sap.Version} vMajor the major part of the version (int) or any of the single parameter variants explained above. * @param {int} iMinor the minor part of the version number * @param {int} iPatch the patch part of the version number * @param {string} sSuffix the suffix part of the version number * @return {jQuery.sap.Version} the version object as determined from the parameters * * @class Represents a version consisting of major, minor, patch version and suffix, e.g. '1.2.7-SNAPSHOT'. * * @author SAP SE * @version 1.32.10 * @constructor * @public * @since 1.15.0 * @name jQuery.sap.Version */ function Version(vMajor, iMinor, iPatch, sSuffix) { if ( vMajor instanceof Version ) { // note: even a constructor may return a value different from 'this' return vMajor; } if ( !(this instanceof Version) ) { // act as a cast operator when called as function (not as a constructor) return new Version(vMajor, iMinor, iPatch, sSuffix); } var m; if (typeof vMajor === "string") { m = rVersion.exec(vMajor); } else if (jQuery.isArray(vMajor)) { m = vMajor; } else { m = arguments; } m = m || []; function norm(v) { v = parseInt(v,10); return isNaN(v) ? 0 : v; } vMajor = norm(m[0]); iMinor = norm(m[1]); iPatch = norm(m[2]); sSuffix = String(m[3] || ""); /** * Returns a string representation of this version. * * @return {string} a string representation of this version. * @name jQuery.sap.Version#toString * @public * @since 1.15.0 * @function */ this.toString = function() { return vMajor + "." + iMinor + "." + iPatch + sSuffix; }; /** * Returns the major version part of this version. * * @return {int} the major version part of this version * @name jQuery.sap.Version#getMajor * @public * @since 1.15.0 * @function */ this.getMajor = function() { return vMajor; }; /** * Returns the minor version part of this version. * * @return {int} the minor version part of this version * @name jQuery.sap.Version#getMinor * @public * @since 1.15.0 * @function */ this.getMinor = function() { return iMinor; }; /** * Returns the patch (or micro) version part of this version. * * @return {int} the patch version part of this version * @name jQuery.sap.Version#getPatch * @public * @since 1.15.0 * @function */ this.getPatch = function() { return iPatch; }; /** * Returns the version suffix of this version. * * @return {string} the version suffix of this version * @name jQuery.sap.Version#getSuffix * @public * @since 1.15.0 * @function */ this.getSuffix = function() { return sSuffix; }; /** * Compares this version with a given one. * * The version with which this version should be compared can be given as * <code>jQuery.sap.Version</code> instance, as a string (e.g. <code>v.compareto("1.4.5")</code>) * or major, minor, patch and suffix cab be given as separate parameters (e.g. <code>v.compareTo(1, 4, 5)</code>) * or in an array (e.g. <code>v.compareTo([1, 4, 5])</code>). * * @return {int} 0, if the given version is equal to this version, a negative value if the given version is greater and a positive value otherwise * @name jQuery.sap.Version#compareTo * @public * @since 1.15.0 * @function */ this.compareTo = function() { var vOther = Version.apply(window, arguments); /*eslint-disable no-nested-ternary */ return vMajor - vOther.getMajor() || iMinor - vOther.getMinor() || iPatch - vOther.getPatch() || ((sSuffix < vOther.getSuffix()) ? -1 : (sSuffix === vOther.getSuffix()) ? 0 : 1); /*eslint-enable no-nested-ternary */ }; } /** * Checks whether this version is in the range of the given versions (start included, end excluded). * * The boundaries against which this version should be checked can be given as * <code>jQuery.sap.Version</code> instances (e.g. <code>v.inRange(v1, v2)</code>), as strings (e.g. <code>v.inRange("1.4", "2.7")</code>) * or as arrays (e.g. <code>v.inRange([1,4], [2,7])</code>). * * @param {string|any[]|jQuery.sap.Version} vMin the start of the range (inclusive) * @param {string|any[]|jQuery.sap.Version} vMax the end of the range (exclusive) * @return {boolean} <code>true</code> if this version is greater or equal to <code>vMin</code> and smaller than <code>vMax</code>, <code>false</code> otherwise. * @name jQuery.sap.Version#inRange * @public * @since 1.15.0 * @function */ Version.prototype.inRange = function(vMin, vMax) { return this.compareTo(vMin) >= 0 && this.compareTo(vMax) < 0; }; // ----------------------------------------------------------------------- var oJQVersion = Version(jQuery.fn.jquery); if ( !oJQVersion.inRange("1.7.0", "2.2.0") ) { _earlyLog("error", "SAPUI5 requires a jQuery version of 1.7 or higher, but lower than 2.2; current version is " + jQuery.fn.jquery); } // TODO move to a separate module? Only adds 385 bytes (compressed), but... if ( !jQuery.browser ) { // re-introduce the jQuery.browser support if missing (jQuery-1.9ff) jQuery.browser = (function( ua ) { var rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, ua = ua.toLowerCase(), match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || [], browser = {}; if ( match[1] ) { browser[ match[1] ] = true; browser.version = match[2] || "0"; if ( browser.webkit ) { browser.safari = true; } } return browser; }(window.navigator.userAgent)); } // XHR overrides for IE if (!!sap.ui.Device.browser.internet_explorer) { // Fixes the CORS issue (introduced by jQuery 1.7) when loading resources // (e.g. SAPUI5 script) from other domains for IE browsers. // The CORS check in jQuery filters out such browsers who do not have the // property "withCredentials" which is the IE and Opera and prevents those // browsers to request data from other domains with jQuery.ajax. The CORS // requests are simply forbidden nevertheless if it works. In our case we // simply load our script resources from another domain when using the CDN // variant of SAPUI5. The following fix is also recommended by jQuery: jQuery.support = jQuery.support || {}; jQuery.support.cors = true; // Fixes XHR factory issue (introduced by jQuery 1.11). In case of IE // it uses by mistake the ActiveXObject XHR. In the list of XHR supported // HTTP methods PATCH and MERGE are missing which are required for OData. // The related ticket is: #2068 (no downported to jQuery 1.x planned) var oJQV = Version(jQuery.fn.jquery); // the fix will only be applied to jQuery >= 1.11.0 (only for jQuery 1.x) if (window.ActiveXObject !== undefined && oJQV.getMajor() == 1 && oJQV.getMinor() >= 11) { var fnCreateStandardXHR = function() { try { return new window.XMLHttpRequest(); } catch (e) { /* ignore */ } }; var fnCreateActiveXHR = function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { /* ignore */ } }; jQuery.ajaxSettings = jQuery.ajaxSettings || {}; jQuery.ajaxSettings.xhr = function() { return !this.isLocal ? fnCreateStandardXHR() : fnCreateActiveXHR(); }; } } /** * Find the script URL where the SAPUI5 is loaded from and return an object which * contains the identified script-tag and resource root */ var _oBootstrap = (function() { var oTag, sUrl, sResourceRoot, reConfigurator = /^(.*\/)?download\/configurator[\/\?]/, reBootScripts = /^(.*\/)?(sap-ui-(core|custom|boot|merged)(-.*)?)\.js([?#]|$)/, reResources = /^(.*\/)?resources\//; // check all script tags that have a src attribute jQuery("script[src]").each(function() { var src = this.getAttribute("src"), m; if ( (m = src.match(reConfigurator)) !== null ) { // guess 1: script tag src contains "/download/configurator[/?]" (for dynamically created bootstrap files) oTag = this; sUrl = src; sResourceRoot = (m[1] || "") + "resources/"; return false; } else if ( (m = src.match(reBootScripts)) !== null ) { // guess 2: src contains one of the well known boot script names oTag = this; sUrl = src; sResourceRoot = m[1] || ""; return false; } else if ( this.id == 'sap-ui-bootstrap' && (m = src.match(reResources)) ) { // guess 2: script tag has well known id and src contains "resources/" oTag = this; sUrl = src; sResourceRoot = m[0]; return false; } }); return { tag: oTag, url: sUrl, resourceRoot: sResourceRoot }; })(); /** * Determine whether sap-bootstrap-debug is set, run debugger statement and allow * to restart the core from a new URL */ (function() { if (/sap-bootstrap-debug=(true|x|X)/.test(location.search)) { // Dear developer, the way to reload UI5 from a different location has changed: it can now be directly configured in the support popup (Ctrl-Alt-Shift-P), // without stepping into the debugger. // However, for convenience or cases where this popup is disabled, or for other usages of an early breakpoint, the "sap-bootstrap-debug" URL parameter option is still available. // To reboot an alternative core just step down a few lines and set sRebootUrl /*eslint-disable no-debugger */ debugger; } // Check local storage for booting a different core var sRebootUrl; try { // Necessary for FF when Cookies are disabled sRebootUrl = window.localStorage.getItem("sap-ui-reboot-URL"); window.localStorage.removeItem("sap-ui-reboot-URL"); // only reboot once from there (to avoid a deadlock when the alternative core is broken) } catch (e) { /* no warning, as this will happen on every startup, depending on browser settings */ } if (sRebootUrl && sRebootUrl !== "undefined") { // sic! It can be a string. /*eslint-disable no-alert*/ var bUserConfirmed = confirm("WARNING!\n\nUI5 will be booted from the URL below.\nPress 'Cancel' unless you have configured this.\n\n" + sRebootUrl); /*eslint-enable no-alert*/ if (bUserConfirmed) { // replace the bootstrap tag with a newly created script tag to enable restarting the core from a different server var oScript = _oBootstrap.tag, sScript = "<script src=\"" + sRebootUrl + "\""; jQuery.each(oScript.attributes, function(i, oAttr) { if (oAttr.nodeName.indexOf("data-sap-ui-") == 0) { sScript += " " + oAttr.nodeName + "=\"" + oAttr.nodeValue.replace(/"/g, "&quot;") + "\""; } }); sScript += "></script>"; oScript.parentNode.removeChild(oScript); // clean up cachebuster stuff jQuery("#sap-ui-bootstrap-cachebusted").remove(); window["sap-ui-config"] && window["sap-ui-config"].resourceRoots && (window["sap-ui-config"].resourceRoots[""] = undefined); document.write(sScript); // now this core commits suicide to enable clean loading of the other core var oRestart = new Error("This is not a real error. Aborting UI5 bootstrap and rebooting from: " + sRebootUrl); oRestart.name = "Restart"; throw oRestart; } } })(); /** * Determine whether to use debug sources depending on URL parameter and local storage * and load debug library if necessary */ (function() { //Check URI param var bDebugSources = /sap-ui-debug=(true|x|X)/.test(location.search), bIsOptimized = window["sap-ui-optimized"]; //Check local storage try { bDebugSources = bDebugSources || (window.localStorage.getItem("sap-ui-debug") == "X"); } catch (e) { //Happens in FF when Cookies are deactivated } window["sap-ui-debug"] = bDebugSources; // if bootstap URL already contains -dbg URL, just set sap-ui-loaddbg if (/-dbg\.js([?#]|$)/.test(_oBootstrap.url)) { window["sap-ui-loaddbg"] = true; window["sap-ui-debug"] = true; } // if current sources are optimized and debug sources are wanted, restart with debug URL if (bIsOptimized && bDebugSources) { var sDebugUrl = _oBootstrap.url.replace(/\/(?:sap-ui-cachebuster\/)?([^\/]+)\.js/, "/$1-dbg.js"); window["sap-ui-optimized"] = false; window["sap-ui-loaddbg"] = true; document.write("<script type=\"text/javascript\" src=\"" + sDebugUrl + "\"></script>"); var oRestart = new Error("Aborting UI5 bootstrap and restarting from: " + sDebugUrl); oRestart.name = "Restart"; throw oRestart; } })(); /* * Merged, raw (un-interpreted) configuration data from the following sources * (last one wins) * <ol> * <li>global configuration object <code>window["sap-ui-config"]</code> (could be either a string/url or a configuration object)</li> * <li><code>data-sap-ui-config</code> attribute of the bootstrap script tag</li> * <li>other <code>data-sap-ui-<i>xyz</i></code> attributes of the bootstrap tag</li> * </ol> */ var oCfgData = _window["sap-ui-config"] = (function() { function normalize(o) { jQuery.each(o, function(i, v) { var il = i.toLowerCase(); if ( !o.hasOwnProperty(il) ) { o[il] = v; delete o[i]; } }); return o; } var oScriptTag = _oBootstrap.tag, oCfg = _window["sap-ui-config"], sCfgFile = "sap-ui-config.json"; // load the configuration from an external JSON file if (typeof oCfg === "string") { _earlyLog("warning", "Loading external bootstrap configuration from \"" + oCfg + "\". This is a design time feature and not for productive usage!"); if (oCfg !== sCfgFile) { _earlyLog("warning", "The external bootstrap configuration file should be named \"" + sCfgFile + "\"!"); } jQuery.ajax({ url : oCfg, dataType : 'json', async : false, success : function(oData, sTextStatus, jqXHR) { oCfg = oData; }, error : function(jqXHR, sTextStatus, oError) { _earlyLog("error", "Loading externalized bootstrap configuration from \"" + oCfg + "\" failed! Reason: " + oError + "!"); oCfg = undefined; } }); } oCfg = normalize(oCfg || {}); oCfg.resourceroots = oCfg.resourceroots || {}; oCfg.themeroots = oCfg.themeroots || {}; oCfg.resourceroots[''] = oCfg.resourceroots[''] || _oBootstrap.resourceRoot; oCfg['xx-loadallmode'] = /(^|\/)(sap-?ui5|[^\/]+-all).js([?#]|$)/.test(_oBootstrap.url); // if a script tag has been identified, collect its configuration info if ( oScriptTag ) { // evaluate the config attribute first - if present var sConfig = oScriptTag.getAttribute("data-sap-ui-config"); if ( sConfig ) { try { /*eslint-disable no-new-func */ jQuery.extend(oCfg, normalize((new Function("return {" + sConfig + "};"))())); // TODO jQuery.parseJSON would be better but imposes unwanted restrictions on valid syntax /*eslint-enable no-new-func */ } catch (e) { // no log yet, how to report this error? _earlyLog("error", "failed to parse data-sap-ui-config attribute: " + (e.message || e)); } } // merge with any existing "data-sap-ui-" attributes jQuery.each(oScriptTag.attributes, function(i, attr) { var m = attr.name.match(/^data-sap-ui-(.*)$/); if ( m ) { // the following (deactivated) conversion would implement multi-word names like "resource-roots" m = m[1].toLowerCase(); // .replace(/\-([a-z])/g, function(s,w) { return w.toUpperCase(); }) if ( m === 'resourceroots' ) { // merge map entries instead of overwriting map jQuery.extend(oCfg[m], jQuery.parseJSON(attr.value)); } else if ( m === 'theme-roots' ) { // merge map entries, but rename to camelCase jQuery.extend(oCfg.themeroots, jQuery.parseJSON(attr.value)); } else if ( m !== 'config' ) { oCfg[m] = attr.value; } } }); } return oCfg; }()); // check whether noConflict must be used... if ( oCfgData.noconflict === true || oCfgData.noconflict === "true" || oCfgData.noconflict === "x" ) { jQuery.noConflict(); } /** * Root Namespace for the jQuery plug-in provided by SAP SE. * * @version 1.32.10 * @namespace * @public * @static */ jQuery.sap = {}; // -------------------------- VERSION ------------------------------------- jQuery.sap.Version = Version; // -------------------------- PERFORMANCE NOW ------------------------------------- /** * Returns a high resolution timestamp for measurements. * The timestamp is based on 01/01/1970 00:00:00 as float with microsecond precision or * with millisecond precision, if high resolution timestamps are not available. * The fractional part of the timestamp represents microseconds. * Converting to a <code>Date</code> is possible using <code>new Date(jQuery.sap.now())</code> * * @public * @returns {float} high resolution timestamp for measurements */ jQuery.sap.now = !(window.performance && window.performance.now && window.performance.timing) ? Date.now : function() { return window.performance.timing.navigationStart + window.performance.now(); }; // -------------------------- DEBUG LOCAL STORAGE ------------------------------------- jQuery.sap.debug = function(bEnable) { if (!window.localStorage) { return null; } function reloadHint(bUsesDbgSrc){ /*eslint-disable no-alert */ alert("Usage of debug sources is " + (bUsesDbgSrc ? "on" : "off") + " now.\nFor the change to take effect, you need to reload the page."); /*eslint-enable no-alert */ } if (bEnable === true) { window.localStorage.setItem("sap-ui-debug", "X"); reloadHint(true); } else if (bEnable === false) { window.localStorage.removeItem("sap-ui-debug"); reloadHint(false); } return window.localStorage.getItem("sap-ui-debug") == "X"; }; /** * Sets the URL to reboot this app from, the next time it is started. Only works with localStorage API available * (and depending on the browser, if cookies are enabled, even though cookies are not used). * * @param sRebootUrl the URL to sap-ui-core.js, from which the application should load UI5 on next restart; undefined clears the restart URL * @returns the current reboot URL or undefined in case of an error or when the reboot URL has been cleared * * @private */ jQuery.sap.setReboot = function(sRebootUrl) { // null-ish clears the reboot request var sUrl; if (!window.localStorage) { return null; } try { if (sRebootUrl) { window.localStorage.setItem("sap-ui-reboot-URL", sRebootUrl); // remember URL to reboot from /*eslint-disable no-alert */ alert("Next time this app is launched (only once), it will load UI5 from:\n" + sRebootUrl + ".\nPlease reload the application page now."); /*eslint-enable no-alert */ } else { window.localStorage.removeItem("sap-ui-reboot-URL"); // clear reboot URL, so app will start normally } sUrl = window.localStorage.getItem("sap-ui-reboot-URL"); } catch (e) { jQuery.sap.log.warning("Could not access localStorage while setting reboot URL '" + sRebootUrl + "' (are cookies disabled?): " + e.message); } return sUrl; }; // -------------------------- STATISTICS LOCAL STORAGE ------------------------------------- jQuery.sap.statistics = function(bEnable) { if (!window.localStorage) { return null; } function gatewayStatsHint(bUsesDbgSrc){ /*eslint-disable no-alert */ alert("Usage of Gateway statistics " + (bUsesDbgSrc ? "on" : "off") + " now.\nFor the change to take effect, you need to reload the page."); /*eslint-enable no-alert */ } if (bEnable === true) { window.localStorage.setItem("sap-ui-statistics", "X"); gatewayStatsHint(true); } else if (bEnable === false) { window.localStorage.removeItem("sap-ui-statistics"); gatewayStatsHint(false); } return window.localStorage.getItem("sap-ui-statistics") == "X"; }; // -------------------------- Logging ------------------------------------- (function() { var FATAL = 0, ERROR = 1, WARNING = 2, INFO = 3, DEBUG = 4, TRACE = 5, /** * Unique prefix for this instance of the core in a multi-frame environment. */ sWindowName = (window.top == window) ? "" : "[" + window.location.pathname.split('/').slice(-1)[0] + "] ", // Note: comparison must use type coercion (==, not ===), otherwise test fails in IE /** * The array that holds the log entries that have been recorded so far */ aLog = [], /** * Maximum log level to be recorded (per component). */ mMaxLevel = { '' : ERROR }, /** * Registered listener to be informed about new log entries. */ oListener = null; function pad0(i,w) { return ("000" + String(i)).slice(-w); } function level(sComponent) { return (!sComponent || isNaN(mMaxLevel[sComponent])) ? mMaxLevel[''] : mMaxLevel[sComponent]; } function listener(){ if (!oListener) { oListener = { listeners: [], onLogEntry: function(oLogEntry){ for (var i = 0; i < oListener.listeners.length; i++) { if (oListener.listeners[i].onLogEntry) { oListener.listeners[i].onLogEntry(oLogEntry); } } }, attach: function(oLogger, oLstnr){ if (oLstnr) { oListener.listeners.push(oLstnr); if (oLstnr.onAttachToLog) { oLstnr.onAttachToLog(oLogger); } } }, detach: function(oLogger, oLstnr){ for (var i = 0; i < oListener.listeners.length; i++) { if (oListener.listeners[i] === oLstnr) { if (oLstnr.onDetachFromLog) { oLstnr.onDetachFromLog(oLogger); } oListener.listeners.splice(i,1); return; } } } }; } return oListener; } /** * Creates a new log entry depending on its level and component. * * If the given level is higher than the max level for the given component * (or higher than the global level, if no component is given), * then no entry is created. */ function log(iLevel, sMessage, sDetails, sComponent) { if (iLevel <= level(sComponent) ) { var fNow = jQuery.sap.now(), oNow = new Date(fNow), iMicroSeconds = Math.floor((fNow - Math.floor(fNow)) * 1000), oLogEntry = { time : pad0(oNow.getHours(),2) + ":" + pad0(oNow.getMinutes(),2) + ":" + pad0(oNow.getSeconds(),2) + "." + pad0(oNow.getMilliseconds(),3) + pad0(iMicroSeconds,3), date : pad0(oNow.getFullYear(),4) + "-" + pad0(oNow.getMonth() + 1,2) + "-" + pad0(oNow.getDate(),2), timestamp: fNow, level : iLevel, message : String(sMessage || ""), details : String(sDetails || ""), component: String(sComponent || "") }; aLog.push( oLogEntry ); if (oListener) { oListener.onLogEntry(oLogEntry); } /* * Console Log, also tries to log to the window.console, if available. * * Unfortunately, the support for window.console is quite different between the UI5 browsers. The most important differences are: * - in IE (checked until IE9), the console object does not exist in a window, until the developer tools are opened for that window. * After opening the dev tools, the console remains available even when the tools are closed again. Only using a new window (or tab) * restores the old state without console. * When the console is available, it provides most standard methods, but not debug and trace * - in FF3.6 the console is not available, until FireBug is opened. It disappears again, when fire bug is closed. * But when the settings for a web site are stored (convenience), the console remains open * When the console is available, it supports all relevant methods * - in FF9.0, the console is always available, but method assert is only available when firebug is open * - in Webkit browsers, the console object is always available and has all required methods * - Exception: in the iOS Simulator, console.info() does not exist */ /*eslint-disable no-console */ if (window.console) { // in IE and FF, console might not exist; in FF it might even disappear var logText = oLogEntry.date + " " + oLogEntry.time + " " + sWindowName + oLogEntry.message + " - " + oLogEntry.details + " " + oLogEntry.component; switch (iLevel) { case FATAL: case ERROR: console.error(logText); break; case WARNING: console.warn(logText); break; case INFO: console.info ? console.info(logText) : console.log(logText); break; // info not available in iOS simulator case DEBUG: console.debug ? console.debug(logText) : console.log(logText); break; // debug not available in IE, fallback to log case TRACE: console.trace ? console.trace(logText) : console.log(logText); break; // trace not available in IE, fallback to log (no trace) } } /*eslint-enable no-console */ return oLogEntry; } } /** * Creates a new Logger instance which will use the given component string * for all logged messages without a specific component. * * @param {string} sDefaultComponent * * @class A Logger class * @name jQuery.sap.log.Logger * @since 1.1.2 * @public */ function Logger(sDefaultComponent) { /** * Creates a new fatal-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log instance for method chaining * @name jQuery.sap.log.Logger#fatal * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.fatal = function (sMessage, sDetails, sComponent) { log(FATAL, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Creates a new error-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log instance * @name jQuery.sap.log.Logger#error * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.error = function error(sMessage, sDetails, sComponent) { log(ERROR, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Creates a new warning-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log instance * @name jQuery.sap.log.Logger#warning * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.warning = function warning(sMessage, sDetails, sComponent) { log(WARNING, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Creates a new info-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log instance * @name jQuery.sap.log.Logger#info * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.info = function info(sMessage, sDetails, sComponent) { log(INFO, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Creates a new debug-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log instance * @name jQuery.sap.log.Logger#debug * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.debug = function debug(sMessage, sDetails, sComponent) { log(DEBUG, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Creates a new trace-level entry in the log with the given message, details and calling component. * * @param {string} sMessage Message text to display * @param {string} [sDetails=''] Details about the message, might be omitted * @param {string} [sComponent=''] Name of the component that produced the log entry * @return {jQuery.sap.log.Logger} The log-instance * @name jQuery.sap.log.Logger#trace * @function * @public * @SecSink {0 1 2|SECRET} Could expose secret data in logs */ this.trace = function trace(sMessage, sDetails, sComponent) { log(TRACE, sMessage, sDetails, sComponent || sDefaultComponent); return this; }; /** * Defines the maximum jQuery.sap.log.Level of log entries that will be recorded. * Log entries with a higher (less important) log level will be omitted from the log. * When a component name is given, the log level will be configured for that component * only, otherwise the log level for the default component of this logger is set. * For the global logger, the global default level is set. * * <b>Note</b>: Setting a global default log level has no impact on already defined * component log levels. They always override the global default log level. * * @param {jQuery.sap.log.Level} iLogLevel * @param {string} [sComponent] The log component to set the log level for. * @return {jQuery.sap.log} The global logger to allow method chaining * @name jQuery.sap.log.Logger#setLevel * @function * @public */ this.setLevel = function setLevel(iLogLevel, sComponent) { sComponent = sComponent || sDefaultComponent || ''; mMaxLevel[sComponent] = iLogLevel; var mBackMapping = []; jQuery.each(jQuery.sap.log.LogLevel, function(idx, v){ mBackMapping[v] = idx; }); log(INFO, "Changing log level " + (sComponent ? "for '" + sComponent + "' " : "") + "to " + mBackMapping[iLogLevel], "", "jQuery.sap.log"); return this; }; /** * Returns the log level currently effective for the given component. * If no component is given or when no level has been configured for a * given component, the log level for the default component of this logger is returned. * * @param {string} [sComponent] Name of the component to retrieve the log level for * @return {int} The log level for the given component or the default log level * @name jQuery.sap.log.Logger#getLevel * @function * @public * @since 1.1.2 */ this.getLevel = function getLevel(sComponent) { return level(sComponent || sDefaultComponent); }; /** * Checks whether logging is enabled for the given log level, * depending on the currently effective log level for the given component. * * If no component is given, the default component of this logger will be taken into account. * * @param {int} [iLevel=Level.DEBUG] the log level in question * @param {string} [sComponent] Name of the component to check the log level for * @return {boolean} Whether logging is enabled or not * @name jQuery.sap.log.Logger#isLoggable * @function * @public * @since 1.13.2 */ this.isLoggable = function (iLevel, sComponent) { return (iLevel == null ? DEBUG : iLevel) <= level(sComponent || sDefaultComponent); }; } /** * A Logging API for JavaScript. * * Provides methods to manage a client-side log and to create entries in it. Each of the logging methods * {@link jQuery.sap.log.#debug}, {@link jQuery.sap.log.#info}, {@link jQuery.sap.log.#warning}, * {@link jQuery.sap.log.#error} and {@link jQuery.sap.log.#fatal} creates and records a log entry, * containing a timestamp, a log level, a message with details and a component info. * The log level will be one of {@link jQuery.sap.log.Level} and equals the name of the concrete logging method. * * By using the {@link jQuery.sap.log#setLevel} method, consumers can determine the least important * log level which should be recorded. Less important entries will be filtered out. (Note that higher numeric * values represent less important levels). The initially set level depends on the mode that UI5 is running in. * When the optimized sources are executed, the default level will be {@link jQuery.sap.log.Level.ERROR}. * For normal (debug sources), the default level is {@link jQuery.sap.log.Level.DEBUG}. * * All logging methods allow to specify a <b>component</b>. These components are simple strings and * don't have a special meaning to the UI5 framework. However they can be used to semantically group * log entries that belong to the same software component (or feature). There are two APIs that help * to manage logging for such a component. With <code>{@link jQuery.sap.log.getLogger}(sComponent)</code>, * one can retrieve a logger that automatically adds the given <code>sComponent</code> as component * parameter to each log entry, if no other component is specified. Typically, JavaScript code will * retrieve such a logger once during startup and reuse it for the rest of its lifecycle. * Second, the {@link jQuery.sap.log.Logger#setLevel}(iLevel, sComponent) method allows to set the log level * for a specific component only. This allows a more fine granular control about the created logging entries. * {@link jQuery.sap.log.Logger.getLevel} allows to retrieve the currently effective log level for a given * component. * * {@link jQuery.sap.log#getLog} returns an array of the currently collected log entries. * * Furthermore, a listener can be registered to the log. It will be notified whenever a new entry * is added to the log. The listener can be used for displaying log entries in a separate page area, * or for sending it to some external target (server). * * @author SAP SE * @since 0.9.0 * @namespace * @public * @borrows jQuery.sap.log.Logger#fatal as fatal * @borrows jQuery.sap.log.Logger#error as error * @borrows jQuery.sap.log.Logger#warning as warning * @borrows jQuery.sap.log.Logger#info as info * @borrows jQuery.sap.log.Logger#debug as debug * @borrows jQuery.sap.log.Logger#trace as trace * @borrows jQuery.sap.log.Logger#getLevel as getLevel * @borrows jQuery.sap.log.Logger#setLevel as setLevel * @borrows jQuery.sap.log.Logger#isLoggable as isLoggable */ jQuery.sap.log = jQuery.extend(new Logger(), /** @lends jQuery.sap.log */ { /** * Enumeration of the configurable log levels that a Logger should persist to the log. * * Only if the current LogLevel is higher than the level {@link jQuery.sap.log.Level} of the currently added log entry, * then this very entry is permanently added to the log. Otherwise it is ignored. * @see jQuery.sap.log.Logger#setLevel * @namespace * @public */ Level : { /** * Do not log anything * @public */ NONE : FATAL - 1, /** * Fatal level. Use this for logging unrecoverable situations * @public */ FATAL : FATAL, /** * Error level. Use this for logging of erroneous but still recoverable situations * @public */ ERROR : ERROR, /** * Warning level. Use this for logging unwanted but foreseen situations * @public */ WARNING : WARNING, /** * Info level. Use this for logging information of purely informative nature * @public */ INFO : INFO, /** * Debug level. Use this for logging information necessary for debugging * @public */ DEBUG : DEBUG, /** * Trace level. Use this for tracing the program flow. * @public */ TRACE : TRACE, /* TODO Think about changing to 10 and thus to pull out of logging... -> Make tracing explicit */ /** * Trace level to log everything. */ ALL : (TRACE + 1) /* TODO if TRACE is changed to make sure this is 6 again. There would then be some special TRACE handling. */ }, /** * Returns a {@link jQuery.sap.log.Logger} for the given component. * * The method might or might not return the same logger object across multiple calls. * While loggers are assumed to be light weight objects, consumers should try to * avoid redundant calls and instead keep references to already retrieved loggers. * * The optional second parameter <code>iDefaultLogLevel</code> allows to specify * a default log level for the component. It is only applied when no log level has been * defined so far for that component (ignoring inherited log levels). If this method is * called multiple times for the same component but with different log levels, * only the first call one might be taken into account. * * @param {string} sComponent Component to create the logger for * @param {int} [iDefaultLogLevel] a default log level to be used for the component, * if no log level has been defined for it so far. * @return {jQuery.sap.log.Logger} A logger for the component. * @public * @static * @since 1.1.2 */ getLogger : function(sComponent, iDefaultLogLevel) { if ( !isNaN(iDefaultLogLevel) && mMaxLevel[sComponent] == null ) { mMaxLevel[sComponent] = iDefaultLogLevel; } return new Logger(sComponent); }, /** * Returns the logged entries recorded so far as an array. * * Log entries are plain JavaScript objects with the following properties * <ul> * <li>timestamp {number} point in time when the entry was created * <li>level {int} LogLevel level of the entry * <li>message {string} message text of the entry * </ul> * * @return {object[]} an array containing the recorded log entries * @public * @static * @since 1.1.2 */ getLogEntries : function () { return aLog.slice(); }, /** * Allows to add a new LogListener that will be notified for new log entries. * The given object must provide method <code>onLogEntry</code> and can also be informed * about <code>onDetachFromLog</code> and <code>onAttachToLog</code> * @param {object} oListener The new listener object that should be informed * @return {jQuery.sap.log} The global logger * @public * @static */ addLogListener : function(oListener) { listener().attach(this, oListener); return this; }, /** * Allows to remove a registered LogListener. * @param {object} oListener The new listener object that should be removed * @return {jQuery.sap.log} The global logger * @public * @static */ removeLogListener : function(oListener) { listener().detach(this, oListener); return this; } }); /** * Enumeration of levels that can be used in a call to {@link jQuery.sap.log.Logger#setLevel}(iLevel, sComponent). * * @deprecated Since 1.1.2. To streamline the Logging API a bit, the separation between Level and LogLevel has been given up. * Use the (enriched) enumeration {@link jQuery.sap.log.Level} instead. * @namespace * @public */ jQuery.sap.log.LogLevel = jQuery.sap.log.Level; /** * Retrieves the currently recorded log entries. * @deprecated Since 1.1.2. To avoid confusion with getLogger, this method has been renamed to {@link jQuery.sap.log.getLogEntries}. * @function * @public * @static */ jQuery.sap.log.getLog = jQuery.sap.log.getLogEntries; // *** Performance measure *** function PerfMeasurement() { function Measurement(sId, sInfo, iStart, iEnd, aCategories) { this.id = sId; this.info = sInfo; this.start = iStart; this.end = iEnd; this.pause = 0; this.resume = 0; this.duration = 0; // used time this.time = 0; // time from start to end this.categories = aCategories; this.average = false; //average duration enabled this.count = 0; //average count this.completeDuration = 0; //complete duration } function matchCategories(aCategories) { if (!aRestrictedCategories) { return true; } if (!aCategories) { return aRestrictedCategories === null; } //check whether active categories and current categories match for (var i = 0; i < aRestrictedCategories.length; i++) { if (aCategories.indexOf(aRestrictedCategories[i]) > -1) { return true; } } return false; } function checkCategories(aCategories) { if (!aCategories) { aCategories = ["javascript"]; } aCategories = typeof aCategories === "string" ? aCategories.split(",") : aCategories; if (!matchCategories(aCategories)) { return null; } return aCategories; } var bActive = false, fnAjax = jQuery.ajax, aRestrictedCategories = null, aAverageMethods = [], aOriginalMethods = [], aMethods = ["start", "end", "pause", "resume", "add", "remove", "clear", "average"]; /** * Gets the current state of the perfomance measurement functionality * * @return {boolean} current state of the perfomance measurement functionality * @name jQuery.sap.measure#getActive * @function * @public */ this.getActive = function() { return bActive; }; /** * Activates or deactivates the performance measure functionality * Optionally a category or list of categories can be passed to restrict measurements to certain categories * like "javascript", "require", "xmlhttprequest", "render" * @param {boolean} bOn state of the perfomance measurement functionality to set * @param {string | string[]} An optional list of categories that should be measured * * @return {boolean} current state of the perfomance measurement functionality * @name jQuery.sap.measure#setActive * @function * @public */ this.setActive = function(bOn, aCategories) { //set restricted categories if (!aCategories) { aCategories = null; } else if (typeof aCategories === "string") { aCategories = aCategories.split(","); } aRestrictedCategories = aCategories; if (bActive === bOn) { return; } bActive = bOn; if (bActive) { //activate method implementations once for (var i = 0; i < aMethods.length; i++) { this[aMethods[i]] = this["_" + aMethods[i]]; } aMethods = []; // wrap and instrument jQuery.ajax jQuery.ajax = function(url, options) { if ( typeof url === 'object' ) { options = url; url = undefined; } options = options || {}; var sMeasureId = new URI(url || options.url).absoluteTo(document.location.origin + document.location.pathname).href(); jQuery.sap.measure.start(sMeasureId, "Request for " + sMeasureId, "xmlhttprequest"); var fnComplete = options.complete; options.complete = function() { jQuery.sap.measure.end(sMeasureId); if (fnComplete) { fnComplete.apply(this, arguments); } }; // strict mode: we potentially modified 'options', so we must not use 'arguments' return fnAjax.call(this, url, options); }; } else if (fnAjax) { jQuery.ajax = fnAjax; } return bActive; }; this.mMeasurements = {}; /** * Starts a performance measure. * Optionally a category or list of categories can be passed to allow filtering of measurements. * * @param {string} sId ID of the measurement * @param {string} sInfo Info for the measurement * @param {string | string[]} [aCategories = "javascript"] An optional list of categories for the measure * * @return {object} current measurement containing id, info and start-timestamp (false if error) * @name jQuery.sap.measure#start * @function * @public */ this._start = function(sId, sInfo, aCategories) { if (!bActive) { return; } aCategories = checkCategories(aCategories); if (!aCategories) { return; } var iTime = jQuery.sap.now(), oMeasurement = new Measurement( sId, sInfo, iTime, 0, aCategories); // create timeline entries if available /*eslint-disable no-console */ if (window.console && console.time) { console.time(sInfo + " - " + sId); } /*eslint-enable no-console */ // jQuery.sap.log.info("Performance measurement start: "+ sId + " on "+ iTime); if (oMeasurement) { this.mMeasurements[sId] = oMeasurement; return this.getMeasurement(oMeasurement.id); } else { return false; } }; /** * Pauses a performance measure * * @param {string} sId ID of the measurement * @return {object} current measurement containing id, info and start-timestamp, pause-timestamp (false if error) * @name jQuery.sap.measure#pause * @function * @public */ this._pause = function(sId) { if (!bActive) { return; } var iTime = jQuery.sap.now(); var oMeasurement = this.mMeasurements[sId]; if (oMeasurement && oMeasurement.end > 0) { // already ended -> no pause possible return false; } if (oMeasurement && oMeasurement.pause == 0) { // not already paused oMeasurement.pause = iTime; if (oMeasurement.pause >= oMeasurement.resume && oMeasurement.resume > 0) { oMeasurement.duration = oMeasurement.duration + oMeasurement.pause - oMeasurement.resume; oMeasurement.resume = 0; } else if (oMeasurement.pause >= oMeasurement.start) { oMeasurement.duration = oMeasurement.pause - oMeasurement.start; } } // jQuery.sap.log.info("Performance measurement pause: "+ sId + " on "+ iTime + " duration: "+ oMeasurement.duration); if (oMeasurement) { return this.getMeasurement(oMeasurement.id); } else { return false; } }; /** * Resumes a performance measure * * @param {string} sId ID of the measurement * @return {object} current measurement containing id, info and start-timestamp, resume-timestamp (false if error) * @name jQuery.sap.measure#resume * @function * @public */ this._resume = function(sId) { if (!bActive) { return; } var iTime = jQuery.sap.now(); var oMeasurement = this.mMeasurements[sId]; // jQuery.sap.log.info("Performance measurement resume: "+ sId + " on "+ iTime + " duration: "+ oMeasurement.duration); if (oMeasurement && oMeasurement.pause > 0) { // already paused oMeasurement.pause = 0; oMeasurement.resume = iTime; } if (oMeasurement) { return this.getMeasurement(oMeasurement.id); } else { return false; } }; /** * Ends a performance measure * * @param {string} sId ID of the measurement * @return {object} current measurement containing id, info and start-timestamp, end-timestamp, time, duration (false if error) * @name jQuery.sap.measure#end * @function * @public */ this._end = function(sId) { if (!bActive) { return; } var iTime = jQuery.sap.now(); var oMeasurement = this.mMeasurements[sId]; // jQuery.sap.log.info("Performance measurement end: "+ sId + " on "+ iTime); if (oMeasurement && !oMeasurement.end) { oMeasurement.end = iTime; if (oMeasurement.end >= oMeasurement.resume && oMeasurement.resume > 0) { oMeasurement.duration = oMeasurement.duration + oMeasurement.end - oMeasurement.resume; oMeasurement.resume = 0; } else if (oMeasurement.pause > 0) { // duration already calculated oMeasurement.pause = 0; } else if (oMeasurement.end >= oMeasurement.start) { if (oMeasurement.average) { oMeasurement.completeDuration += (oMeasurement.end - oMeasurement.start); oMeasurement.count++; oMeasurement.duration = oMeasurement.completeDuration / oMeasurement.count; oMeasurement.start = iTime; } else { oMeasurement.duration = oMeasurement.end - oMeasurement.start; } } if (oMeasurement.end >= oMeasurement.start) { oMeasurement.time = oMeasurement.end - oMeasurement.start; } } if (oMeasurement) { // end timeline entry /*eslint-disable no-console */ if (window.console && console.timeEnd) { console.timeEnd(oMeasurement.info + " - " + sId); } /*eslint-enable no-console */ return this.getMeasurement(sId); } else { return false; } }; /** * Clears all performance measurements * * @name jQuery.sap.measure#clear * @function * @public */ this._clear = function() { this.mMeasurements = {}; }; /** * Removes a performance measure * * @param {string} sId ID of the measurement * @name jQuery.sap.measure#remove * @function * @public */ this._remove = function(sId) { delete this.mMeasurements[sId]; }; /** * Adds a performance measurement with all data * This is usefull to add external measurements (e.g. from a backend) to the common measurement UI * * @param {string} sId ID of the measurement * @param {string} sInfo Info for the measurement * @param {int} iStart start timestamp * @param {int} iEnd end timestamp * @param {int} iTime time in milliseconds * @param {int} iDuration effective time in milliseconds * @param {string | string[]} [aCategories = "javascript"] An optional list of categories for the measure * @return {object} [] current measurement containing id, info and start-timestamp, end-timestamp, time, duration, categories (false if error) * @name jQuery.sap.measure#add * @function * @public */ this._add = function(sId, sInfo, iStart, iEnd, iTime, iDuration, aCategories) { if (!bActive) { return; } aCategories = checkCategories(aCategories); if (!aCategories) { return false; } var oMeasurement = new Measurement( sId, sInfo, iStart, iEnd, aCategories); oMeasurement.time = iTime; oMeasurement.duration = iDuration; if (oMeasurement) { this.mMeasurements[sId] = oMeasurement; return this.getMeasurement(oMeasurement.id); } else { return false; } }; /** * Starts an average performance measure. * The duration of this measure is an avarage of durations measured for each call. * Optionally a category or list of categories can be passed to allow filtering of measurements. * * @param {string} sId ID of the measurement * @param {string} sInfo Info for the measurement * @param {string | string[]} [aCategories = "javascript"] An optional list of categories for the measure * @return {object} current measurement containing id, info and start-timestamp (false if error) * @name jQuery.sap.measure#average * @function * @public */ this._average = function(sId, sInfo, aCategories) { if (!bActive) { return; } aCategories = checkCategories(aCategories); if (!aCategories) { return; } var oMeasurement = this.mMeasurements[sId], iTime = jQuery.sap.now(); if (!oMeasurement || !oMeasurement.average) { this.start(sId, sInfo, aCategories); oMeasurement = this.mMeasurements[sId]; oMeasurement.average = true; } else { if (!oMeasurement.end) { oMeasurement.completeDuration += (iTime - oMeasurement.start); oMeasurement.count++; } oMeasurement.start = iTime; oMeasurement.end = 0; } return this.getMeasurement(oMeasurement.id); }; /** * Gets a performance measure * * @param {string} sId ID of the measurement * @return {object} current measurement containing id, info and start-timestamp, end-timestamp, time, duration (false if error) * @name jQuery.sap.measure#getMeasurement * @function * @public */ this.getMeasurement = function(sId) { var oMeasurement = this.mMeasurements[sId]; if (oMeasurement) { return {id: oMeasurement.id, info: oMeasurement.info, start: oMeasurement.start, end: oMeasurement.end, pause: oMeasurement.pause, resume: oMeasurement.resume, time: oMeasurement.time, duration: oMeasurement.duration, completeDuration: oMeasurement.completeDuration, count: oMeasurement.count, average: oMeasurement.average, categories: oMeasurement.categories}; } else { return false; } }; /** * Gets all performance measurements * * @param {boolean} [bCompleted] Whether only completed measurements should be returned, if explicitly set to false only incomplete measurements are returned * @return {object} [] current measurement containing id, info and start-timestamp, end-timestamp, time, duration, categories * @name jQuery.sap.measure#getAllMeasurements * @function * @public */ this.getAllMeasurements = function(bCompleted) { return this.filterMeasurements(function(oMeasurement) { return oMeasurement; }, bCompleted); }; /** * Gets all performance measurements where a provided filter function returns true. * The filter function is called for every measurement and should return the measurement to be added. * If no filter function is provided an empty array is returned. * To filter for certain categories of measurements a fnFilter can be implemented like this * <code> * function(oMeasurement) { * return oMeasurement.categories.indexOf("rendering") > -1 ? oMeasurement : null * }</code> * * @param {function} fnFilter a filter function that returns true if the passed measurement should be added to the result * @param {boolean} [bCompleted] Whether only completed measurements should be returned, if explicitly set to false only incomplete measurements are returned * * @return {object} [] current measurements containing id, info and start-timestamp, end-timestamp, time, duration, categories (false if error) * @name jQuery.sap.measure#filterMeasurements * @function * @public * @since 1.34.0 */ this.filterMeasurements = function(fnFilter, bCompleted) { var aMeasurements = [], that = this; jQuery.each(this.mMeasurements, function(sId){ var oMeasurement = that.getMeasurement(sId); if (fnFilter) { var oResult = fnFilter(oMeasurement); if (oResult && ((bCompleted === false && oResult.end === 0) || (bCompleted !== false && (!bCompleted || oResult.end)))) { aMeasurements.push(oResult); } } }); return aMeasurements; }; /** * Registers an average measurement for a given objects method * * @param {string} sId the id of the measurement * @param {object} oObject the object of the method * @param {string} sMethod the name of the method * @param {string[]} [aCategories = ["javascript"]] An optional categories list for the measurement * * @returns {boolean} true if the registration was successful * @name jQuery.sap.measure#registerMethod * @function * @public * @since 1.34.0 */ this.registerMethod = function(sId, oObject, sMethod, aCategories) { var fnMethod = oObject[sMethod]; if (fnMethod && typeof fnMethod === "function") { var bFound = aAverageMethods.indexOf(fnMethod) > -1; if (!bFound) { aOriginalMethods.push({func : fnMethod, obj: oObject, method: sMethod, id: sId}); oObject[sMethod] = function() { jQuery.sap.measure.average(sId, sId + " method average", aCategories); var result = fnMethod.apply(this, arguments); jQuery.sap.measure.end(sId); return result; }; aAverageMethods.push(oObject[sMethod]); return true; } } else { jQuery.sap.log.debug(sMethod + " in not a function. jQuery.sap.measure.register failed"); } return false; }; /** * Unregisters an average measurement for a given objects method * * @param {string} sId the id of the measurement * @param {object} oObject the object of the method * @param {string} sMethod the name of the method * * @returns {boolean} true if the unregistration was successful * @name jQuery.sap.measure#unregisterMethod * @function * @public * @since 1.34.0 */ this.unregisterMethod = function(sId, oObject, sMethod) { var fnFunction = oObject[sMethod], iIndex = aAverageMethods.indexOf(fnFunction); if (fnFunction && iIndex > -1) { oObject[sMethod] = aOriginalMethods[iIndex].func; aAverageMethods.splice(iIndex, 1); aOriginalMethods.splice(iIndex, 1); return true; } return false; }; /** * Unregisters all average measurements * @name jQuery.sap.measure#unregisterAllMethods * @function * @public * @since 1.34.0 */ this.unregisterAllMethods = function() { while (aOriginalMethods.length > 0) { var oOrig = aOriginalMethods[0]; this.unregisterMethod(oOrig.id, oOrig.obj, oOrig.method); } }; // ** Interaction measure ** var aInteractions = []; var oPendingInteraction; /** * Gets all interaction measurements * @return {object[]} all interaction measurements * @name jQuery.sap.measure#getAllInteractionMeasurements * @function * @public * @since 1.34.0 */ this.getAllInteractionMeasurements = function() { return aInteractions; }; /** * Gets the incomplete pending interaction * @return {object} interaction measurement * @name jQuery.sap.measure#getInteractionMeasurement * @function * @private * @since 1.34.0 */ this.getPendingInteractionMeasurement = function() { return oPendingInteraction; }; /** * Clears all interaction measurements * @name jQuery.sap.measure#getLastInteractionMeasurement * @function * @public * @since 1.34.0 */ this.clearInteractionMeasurements = function() { aInteractions = []; }; function finalizeInteraction(iTime) { if (oPendingInteraction) { oPendingInteraction.end = iTime; oPendingInteraction.duration = oPendingInteraction.processing; oPendingInteraction.requests = jQuery.sap.measure.getRequestTimings(); oPendingInteraction.measurements = jQuery.sap.measure.filterMeasurements(function(oMeasurement) { return (oMeasurement.start > oPendingInteraction.start && oMeasurement.end < oPendingInteraction.end) ? oMeasurement : null; }, true); if (oPendingInteraction.requests.length > 0) { // determine Performance API timestamp for latestly completed request var iEnd = oPendingInteraction.requests[0].startTime, iNavLo = oPendingInteraction.requests[0].startTime, iNavHi = oPendingInteraction.requests[0].requestStart, iRtLo = oPendingInteraction.requests[0].requestStart, iRtHi = oPendingInteraction.requests[0].responseEnd; oPendingInteraction.requests.forEach(function(oRequest) { iEnd = oRequest.responseEnd > iEnd ? oRequest.responseEnd : iEnd; oPendingInteraction.requestTime += (oRequest.responseEnd - oRequest.startTime); // summarize navigation and roundtrip with respect to requests overlapping and times w/o requests if (iRtHi < oRequest.startTime) { oPendingInteraction.navigation += (iNavHi - iNavLo); oPendingInteraction.roundtrip += (iRtHi - iRtLo); iNavLo = oRequest.startTime; iRtLo = oRequest.requestStart; } if (oRequest.responseEnd > iRtHi) { iNavHi = oRequest.requestStart; iRtHi = oRequest.responseEnd; } }); oPendingInteraction.navigation += iNavHi - iNavLo; oPendingInteraction.roundtrip += iRtHi - iRtLo; // calculate average network time per request oPendingInteraction.networkTime = oPendingInteraction.networkTime ? ((oPendingInteraction.requestTime - oPendingInteraction.networkTime) / oPendingInteraction.requests.length) : 0; // in case processing is not determined, which means no re-rendering occured, take start to iEnd if (oPendingInteraction.duration === 0) { oPendingInteraction.duration = oPendingInteraction.navigation + oPendingInteraction.roundtrip; } } // calculate real processing time if any processing took place, cannot be negative as then requests took longer than processing if (oPendingInteraction.processing !== 0) { var iProcessing = oPendingInteraction.processing - oPendingInteraction.navigation - oPendingInteraction.roundtrip; oPendingInteraction.processing = iProcessing > 0 ? iProcessing : 0; } aInteractions.push(oPendingInteraction); jQuery.sap.log.info("Interaction step finished: trigger: " + oPendingInteraction.trigger + "; duration: " + oPendingInteraction.duration + "; requests: " + oPendingInteraction.requests.length); oPendingInteraction = null; } } /** * Start an interaction measurements * * @param {string} sType type of the event which triggered the interaction * @param {object} oSrcElement the control on which the interaction was triggered * * @name jQuery.sap.measure#startInteraction * @function * @public * @since 1.34.0 */ this.startInteraction = function(sType, oSrcElement) { // component determination - heuristic function identifyOwnerComponent(oSrcElement) { if (oSrcElement) { var Component, oComponent; Component = sap.ui.require("sap/ui/core/Component"); while (Component && oSrcElement && oSrcElement.getParent) { oComponent = Component.getOwnerComponentFor(oSrcElement); if (oComponent || oSrcElement instanceof Component) { oComponent = oComponent || oSrcElement; var oApp = oComponent.getMetadata().getManifestEntry("sap.app"); // get app id or module name for FESR return oApp && oApp.id || oComponent.getMetadata().getName(); } oSrcElement = oSrcElement.getParent(); } } return "undetermined"; } var iTime = jQuery.sap.now(); if (oPendingInteraction) { finalizeInteraction(iTime); } // clear request timings for new interaction this.clearRequestTimings(); // setup new pending interaction oPendingInteraction = { event: sType, // event which triggered interaction trigger: oSrcElement && oSrcElement.getId ? oSrcElement.getId() : "undetermined", // control which triggered interaction component: identifyOwnerComponent(oSrcElement), // component or app identifier start : iTime, // interaction start end: 0, // interaction end navigation: 0, // sum over all navigation times roundtrip: 0, // time from first request sent to last received response end processing: 0, // client processing time duration: 0, // interaction duration requests: [], // Performance API requests during interaction measurements: [], // jQuery.sap.measure Measurements sapStatistics: [], // SAP Statistics for OData, added by jQuery.sap.trace requestTime: 0, // summ over all requests in the interaction (oPendingInteraction.requests[0].responseEnd-oPendingInteraction.requests[0].requestStart) networkTime: 0, // request time minus server time from the header, added by jQuery.sap.trace bytesSent: 0, // sum over all requests bytes, added by jQuery.sap.trace bytesReceived: 0, // sum over all response bytes, added by jQuery.sap.trace requestCompression: undefined // true if all responses have been sent gzipped }; jQuery.sap.log.info("Interaction step started: trigger: " + oPendingInteraction.trigger + "; type: " + oPendingInteraction.event); }; /** * End an interaction measurements * * @param {boolean} bForce forces end of interaction now and ignores further re-renderings * * @name jQuery.sap.measure#endInteraction * @function * @public * @since 1.34.0 */ this.endInteraction = function(bForce) { if (oPendingInteraction) { // set provisionary processing time from start to end and calculate later if (!bForce) { oPendingInteraction.processing = jQuery.sap.now() - oPendingInteraction.start; } else { finalizeInteraction(jQuery.sap.now()); } } }; /** * Sets the request buffer size for the interaction measurement * * @param {integer} iSize size of the buffer * * @name jQuery.sap.measure#setRequestBufferSize * @function * @public * @since 1.34.0 */ this.setRequestBufferSize = function(iSize) { if (!window.performance) { return; } if (window.performance.setResourceTimingBufferSize) { window.performance.setResourceTimingBufferSize(iSize); } else if (window.performance.webkitSetResourceTimingBufferSize) { window.performance.webkitSetResourceTimingBufferSize(iSize); } }; /** * Gets the request timings for the interaction measurement * * @return {object[]} iSize size of the buffer * @name jQuery.sap.measure#getRequestTimings * @function * @public * @since 1.34.0 */ this.getRequestTimings = function() { if (window.performance && window.performance.getEntriesByType) { return jQuery.extend(window.performance.getEntriesByType("resource"),{}); } return []; }; /** * Clears all request timings * * @name jQuery.sap.measure#clearRequestTimings * @function * @public * @since 1.34.0 */ this.clearRequestTimings = function() { if (!window.performance) { return; } if (window.performance.clearResourceTimings) { window.performance.clearResourceTimings(); } else if (window.performance.webkitClearResourceTimings){ window.performance.webkitClearResourceTimings(); } }; this.setRequestBufferSize(1000); var aMatch = location.search.match(/sap-ui-measure=([^\&]*)/); if (aMatch && aMatch[1]) { if (aMatch[1] === "true" || aMatch[1] === "x" || aMatch[1] === "X") { this.setActive(true); } else { this.setActive(true, aMatch[1]); } } else { var fnInactive = function() { //measure not active return null; }; //deactivate methods implementations for (var i = 0; i < aMethods.length; i++) { this[aMethods[i]] = fnInactive; } } } /** * Namespace for the jQuery performance measurement plug-in provided by SAP SE. * * @namespace * @name jQuery.sap.measure * @public * @static */ jQuery.sap.measure = new PerfMeasurement(); /** * A simple assertion mechanism that logs a message when a given condition is not met. * * <b>Note:</b> Calls to this method might be removed when the JavaScript code * is optimized during build. Therefore, callers should not rely on any side effects * of this method. * * @param {boolean} bResult result of the checked assertion * @param {string|function} vMessage message that will be raised when the result is <code>false</code>. In case this is a function, the return value of the function will be displayed. This can be used to execute complex code only if the assertion fails. * * @public * @static * @SecSink {1|SECRET} Could expose secret data in logs */ jQuery.sap.assert = function(bResult, vMessage) { if ( !bResult ) { var sMessage = typeof vMessage === "function" ? vMessage() : vMessage; /*eslint-disable no-console */ if ( window.console && console.assert ) { console.assert(bResult, sWindowName + sMessage); } else { // console is not always available (IE, FF) and IE doesn't support console.assert jQuery.sap.log.debug("[Assertions] " + sMessage); } /*eslint-enable no-console */ } }; // against all our rules: use side effect of assert to differentiate between optimized and productive code jQuery.sap.assert( !!(mMaxLevel[''] = DEBUG), "will be removed in optimized version"); // evaluate configuration oCfgData.loglevel = (function() { var m = /(?:\?|&)sap-ui-log(?:L|-l)evel=([^&]*)/.exec(window.location.search); return m && m[1]; }()) || oCfgData.loglevel; if ( oCfgData.loglevel ) { jQuery.sap.log.setLevel(jQuery.sap.log.Level[oCfgData.loglevel.toUpperCase()] || parseInt(oCfgData.loglevel,10)); } jQuery.sap.log.info("SAP Logger started."); // log early logs jQuery.each(_earlyLogs, function(i,e) { jQuery.sap.log[e.level](e.message); }); _earlyLogs = null; }()); // --------------------------------------------------------------------------------------------------- /** * Returns a new constructor function that creates objects with * the given prototype. * * @param {object} oPrototype * @return {function} the newly created constructor function * @public * @static */ jQuery.sap.factory = function factory(oPrototype) { function Factory() {} Factory.prototype = oPrototype; return Factory; }; /** * Returns a new object which has the given oPrototype as its prototype. * * If several objects with the same prototype are to be created, * {@link jQuery.sap.factory} should be used instead. * * @param {object} oPrototype * @return {object} new object * @public * @static */ jQuery.sap.newObject = function newObject(oPrototype) { return new (jQuery.sap.factory(oPrototype))(); }; /** * Returns a new function that returns the given <code>oValue</code> (using its closure). * * Avoids the need for a dedicated member for the value. * * As closures don't come for free, this function should only be used when polluting * the enclosing object is an absolute "must-not" (as it is the case in public base classes). * * @param {object} oValue * * @public * @static */ jQuery.sap.getter = function getter(oValue) { return function() { return oValue; }; }; /** * Returns a JavaScript object which is identified by a sequence of names. * * A call to <code>getObject("a.b.C")</code> has essentially the same effect * as accessing <code>window.a.b.C</code> but with the difference that missing * intermediate objects (a or b in the example above) don't lead to an exception. * * When the addressed object exists, it is simply returned. If it doesn't exists, * the behavior depends on the value of the second, optional parameter * <code>iNoCreates</code> (assuming 'n' to be the number of names in the name sequence): * <ul> * <li>NaN: if iNoCreates is not a number and the addressed object doesn't exist, * then <code>getObject()</code> returns <code>undefined</code>. * <li>0 &lt; iNoCreates &lt; n: any non-existing intermediate object is created, except * the <i>last</i> <code>iNoCreates</code> ones. * </ul> * * Example: * <pre> * getObject() -- returns the context object (either param or window) * getObject("a.b.C") -- will only try to get a.b.C and return undefined if not found. * getObject("a.b.C", 0) -- will create a, b, and C in that order if they don't exists * getObject("a.b.c", 1) -- will create a and b, but not C. * </pre> * * When a <code>oContext</code> is given, the search starts in that object. * Otherwise it starts in the <code>window</code> object that this plugin * has been created in. * * Note: Although this method internally uses <code>object["key"]</code> to address object * properties, it does not support all possible characters in a name. * Especially the dot ('.') is not supported in the individual name segments, * as it is always interpreted as a name separator. * * @param {string} sName a dot separated sequence of names that identify the required object * @param {int} [iNoCreates=NaN] number of objects (from the right) that should not be created * @param {object} [oContext=window] the context to execute the search in * * @public * @static */ jQuery.sap.getObject = function getObject(sName, iNoCreates, oContext) { var oObject = oContext || _window, aNames = (sName || "").split("."), l = aNames.length, iEndCreate = isNaN(iNoCreates) ? 0 : l - iNoCreates, i; for (i = 0; oObject && i < l; i++) { if (!oObject[aNames[i]] && i < iEndCreate ) { oObject[aNames[i]] = {}; } oObject = oObject[aNames[i]]; } return oObject; }; /** * Sets an object property to a given value, where the property is * identified by a sequence of names (path). * * When a <code>oContext</code> is given, the path starts in that object. * Otherwise it starts in the <code>window</code> object that this plugin * has been created for. * * Note: Although this method internally uses <code>object["key"]</code> to address object * properties, it does not support all possible characters in a name. * Especially the dot ('.') is not supported in the individual name segments, * as it is always interpreted as a name separator. * * @param {string} sName a dot separated sequence of names that identify the property * @param {any} vValue value to be set, can have any type * @param {object} [oContext=window] the context to execute the search in * @public * @static */ jQuery.sap.setObject = function (sName, vValue, oContext) { var oObject = oContext || _window, aNames = (sName || "").split("."), l = aNames.length, i; if ( l > 0 ) { for (i = 0; oObject && i < l - 1; i++) { if (!oObject[aNames[i]] ) { oObject[aNames[i]] = {}; } oObject = oObject[aNames[i]]; } oObject[aNames[l - 1]] = vValue; } }; // ---------------------- sync point ------------------------------------------------------------- /* * Internal class that can help to synchronize a set of asynchronous tasks. * Each task must be registered in the sync point by calling startTask with * an (purely informative) title. The returned value must be used in a later * call to finishTask. * When finishTask has been called for all tasks that have been started, * the fnCallback will be fired. * When a timeout is given and reached, the callback is called at that * time, no matter whether all tasks have been finished or not. */ function SyncPoint(sName, fnCallback, iTimeout) { var aTasks = [], iOpenTasks = 0, iFailures = 0, sTimer; this.startTask = function(sTitle) { var iId = aTasks.length; aTasks[iId] = { name : sTitle, finished : false }; iOpenTasks++; return iId; }; this.finishTask = function(iId, bSuccess) { if ( !aTasks[iId] || aTasks[iId].finished ) { throw new Error("trying to finish non existing or already finished task"); } aTasks[iId].finished = true; iOpenTasks--; if ( bSuccess === false ) { iFailures++; } if ( iOpenTasks === 0 ) { jQuery.sap.log.info("Sync point '" + sName + "' finished (tasks:" + aTasks.length + ", open:" + iOpenTasks + ", failures:" + iFailures + ")"); if ( sTimer ) { clearTimeout(sTimer); sTimer = null; } finish(); } }; function finish() { fnCallback && fnCallback(iOpenTasks, iFailures); fnCallback = null; } if ( !isNaN(iTimeout) ) { sTimer = setTimeout(function() { jQuery.sap.log.info("Sync point '" + sName + "' timed out (tasks:" + aTasks.length + ", open:" + iOpenTasks + ", failures:" + iFailures + ")"); finish(); }, iTimeout); } jQuery.sap.log.info("Sync point '" + sName + "' created" + (iTimeout ? "(timeout after " + iTimeout + " ms)" : "")); } /** * Internal function to create a sync point. * @private */ jQuery.sap.syncPoint = function(sName, fnCallback, iTimeout) { return new SyncPoint(sName, fnCallback, iTimeout); }; // ---------------------- require/declare -------------------------------------------------------- var getModuleSystemInfo = (function() { /** * Local logger, by default only logging errors. Can be configured to DEBUG via config parameter. * @private */ var log = jQuery.sap.log.getLogger("sap.ui.ModuleSystem", (/sap-ui-xx-debug(M|-m)odule(L|-l)oading=(true|x|X)/.test(location.search) || oCfgData["xx-debugModuleLoading"]) ? jQuery.sap.log.Level.DEBUG : jQuery.sap.log.Level.INFO ), /** * A map of URL prefixes keyed by the corresponding module name prefix. * URL prefix can either be given as string or as object with properties url and final. * When final is set to true, module name prefix cannot be overwritten. * @see jQuery.sap.registerModulePath * * Note that the empty prefix ('') will always match and thus serves as a fallback. * @private */ mUrlPrefixes = { '' : { 'url' : 'resources/' } }, /** * Module neither has been required nor preloaded not declared, but someone asked for it. */ INITIAL = 0, /** * Module has been preloaded, but not required or declared */ PRELOADED = -1, /** * Module has been declared. */ LOADING = 1, /** * Module has been loaded, but not yet executed. */ LOADED = 2, /** * Module is currently being executed */ EXECUTING = 3, /** * Module has been loaded and executed without errors. */ READY = 4, /** * Module either could not be loaded or execution threw an error */ FAILED = 5, /** * Set of modules that have been loaded (required) so far. * * Each module is an object that can have the following members * <ul> * <li>{int} state one of the module states defined in this function * <li>{string} url URL where the module has been loaded from * <li>{any} data temp. raw content of the module (between loaded and ready) * <li>{string} error an error description for state <code>FAILED</code> * <li>{any} content the content of the module as exported via define() * </ul> * @private */ mModules = { // predefine already loaded modules to avoid redundant loading // "sap/ui/thirdparty/jquery/jquery-1.7.1.js" : { state : READY, url : _sBootstrapUrl, content : jQuery }, "sap/ui/thirdparty/URI.js" : { state : READY, url : _sBootstrapUrl, content : URI }, "sap/ui/Device.js" : { state : READY, url : _sBootstrapUrl, content : sap.ui.Device }, "jquery.sap.global.js" : { state : READY, url : _sBootstrapUrl, content : jQuery } }, mPreloadModules = {}, /* for future use /** * Mapping from default AMD names to UI5 AMD names. * * For simpler usage in requireModule, the names are already converted to * normalized resource names. * * / mAMDAliases = { 'blanket.js': 'sap/ui/thirdparty/blanket.js', 'crossroads.js': 'sap/ui/thirdparty/crossroads.js', 'd3.js': 'sap/ui/thirdparty/d3.js', 'handlebars.js': 'sap/ui/thirdparty/handlebars.js', 'hasher.js': 'sap/ui/thirdparty/hasher.js', 'IPv6.js': 'sap/ui/thirdparty/IPv6.js', 'jquery.js': 'sap/ui/thirdparty/jquery.js', 'jszip.js': 'sap/ui/thirdparty/jszip.js', 'less.js': 'sap/ui/thirdparty/less.js', 'OData.js': 'sap/ui/thirdparty/datajs.js', 'punycode.js': 'sap/ui/thirdparty/punycode.js', 'SecondLevelDomains.js': 'sap/ui/thirdparty/SecondLevelDomains.js', 'sinon.js': 'sap/ui/thirdparty/sinon.js', 'signals.js': 'sap/ui/thirdparty/signals.js', 'URI.js': 'sap/ui/thirdparty/URI.js', 'URITemplate.js': 'sap/ui/thirdparty/URITemplate.js', 'esprima.js': 'sap/ui/demokit/js/esprima.js' }, */ /** * Information about third party modules that are delivered with the sap.ui.core library. * * The information maps the name of the module (including extension '.js') to an info object with the * following properties: * * <ul> * <li>amd:boolean : whether the module uses an AMD loader if present. UI5 will disable the AMD loader while loading * such modules to force the modules to expose their content via global names.</li> * <li>exports:string[]|string : global name (or names) that are exported by the module. If one ore multiple names are defined, * the first one will be read from the global object and will be used as value of the module.</li> * <li>deps:string[] : list of modules that the module depends on. The modules will be loaded first before loading the module itself.</li> * </ul> * to be able to work with jQuery.sap.require no matter whether an AMD loader is present or not. * * Note: this is a map for future extension * Note: should be maintained together with raw-module info in .library files * @private */ mAMDShim = { 'sap/ui/thirdparty/blanket.js': { amd: true, exports: 'blanket' // '_blanket', 'esprima', 'falafel', 'inBrowser', 'parseAndModify' }, 'sap/ui/thirdparty/caja-html-sanitizer.js': { amd: false, exports: 'html' // 'html_sanitizer', 'html4' }, 'sap/ui/thirdparty/crossroads.js': { amd: true, exports: 'crossroads', deps: ['sap/ui/thirdparty/signals.js'] }, 'sap/ui/thirdparty/d3.js': { amd: true, exports: 'd3' }, 'sap/ui/thirdparty/datajs.js': { amd: true, exports: 'OData' // 'datajs' }, 'sap/ui/thirdparty/es6-promise.js' : { amd: true, exports: 'ES6Promise' }, 'sap/ui/thirdparty/flexie.js': { exports: 'Flexie' }, 'sap/ui/thirdparty/handlebars.js': { amd: true, exports: 'Handlebars' }, 'sap/ui/thirdparty/hasher.js': { amd: true, exports: 'hasher', deps: ['sap/ui/thirdparty/signals.js'] }, 'sap/ui/thirdparty/IPv6.js': { amd: true, exports: 'IPv6' }, 'sap/ui/thirdparty/iscroll-lite.js': { exports: 'iScroll' }, 'sap/ui/thirdparty/iscroll.js': { exports: 'iScroll' }, 'sap/ui/thirdparty/jquery.js': { amd: true }, 'sap/ui/thirdparty/jquery/jquery-1.11.1.js': { amd: true }, 'sap/ui/thirdparty/jquery/jquery-1.10.2.js': { amd: true }, 'sap/ui/thirdparty/jquery/jquery-1.10.1.js': { amd: true }, 'sap/ui/thirdparty/jquery/jquery.1.7.1.js': { amd: true }, 'sap/ui/thirdparty/jquery/jquery.1.8.1.js': { amd: true }, 'sap/ui/thirdparty/jquery-mobile-custom.js': { amd: true, exports: 'jQuery.mobile' }, 'sap/ui/thirdparty/jszip.js': { amd: true, exports: 'JSZip' }, 'sap/ui/thirdparty/less.js': { amd: true, exports: 'less' }, 'sap/ui/thirdparty/mobify-carousel.js': { exports: 'Mobify' // or Mobify.UI.Carousel? }, 'sap/ui/thirdparty/punycode.js': { amd: true, exports: 'punycode' }, 'sap/ui/thirdparty/require.js': { exports: 'define' // 'require', 'requirejs' }, 'sap/ui/thirdparty/SecondLevelDomains.js': { amd: true, exports: 'SecondLevelDomains' }, 'sap/ui/thirdparty/signals.js': { amd: true, exports: 'signals' }, 'sap/ui/thirdparty/sinon.js': { amd: true, exports: 'sinon' }, 'sap/ui/thirdparty/sinon-server.js': { amd: true, exports: 'sinon' // really sinon! sinon-server is a subset of server and uses the same global for export }, 'sap/ui/thirdparty/unorm.js': { exports: 'UNorm' }, 'sap/ui/thirdparty/unormdata.js': { exports: 'UNorm', // really 'UNorm'! module extends UNorm deps: ['sap/ui/thirdparty/unorm.js'] }, 'sap/ui/thirdparty/URI.js' : { amd: true, exports: 'URI' }, 'sap/ui/thirdparty/URITemplate.js' : { amd: true, exports: 'URITemplate', deps: ['sap/ui/thirdparty/URI.js'] }, 'sap/ui/thirdparty/vkbeautify.js' : { exports: 'vkbeautify' }, 'sap/ui/thirdparty/zyngascroll.js' : { exports: 'Scroller' // 'requestAnimationFrame', 'cancelRequestAnimationFrame', 'core' }, 'sap/ui/demokit/js/esprima.js' : { amd: true, exports: 'esprima' } }, /** * Stack of modules that are currently executed. * * Allows to identify the containing module in case of multi module files (e.g. sap-ui-core) * @private */ _execStack = [ ], /** * A prefix that will be added to module loading log statements and which reflects the nesting of module executions. * @private */ sLogPrefix = "", // max size a script should have when executing it with execScript (IE). Otherwise fallback to eval MAX_EXEC_SCRIPT_LENGTH = 512 * 1024, sDocumentLocation = document.location.href.replace(/\?.*|#.*/g, ""), FRAGMENT = "fragment", VIEW = "view", mKnownSubtypes = { js : [VIEW, FRAGMENT, "controller", "designtime"], xml: [VIEW, FRAGMENT], json: [VIEW, FRAGMENT], html: [VIEW, FRAGMENT] }, rJSSubtypes = new RegExp("(\\.(?:" + mKnownSubtypes.js.join("|") + "))?\\.js$"), rTypes, rSubTypes; (function() { var s = "", sSub = ""; jQuery.each(mKnownSubtypes, function(sType, aSubtypes) { s = (s ? s + "|" : "") + sType; sSub = (sSub ? sSub + "|" : "") + "(?:(?:" + aSubtypes.join("\\.|") + "\\.)?" + sType + ")"; }); s = "\\.(" + s + ")$"; sSub = "\\.(?:" + sSub + "|[^./]+)$"; log.debug("constructed regexp for file types :" + s); log.debug("constructed regexp for file sub-types :" + sSub); rTypes = new RegExp(s); rSubTypes = new RegExp(sSub); }()); /** * Name conversion function that converts a name in UI5 module name syntax to a name in requireJS module name syntax. * @private */ function ui5ToRJS(sName) { if ( /^sap\.ui\.thirdparty\.jquery\.jquery-/.test(sName) ) { return "sap/ui/thirdparty/jquery/jquery-" + sName.slice("sap.ui.thirdparty.jquery.jquery-".length); } else if ( /^jquery\.sap\./.test(sName) ) { return sName; } return sName.replace(/\./g, "/"); } /** * Name conversion function that converts a name in unified resource name syntax to a name in UI5 module name syntax. * If the name cannot be converted (e.g. doesn't end with '.js'), then <code>undefined</code> is returned. * * @private */ function urnToUI5(sName) { // UI5 module name syntax is only defined for JS resources if ( !/\.js$/.test(sName) ) { return; } sName = sName.slice(0, -3); if ( /^sap\/ui\/thirdparty\/jquery\/jquery-/.test(sName) ) { return "sap.ui.thirdparty.jquery.jquery-" + sName.slice("sap/ui/thirdparty/jquery/jquery-".length); } else if ( /^jquery\.sap\./.test(sName) ) { return sName; // do nothing } return sName.replace(/\//g, "."); } // find longest matching prefix for resource name function getResourcePath(sResourceName, sSuffix) { // split name into segments var aSegments = sResourceName.split(/\//), l, sNamePrefix, sResult, m; // if no suffix was given and if the name is not empty, try to guess the suffix from the last segment if ( arguments.length === 1 && aSegments.length > 0 ) { // only known types (and their known subtypes) are accepted m = rSubTypes.exec(aSegments[aSegments.length - 1]); if ( m ) { sSuffix = m[0]; aSegments[aSegments.length - 1] = aSegments[aSegments.length - 1].slice(0, m.index); } else { sSuffix = ""; } } // search for a defined name prefix, starting with the full name and successively removing one segment for (l = aSegments.length; l >= 0; l--) { sNamePrefix = aSegments.slice(0, l).join('/'); if ( mUrlPrefixes[sNamePrefix] ) { sResult = mUrlPrefixes[sNamePrefix].url; if ( l < aSegments.length ) { sResult += aSegments.slice(l).join('/'); } if ( sResult.slice(-1) === '/' ) { sResult = sResult.slice(0, -1); } return sResult + (sSuffix || ''); } } jQuery.sap.assert(false, "should never happen"); } function guessResourceName(sURL) { var sNamePrefix, sUrlPrefix, sResourceName; for (sNamePrefix in mUrlPrefixes) { if ( mUrlPrefixes.hasOwnProperty(sNamePrefix) ) { // Note: configured URL prefixes are guaranteed to end with a '/' // But to support the legacy scenario promoted by the application tools ( "registerModulePath('Application','Application')" ) // the prefix check here has to be done without the slash sUrlPrefix = mUrlPrefixes[sNamePrefix].url.slice(0, -1); if ( sURL.indexOf(sUrlPrefix) === 0 ) { // calc resource name sResourceName = sNamePrefix + sURL.slice(sUrlPrefix.length); // remove a leading '/' (occurs if name prefix is empty and if match was a full segment match if ( sResourceName.charAt(0) === '/' ) { sResourceName = sResourceName.slice(1); } if ( mModules[sResourceName] && mModules[sResourceName].data ) { return sResourceName; } } } } // return undefined; } var rDotsAnywhere = /(?:^|\/)\.+/; var rDotSegment = /^\.*$/; /** * Resolves relative module names that contain <code>./</code> or <code>../</code> segments to absolute names. * E.g.: A name <code>../common/validation.js</code> defined in <code>sap/myapp/controller/mycontroller.controller.js</code> * may resolve to <code>sap/myapp/common/validation.js</code>. * * When sBaseName is <code>null</code>, relative names are not allowed (e.g. for a <code>sap.ui.require</code> call) * and their usage results in an error being thrown. * * @param {string|null} sBaseName name of a reference module * @param {string} sModuleName the name to resolve * @returns {string} resolved name * @private */ function resolveModuleName(sBaseName, sModuleName) { var m = rDotsAnywhere.exec(sModuleName), aSegments, sSegment, i,j,l; // check whether the name needs to be resolved at all - if not, just return the sModuleName as it is. if ( !m ) { return sModuleName; } // if the name starts with a relative segments then there must be a base name (a global sap.ui.require doesn't support relative names) if ( m.index === 0 && sBaseName == null ) { throw new Error("relative name not supported ('" + sModuleName + "'"); } // if relative name starts with a dot segment, then prefix it with the base path aSegments = (m.index === 0 ? sBaseName + sModuleName : sModuleName).split('/'); // process path segments for (i = 0, j = 0, l = aSegments.length; i < l; i++) { var sSegment = aSegments[i]; if ( rDotSegment.test(sSegment) ) { if (sSegment === '.' || sSegment === '') { // ignore '.' as it's just a pointer to current package. ignore '' as it results from double slashes (ignored by browsers as well) continue; } else if (sSegment === '..') { // move to parent directory if ( j === 0 ) { throw new Error("Can't navigate to parent of root (base='" + sBaseName + "', name='" + sModuleName + "'");// sBaseNamegetPackagePath(), relativePath)); } j--; } else { throw new Error("illegal path segment '" + sSegment + "'"); } } else { aSegments[j++] = sSegment; } } aSegments.length = j; return aSegments.join('/'); } function declareModule(sModuleName) { var oModule; // sModuleName must be a unified resource name of type .js jQuery.sap.assert(/\.js$/.test(sModuleName), "must be a Javascript module"); oModule = mModules[sModuleName] || (mModules[sModuleName] = { state : INITIAL }); if ( oModule.state > INITIAL ) { return oModule; } if ( log.isLoggable() ) { log.debug(sLogPrefix + "declare module '" + sModuleName + "'"); } // avoid cycles oModule.state = READY; // the first call to declareModule is assumed to identify the bootstrap module // Note: this is only a guess and fails e.g. when multiple modules are loaded via a script tag // to make it safe, we could convert 'declare' calls to e.g. 'subdeclare' calls at build time. if ( _execStack.length === 0 ) { _execStack.push(sModuleName); oModule.url = oModule.url || _sBootstrapUrl; } return oModule; } function requireModule(sModuleName) { // TODO enable when preload has been adapted: // sModuleName = mAMDAliases[sModuleName] || sModuleName; var m = rJSSubtypes.exec(sModuleName), oShim = mAMDShim[sModuleName], sBaseName, sType, oModule, aExtensions, i; // only for robustness, should not be possible by design (all callers append '.js') if ( !m ) { log.error("can only require Javascript module, not " + sModuleName); return; } if ( oShim && oShim.deps ) { if ( log.isLoggable() ) { log.debug("require dependencies of raw module " + sModuleName); } for (i = 0; i < oShim.deps.length; i++) { if ( log.isLoggable() ) { log.debug(" require " + oShim.deps[i]); } requireModule(oShim.deps[i]); } } // in case of having a type specified ignore the type for the module path creation and add it as file extension sBaseName = sModuleName.slice(0, m.index); sType = m[0]; // must be a normalized resource name of type .js sType can be empty or one of view|controller|fragment oModule = mModules[sModuleName] || (mModules[sModuleName] = { state : INITIAL }); if ( log.isLoggable() ) { log.debug(sLogPrefix + "require '" + sModuleName + "' of type '" + sType + "'"); } // check if module has been loaded already if ( oModule.state !== INITIAL ) { if ( oModule.state === PRELOADED ) { oModule.state = LOADED; execModule(sModuleName); } if ( oModule.state === READY ) { if ( log.isLoggable() ) { log.debug(sLogPrefix + "module '" + sModuleName + "' has already been loaded (skipped)."); } return this; } else if ( oModule.state === FAILED ) { throw new Error("found in negative cache: '" + sModuleName + "' from " + oModule.url + ": " + oModule.error); } else { // currently loading return this; } } // set marker for loading modules (to break cycles) oModule.state = LOADING; // if debug is enabled, try to load debug module first aExtensions = window["sap-ui-loaddbg"] ? ["-dbg", ""] : [""]; for (i = 0; i < aExtensions.length && oModule.state !== LOADED; i++) { // create module URL for the current extension oModule.url = getResourcePath(sBaseName, aExtensions[i] + sType); if ( log.isLoggable() ) { log.debug(sLogPrefix + "loading " + (aExtensions[i] ? aExtensions[i] + " version of " : "") + "'" + sModuleName + "' from '" + oModule.url + "'"); } /*eslint-disable no-loop-func */ jQuery.ajax({ url : oModule.url, dataType : 'text', async : false, success : function(response, textStatus, xhr) { oModule.state = LOADED; oModule.data = response; }, error : function(xhr, textStatus, error) { oModule.state = FAILED; oModule.error = xhr ? xhr.status + " - " + xhr.statusText : textStatus; } }); /*eslint-enable no-loop-func */ } // execute module __after__ loading it, this reduces the required stack space! if ( oModule.state === LOADED ) { execModule(sModuleName); } if ( oModule.state !== READY ) { throw new Error("failed to load '" + sModuleName + "' from " + oModule.url + ": " + oModule.error); } } // sModuleName must be a normalized resource name of type .js function execModule(sModuleName) { var oModule = mModules[sModuleName], oShim = mAMDShim[sModuleName], sOldPrefix, sScript, vAMD; if ( oModule && oModule.state === LOADED && typeof oModule.data !== "undefined" ) { // check whether the module is known to use an existing AMD loader, remember the AMD flag vAMD = (oShim === true || (oShim && oShim.amd)) && typeof window.define === "function" && window.define.amd; try { if ( vAMD ) { // temp. remove the AMD Flag from the loader delete window.define.amd; } if ( log.isLoggable() ) { log.debug(sLogPrefix + "executing '" + sModuleName + "'"); sOldPrefix = sLogPrefix; sLogPrefix = sLogPrefix + ": "; } // execute the script in the window context oModule.state = EXECUTING; _execStack.push(sModuleName); if ( typeof oModule.data === "function" ) { oModule.data.call(window); } else if ( jQuery.isArray(oModule.data) ) { sap.ui.define.apply(sap.ui, oModule.data); } else { sScript = oModule.data; // sourceURL: Firebug, Chrome, Safari and IE11 debugging help, appending the string seems to cost ZERO performance // Note: IE11 supports sourceURL even when running in IE9 or IE10 mode // Note: make URL absolute so Chrome displays the file tree correctly // Note: do not append if there is already a sourceURL / sourceMappingURL if (sScript && !sScript.match(/\/\/[#@] source(Mapping)?URL=.*$/)) { sScript += "\n//# sourceURL=" + URI(oModule.url).absoluteTo(sDocumentLocation); } // framework internal hook to intercept the loaded script and modify // it before executing the script - e.g. useful for client side coverage if (typeof jQuery.sap.require._hook === "function") { sScript = jQuery.sap.require._hook(sScript, sModuleName); } if (_window.execScript && (!oModule.data || oModule.data.length < MAX_EXEC_SCRIPT_LENGTH) ) { try { oModule.data && _window.execScript(sScript); // execScript fails if data is empty } catch (e) { _execStack.pop(); // eval again with different approach - should fail with a more informative exception jQuery.sap.globalEval(oModule.data); throw e; // rethrow err in case globalEval succeeded unexpectedly } } else { _window.eval(sScript); } } _execStack.pop(); oModule.state = READY; oModule.data = undefined; // best guess for raw and legacy modules that don't use sap.ui.define oModule.content = oModule.content || jQuery.sap.getObject((oShim && oShim.exports) || urnToUI5(sModuleName)); if ( log.isLoggable() ) { sLogPrefix = sOldPrefix; log.debug(sLogPrefix + "finished executing '" + sModuleName + "'"); } } catch (err) { oModule.state = FAILED; oModule.error = ((err.toString && err.toString()) || err.message) + (err.line ? "(line " + err.line + ")" : "" ); oModule.data = undefined; if ( window["sap-ui-debug"] && (/sap-ui-xx-show(L|-l)oad(E|-e)rrors=(true|x|X)/.test(location.search) || oCfgData["xx-showloaderrors"]) ) { log.error("error while evaluating " + sModuleName + ", embedding again via script tag to enforce a stack trace (see below)"); jQuery.sap.includeScript(oModule.url); return; } } finally { // restore AMD flag if ( vAMD ) { window.define.amd = vAMD; } } } } function requireAll(sBaseName, aDependencies, fnCallback) { var aModules = [], i, sDepModName; for (i = 0; i < aDependencies.length; i++) { sDepModName = resolveModuleName(sBaseName, aDependencies[i]); log.debug(sLogPrefix + "require '" + sDepModName + "'"); requireModule(sDepModName + ".js"); // best guess for legacy modules that don't use sap.ui.define // TODO implement fallback for raw modules aModules[i] = mModules[sDepModName + ".js"].content || jQuery.sap.getObject(urnToUI5(sDepModName + ".js")); log.debug(sLogPrefix + "require '" + sDepModName + "': done."); } fnCallback(aModules); } /** * Constructs an URL to load the module with the given name and file type (suffix). * * Searches the longest prefix of the given module name for which a registration * exists (see {@link jQuery.sap.registerModulePath}) and replaces that prefix * by the registered URL prefix. * * The remainder of the module name is appended to the URL, replacing any dot with a slash. * * Finally, the given suffix (typically a file name extension) is added (unconverted). * * The returned name (without the suffix) doesn't end with a slash. * * @param {string} sModuleName module name to detemrine the path for * @param {string} sSuffix suffix to be added to the resulting path * @return {string} calculated path (URL) to the given module * * @public * @static */ jQuery.sap.getModulePath = function(sModuleName, sSuffix) { return getResourcePath(ui5ToRJS(sModuleName), sSuffix); }; /** * Determines the URL for a resource given its unified resource name. * * Searches the longest prefix of the given resource name for which a registration * exists (see {@link jQuery.sap.registerResourcePath}) and replaces that prefix * by the registered URL prefix. * * The remainder of the resource name is appended to the URL. * * <b>Unified Resource Names</b> * Several UI5 APIs use <i>Unified Resource Names (URNs)</i> as naming scheme for resources that * they deal with (e.h. Javascript, CSS, JSON, XML, ...). URNs are similar to the path * component of an URL: * <ul> * <li>they consist of a non-empty sequence of name segments</li> * <li>segments are separated by a forward slash '/'</li> * <li>name segments consist of URL path segment characters only. It is recommened to use only ASCII * letters (upper or lower case), digits and the special characters '$', '_', '-', '.')</li> * <li>the empty name segment is not supported</li> * <li>names consisting of dots only, are reserved and must not be used for resources</li> * <li>names are case sensitive although the underlying server might be case-insensitive</li> * <li>the behavior with regard to URL encoded characters is not specified, %ddd notation should be avoided</li> * <li>the meaning of a leading slash is undefined, but might be defined in future. It therefore should be avoided</li> * </ul> * * UI5 APIs that only deal with Javascript resources, use a slight variation of this scheme, * where the extension '.js' is always omitted (see {@link sap.ui.define}, {@link sap.ui.require}). * * * <b>Relationship to old Module Name Syntax</b> * * Older UI5 APIs that deal with resources (like {@link jQuery.sap.registerModulePath}, * {@link jQuery.sap.require} and {@link jQuery.sap.declare}) used a dot-separated naming scheme * (called 'module names') which was motivated by object names in the global namespace in * Javascript. * * The new URN scheme better matches the names of the corresponding resources (files) as stored * in a server and the dot ('.') is no longer a forbidden character in a resource name. This finally * allows to handle resources with different types (extensions) with the same API, not only JS files. * * Last but not least does the URN scheme better match the naming conventions used by AMD loaders * (like <code>requireJS</code>). * * @param {string} sResourceName unified resource name of the resource * @returns {string} URL to load the resource from * @public * @experimental Since 1.27.0 * @function */ jQuery.sap.getResourcePath = getResourcePath; /** * Registers an URL prefix for a module name prefix. * * Before a module is loaded, the longest registered prefix of its module name * is searched for and the associated URL prefix is used as a prefix for the request URL. * The remainder of the module name is attached to the request URL by replacing * dots ('.') with slashes ('/'). * * The registration and search operates on full name segments only. So when a prefix * * 'sap.com' -> 'http://www.sap.com/ui5/resources/' * * is registered, then it will match the name * * 'sap.com.Button' * * but not * * 'sap.commons.Button' * * Note that the empty prefix ('') will always match and thus serves as a fallback for * any search. * * The prefix can either be given as string or as object which contains the url and a 'final' property. * If 'final' is set to true, overwriting a module prefix is not possible anymore. * * @param {string} sModuleName module name to register a path for * @param {string | object} vUrlPrefix path prefix to register, either a string literal or an object (e.g. {url : 'url/to/res', 'final': true}) * @param {string} [vUrlPrefix.url] path prefix to register * @param {boolean} [vUrlPrefix.final] flag to avoid overwriting the url path prefix for the given module name at a later point of time * * @public * @static * @SecSink {1|PATH} Parameter is used for future HTTP requests */ jQuery.sap.registerModulePath = function registerModulePath(sModuleName, vUrlPrefix) { jQuery.sap.assert(!/\//.test(sModuleName), "module path must not contain a slash."); sModuleName = sModuleName.replace(/\./g, "/"); // URL must not be empty vUrlPrefix = vUrlPrefix || '.'; jQuery.sap.registerResourcePath(sModuleName, vUrlPrefix); }; /** * Registers an URL prefix for a resource name prefix. * * Before a resource is loaded, the longest registered prefix of its unified resource name * is searched for and the associated URL prefix is used as a prefix for the request URL. * The remainder of the resource name is attached to the request URL 1:1. * * The registration and search operates on full name segments only. So when a prefix * * 'sap/com' -> 'http://www.sap.com/ui5/resources/' * * is registered, then it will match the name * * 'sap/com/Button' * * but not * * 'sap/commons/Button' * * Note that the empty prefix ('') will always match and thus serves as a fallback for * any search. * * The url prefix can either be given as string or as object which contains the url and a final flag. * If final is set to true, overwriting a resource name prefix is not possible anymore. * * @param {string} sResourceNamePrefix in unified resource name syntax * @param {string | object} vUrlPrefix prefix to use instead of the sResourceNamePrefix, either a string literal or an object (e.g. {url : 'url/to/res', 'final': true}) * @param {string} [vUrlPrefix.url] path prefix to register * @param {boolean} [vUrlPrefix.final] flag to avoid overwriting the url path prefix for the given module name at a later point of time * * @public * @static * @SecSink {1|PATH} Parameter is used for future HTTP requests */ jQuery.sap.registerResourcePath = function registerResourcePath(sResourceNamePrefix, vUrlPrefix) { sResourceNamePrefix = String(sResourceNamePrefix || ""); if (mUrlPrefixes[sResourceNamePrefix] && mUrlPrefixes[sResourceNamePrefix]["final"] == true) { log.warning( "registerResourcePath with prefix " + sResourceNamePrefix + " already set as final to '" + mUrlPrefixes[sResourceNamePrefix].url + "'. This call is ignored." ); return; } if ( typeof vUrlPrefix === 'string' || vUrlPrefix instanceof String ) { vUrlPrefix = { 'url' : vUrlPrefix }; } if ( !vUrlPrefix || vUrlPrefix.url == null ) { delete mUrlPrefixes[sResourceNamePrefix]; log.info("registerResourcePath ('" + sResourceNamePrefix + "') (registration removed)"); } else { vUrlPrefix.url = String(vUrlPrefix.url); // remove query parameters var iQueryIndex = vUrlPrefix.url.indexOf("?"); if (iQueryIndex !== -1) { vUrlPrefix.url = vUrlPrefix.url.substr(0, iQueryIndex); } // remove hash var iHashIndex = vUrlPrefix.url.indexOf("#"); if (iHashIndex !== -1) { vUrlPrefix.url = vUrlPrefix.url.substr(0, iHashIndex); } // ensure that the prefix ends with a '/' if ( vUrlPrefix.url.slice(-1) != '/' ) { vUrlPrefix.url += '/'; } mUrlPrefixes[sResourceNamePrefix] = vUrlPrefix; log.info("registerResourcePath ('" + sResourceNamePrefix + "', '" + vUrlPrefix.url + "')" + ((vUrlPrefix['final']) ? " (final)" : "")); } }; /** * Check whether a given module has been loaded / declared already. * * Returns true as soon as a module has been required the first time, even when * loading/executing it has not finished yet. So the main assertion of a * return value of <code>true</code> is that the necessary actions have been taken * to make the module available in the near future. It does not mean, that * the content of the module is already available! * * This fuzzy behavior is necessary to avoid multiple requests for the same module. * As a consequence of the assertion above, a <i>preloaded</i> module does not * count as <i>declared</i>. For preloaded modules, an explicit call to * <code>jQuery.sap.require</code> is necessary to make them available. * * If a caller wants to know whether a module needs to be loaded from the server, * it can set <code>bIncludePreloaded</code> to true. Then, preloaded modules will * be reported as 'declared' as well by this method. * * @param {string} sModuleName name of the module to be checked * @param {boolean} [bIncludePreloaded=false] whether preloaded modules should be reported as declared. * @return {boolean} whether the module has been declared already * @public * @static */ jQuery.sap.isDeclared = function isDeclared(sModuleName, bIncludePreloaded) { sModuleName = ui5ToRJS(sModuleName) + ".js"; return mModules[sModuleName] && (bIncludePreloaded || mModules[sModuleName].state !== PRELOADED); }; /** * Returns the names of all declared modules. * @return {string[]} the names of all declared modules * @see jQuery.sap.isDeclared * @public * @static */ jQuery.sap.getAllDeclaredModules = function() { var aModules = []; jQuery.each(mModules, function(sURN, oModule) { // filter out preloaded modules if ( oModule && oModule.state !== PRELOADED ) { var sModuleName = urnToUI5(sURN); if ( sModuleName ) { aModules.push(sModuleName); } } }); return aModules; }; // take resource roots from configuration if ( oCfgData.resourceroots ) { jQuery.each(oCfgData.resourceroots, jQuery.sap.registerModulePath); } // dump the URL prefixes log.info("URL prefixes set to:"); for (var n in mUrlPrefixes) { log.info(" " + (n ? "'" + n + "'" : "(default)") + " : " + mUrlPrefixes[n].url + ((mUrlPrefixes[n]['final']) ? " (final)" : "") ); } /** * Declares a module as existing. * * By default, this function assumes that the module will create a JavaScript object * with the same name as the module. As a convenience it ensures that the parent * namespace for that object exists (by calling jQuery.sap.getObject). * If such an object creation is not desired, <code>bCreateNamespace</code> must be set to false. * * @param {string | object} sModuleName name of the module to be declared * or in case of an object {modName: "...", type: "..."} * where modName is the name of the module and the type * could be a specific dot separated extension e.g. * <code>{modName: "sap.ui.core.Dev", type: "view"}</code> * loads <code>sap/ui/core/Dev.view.js</code> and * registers as <code>sap.ui.core.Dev.view</code> * @param {boolean} [bCreateNamespace=true] whether to create the parent namespace * * @public * @static */ jQuery.sap.declare = function(sModuleName, bCreateNamespace) { var sNamespaceObj = sModuleName; // check for an object as parameter for sModuleName // in case of this the object contains the module name and the type // which could be {modName: "sap.ui.core.Dev", type: "view"} if (typeof (sModuleName) === "object") { sNamespaceObj = sModuleName.modName; sModuleName = ui5ToRJS(sModuleName.modName) + (sModuleName.type ? "." + sModuleName.type : "") + ".js"; } else { sModuleName = ui5ToRJS(sModuleName) + ".js"; } declareModule(sModuleName); // ensure parent namespace even if module was declared already // (as declare might have been called by require) if (bCreateNamespace !== false) { // ensure parent namespace jQuery.sap.getObject(sNamespaceObj, 1); } return this; }; /** * Ensures that the given module is loaded and executed before execution of the * current script continues. * * By issuing a call to this method, the caller declares a dependency to the listed modules. * * Any required and not yet loaded script will be loaded and execute synchronously. * Already loaded modules will be skipped. * * @param {...string | object} vModuleName one or more names of modules to be loaded * or in case of an object {modName: "...", type: "..."} * where modName is the name of the module and the type * could be a specific dot separated extension e.g. * <code>{modName: "sap.ui.core.Dev", type: "view"}</code> * loads <code>sap/ui/core/Dev.view.js</code> and * registers as <code>sap.ui.core.Dev.view</code> * * @public * @static * @function * @SecSink {0|PATH} Parameter is used for future HTTP requests */ jQuery.sap.require = function(vModuleName, fnCallback) { if ( arguments.length > 1 ) { // legacy mode with multiple arguments, each representing a dependency for (var i = 0; i < arguments.length; i++) { jQuery.sap.require(arguments[i]); } return this; } // check for an object as parameter for sModuleName // in case of this the object contains the module name and the type // which could be {modName: "sap.ui.core.Dev", type: "view"} if (typeof (vModuleName) === "object") { jQuery.sap.assert(!vModuleName.type || jQuery.inArray(vModuleName.type, mKnownSubtypes.js) >= 0, "type must be empty or one of " + mKnownSubtypes.js.join(", ")); vModuleName = ui5ToRJS(vModuleName.modName) + (vModuleName.type ? "." + vModuleName.type : "") + ".js"; } else { vModuleName = ui5ToRJS(vModuleName) + ".js"; } jQuery.sap.measure.start(vModuleName,"Require module " + vModuleName, ["require"]); requireModule(vModuleName); jQuery.sap.measure.end(vModuleName); return this; // TODO }; /** * UI5 internal method that loads the given module, specified in requireJS notation (URL like, without extension). * * Applications MUST NOT USE THIS METHOD as it will be removed in one of the future versions. * It is only intended for sap.ui.component. * * @param {string} sModuleName Module name in requireJS syntax * @private */ jQuery.sap._requirePath = function(sModuleName) { requireModule(sModuleName + ".js"); }; window.sap = window.sap || {}; sap.ui = sap.ui || {}; /** * Defines a Javascript module with its name, its dependencies and a module value or factory. * * The typical and only suggested usage of this method is to have one single, top level call to * <code>sap.ui.define</code> in one Javascript resource (file). When a module is requested by its * name for the first time, the corresponding resource is determined from the name and the current * {@link jQuery.sap.registerResourcePath configuration}. The resource will be loaded and executed * which in turn will execute the top level <code>sap.ui.define</code> call. * * If the module name was omitted from that call, it will be substituted by the name that was used to * request the module. As a preparation step, the dependencies as well as their transitive dependencies, * will be loaded. Then, the module value will be determined: if a static value (object, literal) was * given, that value will be the module value. If a function was given, that function will be called * (providing the module values of the declared dependencies as parameters to the function) and its * return value will be used as module value. The framework internally associates the resulting value * with the module name and provides it to the original requestor of the module. Whenever the module * is requested again, the same value will be returned (modules are executed only once). * * <i>Example:</i><br> * The following example defines a module "SomeClass", but doesn't hard code the module name. * If stored in a file 'sap/mylib/SomeClass.js', it can be requested as 'sap/mylib/SomeClass'. * <pre> * sap.ui.define(['./Helper', 'sap/m/Bar'], function(Helper,Bar) { * * // create a new class * var SomeClass = function(); * * // add methods to its prototype * SomeClass.prototype.foo = function() { * * // use a function from the dependency 'Helper' in the same package (e.g. 'sap/mylib/Helper' ) * var mSettings = Helper.foo(); * * // create and return a sap.m.Bar (using its local name 'Bar') * return new Bar(mSettings); * * } * * // return the class as module value * return SomeClass; * * }); * </pre> * * In another module or in an application HTML page, the {@link sap.ui.require} API can be used * to load the Something module and to work with it: * * <pre> * sap.ui.require(['sap/mylib/Something'], function(Something) { * * // instantiate a Something and call foo() on it * new Something().foo(); * * }); * </pre> * * <b>Module Name Syntax</b><br> * <code>sap.ui.define</code> uses a simplified variant of the {@link jQuery.sap.getResourcePath * unified resource name} syntax for the module's own name as well as for its dependencies. * The only difference to that syntax is, that for <code>sap.ui.define</code> and * <code>sap.ui.require</code>, the extension (which always would be '.js') has to be omitted. * Both methods always add this extension internally. * * As a convenience, the name of a dependency can start with the segment './' which will be * replaced by the name of the package that contains the currently defined module (relative name). * * It is best practice to omit the name of the defined module (first parameter) and to use * relative names for the dependencies whenever possible. This reduces the necessary configuration, * simplifies renaming of packages and allows to map them to a different namespace. * * * <b>Dependency to Modules</b><br> * If a dependencies array is given, each entry represents the name of another module that * the currently defined module depends on. All dependency modules are loaded before the value * of the currently defined module is determined. The module value of each dependency module * will be provided as a parameter to a factory function, the order of the parameters will match * the order of the modules in the dependencies array. * * <b>Note:</b> the order in which the dependency modules are <i>executed</i> is <b>not</b> * defined by the order in the dependencies array! The execution order is affected by dependencies * <i>between</i> the dependency modules as well as by their current state (whether a module * already has been loaded or not). Neither module implementations nor dependants that require * a module set must make any assumption about the execution order (other than expressed by * their dependencies). There is, however, one exception with regard to third party libraries, * see the list of limitations further down below. * * <b>Note:</b>a static module value (a literal provided to <code>sap.ui.define</code>) cannot * depend on the module values of the depency modules. Instead, modules can use a factory function, * calculate the static value in that function, potentially based on the dependencies, and return * the result as module value. The same approach must be taken when the module value is supposed * to be a function. * * * <b>Asynchronous Contract</b><br> * <code>sap.ui.define</code> is designed to support real Asynchronous Module Definitions (AMD) * in future, although it internally still uses the the old synchronous module loading of UI5. * Callers of <code>sap.ui.define</code> therefore must not rely on any synchronous behavior * that they might observe with the current implementation. * * For example, callers of <code>sap.ui.define</code> must not use the module value immediately * after invoking <code>sap.ui.define</code>: * * <pre> * // COUNTER EXAMPLE HOW __NOT__ TO DO IT * * // define a class Something as AMD module * sap.ui.define('Something', [], function() { * var Something = function(); * return Something; * }); * * // DON'T DO THAT! * // accessing the class _synchronously_ after sap.ui.define was called * new Something(); * </pre> * * Applications that need to ensure synchronous module definition or synchronous loading of dependencies * <b>MUST</b> use the old {@link jQuery.sap.declare} and {@link jQuery.sap.require} APIs. * * * <b>(No) Global References</b><br> * To be in line with AMD best practices, modules defined with <code>sap.ui.define</code> * should not make any use of global variables if those variables are also available as module * values. Instead, they should add dependencies to those modules and use the corresponding parameter * of the factory function to access the module value. * * As the current programming model and the documentation of UI5 heavily rely on global names, * there will be a transition phase where UI5 enables AMD modules and local references to module * values in parallel to the old global names. The fourth parameter of <code>sap.ui.define</code> * has been added to support that transition phase. When this parameter is set to true, the framework * provides two additional functionalities * * <ol> * <li>before the factory function is called, the existence of the global parent namespace for * the current module is ensured</li> * <li>the module value will be automatically exported under a global name which is derived from * the name of the module</li> * </ol> * * The parameter lets the framework know whether any of those two operations is needed or not. * In future versions of UI5, a central configuration option is planned to suppress those 'exports'. * * * <b>Third Party Modules</b><br> * Although third party modules don't use UI5 APIs, they still can be listed as dependencies in * a <code>sap.ui.define</code> call. They will be requested and executed like UI5 modules, but their * module value will be <code>undefined</code>. * * If the currently defined module needs to access the module value of such a third party module, * it can access the value via its global name (if the module supports such a usage). * * Note that UI5 temporarily deactivates an existing AMD loader while it executes third party modules * known to support AMD. This sounds contradictarily at a first glance as UI5 wants to support AMD, * but for now it is necessary to fully support UI5 apps that rely on global names for such modules. * * Example: * <pre> * // module 'Something' wants to use third party library 'URI.js' * // It is packaged by UI5 as non-UI5-module 'sap/ui/thirdparty/URI' * * sap.ui.define('Something', ['sap/ui/thirdparty/URI'], function(URIModuleValue) { * * new URIModuleValue(); // fails as module value is undefined * * //global URI // (optional) declare usage of global name so that static code checks don't complain * new URI(); // access to global name 'URI' works * * ... * }); * </pre> * * * <b>Differences to requireJS</b><br> * The current implementation of <code>sap.ui.define</code> differs from <code>requireJS</code> * or other AMD loaders in several aspects: * <ul> * <li>the name <code>sap.ui.define</code> is different from the plain <code>define</code>. * This has two reasons: first, it avoids the impression that <code>sap.ui.define</code> is * an exact implementation of an AMD loader. And second, it allows the coexistence of an AMD * loader (requireJS) and <code>sap.ui.define</code> in one application as long as UI5 or * apps using UI5 are not fully prepared to run with an AMD loader</li> * <li><code>sap.ui.define</code> currently loads modules with synchronous XHR calls. This is * basically a tribute to the synchronous history of UI5. * <b>BUT:</b> synchronous dependency loading and factory execution explicitly it not part of * contract of <code>sap.ui.define</code>. To the contrary, it is already clear and planned * that asynchronous loading will be implemented, at least as an alternative if not as the only * implementation. Also check section <b>Asynchronous Contract</b> above.<br> * Applications that need to ensure synchronous loading of dependencies <b>MUST</b> use the old * {@link jQuery.sap.require} API.</li> * <li><code>sap.ui.define</code> does not support plugins to use other file types, formats or * protocols. It is not planned to support this in future</li> * <li><code>sap.ui.define</code> does <b>not</b> support the 'sugar' of requireJS where CommonJS * style dependency declarations using <code>sap.ui.require("something")</code> are automagically * converted into <code>sap.ui.define</code> dependencies before executing the factory function.</li> * </ul> * * * <b>Limitations, Design Considerations</b><br> * <ul> * <li><b>Limitation</b>: as dependency management is not supported for Non-UI5 modules, the only way * to ensure proper execution order for such modules currently is to rely on the order in the * dependency array. Obviously, this only works as long as <code>sap.ui.define</code> uses * synchronous loading. It will be enhanced when asynchronous loading is implemented.</li> * <li>it was discussed to enfore asynchronous execution of the module factory function (e.g. with a * timeout of 0). But this would have invalidated the current migration scenario where a * sync <code>jQuery.sap.require</code> call can load a <code>sap.ui.define</code>'ed module. * If the module definition would not execute synchronously, the synchronous contract of the * require call would be broken (default behavior in existing UI5 apps)</li> * <li>a single file must not contain multiple calls to <code>sap.ui.define</code>. Multiple calls * currently are only supported in the so called 'preload' files that the UI5 merge tooling produces. * The exact details of how this works might be changed in future implementations and are not * yet part of the API contract</li> * </ul> * @param {string} [sModuleName] name of the module in simplified resource name syntax. * When omitted, the loader determines the name from the request. * @param {string[]} [aDependencies] list of dependencies of the module * @param {function|any} vFactory the module value or a function that calculates the value * @param {boolean} [bExport] whether an export to global names is required - should be used by SAP-owned code only * @since 1.27.0 * @public * @experimental Since 1.27.0 - not all aspects of sap.ui.define are settled yet. If the documented * constraints and limitations are obeyed, SAP-owned code might use it. If the fourth parameter * is not used and if the asynchronous contract is respected, even Non-SAP code might use it. */ sap.ui.define = function(sModuleName, aDependencies, vFactory, bExport) { var sResourceName, sBaseName; // optional id if ( typeof sModuleName === 'string' ) { sResourceName = sModuleName + '.js'; } else { // shift parameters bExport = vFactory; vFactory = aDependencies; aDependencies = sModuleName; sResourceName = _execStack[_execStack.length - 1]; } // convert module name to UI5 module name syntax (might fail!) sModuleName = urnToUI5(sResourceName); // calculate the base name for relative module names sBaseName = sResourceName.slice(0, sResourceName.lastIndexOf('/') + 1); // optional array of dependencies if ( !jQuery.isArray(aDependencies) ) { // shift parameters bExport = vFactory; vFactory = aDependencies; aDependencies = []; } if ( log.isLoggable() ) { log.debug("define(" + sResourceName + ", " + "['" + aDependencies.join("','") + "']" + ")"); } var oModule = declareModule(sResourceName); // Note: dependencies will be resolved and converted from RJS to URN inside requireAll requireAll(sBaseName, aDependencies, function(aModules) { // factory if ( log.isLoggable() ) { log.debug("define(" + sResourceName + "): calling factory " + typeof vFactory); } if ( bExport ) { // ensure parent namespace var sPackage = sResourceName.split('/').slice(0,-1).join('.'); if ( sPackage ) { jQuery.sap.getObject(sPackage, 0); } } if ( typeof vFactory === 'function' ) { oModule.content = vFactory.apply(window, aModules); } else { oModule.content = vFactory; } // HACK: global export if ( bExport ) { if ( oModule.content == null ) { log.error("module '" + sResourceName + "' returned no content, but should be exported"); } else { if ( log.isLoggable() ) { log.debug("exporting content of '" + sResourceName + "': as global object"); } jQuery.sap.setObject(sModuleName, oModule.content); } } }); }; /** * @private */ sap.ui.predefine = function(sModuleName, aDependencies, vFactory, bExport) { if ( typeof sModuleName !== 'string' ) { throw new Error("sap.ui.predefine requires a module name"); } var sResourceName = sModuleName + '.js'; var oModule = mModules[sResourceName]; if ( !oModule ) { mModules[sResourceName] = { state : PRELOADED, url : "TODO???/" + sModuleName, data : [sModuleName, aDependencies, vFactory, bExport], group: null }; } // when a library file is preloaded, also mark its preload file as loaded // for normal library preload, this is redundant, but for non-default merged entities // like sap/fiori/core.js it avoids redundant loading of library preload files if ( sResourceName.match(/\/library\.js$/) ) { mPreloadModules[urnToUI5(sResourceName) + "-preload"] = true; } }; /** * Resolves one or more module dependencies. * * <b>Synchronous Retrieval of a Single Module Value</b> * * When called with a single string, that string is assumed to be the name of an already loaded * module and the value of that module is returned. If the module has not been loaded yet, * or if it is a Non-UI5 module (e.g. third party module), <code>undefined</code> is returned. * This signature variant allows synchronous access to module values without initiating module loading. * * Sample: * <pre> * var JSONModel = sap.ui.require("sap/ui/model/json/JSONModel"); * </pre> * * For modules that are known to be UI5 modules, this signature variant can be used to check whether * the module has been loaded. * * <b>Asynchronous Loading of Multiple Modules</b> * * If an array of strings is given and (optionally) a callback function, then the strings * are interpreted as module names and the corresponding modules (and their transitive * dependencies) are loaded. Then the callback function will be called asynchronously. * The module values of the specified modules will be provided as parameters to the callback * function in the same order in which they appeared in the dependencies array. * * The return value for the asynchronous use case is <code>undefined</code>. * * <pre> * sap.ui.require(['sap/ui/model/json/JSONModel', 'sap/ui/core/UIComponent'], function(JSONModel,UIComponent) { * * var MyComponent = UIComponent.extend('MyComponent', { * ... * }); * ... * * }); * </pre> * * This method uses the same variation of the {@link jQuery.sap.getResourcePath unified resource name} * syntax that {@link sap.ui.define} uses: module names are specified without the implicit extension '.js'. * Relative module names are not supported. * * @param {string|string[]} vDependencies dependency (dependencies) to resolve * @param {function} [fnCallback] callback function to execute after resolving an array of dependencies * @returns {any|undefined} a single module value or undefined * @public * @experimental Since 1.27.0 - not all aspects of sap.ui.require are settled yet. E.g. the return value * of the asynchronous use case might change (currently it is undefined). */ sap.ui.require = function(vDependencies, fnCallback) { jQuery.sap.assert(typeof vDependencies === 'string' || jQuery.isArray(vDependencies), "dependency param either must be a single string or an array of strings"); jQuery.sap.assert(fnCallback == null || typeof fnCallback === 'function', "callback must be a function or null/undefined"); if ( typeof vDependencies === 'string' ) { var sModuleName = vDependencies + '.js', oModule = mModules[sModuleName]; return oModule ? (oModule.content || jQuery.sap.getObject(urnToUI5(sModuleName))) : undefined; } requireAll(null, vDependencies, function(aModules) { if ( typeof fnCallback === 'function' ) { // enforce asynchronous execution of callback setTimeout(function() { fnCallback.apply(window, aModules); },0); } }); // return undefined; }; jQuery.sap.preloadModules = function(sPreloadModule, bAsync, oSyncPoint) { var sURL, iTask; jQuery.sap.assert(!bAsync || oSyncPoint, "if mode is async, a syncpoint object must be given"); if ( mPreloadModules[sPreloadModule] ) { return; } mPreloadModules[sPreloadModule] = true; sURL = jQuery.sap.getModulePath(sPreloadModule, ".json"); log.debug("preload file " + sPreloadModule); iTask = oSyncPoint && oSyncPoint.startTask("load " + sPreloadModule); jQuery.ajax({ dataType : "json", async : bAsync, url : sURL, success : function(data) { if ( data ) { data.url = sURL; } jQuery.sap.registerPreloadedModules(data, bAsync, oSyncPoint); oSyncPoint && oSyncPoint.finishTask(iTask); }, error : function(xhr, textStatus, error) { log.error("failed to preload '" + sPreloadModule + "': " + (error || textStatus)); oSyncPoint && oSyncPoint.finishTask(iTask, false); } }); }; jQuery.sap.registerPreloadedModules = function(oData, bAsync, oSyncPoint) { var bOldSyntax = Version(oData.version || "1.0").compareTo("2.0") < 0; if ( log.isLoggable() ) { log.debug(sLogPrefix + "adding preloaded modules from '" + oData.url + "'"); } if ( oData.name ) { mPreloadModules[oData.name] = true; } jQuery.each(oData.modules, function(sName,sContent) { sName = bOldSyntax ? ui5ToRJS(sName) + ".js" : sName; if ( !mModules[sName] ) { mModules[sName] = { state : PRELOADED, url : oData.url + "/" + sName, data : sContent, group: oData.name }; } // when a library file is preloaded, also mark its preload file as loaded // for normal library preload, this is redundant, but for non-default merged entities // like sap/fiori/core.js it avoids redundant loading of library preload files if ( sName.match(/\/library\.js$/) ) { mPreloadModules[urnToUI5(sName) + "-preload"] = true; } }); if ( oData.dependencies ) { jQuery.each(oData.dependencies, function(idx,sModuleName) { jQuery.sap.preloadModules(sModuleName, bAsync, oSyncPoint); }); } }; /** * Removes a set of resources from the resource cache. * * @param {string} sName unified resource name of a resource or the name of a preload group to be removed * @param {boolean} [bPreloadGroup=true] whether the name specifies a preload group, defaults to true * @param {boolean} [bUnloadAll] Whether all matching resources should be unloaded, even if they have been executed already. * @param {boolean} [bDeleteExports] Whether exportss (global variables) should be destroyed as well. Will be done for UI5 module names only. * @experimental Since 1.16.3 API might change completely, apps must not develop against it. * @private */ jQuery.sap.unloadResources = function(sName, bPreloadGroup, bUnloadAll, bDeleteExports) { var aModules = []; if ( bPreloadGroup == null ) { bPreloadGroup = true; } if ( bPreloadGroup ) { // collect modules that belong to the given group jQuery.each(mModules, function(sURN, oModule) { if ( oModule && oModule.group === sName ) { aModules.push(sURN); } }); // also remove a preload entry delete mPreloadModules[sName]; } else { // single module if ( mModules[sName] ) { aModules.push(sName); } } jQuery.each(aModules, function(i, sURN) { var oModule = mModules[sURN]; if ( oModule && bDeleteExports && sURN.match(/\.js$/) ) { jQuery.sap.setObject(urnToUI5(sURN), undefined); // TODO really delete property } if ( oModule && (bUnloadAll || oModule.state === PRELOADED) ) { delete mModules[sURN]; } }); }; /** * Converts a UI5 module name to a unified resource name. * * Used by View and Fragment APIs to convert a given module name into an URN. * * @experimental Since 1.16.0, not for public usage yet. * @private */ jQuery.sap.getResourceName = function(sModuleName, sSuffix) { return ui5ToRJS(sModuleName) + (sSuffix || ".js"); }; /** * Retrieves the resource with the given name, either from the preload cache or from * the server. The expected data type of the resource can either be specified in the * options (<code>dataType</code>) or it will be derived from the suffix of the <code>sResourceName</code>. * The only supported data types so far are xml, html, json and text. If the resource name extension * doesn't match any of these extensions, the data type must be specified in the options. * * If the resource is found in the preload cache, it will be converted from text format * to the requested <code>dataType</code> using a converter from <code>jQuery.ajaxSettings.converters</code>. * * If it is not found, the resource name will be converted to a resource URL (using {@link #getResourcePath}) * and the resulting URL will be requested from the server with a synchronous jQuery.ajax call. * * If the resource was found in the local preload cache and any necessary conversion succeeded * or when the resource was retrieved from the backend successfully, the content of the resource will * be returned. In any other case, an exception will be thrown, or if option failOnError is set to true, * <code>null</code> will be returned. * * Future implementations of this API might add more options. Generic implementations that accept an * <code>mOptions</code> object and propagate it to this function should limit the options to the currently * defined set of options or they might fail for unknown options. * * For asynchronous calls the return value of this method is an ECMA Script 6 Promise object which callbacks are triggered * when the resource is ready: * If <code>failOnError</code> is <code>false</code> the catch callback of the promise is not called. The argument given to the fullfilled * callback is null in error case. * If <code>failOnError</code> is <code>true</code> the catch callback will be triggered. The argument is an Error object in this case. * * @param {string} [sResourceName] resourceName in unified resource name syntax * @param {object} [mOptions] options * @param {object} [mOptions.dataType] one of "xml", "html", "json" or "text". If not specified it will be derived from the resource name (extension) * @param {string} [mOptions.name] unified resource name of the resource to load (alternative syntax) * @param {string} [mOptions.url] url of a resource to load (alternative syntax, name will only be a guess) * @param {string} [mOptions.headers] Http headers for an eventual XHR request * @param {string} [mOptions.failOnError=true] whether to propagate load errors or not * @param {string} [mOptions.async=false] whether the loading should be performed asynchronously. * @return {string|Document|object|Promise} content of the resource. A string for text or html, an Object for JSON, a Document for XML. For asynchronous calls an ECMA Script 6 Promise object will be returned. * @throws Error if loading the resource failed * @private * @experimental API is not yet fully mature and may change in future. * @since 1.15.1 */ jQuery.sap.loadResource = function(sResourceName, mOptions) { var sType, oData, sUrl, oError, oDeferred; if ( typeof sResourceName === "string" ) { mOptions = mOptions || {}; } else { mOptions = sResourceName || {}; sResourceName = mOptions.name; if ( !sResourceName && mOptions.url) { sResourceName = guessResourceName(mOptions.url); } } // defaulting mOptions = jQuery.extend({ failOnError: true, async: false }, mOptions); sType = mOptions.dataType; if ( sType == null && sResourceName ) { sType = (sType = rTypes.exec(sResourceName)) && sType[1]; } jQuery.sap.assert(/^(xml|html|json|text)$/.test(sType), "type must be one of xml, html, json or text"); oDeferred = mOptions.async ? new jQuery.Deferred() : null; function handleData(d, e) { if ( d == null && mOptions.failOnError ) { oError = e || new Error("no data returned for " + sResourceName); if (mOptions.async) { oDeferred.reject(oError); jQuery.sap.log.error(oError); } return null; } if (mOptions.async) { oDeferred.resolve(d); } return d; } function convertData(d) { var vConverter = jQuery.ajaxSettings.converters["text " + sType]; if ( typeof vConverter === "function" ) { d = vConverter(d); } return handleData(d); } if ( sResourceName && mModules[sResourceName] ) { oData = mModules[sResourceName].data; mModules[sResourceName].state = LOADED; } if ( oData != null ) { if (mOptions.async) { //Use timeout to simulate async behavior for this sync case for easier usage setTimeout(function(){ convertData(oData); }, 0); } else { oData = convertData(oData); } } else { jQuery.ajax({ url : sUrl = mOptions.url || getResourcePath(sResourceName), async : mOptions.async, dataType : sType, headers: mOptions.headers, success : function(data, textStatus, xhr) { oData = handleData(data); }, error : function(xhr, textStatus, error) { oError = new Error("resource " + sResourceName + " could not be loaded from " + sUrl + ". Check for 'file not found' or parse errors. Reason: " + error); oError.status = textStatus; oError.error = error; oError.statusCode = xhr.status; oData = handleData(null, oError); } }); } if ( mOptions.async ) { return Promise.resolve(oDeferred); } if ( oError != null && mOptions.failOnError ) { throw oError; } return oData; }; /* * register a global event handler to detect script execution errors. * Only works for browsers that support document.currentScript. * / window.addEventListener("error", function(e) { if ( document.currentScript && document.currentScript.dataset.sapUiModule ) { var error = { message: e.message, filename: e.filename, lineno: e.lineno, colno: e.colno }; document.currentScript.dataset.sapUiModuleError = JSON.stringify(error); } }); */ /** * Loads the given Javascript resource (URN) asynchronously via as script tag. * Returns a promise that will be resolved when the load event is fired or reject * when the error event is fired. * * Note: execution errors of the script are not reported as 'error'. * * This method is not a full implementation of require. It is intended only for * loading "preload" files that do not define an own module / module value. * * Functionality might be removed/renamed in future, so no code outside the * sap.ui.core library must use it. * * @experimental * @private */ jQuery.sap._loadJSResourceAsync = function(sResource, bIgnoreErrors) { return new Promise(function(resolve,reject) { var oModule = mModules[sResource] || (mModules[sResource] = { state : INITIAL }); var sUrl = oModule.url = getResourcePath(sResource); oModule.state = LOADING; var oScript = window.document.createElement('SCRIPT'); oScript.src = sUrl; oScript.setAttribute("data-sap-ui-module", sResource); // IE9/10 don't support dataset :-( // oScript.setAttribute("data-sap-ui-module-error", ''); oScript.addEventListener('load', function(e) { jQuery.sap.log.info("Javascript resource loaded: " + sResource); // TODO either find a cross-browser solution to detect and assign execution errros or document behavior // var error = e.target.dataset.sapUiModuleError; // if ( error ) { // oModule.state = FAILED; // oModule.error = JSON.parse(error); // jQuery.sap.log.error("failed to load Javascript resource: " + sResource + ":" + error); // reject(oModule.error); // } oModule.state = READY; // TODO oModule.data = ? resolve(); }); oScript.addEventListener('error', function(e) { jQuery.sap.log.error("failed to load Javascript resource: " + sResource); oModule.state = FAILED; // TODO oModule.error = xhr ? xhr.status + " - " + xhr.statusText : textStatus; if ( bIgnoreErrors ) { resolve(); } else { reject(); } }); appendHead(oScript); }); }; return function() { //remove final information in mUrlPrefixes var mFlatUrlPrefixes = {}; jQuery.each(mUrlPrefixes, function(sKey,oUrlPrefix) { mFlatUrlPrefixes[sKey] = oUrlPrefix.url; }); return { modules : mModules, prefixes : mFlatUrlPrefixes }; }; }()); // --------------------- script and stylesheet handling -------------------------------------------------- // appends a link object to the head function appendHead(oElement) { var head = window.document.getElementsByTagName("head")[0]; if (head) { head.appendChild(oElement); } } /** * Includes the script (via &lt;script&gt;-tag) into the head for the * specified <code>sUrl</code> and optional <code>sId</code>. * <br> * <i>In case of IE8 only the load callback will work ignoring in case of success and error.</i> * * @param {string} * sUrl the URL of the script to load * @param {string} * [sId] id that should be used for the script include tag * @param {function} * [fnLoadCallback] callback function to get notified once the script has been loaded * @param {function} * [fnErrorCallback] callback function to get notified once the script loading failed (not supported by IE8) * * @public * @static * @SecSink {0|PATH} Parameter is used for future HTTP requests */ jQuery.sap.includeScript = function includeScript(sUrl, sId, fnLoadCallback, fnErrorCallback){ var oScript = window.document.createElement("script"); oScript.src = sUrl; oScript.type = "text/javascript"; if (sId) { oScript.id = sId; } if (!!sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version < 9) { // in case if IE8 the error callback is not supported! // we can only check the loading via the readystatechange event if (fnLoadCallback) { oScript.onreadystatechange = function() { if (oScript.readyState === "loaded" || oScript.readyState === "complete") { fnLoadCallback(); oScript.onreadystatechange = null; } }; } } else { if (fnLoadCallback) { jQuery(oScript).load(fnLoadCallback); } if (fnErrorCallback) { jQuery(oScript).error(fnErrorCallback); } } // jQuery("head").append(oScript) doesn't work because they filter for the script // and execute them directly instead adding the SCRIPT tag to the head var oOld; if ((sId && (oOld = jQuery.sap.domById(sId)) && oOld.tagName === "SCRIPT")) { jQuery(oOld).remove(); // replacing scripts will not trigger the load event } appendHead(oScript); }; var oIEStyleSheetNode; var mIEStyleSheets = jQuery.sap._mIEStyleSheets = {}; /** * Includes the specified stylesheet via a &lt;link&gt;-tag in the head of the current document. If there is call to * <code>includeStylesheet</code> providing the sId of an already included stylesheet, the existing element will be * replaced. * * @param {string} * sUrl the URL of the script to load * @param {string} * [sId] id that should be used for the script include tag * @param {function} * [fnLoadCallback] callback function to get notified once the link has been loaded * @param {function} * [fnErrorCallback] callback function to get notified once the link loading failed. * In case of usage in IE the error callback will also be executed if an empty stylesheet * is loaded. This is the only option how to determine in IE if the load was successful * or not since the native onerror callback for link elements doesn't work in IE. The IE * always calls the onload callback of the link element. * * @public * @static * @SecSink {0|PATH} Parameter is used for future HTTP requests */ jQuery.sap.includeStyleSheet = function includeStyleSheet(sUrl, sId, fnLoadCallback, fnErrorCallback) { var _createLink = function(sUrl, sId, fnLoadCallback, fnErrorCallback){ // create the new link element var oLink = document.createElement("link"); oLink.type = "text/css"; oLink.rel = "stylesheet"; oLink.href = sUrl; if (sId) { oLink.id = sId; } var fnError = function() { jQuery(oLink).attr("data-sap-ui-ready", "false"); if (fnErrorCallback) { fnErrorCallback(); } }; var fnLoad = function() { jQuery(oLink).attr("data-sap-ui-ready", "true"); if (fnLoadCallback) { fnLoadCallback(); } }; // for IE we will check if the stylesheet contains any rule and then // either trigger the load callback or the error callback if (!!sap.ui.Device.browser.internet_explorer) { var fnLoadOrg = fnLoad; fnLoad = function(oEvent) { var aRules; try { // in cross-origin scenarios the IE can still access the rules of the stylesheet // if the stylesheet has been loaded properly aRules = oEvent.target && oEvent.target.sheet && oEvent.target.sheet.rules; // in cross-origin scenarios now the catch block will be executed because we // cannot access the rules of the stylesheet but for non cross-origin stylesheets // we will get an empty rules array and finally we cannot differ between // empty stylesheet or loading issue correctly => documented in JSDoc! } catch (ex) { // exception happens when the stylesheet could not be loaded from the server // we now ignore this and know that the stylesheet doesn't exists => trigger error } // no rules means error if (aRules && aRules.length > 0) { fnLoadOrg(); } else { fnError(); } }; } jQuery(oLink).load(fnLoad); jQuery(oLink).error(fnError); return oLink; }; var _appendStyle = function(sUrl, sId, fnLoadCallback, fnErrorCallback){ if (sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version <= 9 && document.styleSheets.length >= 28) { // in IE9 only 30 links are alowed, so use stylesheet object insted var sRootUrl = URI.parse(document.URL).path; var sAbsoluteUrl = new URI(sUrl).absoluteTo(sRootUrl).toString(); if (sId) { var oIEStyleSheet = mIEStyleSheets[sId]; if (oIEStyleSheet && oIEStyleSheet.href === sAbsoluteUrl) { // if stylesheet was already included and href is the same, do nothing return; } } jQuery.sap.log.warning("Stylesheet " + (sId ? sId + " " : "") + "not added as LINK because of IE limits", sUrl, "jQuery.sap.includeStyleSheet"); if (!oIEStyleSheetNode) { // create a style sheet to add additional style sheet. But for this the Replace logic will not work any more // the callback functions are not used in this case // the data-sap-ui-ready attribute will not be set -> maybe problems with ThemeCheck oIEStyleSheetNode = document.createStyleSheet(); } // add up to 30 style sheets to every of this style sheets. (result is a tree of style sheets) var bAdded = false; for ( var i = 0; i < oIEStyleSheetNode.imports.length; i++) { var oStyleSheet = oIEStyleSheetNode.imports[i]; if (oStyleSheet.imports.length < 30) { oStyleSheet.addImport(sAbsoluteUrl); bAdded = true; break; } } if (!bAdded) { oIEStyleSheetNode.addImport(sAbsoluteUrl); } if (sId) { // remember id and href URL in internal map as there is no link tag that can be checked mIEStyleSheets[sId] = { href: sAbsoluteUrl }; } // always make sure to re-append the customcss in the end if it exists var oCustomCss = document.getElementById('sap-ui-core-customcss'); if (!jQuery.isEmptyObject(oCustomCss)) { appendHead(oCustomCss); } } else { var oLink = _createLink(sUrl, sId, fnLoadCallback, fnErrorCallback); if (jQuery('#sap-ui-core-customcss').length > 0) { jQuery('#sap-ui-core-customcss').first().before(jQuery(oLink)); } else { appendHead(oLink); } } }; // check for existence of the link var oOld = jQuery.sap.domById(sId); if (oOld && oOld.tagName === "LINK" && oOld.rel === "stylesheet") { // link exists, so we replace it - but only if a callback has to be attached or if the href will change. Otherwise don't touch it if (fnLoadCallback || fnErrorCallback || oOld.href !== URI(String(sUrl), URI().search("") /* returns current URL without search params */ ).toString()) { jQuery(oOld).replaceWith(_createLink(sUrl, sId, fnLoadCallback, fnErrorCallback)); } } else { _appendStyle(sUrl, sId, fnLoadCallback, fnErrorCallback); } }; // TODO should be in core, but then the 'callback' could not be implemented if ( !(oCfgData.productive === true || oCfgData.productive === "true" || oCfgData.productive === "x") ) { jQuery(function() { jQuery(document.body).keydown(function(e) { if ( e.keyCode == 80 && e.shiftKey && e.altKey && e.ctrlKey ) { try { jQuery.sap.require("sap.ui.debug.TechnicalInfo"); } catch (err1) { // alert("Sorry, failed to activate 'P'-mode!"); return; } sap.ui.debug.TechnicalInfo.open(function() { var oInfo = getModuleSystemInfo(); return { modules : oInfo.modules, prefixes : oInfo.prefixes, config: oCfgData }; }); } }); }); jQuery(function() { jQuery(document.body).keydown(function(e) { if ( e.keyCode == 83 /*S*/ && e.shiftKey && e.altKey && e.ctrlKey ) { //TODO: Is this ok? try { jQuery.sap.require("sap.ui.core.support.Support"); var oSupport = sap.ui.core.support.Support.getStub(); if (oSupport.getType() != sap.ui.core.support.Support.StubType.APPLICATION) { return; } oSupport.openSupportTool(); } catch (err2) { // ignore error } } }); }); } // *********** feature detection, enriching jQuery.support ************* // this might go into its own file once there is more stuff added /** * Holds information about the browser's capabilities and quirks. * This object is provided and documented by jQuery. * But it is extended by SAPUI5 with detection for features not covered by jQuery. This documentation ONLY covers the detection properties added by UI5. * For the standard detection properties, please refer to the jQuery documentation. * * These properties added by UI5 are only available temporarily until jQuery adds feature detection on their own. * * @name jQuery.support * @namespace * @since 1.12 * @public */ if (!jQuery.support) { jQuery.support = {}; } jQuery.extend(jQuery.support, {touch: sap.ui.Device.support.touch}); // this is also defined by jquery-mobile-custom.js, but this information is needed earlier var aPrefixes = ["Webkit", "ms", "Moz"]; var oStyle = document.documentElement.style; var preserveOrTestCssPropWithPrefixes = function(detectionName, propName) { if (jQuery.support[detectionName] === undefined) { if (oStyle[propName] !== undefined) { // without vendor prefix jQuery.support[detectionName] = true; // If one of the flex layout properties is supported without the prefix, set the flexBoxPrefixed to false if (propName === "boxFlex" || propName === "flexOrder" || propName === "flexGrow") { // Exception for Chrome up to version 28 // because some versions implemented the non-prefixed properties without the functionality if (!sap.ui.Device.browser.chrome || sap.ui.Device.browser.version > 28) { jQuery.support.flexBoxPrefixed = false; } } return; } else { // try vendor prefixes propName = propName.charAt(0).toUpperCase() + propName.slice(1); for (var i in aPrefixes) { if (oStyle[aPrefixes[i] + propName] !== undefined) { jQuery.support[detectionName] = true; return; } } } jQuery.support[detectionName] = false; } }; /** * Whether the current browser supports (2D) CSS transforms * @type {boolean} * @public * @name jQuery.support.cssTransforms */ preserveOrTestCssPropWithPrefixes("cssTransforms", "transform"); /** * Whether the current browser supports 3D CSS transforms * @type {boolean} * @public * @name jQuery.support.cssTransforms3d */ preserveOrTestCssPropWithPrefixes("cssTransforms3d", "perspective"); /** * Whether the current browser supports CSS transitions * @type {boolean} * @public * @name jQuery.support.cssTransitions */ preserveOrTestCssPropWithPrefixes("cssTransitions", "transition"); /** * Whether the current browser supports (named) CSS animations * @type {boolean} * @public * @name jQuery.support.cssAnimations */ preserveOrTestCssPropWithPrefixes("cssAnimations", "animationName"); /** * Whether the current browser supports CSS gradients. Note that ANY support for CSS gradients leads to "true" here, no matter what the syntax is. * @type {boolean} * @public * @name jQuery.support.cssGradients */ if (jQuery.support.cssGradients === undefined) { var oElem = document.createElement('div'), oStyle = oElem.style; try { oStyle.backgroundImage = "linear-gradient(left top, red, white)"; oStyle.backgroundImage = "-moz-linear-gradient(left top, red, white)"; oStyle.backgroundImage = "-webkit-linear-gradient(left top, red, white)"; oStyle.backgroundImage = "-ms-linear-gradient(left top, red, white)"; oStyle.backgroundImage = "-webkit-gradient(linear, left top, right bottom, from(red), to(white))"; } catch (e) {/* no support...*/} jQuery.support.cssGradients = (oStyle.backgroundImage && oStyle.backgroundImage.indexOf("gradient") > -1); oElem = null; // free for garbage collection } /** * Whether the current browser supports only prefixed flexible layout properties * @type {boolean} * @public * @name jQuery.support.flexBoxPrefixed */ jQuery.support.flexBoxPrefixed = true; // Default to prefixed properties /** * Whether the current browser supports the OLD CSS3 Flexible Box Layout directly or via vendor prefixes * @type {boolean} * @public * @name jQuery.support.flexBoxLayout */ preserveOrTestCssPropWithPrefixes("flexBoxLayout", "boxFlex"); /** * Whether the current browser supports the NEW CSS3 Flexible Box Layout directly or via vendor prefixes * @type {boolean} * @public * @name jQuery.support.newFlexBoxLayout */ preserveOrTestCssPropWithPrefixes("newFlexBoxLayout", "flexGrow"); // Use a new property that IE10 doesn't support /** * Whether the current browser supports the IE10 CSS3 Flexible Box Layout directly or via vendor prefixes * @type {boolean} * @public * @name jQuery.support.ie10FlexBoxLayout * @since 1.12.0 */ // Just using one of the IE10 properties that's not in the new FlexBox spec if (!jQuery.support.newFlexBoxLayout && oStyle.msFlexOrder !== undefined) { jQuery.support.ie10FlexBoxLayout = true; } else { jQuery.support.ie10FlexBoxLayout = false; } /** * Whether the current browser supports any kind of Flexible Box Layout directly or via vendor prefixes * @type {boolean} * @public * @name jQuery.support.hasFlexBoxSupport */ if (jQuery.support.flexBoxLayout || jQuery.support.newFlexBoxLayout || jQuery.support.ie10FlexBoxLayout) { jQuery.support.hasFlexBoxSupport = true; } else { jQuery.support.hasFlexBoxSupport = false; } /** * FrameOptions class */ var FrameOptions = function(mSettings) { /* mSettings: mode, callback, whitelist, whitelistService, timeout, blockEvents, showBlockLayer, allowSameOrigin */ this.mSettings = mSettings || {}; this.sMode = this.mSettings.mode || FrameOptions.Mode.ALLOW; this.fnCallback = this.mSettings.callback; this.iTimeout = this.mSettings.timeout || 10000; this.bBlockEvents = this.mSettings.blockEvents !== false; this.bShowBlockLayer = this.mSettings.showBlockLayer !== false; this.bAllowSameOrigin = this.mSettings.allowSameOrigin !== false; this.sParentOrigin = ''; this.bUnlocked = false; this.bRunnable = false; this.bParentUnlocked = false; this.bParentResponded = false; this.sStatus = "pending"; this.aFPChilds = []; var that = this; this.iTimer = setTimeout(function() { that._callback(false); }, this.iTimeout); var fnHandlePostMessage = function() { that._handlePostMessage.apply(that, arguments); }; FrameOptions.__window.addEventListener('message', fnHandlePostMessage); if (FrameOptions.__parent === FrameOptions.__self || FrameOptions.__parent == null || this.sMode === FrameOptions.Mode.ALLOW) { // unframed page or "allow all" mode this._applyState(true, true); } else { // framed page this._lock(); // "deny" mode blocks embedding page from all origins if (this.sMode === FrameOptions.Mode.DENY) { this._callback(false); return; } if (this.bAllowSameOrigin) { try { var oParentWindow = FrameOptions.__parent; var bOk = false; var bTrue = true; do { var test = oParentWindow.document.domain; if (oParentWindow == FrameOptions.__top) { if (test != undefined) { bOk = true; } break; } oParentWindow = oParentWindow.parent; } while (bTrue); if (bOk) { this._applyState(true, true); } } catch (e) { // access to the top window is not possible this._sendRequireMessage(); } } else { // same origin not allowed this._sendRequireMessage(); } } }; FrameOptions.Mode = { // only allow with same origin parent TRUSTED: 'trusted', // allow all kind of embedding (default) ALLOW: 'allow', // deny all kinds of embedding DENY: 'deny' }; // Allow globals to be mocked in unit test FrameOptions.__window = window; FrameOptions.__parent = parent; FrameOptions.__self = self; FrameOptions.__top = top; // List of events to block while framing is unconfirmed FrameOptions._events = [ "mousedown", "mouseup", "click", "dblclick", "mouseover", "mouseout", "touchstart", "touchend", "touchmove", "touchcancel", "keydown", "keypress", "keyup" ]; // check if string matches pattern FrameOptions.prototype.match = function(sProbe, sPattern) { if (!(/\*/i.test(sPattern))) { return sProbe == sPattern; } else { sPattern = sPattern.replace(/\//gi, "\\/"); // replace / with \/ sPattern = sPattern.replace(/\./gi, "\\."); // replace . with \. sPattern = sPattern.replace(/\*/gi, ".*"); // replace * with .* sPattern = sPattern.replace(/:\.\*$/gi, ":\\d*"); // replace :.* with :\d* (only at the end) if (sPattern.substr(sPattern.length - 1, 1) !== '$') { sPattern = sPattern + '$'; // if not already there add $ at the end } if (sPattern.substr(0, 1) !== '^') { sPattern = '^' + sPattern; // if not already there add ^ at the beginning } // sPattern looks like: ^.*:\/\/.*\.company\.corp:\d*$ or ^.*\.company\.corp$ var r = new RegExp(sPattern, 'i'); return r.test(sProbe); } }; FrameOptions._lockHandler = function(oEvent) { oEvent.stopPropagation(); oEvent.preventDefault(); }; FrameOptions.prototype._createBlockLayer = function() { if (document.readyState == "complete") { var lockDiv = document.createElement("div"); lockDiv.style.position = "absolute"; lockDiv.style.top = "0px"; lockDiv.style.bottom = "0px"; lockDiv.style.left = "0px"; lockDiv.style.right = "0px"; lockDiv.style.opacity = "0"; lockDiv.style.backgroundColor = "white"; lockDiv.style.zIndex = 2147483647; // Max value of signed integer (32bit) document.body.appendChild(lockDiv); this._lockDiv = lockDiv; } }; FrameOptions.prototype._setCursor = function() { if (this._lockDiv) { this._lockDiv.style.cursor = this.sStatus == "denied" ? "not-allowed" : "wait"; } }; FrameOptions.prototype._lock = function() { var that = this; if (this.bBlockEvents) { for (var i = 0; i < FrameOptions._events.length; i++) { document.addEventListener(FrameOptions._events[i], FrameOptions._lockHandler, true); } } if (this.bShowBlockLayer) { this._blockLayer = function() { that._createBlockLayer(); that._setCursor(); }; if (document.readyState == "complete") { this._blockLayer(); } else { document.addEventListener("readystatechange", this._blockLayer); } } }; FrameOptions.prototype._unlock = function() { if (this.bBlockEvents) { for (var i = 0; i < FrameOptions._events.length; i++) { document.removeEventListener(FrameOptions._events[i], FrameOptions._lockHandler, true); } } if (this.bShowBlockLayer) { document.removeEventListener("readystatechange", this._blockLayer); if (this._lockDiv) { document.body.removeChild(this._lockDiv); delete this._lockDiv; } } }; FrameOptions.prototype._callback = function(bSuccess) { this.sStatus = bSuccess ? "allowed" : "denied"; this._setCursor(); clearTimeout(this.iTimer); if (typeof this.fnCallback === 'function') { this.fnCallback.call(null, bSuccess); } }; FrameOptions.prototype._applyState = function(bIsRunnable, bIsParentUnlocked) { if (this.bUnlocked) { return; } if (bIsRunnable) { this.bRunnable = true; } if (bIsParentUnlocked) { this.bParentUnlocked = true; } if (!this.bRunnable || !this.bParentUnlocked) { return; } this._unlock(); this._callback(true); this._notifyChildFrames(); this.bUnlocked = true; }; FrameOptions.prototype._applyTrusted = function(bTrusted) { if (bTrusted) { this._applyState(true, false); } else { this._callback(false); } }; FrameOptions.prototype._check = function(bParentResponsePending) { if (this.bRunnable) { return; } var bTrusted = false; if (this.bAllowSameOrigin && this.sParentOrigin && FrameOptions.__window.document.URL.indexOf(this.sParentOrigin) == 0) { bTrusted = true; } else if (this.mSettings.whitelist && this.mSettings.whitelist.length != 0) { var sHostName = this.sParentOrigin.split('//')[1]; sHostName = sHostName.split(':')[0]; for (var i = 0; i < this.mSettings.whitelist.length; i++) { var match = sHostName.indexOf(this.mSettings.whitelist[i]); if (match != -1 && sHostName.substring(match) == this.mSettings.whitelist[i]) { bTrusted = true; break; } } } if (bTrusted) { this._applyTrusted(bTrusted); } else if (this.mSettings.whitelistService) { var that = this; var xmlhttp = new XMLHttpRequest(); var url = this.mSettings.whitelistService + '?parentOrigin=' + encodeURIComponent(this.sParentOrigin); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { that._handleXmlHttpResponse(xmlhttp, bParentResponsePending); } }; xmlhttp.open('GET', url, true); xmlhttp.setRequestHeader('Accept', 'application/json'); xmlhttp.send(); } else { this._callback(false); } }; FrameOptions.prototype._handleXmlHttpResponse = function(xmlhttp, bParentResponsePending) { if (xmlhttp.status === 200) { var bTrusted = false; var sResponseText = xmlhttp.responseText; var oRuleSet = JSON.parse(sResponseText); if (oRuleSet.active == false) { this._applyState(true, true); } else if (bParentResponsePending) { return; } else { if (this.match(this.sParentOrigin, oRuleSet.origin)) { bTrusted = oRuleSet.framing; } this._applyTrusted(bTrusted); } } else { jQuery.sap.log.warning("The configured whitelist service is not available: " + xmlhttp.status); this._callback(false); } }; FrameOptions.prototype._notifyChildFrames = function() { for (var i = 0; i < this.aFPChilds.length; i++) { this.aFPChilds[i].postMessage('SAPFrameProtection*parent-unlocked','*'); } }; FrameOptions.prototype._sendRequireMessage = function() { FrameOptions.__parent.postMessage('SAPFrameProtection*require-origin', '*'); // If not postmessage response was received, send request to whitelist service // anyway, to check whether frame protection is enabled if (this.mSettings.whitelistService) { setTimeout(function() { if (!this.bParentResponded) { this._check(true); } }.bind(this), 10); } }; FrameOptions.prototype._handlePostMessage = function(oEvent) { var oSource = oEvent.source, sData = oEvent.data; // For compatibility with previous version empty message from parent means parent-unlocked // if (oSource === FrameOptions.__parent && sData == "") { // sData = "SAPFrameProtection*parent-unlocked"; // } if (oSource === FrameOptions.__self || oSource == null || typeof sData !== "string" || sData.indexOf("SAPFrameProtection*") === -1) { return; } if (oSource === FrameOptions.__parent) { this.bParentResponded = true; if (!this.sParentOrigin) { this.sParentOrigin = oEvent.origin; this._check(); } if (sData == "SAPFrameProtection*parent-unlocked") { this._applyState(false, true); } } else if (oSource.parent === FrameOptions.__self && sData == "SAPFrameProtection*require-origin" && this.bUnlocked) { oSource.postMessage("SAPFrameProtection*parent-unlocked", "*"); } else { oSource.postMessage("SAPFrameProtection*parent-origin", "*"); this.aFPChilds.push(oSource); } }; jQuery.sap.FrameOptions = FrameOptions; }()); /** * Executes an 'eval' for its arguments in the global context (without closure variables). * * This is a synchronous replacement for <code>jQuery.globalEval</code> which in some * browsers (e.g. FireFox) behaves asynchronously. * * @type void * @public * @static * @SecSink {0|XSS} Parameter is evaluated */ jQuery.sap.globalEval = function() { /*eslint-disable no-eval */ eval(arguments[0]); /*eslint-enable no-eval */ };
marinho/german-articles
webapp/resources/jquery.sap.global-dbg.js
JavaScript
mit
175,667
//~ name c376 alert(c376); //~ component c377.js
homobel/makebird-node
test/projects/large/c376.js
JavaScript
mit
52
'use strict'; /** * Module dependencies. */ var fs = require('fs'), http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), bodyParser = require('body-parser'), session = require('express-session'), compress = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), passport = require('passport'), MongoStore = require('connect-mongo')(session), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'); module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; app.locals.facebookAppId = config.facebook.clientID; app.locals.jsFiles = config.getJavaScriptAssets(); app.locals.cssFiles = config.getCSSAssets(); //================= start our custom variable===================================== // Setting application local variables for admin app.locals.adminJsFiles = config.getAdminJavaScriptAssets(); app.locals.adminCssFiles = config.getAdminCSSAssets(); //Setting application local variables for theme app.locals.themeJsFiles = config.getThemeJavaScriptAssets(); app.locals.themeCssFiles = config.getThemeCSSAssets(); //================= end our custom variable===================================== // Passing the request url to environment locals app.use(function(req, res, next) { res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './app/views'); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('dev')); // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // CookieParser should be above session app.use(cookieParser()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new MongoStore({ mongooseConnection: db.connection, collection: config.sessionCollection }) })); // use passport session app.use(passport.initialize()); app.use(passport.session()); // connect flash for flash messages app.use(flash()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Setting the app router and static folder app.use(express.static(path.resolve('./public'))); // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { //res.status(404).render('404', { // url: req.originalUrl, // error: 'Not Found' //}); console.log('******** Error status = 404 *********'); res.redirect('/'); }); if (process.env.NODE_ENV === 'secure') { // Log SSL usage console.log('Securely using https protocol'); // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
shaishab/BS-Commerce
config/express.js
JavaScript
mit
4,848
const path = require('path'); const { exec } = require('child_process'); const chalk = require('chalk'); const archive = filename => new Promise(resolve => { const { name } = path.parse(filename); const cmd = [ 'cd dist', 'mkdir -p releases', 'cd package', `zip -9 -r --symlinks ../releases/${filename} ${name}`, ].join(' && '); exec(cmd, { maxBuffer: 1024 * 1024 * 1024 }, err => { resolve({ err, options: { filename } }); }); }); /** * Print the status of the archive */ const printStatus = ({ err, options }) => { if (err) { // eslint-disable-next-line no-console console.log(chalk.red(`${options.filename} archiving error.`)); } else { // eslint-disable-next-line no-console console.log(chalk.green(`${options.filename} archive complete.`)); } }; // start archiving archive('Dext-darwin-x64.zip').then(printStatus);
vutran/dext
scripts/archive.js
JavaScript
mit
901
version https://git-lfs.github.com/spec/v1 oid sha256:1ad0c7b57a0bf2bcb30988c36f9299252af5f341656d573d6b555b8a13cbfb04 size 41466
yogeshsaroya/new-cdnjs
ajax/libs/bacon.js/0.7.50/Bacon.min.js
JavaScript
mit
130
define({ // EXTENSION. EXTENSION_NAME: "SFTP Upload", // MENUS UPLOAD_MENU_NAME: "Загрузить SFTP", DOWNLOAD_MENU_NAME: "Скачать с сервера", // GENERAL. YES: "Да", NO: "Нет", OK: "Ок", CANCEL: "Отмена", UPLOAD: "Загрузить", SKIP: "Пропустить", // TOOLBAR. SERVER_SETUP: "Настройки", UPLOAD_ALL: "Загрузить все", SKIP_ALL: "Пропустить все", // SETTINGS DIALOG. SETTINGS_DIALOG_TITLE: "SFTP Настройки", SETTINGS_DIALOG_TYPE: "Тип соединения", SETTINGS_DIALOG_TYPE_FTP: "FTP", SETTINGS_DIALOG_TYPE_SFTP: "SFTP (SSH)", SETTINGS_DIALOG_HOST: "Хост", SETTINGS_DIALOG_PORT: "Порт", SETTINGS_DIALOG_USERNAME: "Имя пользователя", SETTINGS_DIALOG_PASSWORD: "Пароль пользователя", SETTINGS_DIALOG_PATH: "Директория", SETTINGS_UPLOAD_ON_SAVE: "Загружать при сохранение" });
lamo2k123/brackets-sftpu
nls/ru/Strings.js
JavaScript
mit
1,044
unction solution(array) { var m=null; var d=null var seen=new Set() var tot=0 var len=0 for (var j of array){ if (seen.has(j)){d=j} seen.add(j) tot+=j len++ } return [(len*(len+1)/2)-(tot-d),d] }
Orange9000/Codewars
Solutions/5kyu/5kyu_missing_and_duplicate_numbers.js
JavaScript
mit
238
import { Module } from '../../lib/di'; import RcModule from '../../lib/RcModule'; import isBlank from '../../lib/isBlank'; import moduleStatuses from '../../enums/moduleStatuses'; import composeTextActionTypes from './actionTypes'; import getComposeTextReducer from './getComposeTextReducer'; import getCacheReducer from './getCacheReducer'; import messageSenderMessages from '../MessageSender/messageSenderMessages'; import proxify from '../../lib/proxy/proxify'; /** * @class * @description Compose text managing module */ @Module({ deps: [ 'Alert', 'Auth', 'Storage', 'MessageSender', 'NumberValidate', 'RolesAndPermissions', { dep: 'ContactSearch', optional: true }, { dep: 'ComposeTextOptions', optional: true } ] }) export default class ComposeText extends RcModule { /** * @constructor * @param {Object} params - params object * @param {Alert} params.alert - alert module instance * @param {Auth} params.auth - auth module instance * @param {Storage} params.storage - storage module instance * @param {MessageSender} params.messageSender - messageSender module instance * @param {NumberValidate} params.numberValidate - numberValidate module instance * @param {ContactSearch} params.contactSearch - contactSearch module instance */ constructor({ alert, auth, storage, messageSender, numberValidate, contactSearch, rolesAndPermissions, ...options }) { super({ ...options, actionTypes: composeTextActionTypes, }); this._alert = alert; this._auth = auth; this._storage = storage; this._rolesAndPermissions = rolesAndPermissions; this._storageKey = 'composeText'; this._reducer = getComposeTextReducer(this.actionTypes); this._cacheReducer = getCacheReducer(this.actionTypes); this._messageSender = messageSender; this._numberValidate = numberValidate; this._contactSearch = contactSearch; this._lastContactSearchResult = []; this.senderNumbersList = []; storage.registerReducer({ key: this._storageKey, reducer: this._cacheReducer }); } initialize() { this.store.subscribe(() => this._onStateChange()); } _onStateChange() { if ( this._shouldInit() ) { this.senderNumbersList = this._messageSender.senderNumbersList; this.store.dispatch({ type: this.actionTypes.initSuccess, }); if (this._auth.isFreshLogin) { this.clean(); } this._initSenderNumber(); } else if ( this._shouldHandleRecipient() ) { this._handleRecipient(); } else if ( this._shouldReset() ) { this._resetModuleStatus(); } if ( this.ready && this._messageSender.senderNumbersList.length !== this.senderNumbersList.length ) { this.senderNumbersList = this._messageSender.senderNumbersList; this._initSenderNumber(); } } _shouldInit() { return ( this._messageSender.ready && this._auth.ready && !this.ready ); } _shouldReset() { return ( ( !this._messageSender.ready ) && this.ready ); } _shouldHandleRecipient() { return ( this.ready && (!!this._contactSearch && this._contactSearch.ready && this._contactSearch.searchResult.length > 0) && this._contactSearch.searchResult !== this._lastContactSearchResult ); } _resetModuleStatus() { this.store.dispatch({ type: this.actionTypes.resetSuccess, }); } _initSenderNumber() { const cachedPhoneNumber = this.cache && this.cache.senderNumber; if (cachedPhoneNumber) { this.updateSenderNumber(cachedPhoneNumber); } else { this.updateSenderNumber( this._messageSender.senderNumbersList[0] && this._messageSender.senderNumbersList[0].phoneNumber ); } } _handleRecipient() { const dummy = this.toNumbers.find(toNumber => !toNumber.entityType); if (dummy) { const recipient = this._contactSearch.searchResult.find( item => item.id === dummy.id ); if (recipient) { this.addToNumber(recipient); this._lastContactSearchResult = this._contactSearch.searchResult.slice(); } } } _alertWarning(message) { if (message) { const ttlConfig = message !== messageSenderMessages.noAreaCode ? { ttl: 0 } : null; this._alert.warning({ message, ...ttlConfig }); return true; } return false; } _validatePhoneNumber(phoneNumber) { if (this._validateIsOnlyPager(phoneNumber)) { return null; } const validateResult = this._numberValidate.validateFormat([phoneNumber]); if (!validateResult.result) { const error = validateResult.errors[0]; if (error && this._alertWarning(messageSenderMessages[error.type])) { return false; } this._alertWarning(messageSenderMessages.recipientNumberInvalids); return false; } return true; } _validateIsOnlyPager(phoneNumber) { if ( phoneNumber.length >= 7 && this._rolesAndPermissions.onlyPagerPermission ) { this._alertWarning(messageSenderMessages.noSMSPermission); return true; } return false; } @proxify async send() { const text = this.messageText; const fromNumber = this.senderNumber; const toNumbers = this.toNumbers.map(number => number.phoneNumber); const { typingToNumber } = this; if (!isBlank(typingToNumber)) { if (this._validatePhoneNumber(typingToNumber)) { toNumbers.push(typingToNumber); } else { return null; } } return this._messageSender.send({ fromNumber, toNumbers, text }); } @proxify async updateSenderNumber(number) { this.store.dispatch({ type: this.actionTypes.updateSenderNumber, number: (number || ''), }); } @proxify async updateTypingToNumber(number) { if (number.length > 30) { this._alertWarning(messageSenderMessages.recipientNumberInvalids); return; } this.store.dispatch({ type: this.actionTypes.updateTypingToNumber, number, }); } @proxify async onToNumberMatch({ entityId }) { this.store.dispatch({ type: this.actionTypes.toNumberMatched, entityId, }); } @proxify async addToRecipients(recipient, shouldClean = true) { const isAdded = await this.addToNumber(recipient); if (isAdded && shouldClean) { await this.cleanTypingToNumber(); } } @proxify async cleanTypingToNumber() { this.store.dispatch({ type: this.actionTypes.cleanTypingToNumber, }); } @proxify async addToNumber(number) { if (isBlank(number.phoneNumber)) { return false; } if (!this._validatePhoneNumber(number.phoneNumber)) { return false; } this.store.dispatch({ type: this.actionTypes.addToNumber, number, }); return true; } @proxify async removeToNumber(number) { this.store.dispatch({ type: this.actionTypes.removeToNumber, number, }); } @proxify async updateMessageText(text) { if (text.length > 1000) { this._alertWarning(messageSenderMessages.textTooLong); return; } this.store.dispatch({ type: this.actionTypes.updateMessageText, text, }); } @proxify async clean() { this.store.dispatch({ type: this.actionTypes.clean, }); } @proxify async alertMessageSending() { this._alert.warning({ message: messageSenderMessages.sending, ttl: 0, }); } @proxify async dismissMessageSending() { const alertMessage = this._alert.messages.find(m => ( m.message === messageSenderMessages.sending )); if (alertMessage && alertMessage.id) { this._alert.dismiss(alertMessage.id); } } get cache() { return this._storage.getItem(this._storageKey); } get status() { return this.state.status; } get ready() { return this.status === moduleStatuses.ready; } get senderNumber() { return this.state.senderNumber; } get typingToNumber() { return this.state.typingToNumber; } get toNumbers() { return this.state.toNumbers; } get toNumberEntity() { return this.state.toNumberEntity; } get messageText() { return this.state.messageText; } }
u9520107/ringcentral-js-widget
packages/ringcentral-integration/modules/ComposeText/index.js
JavaScript
mit
8,422
/* Temporarily disabling as we transition to containerized PACS for E2E tests describe('Visual Regression - OHIF VTK Extension', () => { before(() => { cy.checkStudyRouteInViewer( '1.3.6.1.4.1.25403.345050719074.3824.20170125113417.1' ); cy.expectMinimumThumbnails(7); //Waiting for the desired thumbnail content to be displayed cy.get('[data-cy="thumbnail-list"]').should($list => { expect($list).to.contain('Chest 1x10 Soft'); }); // Drag and drop thumbnail into viewport cy.get('[data-cy="thumbnail-list"]') .contains('Chest 1x10 Soft') .drag('.viewport-drop-target'); //Select 2D MPR button cy.get('[data-cy="2d mpr"]').click(); //Wait waitVTKLoading Images cy.waitVTKLoading(); }); beforeEach(() => { cy.initVTKToolsAliases(); cy.wait(1000); //Wait toolbar to finish loading }); afterEach(() => { cy.wait(5000); //wait screen loads back after screenshot //Select Exit 2D MPR button cy.get('[data-cy="exit 2d mpr"]').should($btn => { expect($btn).to.be.visible; $btn.click(); }); //Select 2D MPR button cy.get('[data-cy="2d mpr"]').click(); }); it('checks if VTK buttons are displayed on the toolbar', () => { // Visual comparison cy.percyCanvasSnapshot( 'VTK initial state - Should display toolbar and 3 viewports' ); }); it('checks Crosshairs tool', () => { cy.get('@crosshairsBtn').click(); // Click and Move the mouse inside the viewport cy.get('[data-cy="viewport-container-0"]') .trigger('mousedown', 'center', { which: 1 }) .trigger('mousemove', 'top', { which: 1 }) .trigger('mouseup'); // Visual comparison cy.percyCanvasSnapshot( "VTK Crosshairs tool - Should display crosshairs' green lines" ); }); it('checks WWWC tool', () => { cy.get('@wwwcBtn').click(); // Click and Move the mouse inside the viewport cy.get('[data-cy="viewport-container-0"]') .trigger('mousedown', 'center', { which: 1 }) .trigger('mousemove', 'top', { which: 1 }) .trigger('mousedown', 'center', { which: 1 }) .trigger('mousemove', 'top', { which: 1 }) .trigger('mouseup', { which: 1 }); // Visual comparison cy.percyCanvasSnapshot('VTK WWWC tool - Canvas should be bright'); }); it('checks Rotate tool', () => { cy.get('@rotateBtn').click(); // Click and Move the mouse inside the viewport cy.get('[data-cy="viewport-container-0"]') .trigger('mousedown', 'center', { which: 1 }) .trigger('mousemove', 'top', { which: 1 }) .trigger('mousedown', 'center', { which: 1 }) .trigger('mousemove', 'top', { which: 1 }) .trigger('mouseup', { which: 1 }); // Visual comparison cy.percyCanvasSnapshot('VTK Rotate tool - Should rotate image'); }); }); */
OHIF/Viewers
platform/viewer/cypress/integration/visual-regression/PercyCheckOHIFExtensionVTK.spec.js
JavaScript
mit
2,861
/** @module ecs-js */ import Engine from './engine'; import Entity from './entity'; import Component from './component'; import System from './system'; const ecs = { Engine, Entity, Component, System, }; export default ecs; /** * An error event occurs when an entity encounters an error. * @event module:ecs-js#error * @param {Error} error - The error that was encountered. */
joechimo/transvolve
src/index.js
JavaScript
mit
392
const {app, BrowserWindow} = require('electron'); const ipcPlus = require('../../../index.js'); global.ipcCalls = []; app.on('ready', function () { let win = new BrowserWindow({ x: 300, y: 100, width: 200, height: 200 }); win.loadURL('file://' + __dirname + '/index.html'); }); ipcPlus.on('app:hello', (event, ...args) => { global.ipcCalls.push(`app:hello ${args}`); if ( event.reply ) { global.ipcCalls.push(`${args} replied`); event.reply(null, `${args} received`); } });
electron-utils/electron-ipc-plus
test/fixtures/app-win2main-reply-error-no-callback/main.js
JavaScript
mit
513
var ca = require('../../../../lib/https/ca'); module.exports = function(req, res) { ca.uploadCerts(req.body); var isparsed = req.query.dataType === 'parsed'; res.json(isparsed ? ca.getCustomCertsInfo() : ca.getCustomCertsFiles()); };
avwo/whistle
biz/webui/cgi-bin/certs/upload.js
JavaScript
mit
242
import dts from 'rollup-plugin-dts' import config from './rollup.config' config.output = [ { file: 'dist/check-disk-space.d.ts', format: 'es', }, ] config.plugins.push(dts()) export default config
Alex-D/check-disk-space
rollup.dts.config.js
JavaScript
mit
206
'use strict'; export default (cb) => { return e => { e.preventDefault(); cb(); }; };
daedelus-j/shorterly
shorterly/src/general-libs/preventer.js
JavaScript
mit
98
'use strict'; var firewall = require('../lib'); describe('g4js-firewall module', function(){ describe('exports', function(){ it('should expose Firewall', function(){ assert.isFunction(firewall.Firewall); }); it('should expose FirewallRule', function(){ assert.isFunction(firewall.FirewallRule); }); }); });
AllegiantAir/g4js-firewall
test/index.spec.js
JavaScript
mit
349
var models = require('@bungalow/models'); var views = require('@bungalow/views'); module.exports.resolveUri = function (uri) { }; window.addEventListener('message', function (event) { console.log("Event data", event.data); if (event.data.action === 'navigate') { views.showThrobber(); console.log(event.data.arguments); var id = event.data.arguments[0]; $('#year').html(id); var uri = 'bungalow:year:' + id; $('.sp-album').hide(); var search = models.Search.search('year:' + id, 10, 0, 'tracks'); $('#list').html(""); var contextView = new views.TrackContext(search.tracks, {headers: true, 'fields': ['title', 'duration', 'popularity']}); contextView.node.classList.add('sp-album'); contextView.node.setAttribute('id', 'search_result_' + uri.replace(/\:/g, '__')); $('#playlist').append(contextView.node); views.hideThrobber(); } });
drsounds/bungalow
apps/year/src/js/app.js
JavaScript
mit
956
const BASE_MARGIN = ' '; module.exports = BASE_MARGIN;
halis/cashmere
src/bdd/baseMargin.js
JavaScript
mit
56
var util = require('util'), Relation = require('./Relation'), extend = require('object-extend'); var relationMap = require('../../../config/relationMap'); /** * OrganizationProvidesService relation entity * * Relation (Organization)-[PROVIDES_SERVICE]->(Service) * * Represents an a services provided by the organization * * @param organizationUUID uuid of the organization * @param relationData data to be stored on relation * @param ref referenced object if any * @returns {*} * @constructor * */ var OrganizationProvidesService = function (organizationUUID, relationData, ref) { var data = {}; if (relationData) { extend(data, relationData); } return extend(OrganizationProvidesService.super_( data, ref, relationMap.objects.Organization, relationMap.relations.Organization.PROVIDES_SERVICE, relationMap.objects.Service, organizationUUID, null, false, true), { // Nothing defined yet }); }; util.inherits(OrganizationProvidesService, Relation); module.exports = OrganizationProvidesService;
lagranovskiy/j316-organizer
app/model/relation/OrganizationProvidesService.js
JavaScript
mit
1,181
class microsoft_directmusicmotiftrack { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = microsoft_directmusicmotiftrack;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/Microsoft.DirectMusicMotifTrack.js
JavaScript
mit
599
const { logger: log } = require('./logger'); const { decoratePrisonersWithImages } = require('./prisoner-images'); const { elite2GetRequest } = require('./elite2-api-request'); const valueOrNull = value => value || null; const parseSearchRequest = bookings => bookings.map(booking => ({ bookingId: valueOrNull(booking.bookingId), offenderNo: valueOrNull(booking.offenderNo), firstName: valueOrNull(booking.firstName), middleName: valueOrNull(booking.middleName), lastName: valueOrNull(booking.lastName), dateOfBirth: valueOrNull(booking.dateOfBirth), facialImageId: valueOrNull(booking.facialImageId), })); const findPrisoners = authToken => async (searchQuery) => { try { const result = await elite2GetRequest({ authToken, requestPath: `search-offenders/_/${searchQuery}`, }); return await decoratePrisonersWithImages({ authToken, prisoners: parseSearchRequest(result.body), }); } catch (exception) { log.error(`Search failed on Elite 2 failed for [${searchQuery}] with exception:`); log.error(exception); return []; } }; const createOffenderSearchService = authToken => ({ findPrisonersMatching: findPrisoners(authToken), }); module.exports = createOffenderSearchService;
noms-digital-studio/csra-app
server/services/searchPrisoner.js
JavaScript
mit
1,330
import Colors from './colors'; import ColorManipulator from '../utils/color-manipulator'; import Extend from '../utils/extend'; import update from 'react-addons-update'; export default { //get the MUI theme corresponding to a raw theme getMuiTheme: function(rawTheme) { let returnObj = { appBar: { color: rawTheme.palette.primary1Color, textColor: rawTheme.palette.alternateTextColor, height: rawTheme.spacing.desktopKeylineIncrement, }, avatar: { borderColor: 'rgba(0, 0, 0, 0.08)', }, badge: { color: rawTheme.palette.alternateTextColor, textColor: rawTheme.palette.textColor, primaryColor: rawTheme.palette.accent1Color, primaryTextColor: rawTheme.palette.alternateTextColor, secondaryColor: rawTheme.palette.primary1Color, secondaryTextColor: rawTheme.palette.alternateTextColor, }, button: { height: 36, minWidth: 88, iconButtonSize: rawTheme.spacing.iconSize * 2, }, cardText: { textColor: rawTheme.palette.textColor, }, checkbox: { boxColor: rawTheme.palette.textColor, checkedColor: rawTheme.palette.primary1Color, requiredColor: rawTheme.palette.primary1Color, disabledColor: rawTheme.palette.disabledColor, labelColor: rawTheme.palette.textColor, labelDisabledColor: rawTheme.palette.disabledColor, }, datePicker: { color: rawTheme.palette.primary1Color, textColor: rawTheme.palette.alternateTextColor, calendarTextColor: rawTheme.palette.textColor, selectColor: rawTheme.palette.primary2Color, selectTextColor: rawTheme.palette.alternateTextColor, }, dropDownMenu: { accentColor: rawTheme.palette.borderColor, }, flatButton: { color: rawTheme.palette.alternateTextColor, textColor: rawTheme.palette.textColor, primaryTextColor: rawTheme.palette.accent1Color, secondaryTextColor: rawTheme.palette.primary1Color, }, floatingActionButton: { buttonSize: 56, miniSize: 40, color: rawTheme.palette.accent1Color, iconColor: rawTheme.palette.alternateTextColor, secondaryColor: rawTheme.palette.primary1Color, secondaryIconColor: rawTheme.palette.alternateTextColor, disabledTextColor: rawTheme.palette.disabledColor, }, gridTile: { textColor: Colors.white, }, inkBar: { backgroundColor: rawTheme.palette.accent1Color, }, leftNav: { width: rawTheme.spacing.desktopKeylineIncrement * 4, color: rawTheme.palette.canvasColor, }, listItem: { nestedLevelDepth: 18, }, menu: { backgroundColor: rawTheme.palette.canvasColor, containerBackgroundColor: rawTheme.palette.canvasColor, }, menuItem: { dataHeight: 32, height: 48, hoverColor: 'rgba(0, 0, 0, .035)', padding: rawTheme.spacing.desktopGutter, selectedTextColor: rawTheme.palette.accent1Color, }, menuSubheader: { padding: rawTheme.spacing.desktopGutter, borderColor: rawTheme.palette.borderColor, textColor: rawTheme.palette.primary1Color, }, paper: { backgroundColor: rawTheme.palette.canvasColor, }, radioButton: { borderColor: rawTheme.palette.textColor, backgroundColor: rawTheme.palette.alternateTextColor, checkedColor: rawTheme.palette.primary1Color, requiredColor: rawTheme.palette.primary1Color, disabledColor: rawTheme.palette.disabledColor, size: 24, labelColor: rawTheme.palette.textColor, labelDisabledColor: rawTheme.palette.disabledColor, }, raisedButton: { color: rawTheme.palette.alternateTextColor, textColor: rawTheme.palette.textColor, primaryColor: rawTheme.palette.accent1Color, primaryTextColor: rawTheme.palette.alternateTextColor, secondaryColor: rawTheme.palette.primary1Color, secondaryTextColor: rawTheme.palette.alternateTextColor, }, refreshIndicator: { strokeColor: rawTheme.palette.borderColor, loadingStrokeColor: rawTheme.palette.primary1Color, }, slider: { trackSize: 2, trackColor: rawTheme.palette.primary3Color, trackColorSelected: rawTheme.palette.accent3Color, handleSize: 12, handleSizeDisabled: 8, handleSizeActive: 18, handleColorZero: rawTheme.palette.primary3Color, handleFillColor: rawTheme.palette.alternateTextColor, selectionColor: rawTheme.palette.primary1Color, rippleColor: rawTheme.palette.primary1Color, }, snackbar: { textColor: rawTheme.palette.alternateTextColor, backgroundColor: rawTheme.palette.textColor, actionColor: rawTheme.palette.accent1Color, }, table: { backgroundColor: rawTheme.palette.canvasColor, }, tableHeader: { borderColor: rawTheme.palette.borderColor, }, tableHeaderColumn: { textColor: rawTheme.palette.accent3Color, height: 56, spacing: 24, }, tableFooter: { borderColor: rawTheme.palette.borderColor, textColor: rawTheme.palette.accent3Color, }, tableRow: { hoverColor: rawTheme.palette.accent2Color, stripeColor: ColorManipulator.lighten(rawTheme.palette.primary1Color, 0.55), selectedColor: rawTheme.palette.borderColor, textColor: rawTheme.palette.textColor, borderColor: rawTheme.palette.borderColor, }, tableRowColumn: { height: 48, spacing: 24, }, timePicker: { color: rawTheme.palette.alternateTextColor, textColor: rawTheme.palette.accent3Color, accentColor: rawTheme.palette.primary1Color, clockColor: rawTheme.palette.textColor, clockCircleColor: rawTheme.palette.clockCircleColor, headerColor: rawTheme.palette.pickerHeaderColor || rawTheme.palette.primary1Color, selectColor: rawTheme.palette.primary2Color, selectTextColor: rawTheme.palette.alternateTextColor, }, toggle: { thumbOnColor: rawTheme.palette.primary1Color, thumbOffColor: rawTheme.palette.accent2Color, thumbDisabledColor: rawTheme.palette.borderColor, thumbRequiredColor: rawTheme.palette.primary1Color, trackOnColor: ColorManipulator.fade(rawTheme.palette.primary1Color, 0.5), trackOffColor: rawTheme.palette.primary3Color, trackDisabledColor: rawTheme.palette.primary3Color, labelColor: rawTheme.palette.textColor, labelDisabledColor: rawTheme.palette.disabledColor, }, toolbar: { backgroundColor: ColorManipulator.darken(rawTheme.palette.accent2Color, 0.05), height: 56, titleFontSize: 20, iconColor: 'rgba(0, 0, 0, .40)', separatorColor: 'rgba(0, 0, 0, .175)', menuHoverColor: 'rgba(0, 0, 0, .10)', }, tabs: { backgroundColor: rawTheme.palette.primary1Color, textColor: ColorManipulator.fade(rawTheme.palette.alternateTextColor, 0.6), selectedTextColor: rawTheme.palette.alternateTextColor, }, textField: { textColor: rawTheme.palette.textColor, hintColor: rawTheme.palette.disabledColor, floatingLabelColor: rawTheme.palette.textColor, disabledTextColor: rawTheme.palette.disabledColor, errorColor: Colors.red500, focusColor: rawTheme.palette.primary1Color, backgroundColor: 'transparent', borderColor: rawTheme.palette.borderColor, }, isRtl: false, }; //add properties to objects inside 'returnObj' that depend on existing properties returnObj.flatButton.disabledTextColor = ColorManipulator.fade(returnObj.flatButton.textColor, 0.3); returnObj.raisedButton.disabledColor = ColorManipulator.darken(returnObj.raisedButton.color, 0.1); returnObj.raisedButton.disabledTextColor = ColorManipulator.fade(returnObj.raisedButton.textColor, 0.3); returnObj.toggle.trackRequiredColor = ColorManipulator.fade(returnObj.toggle.thumbRequiredColor, 0.5); //append the raw theme object to 'returnObj' returnObj.rawTheme = rawTheme; //set 'static' key as true (by default) on return object. This is to support the ContextPure mixin. returnObj.static = true; return returnObj; }, //functions to modify properties of raw theme, namely spacing, palette //and font family. These functions use the React update immutability helper //to create a new object for the raw theme, and return a new MUI theme object //function to modify the spacing of the raw theme. This function recomputes //the MUI theme and returns it based on the new theme. modifyRawThemeSpacing: function(muiTheme, newSpacing) { let newRawTheme = update(muiTheme.rawTheme, {spacing: {$set: newSpacing}}); return this.getMuiTheme(newRawTheme); }, //function to modify the palette of the raw theme. This function recomputes //the MUI theme and returns it based on the new raw theme. //keys inside 'newPalette' override values for existing keys in palette modifyRawThemePalette: function(muiTheme, newPaletteKeys) { let newPalette = Extend(muiTheme.rawTheme.palette, newPaletteKeys); let newRawTheme = update(muiTheme.rawTheme, {palette: {$set: newPalette}}); return this.getMuiTheme(newRawTheme); }, //function to modify the font family of the raw theme. This function recomputes //the MUI theme and returns it based on the new raw theme. modifyRawThemeFontFamily: function(muiTheme, newFontFamily) { let newRawTheme = update(muiTheme.rawTheme, {fontFamily: {$set: newFontFamily}}); return this.getMuiTheme(newRawTheme); }, };
XiaonuoGantan/material-ui
src/styles/theme-manager.js
JavaScript
mit
9,970
/* */ "format cjs"; /*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.1-master-491d139 */ goog.provide('ngmaterial.components.bottomSheet'); goog.require('ngmaterial.components.backdrop'); goog.require('ngmaterial.core'); /** * @ngdoc module * @name material.components.bottomSheet * @description * BottomSheet */ MdBottomSheetDirective['$inject'] = ["$mdBottomSheet"]; MdBottomSheetProvider['$inject'] = ["$$interimElementProvider"]; angular .module('material.components.bottomSheet', [ 'material.core', 'material.components.backdrop' ]) .directive('mdBottomSheet', MdBottomSheetDirective) .provider('$mdBottomSheet', MdBottomSheetProvider); /* ngInject */ function MdBottomSheetDirective($mdBottomSheet) { return { restrict: 'E', link : function postLink(scope, element) { element.addClass('_md'); // private md component indicator for styling // When navigation force destroys an interimElement, then // listen and $destroy() that interim instance... scope.$on('$destroy', function() { $mdBottomSheet.destroy(); }); } }; } /** * @ngdoc service * @name $mdBottomSheet * @module material.components.bottomSheet * * @description * `$mdBottomSheet` opens a bottom sheet over the app and provides a simple promise API. * * ## Restrictions * * - The bottom sheet's template must have an outer `<md-bottom-sheet>` element. * - Add the `md-grid` class to the bottom sheet for a grid layout. * - Add the `md-list` class to the bottom sheet for a list layout. * * @usage * <hljs lang="html"> * <div ng-controller="MyController"> * <md-button ng-click="openBottomSheet()"> * Open a Bottom Sheet! * </md-button> * </div> * </hljs> * <hljs lang="js"> * var app = angular.module('app', ['ngMaterial']); * app.controller('MyController', function($scope, $mdBottomSheet) { * $scope.openBottomSheet = function() { * $mdBottomSheet.show({ * template: '<md-bottom-sheet>Hello!</md-bottom-sheet>' * }); * }; * }); * </hljs> */ /** * @ngdoc method * @name $mdBottomSheet#show * * @description * Show a bottom sheet with the specified options. * * @param {object} options An options object, with the following properties: * * - `templateUrl` - `{string=}`: The url of an html template file that will * be used as the content of the bottom sheet. Restrictions: the template must * have an outer `md-bottom-sheet` element. * - `template` - `{string=}`: Same as templateUrl, except this is an actual * template string. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified, it will create a new child scope. * This scope will be destroyed when the bottom sheet is removed unless `preserveScope` is set to true. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false * - `controller` - `{string=}`: The controller to associate with this bottom sheet. * - `locals` - `{string=}`: An object containing key/value pairs. The keys will * be used as names of values to inject into the controller. For example, * `locals: {three: 3}` would inject `three` into the controller with the value * of 3. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the bottom sheet to * close it. Default true. * - `bindToController` - `{boolean=}`: When set to true, the locals will be bound to the controller instance. * - `disableBackdrop` - `{boolean=}`: When set to true, the bottomsheet will not show a backdrop. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the bottom sheet. * Default true. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values * and the bottom sheet will not open until the promises resolve. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope. * - `parent` - `{element=}`: The element to append the bottom sheet to. The `parent` may be a `function`, `string`, * `object`, or null. Defaults to appending to the body of the root element (or the root element) of the application. * e.g. angular.element(document.getElementById('content')) or "#content" * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the bottom sheet is open. * Default true. * * @returns {promise} A promise that can be resolved with `$mdBottomSheet.hide()` or * rejected with `$mdBottomSheet.cancel()`. */ /** * @ngdoc method * @name $mdBottomSheet#hide * * @description * Hide the existing bottom sheet and resolve the promise returned from * `$mdBottomSheet.show()`. This call will close the most recently opened/current bottomsheet (if any). * * @param {*=} response An argument for the resolved promise. * */ /** * @ngdoc method * @name $mdBottomSheet#cancel * * @description * Hide the existing bottom sheet and reject the promise returned from * `$mdBottomSheet.show()`. * * @param {*=} response An argument for the rejected promise. * */ function MdBottomSheetProvider($$interimElementProvider) { // how fast we need to flick down to close the sheet, pixels/ms bottomSheetDefaults['$inject'] = ["$animate", "$mdConstant", "$mdUtil", "$mdTheming", "$mdBottomSheet", "$rootElement", "$mdGesture", "$log"]; var CLOSING_VELOCITY = 0.5; var PADDING = 80; // same as css return $$interimElementProvider('$mdBottomSheet') .setDefaults({ methods: ['disableParentScroll', 'escapeToClose', 'clickOutsideToClose'], options: bottomSheetDefaults }); /* ngInject */ function bottomSheetDefaults($animate, $mdConstant, $mdUtil, $mdTheming, $mdBottomSheet, $rootElement, $mdGesture, $log) { var backdrop; return { themable: true, onShow: onShow, onRemove: onRemove, disableBackdrop: false, escapeToClose: true, clickOutsideToClose: true, disableParentScroll: true }; function onShow(scope, element, options, controller) { element = $mdUtil.extractElementByName(element, 'md-bottom-sheet'); // prevent tab focus or click focus on the bottom-sheet container element.attr('tabindex',"-1"); // Once the md-bottom-sheet has `ng-cloak` applied on his template the opening animation will not work properly. // This is a very common problem, so we have to notify the developer about this. if (element.hasClass('ng-cloak')) { var message = '$mdBottomSheet: using `<md-bottom-sheet ng-cloak >` will affect the bottom-sheet opening animations.'; $log.warn( message, element[0] ); } if (!options.disableBackdrop) { // Add a backdrop that will close on click backdrop = $mdUtil.createBackdrop(scope, "md-bottom-sheet-backdrop md-opaque"); // Prevent mouse focus on backdrop; ONLY programatic focus allowed. // This allows clicks on backdrop to propogate to the $rootElement and // ESC key events to be detected properly. backdrop[0].tabIndex = -1; if (options.clickOutsideToClose) { backdrop.on('click', function() { $mdUtil.nextTick($mdBottomSheet.cancel,true); }); } $mdTheming.inherit(backdrop, options.parent); $animate.enter(backdrop, options.parent, null); } var bottomSheet = new BottomSheet(element, options.parent); options.bottomSheet = bottomSheet; $mdTheming.inherit(bottomSheet.element, options.parent); if (options.disableParentScroll) { options.restoreScroll = $mdUtil.disableScrollAround(bottomSheet.element, options.parent); } return $animate.enter(bottomSheet.element, options.parent, backdrop) .then(function() { var focusable = $mdUtil.findFocusTarget(element) || angular.element( element[0].querySelector('button') || element[0].querySelector('a') || element[0].querySelector($mdUtil.prefixer('ng-click', true)) ) || backdrop; if (options.escapeToClose) { options.rootElementKeyupCallback = function(e) { if (e.keyCode === $mdConstant.KEY_CODE.ESCAPE) { $mdUtil.nextTick($mdBottomSheet.cancel,true); } }; $rootElement.on('keyup', options.rootElementKeyupCallback); focusable && focusable.focus(); } }); } function onRemove(scope, element, options) { var bottomSheet = options.bottomSheet; if (!options.disableBackdrop) $animate.leave(backdrop); return $animate.leave(bottomSheet.element).then(function() { if (options.disableParentScroll) { options.restoreScroll(); delete options.restoreScroll; } bottomSheet.cleanup(); }); } /** * BottomSheet class to apply bottom-sheet behavior to an element */ function BottomSheet(element, parent) { var deregister = $mdGesture.register(parent, 'drag', { horizontal: false }); parent.on('$md.dragstart', onDragStart) .on('$md.drag', onDrag) .on('$md.dragend', onDragEnd); return { element: element, cleanup: function cleanup() { deregister(); parent.off('$md.dragstart', onDragStart); parent.off('$md.drag', onDrag); parent.off('$md.dragend', onDragEnd); } }; function onDragStart(ev) { // Disable transitions on transform so that it feels fast element.css($mdConstant.CSS.TRANSITION_DURATION, '0ms'); } function onDrag(ev) { var transform = ev.pointer.distanceY; if (transform < 5) { // Slow down drag when trying to drag up, and stop after PADDING transform = Math.max(-PADDING, transform / 2); } element.css($mdConstant.CSS.TRANSFORM, 'translate3d(0,' + (PADDING + transform) + 'px,0)'); } function onDragEnd(ev) { if (ev.pointer.distanceY > 0 && (ev.pointer.distanceY > 20 || Math.abs(ev.pointer.velocityY) > CLOSING_VELOCITY)) { var distanceRemaining = element.prop('offsetHeight') - ev.pointer.distanceY; var transitionDuration = Math.min(distanceRemaining / ev.pointer.velocityY * 0.75, 500); element.css($mdConstant.CSS.TRANSITION_DURATION, transitionDuration + 'ms'); $mdUtil.nextTick($mdBottomSheet.cancel,true); } else { element.css($mdConstant.CSS.TRANSITION_DURATION, ''); element.css($mdConstant.CSS.TRANSFORM, ''); } } } } } ngmaterial.components.bottomSheet = angular.module("material.components.bottomSheet");
levanta/levanta.github.io
app/jspm_packages/github/angular/bower-material@master/modules/closure/bottomSheet/bottomSheet.js
JavaScript
mit
10,854
/*! * jQuery++ - 1.0.1 (2013-02-08) * http://jquerypp.com * Copyright (c) 2013 Bitovi * Licensed MIT */ define(['jquery', 'jquerypp/event/drag/core', 'jquerypp/dom/styles'], function ($) { var round = function (x, m) { return Math.round(x / m) * m; } $.Drag.prototype. step = function (amount, container, center) { //on draws ... make sure this happens if (typeof amount == 'number') { amount = { x: amount, y: amount } } container = container || $(document.body); this._step = amount; var styles = container.styles("borderTopWidth", "paddingTop", "borderLeftWidth", "paddingLeft"); var top = parseInt(styles.borderTopWidth) + parseInt(styles.paddingTop), left = parseInt(styles.borderLeftWidth) + parseInt(styles.paddingLeft); this._step.offset = container.offsetv().plus(left, top); this._step.center = center; return this; }; (function () { var oldPosition = $.Drag.prototype.position; $.Drag.prototype.position = function (offsetPositionv) { //adjust required_css_position accordingly if (this._step) { var step = this._step, center = step.center && step.center.toLowerCase(), movingSize = this.movingElement.dimensionsv('outer'), lot = step.offset.top() - (center && center != 'x' ? movingSize.height() / 2 : 0), lof = step.offset.left() - (center && center != 'y' ? movingSize.width() / 2 : 0); if (this._step.x) { offsetPositionv.left(Math.round(lof + round(offsetPositionv.left() - lof, this._step.x))) } if (this._step.y) { offsetPositionv.top(Math.round(lot + round(offsetPositionv.top() - lot, this._step.y))) } } oldPosition.call(this, offsetPositionv) } })(); return $; });
shiftplanning/foxydb
public/js/lib/jquerypp/event/drag/step.js
JavaScript
mit
1,709
/** * @module 101/and */ /** * Functional version of || * @function module:101/and * @param {*} a - any value * @param {*} b - any value * @return {boolean} a || b */ module.exports = or; function or (a, b) { return a || b; }
emilkje/101
or.js
JavaScript
mit
238
$(function() { $(document).ready(function() { $('article').readingTime({ readingTimeTarget: '#bond-post-meta-readtime', wordsPerMinute: 240, appendTimeString: ' read', }); $('article').fitVids(); }); });
joeljfischer/bond-light
assets/js/script.js
JavaScript
mit
243
import { Mongo } from 'meteor/mongo'; import { RocketChat } from 'meteor/rocketchat:lib'; RocketChat.models.Roles = new Mongo.Collection('rocketchat_roles'); Object.assign(RocketChat.models.Roles, { findUsersInRole(name, scope, options) { const role = this.findOne(name); const roleScope = (role && role.scope) || 'Users'; const model = RocketChat.models[roleScope]; return model && model.findUsersInRoles && model.findUsersInRoles(name, scope, options); }, isUserInRoles(userId, roles, scope) { roles = [].concat(roles); return roles.some((roleName) => { const role = this.findOne(roleName); const roleScope = (role && role.scope) || 'Users'; const model = RocketChat.models[roleScope]; return model && model.isUserInRole && model.isUserInRole(userId, roleName, scope); }); }, });
pkgodara/Rocket.Chat
packages/rocketchat-authorization/client/lib/models/Roles.js
JavaScript
mit
815
/** * @fileoverview Rule to enforce a maximum number of nested callbacks. * @author Ian Christian Myers */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "enforce a maximum depth that callbacks can be nested", recommended: false, url: "https://eslint.org/docs/rules/max-nested-callbacks" }, schema: [ { oneOf: [ { type: "integer", minimum: 0 }, { type: "object", properties: { maximum: { type: "integer", minimum: 0 }, max: { type: "integer", minimum: 0 } }, additionalProperties: false } ] } ], messages: { exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}." } }, create(context) { //-------------------------------------------------------------------------- // Constants //-------------------------------------------------------------------------- const option = context.options[0]; let THRESHOLD = 10; if ( typeof option === "object" && (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) ) { THRESHOLD = option.maximum || option.max; } else if (typeof option === "number") { THRESHOLD = option; } //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- const callbackStack = []; /** * Checks a given function node for too many callbacks. * @param {ASTNode} node The node to check. * @returns {void} * @private */ function checkFunction(node) { const parent = node.parent; if (parent.type === "CallExpression") { callbackStack.push(node); } if (callbackStack.length > THRESHOLD) { const opts = { num: callbackStack.length, max: THRESHOLD }; context.report({ node, messageId: "exceed", data: opts }); } } /** * Pops the call stack. * @returns {void} * @private */ function popStack() { callbackStack.pop(); } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- return { ArrowFunctionExpression: checkFunction, "ArrowFunctionExpression:exit": popStack, FunctionExpression: checkFunction, "FunctionExpression:exit": popStack }; } };
platinumazure/eslint
lib/rules/max-nested-callbacks.js
JavaScript
mit
3,509
var React = require("react-native"); var { Image, StyleSheet, Text, TouchableOpacity, View, Component, ActivityIndicatorIOS, ListView, Dimensions, Modal } = React; import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import * as actions from '../store/actions' import Icon from "react-native-vector-icons/FontAwesome" import HTML from "react-native-htmlview" import ParallaxView from "react-native-parallax-view" import { authorAvatar } from '../util' const screen = Dimensions.get('window') import ShotDetail from "./ShotDetail" import ShotCell from "./ShotCell" import Loading from "./Loading" class ShotPlayer extends React.Component { constructor (props) { super(props) this.state = { isModalOpen: false, isLoading: true, dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) } } componentWillReceiveProps (nextProps) { const id = this.props.player.id const shot = nextProps.dribbble.shot[id] if (this.props.dribbble.shot[id] !== shot) { this.setState({dataSource: this._getDataSource(shot)}) } } componentDidMount () { this.props.getDribbbleShot(this.props.player.shots_url) } _getDataSource (data) { return this.state.dataSource.cloneWithRows(data) } _openModal () { this.setState({ isModalOpen: true }) } _closeModal () { this.setState({ isModalOpen: false }) } _renderShots () { return ( <ListView renderRow={this._renderRow.bind(this)} dataSource={this.state.dataSource} automaticallyAdjustContentInsets={false} keyboardDismissMode="on-drag" keyboardShouldPersistTaps={true} showsVerticalScrollIndicator={false} /> ) } _renderRow (shot) { return ( <ShotCell onSelect={() => this._selectShot(shot)} shot={shot} /> ) } _selectShot (shot) { this.props.navigator.push({ component: ShotDetail, passProps: {shot}, title: shot.title }) } render () { return ( <ParallaxView windowHeight={260} backgroundSource={authorAvatar(this.props.player)} blur={"dark"} header={( <TouchableOpacity onPress={this._openModal}> <View style={styles.headerContent}> <View style={styles.innerHeaderContent}> <Image source={authorAvatar(this.props.player)} style={styles.playerAvatar} /> <Text style={styles.playerUsername}>{this.props.player.username}</Text> <Text style={styles.playerName}>{this.props.player.name}</Text> <View style={styles.playerDetailsRow}> <View style={styles.playerCounter}> <Icon name="users" size={18} color="#fff"/> <Text style={styles.playerCounterValue}> {this.props.player.followers_count} </Text> </View> <View style={styles.playerCounter}> <Icon name="camera-retro" size={18} color="#fff"/> <Text style={styles.playerCounterValue}> {this.props.player.shots_count} </Text> </View> <View style={styles.playerCounter}> <Icon name="heart-o" size={18} color="#fff"/> <Text style={styles.playerCounterValue}> {this.props.player.likes_count} </Text> </View> </View> </View> </View> </TouchableOpacity> )} > <View style={styles.shotList}> {this.state.dataSource.length !== 0 ? this._renderShots() : <Loading />} </View> <Modal visible={this.state.isModalOpen} onDismiss={this._closeModal}> <Image source={authorAvatar(this.props.player)} style={styles.playerImageModal}/> </Modal> </ParallaxView> ) } } const styles = StyleSheet.create({ listStyle: { flex: 1, backgroundColor: "red" }, listView: { flex: 1, backgroundColor: "coral" }, spinner: { width: 50, }, headerContent: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "transparent", }, innerHeaderContent: { marginTop: 30, alignItems: "center" }, playerInfo: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "white", flexDirection: "row" }, playerUsername: { color: "#fff", fontWeight: "300" }, playerName: { fontSize: 14, color: "#fff", fontWeight: "900", lineHeight: 18 }, //Player details list playerDetailsRow: { flex: 1, alignItems: "center", justifyContent: "center", flexDirection: "row", width: screen.width / 2, marginTop: 20 }, playerCounter: { flex: 1, alignItems: "center" }, playerCounterValue: { color: "#fff", fontWeight: "900", fontSize: 14, marginTop: 5, }, playerAvatar: { width: 80, height: 80, borderRadius: 40, borderWidth: 2, borderColor: "#fff", marginBottom: 10 }, //Modal playerImageModal: { height: screen.height / 3, resizeMode: "contain" }, //playerContent playerContent: { padding: 20 } }) const stateToProps = (state) => ({...state}) const dispatchToProps = (dispatch) => bindActionCreators({...actions}, dispatch) export default connect(stateToProps, dispatchToProps)(ShotPlayer)
okoala/RNStarter
src/components/ShotPlayer.js
JavaScript
mit
5,551
'use strict'; /** * Module dependencies */ var acl = require('acl'); // Using the memory backend acl = new acl(new acl.memoryBackend()); /** * Invoke Decisions Permissions */ exports.invokeRolesPolicies = function () { acl.allow([{ roles: ['admin'], allows: [{ resources: '/api/decisions', permissions: '*' }, { resources: '/api/decisions/:decisionId', permissions: '*' }] }, { roles: ['user'], allows: [{ resources: '/api/decisions', permissions: ['get', 'post'] }, { resources: '/api/decisions/:decisionId', permissions: ['get'] }] }, { roles: ['guest'], allows: [{ resources: '/api/decisions', permissions: ['get'] }, { resources: '/api/decisions/:decisionId', permissions: ['get'] }] }]); }; /** * Check If Decisions Policy Allows */ exports.isAllowed = function (req, res, next) { var roles = (req.user) ? req.user.roles : ['guest']; // If an Decision is being processed and the current user created it then allow any manipulation if (req.decision && req.user && req.decision.user && req.decision.user.id === req.user.id) { return next(); } // Check for user roles acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) { if (err) { // An authorization error occurred return res.status(500).send('Unexpected authorization error'); } else { if (isAllowed) { // Access granted! Invoke next middleware return next(); } else { return res.status(403).json({ message: 'User is not authorized' }); } } }); };
guilhermeartem/Online-MCDM
modules/decisions/server/policies/decisions.server.policy.js
JavaScript
mit
1,692
'use strict'; $(document).ready(function () { var $form = $('#loginF'); var $name = $('#name'); var $pw = $('#pw'); var $ans = $('#ans'); var $alert = $('#alert'); $form.on('submit', function (e) { $alert.removeClass('hidden'); $alert.removeClass('alert-danger'); $alert.removeClass('alert-success'); if ( $name.val() !== 'mary' || $ans.val() !== $pw.val() ) { e.stopPropagation(); e.preventDefault(); $alert.addClass('alert-danger'); $alert.text('Password is not correct'); } else { $alert.addClass('alert-success'); $alert.text('Password is correct'); } }); });
mondwan/ProjectCUWG
js/authentication/hiddenPassword.js
JavaScript
mit
747
import React from 'react' import moment from 'moment' import { Modal, DatePicker, Button, Form, Input, Row, Col } from 'antd' const FormItem = Form.Item class WrappedSprint extends React.Component { constructor (props) { super(props) const future = moment().add(7, 'days') this.state = { future, MED: moment() } } render () { const { visible } = this.props const { getFieldDecorator } = this.props.form const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 6 } }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 } } } return ( <Modal maskClosable={false} visible={visible} title='Start sprint' onCancel={this._handleClose} footer={[ <Button key='submit' type='primary' size='large' onClick={() => this._handleSprintStart()}> Start sprint now </Button>, <Button key='back' size='large' onClick={this._handleClose}>Cancel</Button> ]} > <Form hideRequiredMark> <FormItem {...formItemLayout} label='Name' hasFeedback colon={false}> <Row> <Col> {getFieldDecorator('name', { rules: [{ min: 5, required: true, message: 'Please enter at least 5 characters for your sprint name' }] })(<Input placeholder='enter the name' />)} </Col> </Row> </FormItem> <FormItem {...formItemLayout} label='Begin date' colon={false}> <Row> <Col> <b>Today</b> </Col> </Row> </FormItem> <FormItem {...formItemLayout} label='End date' colon={false}> <Row> <Col> {getFieldDecorator('end', { initialValue: this.state.future, rules: [{ type: 'object', required: true, message: 'Please select your end date!' }], })(<DatePicker allowClear={false} disabledDate={this.disabledEndDate} placeholder='pick your end date' format='YYYY-MM-DD' />)} </Col> </Row> </FormItem> </Form> </Modal> ) } disabledEndDate = startValue => { return startValue.isSameOrBefore(this.state.MED) } _handleClose = () => { this.props.form.resetFields() this.props.onClose() } _handleSprintStart = () => { this.props.form.validateFields((error, values) => { if (error) return this.props.onConfirm(values) }) } } export const SprintStart = Form.create()(WrappedSprint)
dreitagebart/crispyScrum
src/components/sprint-start.js
JavaScript
mit
2,663
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0];var j=d.createElement(s);var dl=l!='dataLayer'?'&l='+l:'';j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl+'';j.async=true;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-P6T7VWN');
pkfrank/mgocomments
new site/example2_files/google_tag.script.js
JavaScript
mit
348
function init() { var req = chrome.extension.getBackgroundPage().Request.request; req.nameE = document.getElementById("header_name"); req.valueE = document.getElementById("header_value"); req.nameE.value = req.hname; req.valueE.value = req.hvalue; document.getElementById("url").value = req.url; document.getElementById("content_body").value = req.body; var list = document.getElementById("header_list"); list.innerHTML = renderHeaders() document.getElementById("url").addEventListener("keyup", onUrlChanged); document.getElementById("url").addEventListener("blur", onUrlChanged); document.getElementById("header_name").addEventListener("keyup", onHeaderChanged); document.getElementById("header_name").addEventListener("blur", onHeaderChanged); document.getElementById("header_value").addEventListener("keyup", onHeaderChanged); document.getElementById("header_value").addEventListener("blur", onHeaderChanged); document.getElementById("add_header_button").addEventListener("click", onAddChangeHeader); document.getElementById("content_body").addEventListener("keyup", onBodyChanged); document.getElementById("content_body").addEventListener("blur", onBodyChanged); var methods = ["GET", "POST", "DELETE", "HEAD", "PUT"]; for (var i=0; i<methods.length;i++) { (function(index){ var button = document.getElementById(methods[i].toLowerCase() + "_request_button"); button.addEventListener("click", function () { doRequest(methods[index]); }); })(i); } } function onHeaderChanged() { var req = chrome.extension.getBackgroundPage().Request.request; req.hname = req.nameE.value; req.hvalue = req.valueE.value; } function onUrlChanged() { var req = chrome.extension.getBackgroundPage().Request.request; req.url = document.getElementById("url").value;; } function renderHeaders() { var req = chrome.extension.getBackgroundPage().Request.request; var html = "<table border=1>"; html += "<tr><th>name</th><th>value</th></tr>"; for (var i in req.headers) { html += "<tr><td align=\"left\">" + i + "</td><td align=\"right\">" + req.headers[i] + "</td></tr>"; } html += "</table>" return html; } function onAddChangeHeader() { var req = chrome.extension.getBackgroundPage().Request.request; var name = req.nameE.value; if (!name) { return; } var value = req.valueE.value; if (value == "##") { delete req.headers[name]; } else { req.headers[name] = value; } req.nameE.value = req.valueE.value = ""; onHeaderChanged(); var list = document.getElementById("header_list"); list.innerHTML = renderHeaders() } function onBodyChanged() { var req = chrome.extension.getBackgroundPage().Request.request; req.body = document.getElementById("content_body").value; } function doRequest(method) { var req = chrome.extension.getBackgroundPage().Request.request; req.method = method; req.url = document.getElementById("url").value; if (req.method == "POST" || req.method == "PUT") { req.body = document.getElementById("content_body").value; } var xhr = new XMLHttpRequest(); xhr.open( req.method, req.url, false); console.log(method + " " + req.url); for (var i in req.headers) { xhr.setRequestHeader(i, req.headers[i]); console.log(i + " " + req.headers[i]); } xhr.onload = function() { var result = "status: " + xhr.status + " " + xhr.statusText + "<br />"; var header = xhr.getAllResponseHeaders(); var all = header.split("\r\n"); for (var i = 0; i < all.length; i++) { if (all[i] != "") result += ("<li>" + all[i] + "</li>"); } document.getElementById("response_header").innerHTML = result; document.getElementById("response_body").innerText = xhr.responseText; } xhr.send(req.body); } init();
dengzhp/chrome-poster
js/popup.js
JavaScript
mit
4,059
/////////////////////// // formBuilder() version 1.3 ////////////////////// var formBuilder = { helpers: { languageCode: function(defaultLang) { defaultLang = (defaultLang === undefined || defaultLang === null) ? "de" : defaultLang; var path = location.pathname; var lang; if (path === "/") { lang = defaultLang; } else if (path.indexOf('/_temp/') > -1) { lang = path.substr(7, 2); } else { lang = path.substr(1, 2); } return lang; }, badIE: function() { return (typeof FormData === 'undefined') ? true : false; }, /////////////////////// // test for undefined and null => true ////////////////////// isEmpty: function(val) { return (typeof val === 'undefined' || val === null); }, /////////////////////// // test for undefined, null and "" =>true ////////////////////// isReallyEmpty: function(val) { return (formBuilder.helpers.isEmpty(val) || val.length === 0); }, renderMessage: function(obj) { var formContent = []; formContent.push('<table class="form-data">'); obj.find("input,select,textarea").not('[type=hidden]').each(function() { if ($(this).attr('type') === "file") { if ($(this)[0].files[0] !== undefined && $(this)[0].files[0] !== null) { formContent.push('<tr><td>' + $(this).attr('id') + '</td><td>' + $(this)[0].files[0].name + '</td></tr>'); } } else if ($(this).attr('type') === "radio") { formContent.push('<tr><td>' + $(this).attr("name") + " " + $(this).val() + '</td><td>' + $(this)[0].checked + '</td></tr>'); } else { formContent.push('<tr><td>' + $(this).attr("name") + '</td><td>' + $(this).val() + '</td></tr>'); } }); formContent.push('</table>'); return formContent; }, buildFormdata: function(content, obj) { $(content).find("input,select,textarea").not('[type=hidden]').each(function() { if ($(this).attr('type') === "file") { if ($(this)[0].files[0] !== undefined && $(this)[0].files[0] !== null) { obj.append($(this).attr('id'), $(this)[0].files[0]); } } else if ($(this).attr('type') === "radio") { if ($(this)[0].checked === true) { obj.append($(this).attr("name") + '-' + $(this).val(), $(this)[0].checked); } } else if ($(this).attr('type') === 'checkbox'){ if ($(this)[0].checked === true) { obj.append($(this).attr("name") + '-' + $(this).val(), $(this)[0].checked); } } else { obj.append($(this).attr('name'), $(this).val()); } }); return obj; }, renderErrorMessage: function(container, msg){ $(container).html("<div class='error error-message'>" + msg + "</div>"); } }, sendForm: function(params) { var options = $.extend({ apiUrl: "http://cmsapi.seven49.net/FormMail/", sendButton: "#send-form", mailTo: "info@seven49.net", // could also be $('input[name=MailTo]).val() replyTo: "MailFrom", // name of input: client's email in input-field mailFrom: "noreply@seven49.net", // leave it for SPAM filtering mailSubject: "Kontaktformular", validation: true, // default formName: ".feedback-form", formContent: ".feedback-form .ContentItem", sendCCToSender: false, customCCText: '', redirectOnSuccess: $('input[name=MailThanks]').val(), // if undefined or '' the alternateSuccessMessage will be displayed in formContent errorMessage: "Some errors ocurred while transmitting the form! Please refresh the page and try again!", alternateSuccessMessage: "This form was successfully sent!", loader: "<img class='send-form' src='http://cdn.seven49.net/common/images/loading/ajax-loader-2.gif' />" }, params); if (options.validation) { var langCode = formBuilder.helpers.languageCode('de'); $('head').append('<script src="http://cdn.seven49.net/common/js/jquery/plugins/jquery-validation/jquery.validate.min.js"></script>'); if (langCode !== 'en') { setTimeout(function(){ $('head').append('<script src="http://cdn.seven49.net/common/js/jquery/plugins/jquery-validation/localization/messages_' + langCode + '.js"></script>'); }, 200); } } $(options.sendButton).on('click', function() { if (options.validation) { if ($(options.formName).valid()) { formBuilder.processForm({ formContent: options.formContent, apiUrl: options.apiUrl, mailTo: options.mailTo, replyTo: $('input[name='+options.replyTo+']').val(), mailFrom: options.mailFrom, mailSubject: options.mailSubject, formName: options.formName, redirectOnSuccess: options.redirectOnSuccess, sendCCToSender: options.sendCCToSender, customCCText: options.customCCText, errorMessage: options.errorMessage, alternateSuccessMessage: options.alternateSuccessMessage, loader: options.loader }); } } else { formBuilder.processForm({ formContent: options.formContent, apiUrl: options.apiUrl, mailTo: options.mailTo, replyTo: $('input[name='+options.replyTo+']').val(), mailFrom: options.mailFrom, mailSubject: options.mailSubject, sendCCToSender: options.sendCCToSender, customCCText: options.customCCText, formName: options.formName, errorMessage: options.errorMessage, redirectOnSuccess: options.redirectOnSuccess, alternateSuccessMessage: options.alternateSuccessMessage, loader: options.loader }); } }); }, processForm: function(params) { var options = $.extend({ formContent: ".feedback-form .ContentItem", apiUrl: "http://cmsapi.seven49.net/FormMail/", mailTo: "info@seven49.net", replyTo: $('input[name=Email]').val(), mailFrom: "noreply@seven49.net", mailSubject: "Kontaktformular", formName: ".feedback-form", redirectOnSuccess: '', sendCCToSender: false, customCCText: '', errorMessage: "Some errors ocurred while transmitting the form! Please refresh the page and try again!", alternateSuccessMessage: "This form was successfully sent!", loader: "<img class='send-form' src='http://cdn.seven49.net/common/images/loading/ajax-loader-2.gif' alt='sending form' />" }, params); var loader = "<div class='loader' id='form-process-indicator'>" + options.loader + "</div>"; $(options.formContent).append(loader); if (!formBuilder.helpers.isReallyEmpty(options.redirectOnSuccess)) { if(options.redirectOnSuccess.indexOf('http://') === -1) { redirectUrl = location.protocol + "//" + location.hostname +"/" + options.redirectOnSuccess; } } if (formBuilder.helpers.badIE()) { var formContent = formBuilder.helpers.renderMessage($(options.formContent)); $.post(options.apiUrl, { "MailFrom": options.mailFrom, "MailTo": options.mailTo, "ReplyTo": options.replyTo, "MailSubject": options.mailSubject, "MailBody": formContent.join("") + "<br/>" + "Wichtig:" + "Der Kunde hat das Formular mit einem veralteten Browser abgeschickt - bei diesen steht der Dokumenten-Upload nicht zur Verfügung. Bitte fordern Sie diese, falls nötig, per E-Mail vom Kunden an." }, function(){ if (options.sendCCToSender) { $.post(options.apiUrl, { "MailFrom": options.mailFrom, "MailTo": options.replyTo, "ReplyTo": options.mailTo, "MailSubject": options.mailSubject, "MailBody": options.customCCText + formContent.join("") }); } if (formBuilder.helpers.isReallyEmpty(options.redirectOnSuccess)) { $(options.formContent).html("<div class='success-message'>"+options.alternateSuccessMessage+"</div>"); } else { window.location.href = redirectUrl; } }).error(function() { formBuilder.helpers.renderErrorMessage(options.formContent, options.errorMessage); }); } else { var formData = new FormData(); formData.append('MailTo', options.mailTo); formData.append('MailFrom', options.mailFrom); formData.append('ReplyTo', options.replyTo); formData.append('MailSubject', options.mailSubject); formBuilder.helpers.buildFormdata(options.formContent, formData); $.ajax({ url: options.apiUrl, data: formData, type: "POST", contentType: false, processData: false, success: function() { if (options.sendCCToSender) { var customerForm = formBuilder.helpers.renderMessage($(options.formContent)); $.post(options.apiUrl, { "MailFrom": options.mailFrom, "MailTo": options.replyTo, "ReplyTo": options.mailTo, "MailSubject": options.mailSubject, "MailBody":options.customCCText + customerForm.join("") }); } if (formBuilder.helpers.isReallyEmpty(options.redirectOnSuccess)) { $(options.formContent).html("<div class='success-message'>"+options.alternateSuccessMessage+"</div>"); } else { window.location.href = options.redirectOnSuccess; } }, error: function() { formBuilder.helpers.renderErrorMessage(options.formContent, options.errorMessage); } }); } } };
seven49-net/cms-form-builder
formBuilder.js
JavaScript
mit
8,963
export ValueChart from './ValueChart'; export ForecastChart from './ForecastChart';
diman84/Welthperk
client-react/src/components/Charts/index.js
JavaScript
mit
84
module.exports = Animal; function Animal (type) { this.isAlive = true; this.type = type; this.health = 1; }; Animal.prototype.beCute = function() { this.isCute = true; }; ////////async function here///////////////// Animal.prototype.updateHealthStats = function(cb){ // this.health = Math.random(); var self = this; setTimeout(function(){ self.health = Math.random(); cb(); }, 1000); }
jybjones/Nodcha-Chai-Latte
lib/Animal.js
JavaScript
mit
415
//simulation!! window.simulation = d3.forceSimulation() //.force("charge", d3.forceManyBody().strength(-30))//- 18 -550 -32 -34 .force("link", d3.forceLink().id(function(d) { return parseFloat(d.id); })) .force("center", d3.forceCenter(0,0)) .force('collide', d3.forceCollide()) .alphaDecay(1-Math.pow(0.0001,1/3000));//timesteps d3.json("./ics/Nhe_144.json", function(error, graph) { if (error) throw error; console.log(graph);window.graph=graph;run()}); function run(){ window.graph.nodes.forEach(function(d){d.z = 20+100.20*d.s;return d }) graph = window.graph; //scale factor var ptsize = 300;((width*height)/graph.nodes.length)/100000; //300 console.log(ptsize) //simulation.force('collide', d3.forceCollide().radius(function(d,i){return (plus_ns+node_sizes[i])/8 + plus_ns + node_sizes[i]})) //move further out graph.nodes = graph.nodes.filter(function(d){node_sizes.push( d.s * ptsize );d.x = 100*d.x;d.y=100*d.y;return d}, node_sizes=[]); simulation .nodes(graph.nodes) .on("tick", ticked); //send ipc links to other //graph.links.forEach(function(d){var dv= d.value;dummy.push(eval(linkleneq))},dummy=[]); //ipc.send('forwarder',['prefsWindow',window.linkleneq,dummy]); var charge = -300 ; simulation.force("link") .links(graph.links) .distance(function(d){var dv= d.value;return 1*eval(window.linkleneq)}) // 1-dval 500*0.4+(dv*dv*dv)/0.6 .strength(function(d){var dv = d.value;return 1}); simulation.force("charge", d3.forceManyBody().strength(charge)) var ThreeObj = new THREE.Object3D(); window.plotobject = new ThreeLayout.Graph(ThreeObj,window.graph) scene.add(ThreeObj); function ticked() { if (simulation.alpha() < 0.001) { simulation.stop(); // 0.012 function dragstarted(d) {}; function dragended(d) {}; //alert('simulation completed'); UDE On.end }; window.plotobject.setNodePositions(graph) window.plotobject.update(); } ipc.on('command', (event,arg)=> { console.log(event,arg); eval(arg); }) }; /* simulation.stop(); graph_3d = JSON.parse(JSON.stringify(window.graph)) // introduce a 3d force function, but constrain x and y, so remove x and y calculations? //=> rewrite force function window.simulation.vertx = d3.forceSimulation() //.force("charge", d3.forceManyBody().strength(-30))//- 18 -550 -32 -34 .force("link", d3.forceLink().id(function(d) { return parseFloat(d.id); })) .force("center", d3.forceCenter(0,0)) .force("charge", d3.forceManyBody().strength(-1)) .alphaDecay(1-Math.pow(0.0001,1/3000));//timesteps simulation.force("link") .links(graph_3d.links) .distance(function(d){var dv= d.value;return 10*eval(window.linkleneq)}) .strength(function(d){var dv = d.value;return 0.9}); graph_3d.nodes.forEach(function(d){d.z=d.x}); simulation.vertx .nodes(graph_3d.nodes) .on("tick", ticked); function ticked() { graph_3d.nodes.forEach(function(d,i){d.y = JSON.parse(JSON.stringify(graph.nodes[i].y));graph.nodes[i].z = d.x; return d }) window.plotobject.setNodePositions(graph) window.plotobject.update(); } */
wolfiex/VisACC
threeforce/forcegraph.js
JavaScript
mit
3,297
import marked from 'marked'; import Highlight from 'highlight.js'; import xss from 'xss'; export function redirectURL(url) { location = url; } // xss 默认将语法高亮去掉了,使用白名单解决 marked.setOptions({ highlight: function (code) { return Highlight.highlightAuto(code).value; } }); const xssOptions = { whiteList: Object.assign({}, xss.whiteList), }; xssOptions.whiteList.code = ['class']; xssOptions.whiteList.span = ['class']; const myxss = new xss.FilterXSS(xssOptions); export function renderMarkdown(text) { return myxss.process(marked(text)); }
sql370/practice-node-project
frontend/lib/utils.js
JavaScript
mit
591
import Service, { inject as service } from '@ember/service'; import { later } from '@ember/runloop'; import config from 'travis/config/environment'; export default Service.extend({ store: service(), jobState: service(), liveUpdatesRecordFetcher: service(), receive(event, data) { let build, commit, job; let store = this.store; let [name, type] = event.split(':'); if (name === 'repository' && type === 'migration') { const repository = store.peekRecord('repo', data.repositoryId); repository.set('migrationStatus', data.status); // There is a disconnect between the meaning of `active` in the GitHub // apps world and the Legacy Services world. If the repository was // migrated, it's by definition using GitHub apps, which means it is // by definition active. We no longer show toggle switches for GitHub // app-managed repositories, for instance. if (data.status === 'success') { repository.set('active', true); } } if (name === 'job' && data.job && data.job.commit) { store.push(store.normalize('commit', data.job.commit)); } if (name === 'job' && data.job) { store.push(store.normalize('job', data.job)); } if (name === 'job' && data.job && data.job.build_id) { data.job.job_id_number = data.job.number; store.push(store.normalize('job', data.job)); this.jobState.peekJobs.perform(); } if (name === 'build' && data.build && data.build.commit) { build = data.build; commit = { id: build.commit_id, author_email: build.author_email, author_name: build.author_name, branch: build.branch, committed_at: build.committed_at, committer_email: build.committer_email, committer_name: build.committer_name, compare_url: build.compare_url, message: build.message, sha: build.commit }; delete data.build.commit; store.push(store.normalize('commit', commit)); } if (name === 'branch') { // force reload of repo branches // delay to resolve race between github-sync and live const branchName = data.branch; later(() => { store.findRecord('branch', `/repo/${data.repository_id}/branch/${branchName}`); }, config.intervals.branchCreatedSyncDelay); delete data.branch; } if (event === 'job:log') { data = data.job ? data.job : data; job = store.recordForId('job', data.id); return job.appendLog({ number: parseInt(data.number), content: data._log, final: data.final }); } else if (data[name]) { if (data._no_full_payload) { // if payload is too big, travis-live will send us only the id of the // object or id with build_id for jobs. If that happens, just load the // object from the API let payload = {}; if (name === 'job') { payload['build_id'] = data.job.build_id; } this.liveUpdatesRecordFetcher.fetch(name, data[name].id, payload); } else { return this.loadOne(name, data); } } else { if (!type) { throw `can't load data for ${name}`; } } }, loadOne(type, json) { let data, defaultBranch, lastBuildId; let store = this.store; store.push(store.normalize(type, json)); // we get other types of records only in a few situations and // it's not always needed to update data, so I'm specyfing which // things I want to update here: if (type === 'build' && (json.repository || json.repo)) { data = json.repository || json.repo; defaultBranch = data.default_branch; if (defaultBranch) { defaultBranch.default_branch = true; defaultBranch['@href'] = `/repo/${data.id}/branch/${defaultBranch.name}`; } lastBuildId = defaultBranch.last_build_id; const repo = store.peekRecord('repo', data.id); data.email_subscribed = repo ? repo.emailSubscribed : true; // a build is a synchronous relationship on a branch model, so we need to // have a build record present when we put default_branch from a repository // model into the store. We don't send last_build's payload in pusher, so // we need to get it here, if it's not already in the store. In the future // we may decide to make this relationship async, but I don't want to // change the code at the moment let lastBuild = store.peekRecord('build', lastBuildId); if (!lastBuildId || lastBuild) { return store.push(store.normalize('repo', data)); } else { return store.findRecord('build', lastBuildId).then(() => { store.push(store.normalize('repo', data)); }); } } } });
travis-ci/travis-web
app/services/pusher.js
JavaScript
mit
4,800
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var core_1 = require('@angular/core'); var FilterProductsByCategoryPipe = (function () { function FilterProductsByCategoryPipe() { } FilterProductsByCategoryPipe.prototype.transform = function (products, categoryId) { if (!products) { return null; } else if (!categoryId) { return products; } else { return products.filter(function (product) { return product.category.id === categoryId; }); } }; FilterProductsByCategoryPipe = __decorate([ core_1.Pipe({ name: 'filterProductsByCategory' }) ], FilterProductsByCategoryPipe); return FilterProductsByCategoryPipe; }()); exports.FilterProductsByCategoryPipe = FilterProductsByCategoryPipe;
mabuprojects/mbr-publicApp
src/app/pipes/filter-products-by-category.pipe.js
JavaScript
mit
1,362
import {inject, Container} from 'aurelia-dependency-injection'; import {bindable, processContent, noView, TargetInstruction} from 'aurelia-templating'; import {Aurelia} from 'aurelia-framework'; import {join} from 'aurelia-path'; import {Loader} from 'aurelia-loader'; @noView() @processContent(extractRawSource) @inject(TargetInstruction, Loader) export class SourceCode { @bindable src; @bindable lang; constructor(instruction, loader) { this.raw = instruction.elementInstruction.raw; this.loader = loader; } bind(context) { if (this.src) { this.path = join(context.url, '../../../' + this.src); if (context.local) { this.path = './' + this.path; } } } loadText() { if (this.path) { return this.loader.loadText(this.path).then(x => this.raw = x); } return Promise.resolve(this.raw); } createApp(host) { this.app = new Aurelia(this.loader, new Container()); this.app.use.standardConfiguration(); this.app.start().then(a => a.setRoot(this.path, host)); } } function extractRawSource(compiler, resources, element, instruction) { instruction.raw = unescape(element.innerHTML); element.innerHTML = ''; return false; }
joelcoxokc/app-documentation
src/article/language/source-code.js
JavaScript
mit
1,220
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z" }), 'BluetoothSearching');
AlloyTeam/Nuclear
components/icon/esm/bluetooth-searching.js
JavaScript
mit
532
"use strict"; var mongoose = require('mongoose'), morgan = require('morgan'), bodyParser = require('body-parser'), middle = require('./middleware'); mongoose.connect(process.env.DB_URL || 'mongodb://localhost/myApp'); /* * Include all your global env variables here. */ module.exports = exports = function (app, express, routers) { app.set('port', process.env.PORT || 9000); app.set('base url', process.env.URL || 'http://localhost'); app.use(morgan('dev')); app.use(bodyParser()); app.use(middle.cors); app.use(express.static(__dirname + '/../../client')); app.use('/note', routers.NoteRouter); app.use('/mood', routers.MoodRouter); app.use(middle.logError); app.use(middle.handleError); };
aesprice/personifi
server/main/config.js
JavaScript
mit
740
const assert = require("chai").assert; const SelectBuilder = require("./../../../../src/ORM/Builder/SelectBuilder"); describe("SelectBuilderTest", () => { describe("Making simple queries", () => { it("Should return a simple select query", () => { let sb = new SelectBuilder(); assert.equal("SELECT * FROM table_name;", sb.from("table_name").toSql()); }); it("Should validate that query has required informations", () => { let sb = new SelectBuilder(); assert.throw(() => { sb.select().toSql(); }); assert.throw(() => { sb.select("*").from().toSql(); }); }); }); describe("Writing queries that join results", () => { it("Should make simple joins", () => { assert.equal( "SELECT * FROM table_name" + " INNER JOIN another_table ON table_name.fk_id = another_table.id;", new SelectBuilder() .from("table_name") .join({ type: "INNER", table: "another_table", field: "fk_id", other_field: "id" }) .toSql() ); assert.equal( "SELECT * FROM table_name" + " INNER JOIN another_table ON table_name.fk_id = another_table.id" + " LEFT JOIN third_table ON other_table.id = third_table.fk_id;", new SelectBuilder() .from("table_name") .join({ table: "another_table", field: "fk_id", other_field: "id" }) .join({ type: "LEFT", from: "other_table", table: "third_table", field: "id", other_field: "fk_id" }) .toSql() ); }); it("Should still make simple joins in a different way", () => { assert.equal( "SELECT * FROM table_name" + " INNER JOIN another_table ON table_name.fk_id = another_table.id;", new SelectBuilder() .from("table_name") .join("INNER", "another_table", "fk_id", "id") .toSql() ); assert.equal( "SELECT * FROM table_name" + " INNER JOIN another_table ON table_name.fk_id = another_table.id" + " LEFT JOIN third_table ON other_table.id = third_table.fk_id;", new SelectBuilder() .from("table_name") .join("INNER", "another_table", "fk_id", "id") .join("LEFT", "third_table", "id", "fk_id", "other_table") .toSql() ); }); it("Should validate if you wrote a join correctly", () => { assert.throw(() => { new SelectBuilder() .from("table_name") .join({ type: "INNER" }) .toSql(); }); }); }); describe("Writing query filters", () => { let expr = new SelectBuilder().expr(); it("Should make a simple where", () => { assert.equal( "SELECT * FROM table_name WHERE id = 10;", new SelectBuilder().from("table_name").where(expr.eq("id", 10)).toSql() ); assert.equal( "SELECT * FROM table_name WHERE id <> 10;", new SelectBuilder().from("table_name").where(expr.neq("id", 10)).toSql() ); assert.equal( "SELECT * FROM table_name WHERE id IS NOT NULL;", new SelectBuilder() .from("table_name") .where(expr.isNotNull("id")) .toSql() ); }); it("Should make not too much complex wheres", () => { assert.equal( 'SELECT * FROM table_name WHERE id IN (10,20) AND nome LIKE "%test%";', new SelectBuilder() .from("table_name") .where(expr.in("id", [10, 20]), expr.like("nome", "%test%")) .toSql() ); assert.equal( "SELECT * FROM table_name WHERE id NOT IN (1,2,3) OR status IS NULL;", new SelectBuilder() .from("table_name") .where(expr.notIn("id", [1, 2, 3])) .orWhere(expr.isNull("status")) .toSql() ); assert.equal( "SELECT * FROM table_name WHERE num BETWEEN 1 AND 20 OR num > 100;", new SelectBuilder() .from("table_name") .where(expr.between("num", 1, 20)) .orWhere(expr.gt("num", 100)) .toSql() ); }); it("Should make advanced filters and more complex querying", () => { assert.equal( "SELECT * FROM table_name WHERE id >= 1 AND (value < 100 AND amount <= 10);", new SelectBuilder() .from("table_name") .where(expr.gte("id", 1)) .where(expr.andX(expr.lt("value", 100), expr.lte("amount", 10))) .toSql() ); assert.equal( "SELECT * FROM table_name WHERE value < 100 AND " + "(amount > 10 AND (visitor = 2 OR visitor = 2.5));", new SelectBuilder() .from("table_name") .where(expr.lt("value", 100)) .where( expr.andX( expr.gt("amount", 10), expr.orX(expr.eq("visitor", 2), expr.eq("visitor", 2.5)) ) ) .toSql() ); }); }); describe("Grouping results", () => { it("Should simply group results", () => { assert.equal( "SELECT * FROM table_name GROUP BY amount;", new SelectBuilder().from("table_name").group("amount").toSql() ); }); it("Should simply group more that one field", () => { assert.equal( "SELECT * FROM table_name GROUP BY date,amount;", new SelectBuilder().from("table_name").group(["date", "amount"]).toSql() ); assert.equal( "SELECT * FROM table_name GROUP BY date,amount;", new SelectBuilder().from("table_name").group("date", "amount").toSql() ); }); }); describe("Ordering results", () => { it("Should simply order results", () => { assert.equal( "SELECT * FROM table_name ORDER BY id;", new SelectBuilder().from("table_name").order("id").toSql() ); assert.equal( "SELECT * FROM table_name ORDER BY created_at,id;", new SelectBuilder() .from("table_name") .order("created_at") .order("id") .toSql() ); }); it("Should order declaring if ascending or descending", () => { assert.equal( "SELECT * FROM table_name ORDER BY id DESC;", new SelectBuilder().from("table_name").order("id", "DESC").toSql() ); assert.equal( "SELECT * FROM table_name ORDER BY created_at DESC,value ASC,id;", new SelectBuilder() .from("table_name") .order("created_at", "DESC") .order("value", "ASC") .order("id") .toSql() ); }); it("Should validate errors", () => { assert.throw(() => { new SelectBuilder().from("table_name").order("id", "SORT").getSql(); }); }); }); describe("Limiting query data to be returned", () => { it("Should limit query", () => { assert.equal( "SELECT * FROM table_name LIMIT 100;", new SelectBuilder().from("table_name").limit(100).toSql() ); }); it("Should offset query", () => { assert.equal( "SELECT * FROM table_name OFFSET 20;", new SelectBuilder().from("table_name").offset(20).toSql() ); }); it("Should limit AND offset query", () => { assert.equal( "SELECT * FROM table_name LIMIT 10 OFFSET 30;", new SelectBuilder().from("table_name").limit(10).offset(30).toSql() ); }); it("Should validate errors", () => { assert.throw(() => { new SelectBuilder().from("table_name").limit("10").toSql(); }); assert.throw(() => { new SelectBuilder().from("table_name").offset("20").toSql(); }); }); }); });
vinyguedess/mynodefy
test/Unit/ORM/Builder/SelectBuilderTest.js
JavaScript
mit
7,857
/*! * ng-phone-number v1.0.0 * https://github.com/deopard/ng-phone-number#readme * Copyright (c) 2015 Tom Kim * License: MIT */ /** * @ngdoc directive * @name deopard.ngPhoneNumber:phoneNumber * @description * Makes text inputs to take only phone-number-valid characters (number, +, -) */ (function () { angular .module('deopard.ngPhoneNumber', []) .directive('phoneNumber', PhoneNumber); function PhoneNumber () { var directive = { restrict: 'A', require: 'ngModel', link: linkFunc }; return directive; function linkFunc(scope, el, attr, ctrl) { ctrl.$parsers.push(function (inputValue) { if (inputValue === undefined) return ''; var transformedInput = inputValue.replace(/[^0-9\-+]/g, ''); if (transformedInput != inputValue) { ctrl.$setViewValue(transformedInput); ctrl.$render(); } return transformedInput; }); } } })();
deopard/ng-phone-number
dist/ng-phone-number.js
JavaScript
mit
969
var createPool = require("@nathanfaucett/create_pool"), consts = require("./consts"); var RemovePatchPrototype; module.exports = RemovePatch; function RemovePatch() { this.type = consts.REMOVE; this.id = null; this.childId = null; this.index = null; } createPool(RemovePatch); RemovePatchPrototype = RemovePatch.prototype; RemovePatch.create = function(id, childId, index) { var patch = RemovePatch.getPooled(); patch.id = id; patch.childId = childId; patch.index = index; return patch; }; RemovePatchPrototype.destructor = function() { this.id = null; this.childId = null; this.index = null; return this; }; RemovePatchPrototype.destroy = function() { return RemovePatch.release(this); };
nathanfaucett/virt
src/Transaction/RemovePatch.js
JavaScript
mit
758
module.exports={A:{A:{"1":"E A B","2":"L H G jB"},B:{"1":"8 C D e K I N J"},C:{"1":"0 1 2 3 4 5 7 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB","2":"gB BB aB","36":"ZB"},D:{"1":"0 1 2 3 5 7 8 9 K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB","516":"4 F L H G E A B C D e"},E:{"1":"6 H G E A B C D WB XB YB p bB","772":"4 F L SB KB UB VB"},F:{"1":"0 1 2 3 5 6 7 B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z eB fB p AB hB","2":"E cB","36":"dB"},G:{"1":"G D MB nB oB pB qB rB sB tB uB vB","4":"KB iB FB lB","516":"kB"},H:{"132":"wB"},I:{"1":"O 1B 2B","36":"xB","516":"BB F 0B FB","548":"yB zB"},J:{"1":"H A"},K:{"1":"6 A B C M p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"1":"A B"},O:{"1":"3B"},P:{"1":"F 4B 5B 6B 7B 8B"},Q:{"1":"9B"},R:{"1":"AC"},S:{"1":"BC"}},B:4,C:"CSS3 Background-image options"};
Dans-labs/dariah
client/node_modules/caniuse-lite/data/features/background-img-opts.js
JavaScript
mit
989
(function(d){var j=d(document.getElementById("menu-form")),i=d(document.getElementById("definitions")),h=j.data("prototype"),f=0;var c=function(o){var m=d(o),n=[];m.find("input, select").each(function(p,q){n.push(d(q).val())});return n};var a=function(o,n){var m=d(o);m.find("input, select").each(function(p,q){d(q).val(n.shift())})};var g=function(n,m){var q=d(n),p=d(m);var r=c(q),o=c(p);a(q,o);a(p,r)};var l=function(o){var m=d(o),n=m.prev(".item-row");if(n.size()<=0){return}g(m,n)};var b=function(o){var m=d(o),n=m.next(".item-row");if(n.size()<=0){return}g(m,n)};var k=function(n){var m=d(n);m.find(".remove").click(function(){m.slideUp("fast",function(){m.remove()})});m.find(".move-up").click(function(){l(m)});m.find(".move-down").click(function(){b(m)})};d(".add-item",j).click(function(){e()});var e=function(){var n=h.replace(/__name__/g,f),m=d(n).hide().appendTo(i).slideDown("fast");f++;k(m)};d(".item-row",i).each(function(m,n){f++;k(n)});return{}})(jQuery);
tyler-sommer/TylerSommerdotcom
web/js/menu_editor.js
JavaScript
mit
973
import React from 'react'; import UserPicture from '../User/UserPicture'; export default class UserList extends React.Component { isSeenUserListShown() { const userCount = this.props.users.length; if (0 < userCount && userCount <= 10) { return true; } return false; } render() { if (!this.isSeenUserListShown()) { return null; } const users = this.props.users.map((user) => { return ( <a key={user._id} data-user-id={user._id} href={'/user/' + user.username} title={user.name}> <UserPicture user={user} size="xs" /> </a> ); }); return ( <p className="seen-user-list"> {users} </p> ); } } UserList.propTypes = { users: React.PropTypes.array, }; UserList.defaultProps = { users: [], };
crow-misia/crowi
resource/js/components/SeenUserList/UserList.js
JavaScript
mit
814
define([ 'jquery', 'jquery' ], function (jQuery, $) { (function ($) { $.fn.cat = function() { console.log("i am a cat."); } })(jQuery); ; return jQuery; });
tristanguo/grunt-shadow
test/expected/jquery.cat.shadowed.js
JavaScript
mit
163
import useWebChatAPIContext from './useWebChatAPIContext'; export default function useLocalizedStrings() { const { localizedStrings } = useWebChatAPIContext(); return localizedStrings; }
billba/botchat
packages/api/src/hooks/internal/useLocalizedStrings.js
JavaScript
mit
193
describe( 'shop product new section', function() { beforeEach(module('meanShop.shop.productNew')); beforeEach(module('store')); it('should have a dummy test', inject( function() { expect(true).toBeTruthy(); })); });
aeife/meanshop
client/src/app/shop/product/new/productNew.spec.js
JavaScript
mit
233
import { NativeModules } from 'react-native'; export default NativeModules.AppSee;
tomauty/react-native-appsee
index.js
JavaScript
mit
83
'use strict'; var test = require('selenium-webdriver/testing'), By = require('selenium-webdriver').By, expect = require('chai').expect, moment = require('moment'), register_new_user_func = require('../lib/register_new_user'), login_user_func = require('../lib/login_with_user'), open_page_func = require('../lib/open_page'), submit_form_func = require('../lib/submit_form'), add_new_user_func = require('../lib/add_new_user'), logout_user_func = require('../lib/logout_user'), user_info_func = require('../lib/user_info'), config = require('../lib/config'), application_host = config.get_application_host(); /* * Scenario to check: * * Create EMPLOYEE * * Deactivate EMPLOYEE * * Logout from ADMIN * * Register new account for EMPLOYEE email * * Logout * * Login back as ADMIN * * Try to activate EMPLOYEE back * * Make sure system prevent of doing this * * */ describe('Deactivate and activate user', function(){ this.timeout( config.get_execution_timeout() ); var email_admin, email_employee, employee_id, driver; it('Create new company', function(done){ register_new_user_func({ application_host : application_host, }) .then(function(data){ email_admin = data.email; driver = data.driver; done(); }); }); it("Create EMPLOYEE", function(done){ add_new_user_func({ application_host : application_host, driver : driver, }) .then(function(data){ email_employee = data.new_user_email; done(); }); }); it("Obtain information about employee", function(done){ user_info_func({ driver : driver, email : email_employee, }) .then(function(data){ employee_id = data.user.id; done(); }); }); it('Check that the deactivated badge is not displayed', function(done){ driver.findElements(By.className('badge alert-warning')) .then(els => { if (els.length > 0){ throw new Error('The badge was found') } else { done(); } }) }); it('Mark EMPLOYEE as inactive by specifying end date to be in past', function(done){ open_page_func({ url : application_host + 'users/edit/'+employee_id+'/', driver : driver, }) .then(function(){ submit_form_func({ driver : driver, form_params : [{ selector : 'input#end_date_inp', value : moment().subtract(1, 'days').format('YYYY-MM-DD'), }], submit_button_selector : 'button#save_changes_btn', message : /Details for .+ were updated/, should_be_successful : true, }) .then(function(){ done() }); }); }); it('Check that the deactivated badge is displayed', function(done){ driver.findElements(By.className('badge alert-warning')) .then(els => {expect(els.length).to.be.eql(1, 'No badge visible'); return els[0].getText(); }) .then(val => { expect(val).to.be.eql('Deactivated', 'It is not the deactivated badge'); done(); }); }); it("Logout from ADMIN", function(done){ logout_user_func({ application_host : application_host, driver : driver, }) .then(function(){ done() }); }); it('Create another company for EMPLOYEE email', function(done){ register_new_user_func({ application_host : application_host, user_email : email_employee, driver : driver, }) .then(function(){ done() }); }); it("Logout from new company created by EMPLOYEE", function(done){ logout_user_func({ application_host : application_host, driver : driver, }) .then(function(){ done() }); }); it("Login back as ADMIN", function(done){ login_user_func({ application_host : application_host, user_email : email_admin, driver : driver, }) .then(function(){ done() }); }); it("Try to activate EMPLOYEE back. Open details page", function(done){ open_page_func({ url : application_host + 'users/edit/'+employee_id+'/', driver : driver, }) .then(function(){ done() }); }); it('... use end_date in future', function(done){ submit_form_func({ driver : driver, form_params : [{ selector : 'input#end_date_inp', value : moment().add(1, 'days').format('YYYY-MM-DD'), }], submit_button_selector : 'button#save_changes_btn', message : /There is an active account with similar email somewhere within system/, }) .then(function(){ done() }); }); it("... use empty end_date", function(done){ submit_form_func({ driver : driver, form_params : [{ selector : 'input#end_date_inp', value : '', }], submit_button_selector : 'button#save_changes_btn', message : /There is an active account with similar email somewhere within system/, }) .then(function(){ done() }); }); it('Although setting end_date to some value in past still works', function(done){ submit_form_func({ driver : driver, form_params : [{ selector : 'input#end_date_inp', value : moment().subtract(3, 'days').format('YYYY-MM-DD'), }], submit_button_selector : 'button#save_changes_btn', message : /Details for .+ were updated/, }) .then(function(){ done() }); }); after(function(done){ driver.quit().then(function(){ done(); }); }); });
timeoff-management/application
t/integration/deactivate_and_activate_user.js
JavaScript
mit
5,649
const html = require('choo/html'); module.exports = (state, prev, send) => { return html` <div class="issues__location"> ${pretext(state)} ${addressForm(state)} </div> `; function pretext(state) { if (state.fetchingLocation) { return html`<p class="loadingAnimation">Getting your location</p>`; } else if (state.askingLocation) { return html``; } else { if (state.address != '') { return html`<p>for <a href="#" onclick=${enterLocation}>${state.address}</a></p>` } else if (state.cachedCity != '') { return html`<p>for <a href="#" onclick=${enterLocation}> ${state.cachedCity}</a> ${debugText(state.debug)}</p>` } else { return html`<p><a href="#" onclick=${enterLocation}>Choose a location</a></p>` } } } function addressForm(state) { const className = (state.askingLocation && !state.fetchingLocation) ? '' : 'hidden'; return html`<p><form onsubmit=${submitAddress} class=${className}><input type="text" autofocus="true" id="address" name="address" placeholder="Enter an address or zip code" /> <button>Go</button></form></p>` } function debugText(debug) { return debug ? html`<a href="#" onclick=${unsetLocation}>reset</a>` : html``; } function submitAddress(e) { e.preventDefault(); address = this.elements["address"].value; send('setLocation', address); } function enterLocation(e) { e.preventDefault(); send('enterLocation'); } function unsetLocation() { send('unsetLocation'); } }
jameshome/5calls
static/js/components/issuesLocation.js
JavaScript
mit
1,556
var gulp = require('gulp'); require('./tasks'); gulp.task('default',['sass']);
vldk/typescript-karma-example
gulpfile.js
JavaScript
mit
80
System.register("test/spec/register", ["test/js/sayhi", "test/js/6import-sayhi", "test/js/sayhi-define"], function(sayhi, sayhi6, sayhidefine) { describe("System.register - Say Hi Test suite", function() { it("System sayhi-6", function() { expect(sayhi6).to.equal("Say Hi 6"); }); it("System sayhi-cjs", function() { expect(sayhi).to.equal("Say Hi"); }); it("System sayhi-define", function() { expect(sayhidefine).to.equal("Say Hi Define"); }); }); });
MiguelCastillo/bit-sandbox
test/spec/register.js
JavaScript
mit
501
/* * * EditPostPage * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import { createStructuredSelector } from 'reselect'; import { notify } from 'react-notify-toast'; import Loader from 'react-loader'; import H3 from 'components/H3'; import { makeSelectEditPostPage, selectPostId, selectPost, selectLoading, } from './selectors'; import { resetPostAction, savePostAction, loadPostAction, changePostId, } from './actions'; const Input = styled.input` width: 100%; border-bottom: #41addd 2px solid; color: #777777; font-size: 17px; padding:8px 10px; margin-bottom: 18px; font-family: arial; &:focus { outline: none; } `; const TextArea = styled.textarea` width: 100%; border-bottom: #41addd 2px solid; color: #777777; font-size: 17px; padding:8px 10px; height: 70px; overflow: auto; margin-bottom: 18px; font-family: arial; &:focus { outline: none; } `; const ContentWrapper = styled.div` max-width: calc(768px + 16px * 2); margin: 0 auto; padding: 10px 16px 32px 16px; `; const PostWrapper = styled.div` width: 100%; border: 1px #cccccc solid; margin:8px 0; padding:0 25px 25px 25px; `; const ToolBar = styled.div` width: 100%; padding:10px 16px; text-align: right; `; const PostBody = styled.div` width: 100%; color: #777777; font-size: 16px; `; const Button = styled.button` display: inline-block; box-sizing: border-box; line-height: 1.5; margin-left:10px; padding: 0.25em 2em; text-decoration: none; border-radius: 4px; -webkit-font-smoothing: antialiased; -webkit-touch-callout: none; user-select: none; cursor: pointer; outline: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: bold; font-size: 16px; border: 2px solid #41addd; color: #41addd; &:active { background: #41addd; color: #fff; } &:disabled { color: #81d8dd; border: 2px solid #81d8dd; cursor: not-allowed; } `; const BackLink = styled(Link)` display: inline-block; box-sizing: border-box; margin-left:10px; padding: 0.25em 2em; text-decoration: none; border-radius: 4px; -webkit-font-smoothing: antialiased; -webkit-touch-callout: none; user-select: none; cursor: pointer; outline: 0; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: bold; font-size: 16px; border: 2px solid #41addd; color: #41addd; &:active { background: #41addd; color: #fff; } `; export class EditPostPage extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); if (this.props.params.id) { this.state = { id: '', title: '', body: '', userId: '1', }; } else { this.state = { title: '', body: '', userId: '1', }; } } componentWillMount() { this.props.doReset(); if (this.props.params.id) { this.props.onChangePostId(this.props.params.id); } } componentDidMount() { if (this.props.params.id) { this.props.doLoad(); } } componentWillReceiveProps(nextProps) { if (nextProps.post.success === 'Success') { notify.show('Post Saved Successfully', 'success'); this.props.router.push('/posts'); } if (nextProps.post.error === 'Error') { notify.show('Failed Saving the Post', 'error'); } if (nextProps.post && nextProps.post.title !== '') { this.setState(nextProps.post); } } onChangeTitle(e) { this.setState({ ['title']: e.target.value }); } onChangeBody(e) { this.setState({ ['body']: e.target.value }); } submitPost() { this.props.doSave(this.state); } render() { let backBtn = null; let head = null; if (this.props.params.id) { backBtn = <Link style={{ color: '#41addd', fontWeight: 'bold', textDecoration: 'none' }} to={'/posts/' + this.props.pid}>{ '<< Back to Post' }</Link>; head = <H3>Edit Post - {this.props.pid}</H3>; } else { backBtn = <Link style={{ color: '#41addd', fontWeight: 'bold', textDecoration: 'none' }} to="/posts">{ '<< Back to Posts' }</Link>; head = <H3>Create New Post</H3>; } return ( <Loader loaded={this.props.post && this.props.post.loading !== 'Loading' && this.props.loading !== 'Loading'} lines={13} length={20} width={10} radius={30} corners={1} rotate={0} direction={1} color="#000" speed={1} trail={60} shadow={false} hwaccel={false} className="spinner" zIndex={2e9} top="50%" left="50%" scale={1.00} loadedClassName="loadedContent"> <ContentWrapper> <Helmet title="EditPostPage" meta={[ { name: 'description', content: 'Description of EditPostPage' }, ]} /> <PostWrapper> {head} <PostBody> <Input value={this.state.title} onChange={(value) => this.onChangeTitle(value)} type="text" id="title" name="title" placeholder="Post Title" /> <TextArea value={this.state.body} onChange={(value) => this.onChangeBody(value)} id="body" name="body" placeholder="Post Content" /> <ToolBar> <Button disabled={!this.state.title || !this.state.body} onClick={() => this.submitPost()}>Save</Button> <BackLink to="/posts">Cancel</BackLink> <div style={{ float: 'left', marginTop: '10px' }}> {backBtn} </div> </ToolBar> </PostBody> </PostWrapper> </ContentWrapper> </Loader> ); } } EditPostPage.propTypes = { dispatch: PropTypes.func.isRequired, post: PropTypes.object, pid: PropTypes.string, loading: PropTypes.string, doSave: PropTypes.func, doLoad: PropTypes.func, doReset: PropTypes.func, }; const mapStateToProps = createStructuredSelector({ EditPostPage: makeSelectEditPostPage(), post: selectPost(), pid: selectPostId(), loading: selectLoading(), }); function mapDispatchToProps(dispatch) { return { doSave: (state) => { dispatch(savePostAction(state)); }, onChangePostId: (pid) => dispatch(changePostId(pid)), doLoad: () => { dispatch(loadPostAction()); }, doReset: () => { dispatch(resetPostAction()); }, dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(EditPostPage);
ajanthvofox/react-crud
app/containers/EditPostPage/index.js
JavaScript
mit
6,618
module.exports = function entry_store (options) { var seneca = this seneca.add('store:save,kind:student', function(msg, done) { this .make('student', { when: msg.when, user: msg.user, text: msg.text }) .save$(function(err, entry) { if(err) return done(err) this.act( { timeline: 'insert', users: [msg.user], }, entry, function(err) { return done(err, entry) }) }) }) seneca.add('store:list,kind:student', function(msg, done) { this .make('student') .list$( {user: msg.user}, function(err, list) { if(err) return done(err) list.reverse( function(a, b) { return a.when - b.when }) done( null, list ) }) }) }
TomerG2/regme-microservices
services/student-store/student-store-logic.js
JavaScript
mit
841
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Report = mongoose.model('Report'), _ = require('lodash'); /** * Find report by id */ exports.report = function(req, res, next, id) { Report.load(id, function(err, report) { if (err) return next(err); if (!report) return next(new Error('Failed to load report ' + id)); req.report = report; next(); }); }; /** * Create an report */ exports.create = function(req, res) { var report = new Report(req.body); report.user = req.user; report.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, report: report }); } else { res.jsonp(report); } }); }; /** * Update an report */ exports.update = function(req, res) { var report = req.report; report = _.extend(report, req.body); report.save(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, report: report }); } else { res.jsonp(report); } }); }; /** * Delete an report */ exports.destroy = function(req, res) { var report = req.report; report.remove(function(err) { if (err) { return res.send('users/signup', { errors: err.errors, report: report }); } else { res.jsonp(report); } }); }; /** * Show an report */ exports.show = function(req, res) { res.jsonp(req.report); }; /** * List of Reports */ exports.all = function(req, res) { Report.find().sort('-created').populate('user', 'name username').exec(function(err, reports) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(reports); } }); };
grappleio/olrhain
app/controllers/reports.js
JavaScript
mit
1,982