code
stringlengths 2
1.05M
|
|---|
import Ember from 'ember';
const {
Route
} = Ember;
export default Route.extend({
model(params) {
return this.get('store').findRecord('item', params.id);
}
});
|
app.service('UserService', function (FIREBASE_URL, $firebase) {
var connectedUsersRef = new Firebase(FIREBASE_URL + 'whiteBoard/connectedUsers');
this.userRef = null;
this.setCurrentUser = function(user) {
this.userRef = connectedUsersRef.push(user);
this.userRef.onDisconnect().remove();
};
this.getConnectedUsersRef = function() {
return $firebase(connectedUsersRef);
};
this.getCurrentUserKey = function() {
return this.userRef.name();
};
});
|
const server = require('./server')
const port = process.env.PORT || 3000
server.listen(port, () => {
console.log('Listening on port %s', port)
})
|
/* eslint-disable */
const NODE_ENV = process.env.NODE_ENV;
if (NODE_ENV !== 'development' && NODE_ENV !== 'production') {
throw new Error('NODE_ENV must either be set to development or production.');
}
global.__DEV__ = NODE_ENV === 'development';
global.requestAnimationFrame = function(callback) {
setTimeout(callback);
};
global.requestIdleCallback = function(callback) {
return setTimeout(() => {
callback({
timeRemaining() {
return Infinity;
},
});
});
};
global.cancelIdleCallback = function(callbackID) {
clearTimeout(callbackID);
};
// By default React console.error()'s any errors, caught or uncaught.
// However it is annoying to assert that a warning fired each time
// we assert that there is an exception in our tests. This lets us
// opt out of extra console error reporting for most tests except
// for the few that specifically test the logging by shadowing this
// property. In real apps, it would usually not be defined at all.
Error.prototype.suppressReactErrorLogging = true;
if (typeof window !== 'undefined') {
// Same as above.
DOMException.prototype.suppressReactErrorLogging = true;
// Also prevent JSDOM from logging intentionally thrown errors.
// TODO: it might make sense to do it the other way around.
// https://github.com/facebook/react/issues/11098#issuecomment-355032539
window.addEventListener('error', event => {
if (event.error != null && event.error.suppressReactErrorLogging) {
event.preventDefault();
}
});
}
// Preserve the empty object identity across module resets.
// This is needed for some tests that rely on string refs
// but reset modules between loading different renderers.
const obj = require.requireActual('fbjs/lib/emptyObject');
jest.mock('fbjs/lib/emptyObject', () => obj);
|
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Favorites', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.STRING
},
recipeId: {
type: Sequelize.STRING
},
recipeId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Recipes',
key: 'id'
}
},
userId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Favorites');
}
};
|
var group___d_m_a_ex =
[
[ "DMAEx Exported Types", "group___d_m_a_ex___exported___types.html", "group___d_m_a_ex___exported___types" ],
[ "DMAEx Exported Functions", "group___d_m_a_ex___exported___functions.html", "group___d_m_a_ex___exported___functions" ],
[ "DMAEx Private Functions", "group___d_m_a_ex___private___functions.html", null ]
];
|
var relativeImports = /import\s*{[a-zA-Z\,\s]+}\s*from\s*'\.\/[a-zA-Z\-]+';\s*/g;
var nonRelativeImports = /import\s*{?[a-zA-Z\*\,\s]+}?\s*from\s*'[a-zA-Z\-]+';\s*/g;
var importGrouper = /import\s*{([a-zA-Z\,\s]+)}\s*from\s*'([a-zA-Z\-]+)'\s*;\s*/;
exports.extractImports = function(content, importsToAdd){
var matchesToKeep = content.match(nonRelativeImports);
if(matchesToKeep){
matchesToKeep.forEach(function(toKeep){ importsToAdd.push(toKeep) });
}
content = content.replace(nonRelativeImports, '');
content = content.replace(relativeImports, '');
return content;
};
exports.createImportBlock = function(importsToAdd){
var finalImports = {}, importBlock = '';
importsToAdd.forEach(function(toAdd){
var groups = importGrouper.exec(toAdd);
if(!groups) {
toAdd = toAdd.trim();
if(importBlock.indexOf(toAdd) === -1){
importBlock += toAdd + '\n';
}
return;
};
var theImports = groups[1].split(',');
var theSource = groups[2].trim();
var theList = finalImports[theSource] || (finalImports[theSource] = []);
theImports.forEach(function(item){
item = item.trim();
if(theList.indexOf(item) === -1){
theList.push(item);
}
});
});
Object.keys(finalImports).forEach(function(key) {
importBlock += 'import {' + finalImports[key].join(',') + '} from \'' + key + '\';\n';
});
return importBlock + '\n';
};
|
'use strict';
module.exports = function(app) {
// Root routing
var core = require('../../app/controllers/core.server.controller');
app.route('/').get(core.index);
app.route('/check').put(core.check);
};
|
const AuthUtil = require('../thulib/auth')
const User = require('../models/user')
const updateCourseInfo = require('./update_course_info')
const updateCurriculumInfo = require('./update_curriculum_info')
const updateScheduleInfo = require('./update_schedule_info')
const taskScheduler = require('./task_scheduler')
const register = async(username, password) => {
const authResult = await AuthUtil.auth(username, password)
if (authResult) {
let user = await User.findOne({username: username})
const existed = !!user
if (!existed) {
const info = await AuthUtil.getUserInfo(username, password)
user = new User({
username: username,
password: password,
info: info
})
await user.save()
taskScheduler.add(updateCourseInfo, user, 3600000)
taskScheduler.add(updateCurriculumInfo, user, 3600000)
taskScheduler.add(updateScheduleInfo, user, 3600000)
} else if (existed && user.getPassword() !== password) {
user.password = password
user.save()
}
return [user, existed]
} else {
return [null, false]
}
}
module.exports = register
|
/**
* Created by hbzhang on 8/5/15.
*/
'use strict';
angular.module('mean.helpers').factory('AllWidgetData',['$resource','$rootScope', function($resource,$rootScope) {
var allwidgets=[
{
name: 'Announcement',
data: []
},
{
name: 'Information',
data: []
}
];
return {
allwidgets:allwidgets
};
}]);
|
import JoiBase from 'joi';
import {postHandlerFactory, getHandlerFactory} from './common';
import FullDateValidator from '../../../../shared/lib/joi-full-date-validator';
const Joi = JoiBase.extend(FullDateValidator);
const schema = Joi.object().keys({
'day': Joi.number().integer().min(1).max(31).required().label('Day')
.meta({
componentType: 'numeric',
fieldset: true,
legendText:'What is your date of birth?',
legendClass: 'legend-hidden' })
.options({
language: {
number: {
base: 'Please enter a valid day using numbers only',
min: 'Please enter a valid day',
max: 'Please enter a valid day'
}
}
}),
'month': Joi.number().integer().min(1).max(12).required().label('Month').meta({ componentType: 'numeric' }).options({
language: {
number: {
base: 'Please enter a valid month using numbers only',
min: 'Please enter a valid month',
max: 'Please enter a valid month'
}
}
}),
'year': Joi.number().integer().min(1885).max(2025).required().label('Year')
.meta({
componentType: 'numeric',
fieldsetEnd: true })
.options({
language: {
number: {
base: 'Please enter a valid year using numbers only',
min: 'Please enter a year after 1885',
max: 'Please enter a valid year'
}
}
}),
'submit': Joi.any().optional().strip()
}).fulldate();
const title = 'What is your date of birth?';
const key = 'dateOfBirth';
const slug = 'date-of-birth';
const defails = {
hint: 'For example, 31 3 1980'
};
const handlers = {
GET: (prevSteps) => getHandlerFactory(key, title, schema, prevSteps, defails),
POST: (prevSteps, nextSteps) => postHandlerFactory(key, title, schema, prevSteps, nextSteps, defails),
};
/**
* @type Step
*/
export default {
key,
slug,
title,
schema,
handlers
};
|
var getDefaultViewController = function () {
var defaultView = getSetting('defaultView', 'top');
defaultView = defaultView.charAt(0).toUpperCase() + defaultView.slice(1);
return eval("Posts"+defaultView+"Controller");
};
// Controller for all posts lists
PostsListController = FastRender.RouteController.extend({
template: getTemplate('posts_list'),
subscriptions: function () {
// take the first segment of the path to get the view, unless it's '/' in which case the view default to 'top'
// note: most of the time this.params.slug will be empty
this._terms = {
view: this.view,
limit: this.params.limit || getSetting('postsPerPage', 10),
category: this.params.slug
};
if(Meteor.isClient) {
this._terms.query = Session.get('searchQuery');
}
this.postsListSub = coreSubscriptions.subscribe('postsList', this._terms);
this.postsListUsersSub = coreSubscriptions.subscribe('postsListUsers', this._terms);
},
data: function () {
this._terms = {
view: this.view,
limit: this.params.limit || getSetting('postsPerPage', 10),
category: this.params.slug
};
if(Meteor.isClient) {
this._terms.query = Session.get('searchQuery');
}
var parameters = getPostsParameters(this._terms),
postCount = Posts.find(parameters.find, parameters.options).count();
parameters.find.createdAt = { $lte: Session.get('listPopulatedAt') };
var posts = Posts.find(parameters.find, parameters.options);
// Incoming posts
parameters.find.createdAt = { $gt: Session.get('listPopulatedAt') };
var postsIncoming = Posts.find(parameters.find, parameters.options);
Session.set('postsLimit', this._terms.limit);
return {
incoming: postsIncoming,
postsList: posts,
postCount: postCount,
ready: this.postsListSub.ready
};
},
onAfterAction: function() {
Session.set('view', this.view);
}
});
PostsTopController = PostsListController.extend({
view: 'top'
});
PostsNewController = PostsListController.extend({
view: 'new'
});
PostsBestController = PostsListController.extend({
view: 'best'
});
PostsPendingController = PostsListController.extend({
view: 'pending'
});
// Controller for post digest
PostsDigestController = FastRender.RouteController.extend({
template: getTemplate('posts_digest'),
waitOn: function() {
// if day is set, use that. If not default to today
var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : new Date(),
terms = {
view: 'digest',
after: moment(currentDate).startOf('day').toDate(),
before: moment(currentDate).endOf('day').toDate()
};
return [
coreSubscriptions.subscribe('postsList', terms),
coreSubscriptions.subscribe('postsListUsers', terms)
];
},
data: function() {
var currentDate = this.params.day ? new Date(this.params.year, this.params.month-1, this.params.day) : Session.get('today'),
terms = {
view: 'digest',
after: moment(currentDate).startOf('day').toDate(),
before: moment(currentDate).endOf('day').toDate()
},
parameters = getPostsParameters(terms);
Session.set('currentDate', currentDate);
parameters.find.createdAt = { $lte: Session.get('listPopulatedAt') };
var posts = Posts.find(parameters.find, parameters.options);
// Incoming posts
parameters.find.createdAt = { $gt: Session.get('listPopulatedAt') };
var postsIncoming = Posts.find(parameters.find, parameters.options);
return {
incoming: postsIncoming,
posts: posts
};
}
});
// Controller for post pages
PostPageController = FastRender.RouteController.extend({
template: getTemplate('post_page'),
waitOn: function() {
this.postSubscription = coreSubscriptions.subscribe('singlePost', this.params._id);
this.postUsersSubscription = coreSubscriptions.subscribe('postUsers', this.params._id);
this.commentSubscription = coreSubscriptions.subscribe('postComments', this.params._id);
},
post: function() {
return Posts.findOne(this.params._id);
},
onBeforeAction: function() {
if (! this.post()) {
if (this.postSubscription.ready()) {
this.render(getTemplate('not_found'));
} else {
this.render(getTemplate('loading'));
}
} else {
this.next();
}
},
onRun: function() {
var sessionId = Meteor.default_connection && Meteor.default_connection._lastSessionId ? Meteor.default_connection._lastSessionId : null;
Meteor.call('increasePostViews', this.params._id, sessionId);
},
data: function() {
return this.post();
}
});
Meteor.startup(function () {
Router.route('/resources', {
name: 'posts_default',
controller: getDefaultViewController()
});
Router.route('/top/:limit?', {
name: 'posts_top',
controller: PostsTopController
});
// New
Router.route('/new/:limit?', {
name: 'posts_new',
controller: PostsNewController
});
// Best
Router.route('/best/:limit?', {
name: 'posts_best',
controller: PostsBestController
});
// Pending
Router.route('/pending/:limit?', {
name: 'posts_pending',
controller: PostsPendingController
});
// TODO: enable /category/new, /category/best, etc. views
// Digest
Router.route('/digest/:year/:month/:day', {
name: 'posts_digest',
controller: PostsDigestController
});
Router.route('/digest', {
name: 'posts_digest_default',
controller: PostsDigestController
});
// Post Page
Router.route('/posts/:_id', {
name: 'post_page',
controller: PostPageController
});
Router.route('/posts/:_id/comment/:commentId', {
name: 'post_page_comment',
controller: PostPageController,
onAfterAction: function () {
// TODO: scroll to comment position
}
});
// Post Edit
Router.route('/posts/:_id/edit', {
name: 'post_edit',
template: getTemplate('post_edit'),
waitOn: function () {
return [
coreSubscriptions.subscribe('singlePost', this.params._id),
coreSubscriptions.subscribe('allUsersAdmin')
];
},
data: function() {
return {
postId: this.params._id,
post: Posts.findOne(this.params._id)
};
},
fastRender: true
});
// Post Submit
Router.route('/submit', {
name: 'post_submit',
template: getTemplate('post_submit'),
waitOn: function () {
return coreSubscriptions.subscribe('allUsersAdmin');
}
});
});
|
'use strict';
const Gitlab = require('gitlab');
const async = require('async');
const utils = require('./utils');
const moment = require('moment');
class GitLabWrapper {
constructor(config, notifier) {
this.config = config;
this.client = null;
this.projects = {};
this.users = {};
this.currentUserId = -1;
this.notifier = notifier;
}
init(callback) {
var config = this.config;
var state = createState(config);
if(!config.hasServerInfo()) {
state.error = "Gitlab URL and Token are mandatory.";
callback(state);
return;
}
this.client = createClient(config);
async.parallel([
this.loadCurrentUser.bind(this),
this.loadProjectsList.bind(this)], (err) => {
if(err) {
state.error = err;
callback(state);
}
else
this.sync(callback, state);
});
}
onUpdateConfig(callback) {
this.init(callback);
}
sync(callback, state) {
state = state || createState(this.config);
async.parallel([
this.loadMergeRequests.bind(this, true)
], (error, results) => {
if(error)
state.error = error;
updateState(state, this.projects, this.users, this.currentUserId);
callback(state);
});
}
onUpdateProjects(callback) {
var watchProjects = this.config.getWatchProjects();
for(let projectId in this.projects) {
let project = this.projects[projectId];
project.isWatching = watchProjects.indexOf(parseInt(projectId)) >= 0;
project.mergeRequests = [];
}
this.sync(callback);
}
onTimeoutSync(callback) {
let operations = [];
let state = createState(this.config);
operations.push(this.loadMergeRequests.bind(this, false));
async.parallel(operations, (err) => {
if(err)
state.error = err;
updateState(state, this.projects, this.users, this.currentUserId);
callback(state);
});
}
getUserId(id, userInfo) {
if(!this.users[id]) {
this.users[id] = {
id: id,
username: userInfo["username"],
email: userInfo["email"],
name: userInfo["name"]
};
}
return id;
}
/* async operations */
loadMergeRequests(skipChanges, callback) {
var watchProjects = this.config.getWatchProjects().filter(pid => !!this.projects[pid]);
let _this = this;
async.map(watchProjects, (projectId, cb) => {
_this.client.projects.merge_requests.list(projectId, (mergeRequests) => {
let project = this.projects[projectId];
if(!mergeRequests) {
cb(`Cannot load merge requests for '${utils.getProjectFullName(project)}'`);
return;
}
let oldMergeRequests = {};
let changes = [];
for(let i = 0, mr; mr = project.mergeRequests[i]; i++)
oldMergeRequests[mr.id] = mr;
project.mergeRequests = [];
for(let i = 0, mergeRequest; mergeRequest = mergeRequests[i]; i++) {
let author = mergeRequest["author"];
let assignee = mergeRequest["assignee"];
let guid = project.id + "_" + mergeRequest["id"];
let mr = {
id: mergeRequest["id"],
iid: mergeRequest["iid"],
guid: guid,
createdAt: mergeRequest["created_at"],
updatedAt: mergeRequest["updated_at"],
description: mergeRequest["description"],
targetBranch: mergeRequest["target_branch"],
sourceBranch: mergeRequest["source_branch"],
targetProjectId: mergeRequest["target_project_id"],
sourceProjectId: mergeRequest["source_project_id"],
title: mergeRequest["title"],
state: mergeRequest["state"],
author: _this.getUserId(author["id"], author),
assignee: assignee ? _this.getUserId(assignee["id"], assignee) : -1
};
project.mergeRequests.push(mr);
if(!skipChanges)
changes.push({source: oldMergeRequests[mr.id], target: mr});
}
cb(null, changes);
});
}, (err, results) => {
let changes = [];
for(let i = 0, pResults; pResults = results[i]; i++)
changes = changes.concat(pResults);
if(changes.length)
this.notifier.onMergeRequestChanges(changes, this.currentUserId, this.users, this.projects);
callback(err);
});
}
loadCurrentUser(callback) {
this.currentUserId = -1;
let _this = this;
this.client.users.current(function(result) {
if (result) {
_this.currentUserId = result["id"];
_this.getUserId(result["id"], result);
callback();
}
else
callback();
});
}
loadProjectsList(callback) {
this.projects = {};
var watchProjects = this.config.getWatchProjects();
let _this = this;
this.client.projects.all((result) => {
if(typeof result === 'string' || result instanceof String) {
callback(result);
}
else {
for(let i = 0, project; project = result[i]; i++) {
let projectId = project["id"];
_this.projects[projectId] = {
id: projectId,
description: project["description"],
public: project["public"],
webUrl: project["web_url"],
name: project["name"],
namespace: {
id: project["namespace"]["id"],
name: project["namespace"]["name"],
},
star_count: project["star_count"],
mergeRequests: [],
isWatching: watchProjects.indexOf(projectId) > -1,
isAccessible: true
};
}
callback();
}
//}
});
}
}
function updateState(state, projects, users, currentUserId) {
state.projects = [];
state.users = users;
state.userId = currentUserId;
for(let projectId in projects)
state.projects.push(projects[projectId]);
}
function createClient(config) {
var serverInfo = config.getServerInfo();
return new Gitlab({
url: serverInfo.url,
token: serverInfo.token
});
}
function createState(config) {
var serverInfo = config.getServerInfo();
var updateTimeout = config.getUpdateTimeout();
return {
gitlabUrl: serverInfo.url,
gitlabToken: serverInfo.token,
updateTimeout: updateTimeout,
projects: [],
users: {},
error: "",
userId: -1
};
}
module.exports = GitLabWrapper;
|
const gulp = require('gulp');
const size = require('gulp-size');
const sass = require('gulp-sass');
const plumber = require('gulp-plumber');
const cleanCss = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
/**
* Copy app.css to dist/ without any minification
*/
gulp.task('styles:dev', ['styles:scss'], () => {
gulp.src('app/styles/app.css')
.pipe(gulp.dest('dist/css/'));
});
/**
* Miniy app.css (which was created in the styles:scss task). Copy the result to dist/.
*/
gulp.task('styles:prod', ['styles:scss'], () => {
gulp.src('app/styles/app.css')
.pipe(size({
showFiles: true,
title: 'size of initial css'
}))
.pipe(cleanCss({processImport: false}))
.pipe(size({
showFiles: true,
title: 'size of css after minify'
}))
.pipe(gulp.dest('dist/css/'));
});
/**
* Compile app.scss into a CSS file. This is a synchronous task (using the "return a stream"
* paradigm) so that it will finish before "styles:dev" or "styles:prod" attempt to copy the
* generated CSS.
*/
gulp.task('styles:scss', () => {
return gulp.src('app/styles/app.scss')
.pipe(size({
showFiles: true,
title: 'initial scss files'
}))
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(sass({
errLogToConsole: true
}))
.pipe(sourcemaps.write())
.pipe(size({
showFiles: true,
title: 'compiled css files with sourcemaps'
}))
.pipe(gulp.dest('app/styles/'));
});
/**
* Watch for changes to our SCSS files. If an SCSS file changes, run the 'styles:dev' task again.
*/
gulp.task('styles:watch', () => {
gulp.watch('app/styles/**/*.scss', ['styles:dev']);
});
|
import React, { Component } from 'react';
import axios from 'axios';
import { Router, Link } from 'react-router';
import { Button } from 'react-bootstrap';
export default class trueMenu extends Component {
constructor(props) {
super();
this.state = {
displayCreateBoard: false,
displayJoin: false,
name: '',
placeholder: 'Join a room',
userId: 0,
list: [],
isValid: true
};
this.handleName = this.handleName.bind(this);
this.handleJoination = this.handleJoination.bind(this);
}
handleJoination(e) {
e.preventDefault();
if(this.state.name === ''){
this.setState({placeholder: "Please enter a room name", isValid: false})
return;
} else if (this.state.name.indexOf(' ') !== -1){
this.setState({placeholder: "Room names can not contain spaces", name: '', isValid: false})
return;
}else if (/[^a-zA-Z0-9\-\/]/.test(this.state.name)) {
this.setState({placeholder: "Special characters are not allowed", name: '', isValid: false})
return;
}
socket.emit('create board', {name: this.state.name});
window.location.assign('/#/code')
}
handleName(event) {
window.roomName = event.target.value;
this.setState({
name: event.target.value
});
}
render() {
const logoStyle = {
'marginTop': '14%'
}
const imageSize = {
width: '400px'
}
return (
<div className="center-roomselect" id="createroom">
<form style={logoStyle} className="animated fadeInUp" onSubmit={this.handleJoination}>
<img style={imageSize} src="./media/codeout.png" />
<br />
<input
placeholder={this.state.placeholder}
value={this.state.name}
onChange={(e) => this.handleName(e)}
className={!this.state.isValid ? 'animated shake search-style' : 'search-style'}
/>
<p>
<button className="btn btn-primary button-spacing"
onClick={this.handleJoination}>Enter Room
</button>
</p>
</form>
</div>
)
};
};
|
/* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
cache: null,
},
mutations: {
setCache(state, value) {
state.cache = value;
},
},
actions: {
get({ state, commit }, cache = true) {
if (cache && state.cache) {
return new Promise((resolve) => {
resolve(state.cache);
});
}
return Vue.http.get('api/server/self-update').then(
response => response.body,
(response) => {
if (response.status === 501) {
return {
current_version: null,
latest_version: null,
channel: 'dev',
supported: false,
error: null,
};
}
throw response;
},
).then((result) => {
commit('setCache', result);
return result;
});
},
async latest() {
const response = await Vue.http.get('https://download.contao.org/contao-manager/stable/contao-manager.version');
return response.body.version;
},
},
};
|
$(function () {
$('.imageUploadMultiple').each(function (index, item) {
var $item = $(item);
var $group = $item.closest('.form-group');
var $innerGroup = $item.find('.form-group');
var $errors = $item.find('.errors');
var $input = $item.find('.imageValue');
var flow = new Flow({
target: $item.data('target'),
testChunks: false,
chunkSize: 1024 * 1024 * 1024,
query: {
_token: $item.data('token')
}
});
var updateValue = function () {
var values = [];
$item.find('img[data-value]').each(function () {
values.push($(this).data('value'));
});
$input.val(values.join(','));
};
flow.assignBrowse($item.find('.imageBrowse'));
flow.on('filesSubmitted', function (file) {
flow.upload();
});
flow.on('fileSuccess', function (file, message) {
flow.removeFile(file);
$errors.html('');
$group.removeClass('has-error');
var result = $.parseJSON(message);
var template = $($('#thumbnail_template').html());
template.find('img').attr('src', result.url).attr('data-value', result.value);
$innerGroup.append(template);
updateValue();
});
flow.on('fileError', function (file, message) {
flow.removeFile(file);
var response = $.parseJSON(message);
var errors = '';
$.each(response, function (index, error) {
errors += '<p class="help-block">' + error + '</p>'
});
$errors.html(errors);
$group.addClass('has-error');
});
$item.on('click', '.imageRemove', function (e) {
e.preventDefault();
$(this).closest('.imageThumbnail').remove();
updateValue();
});
$innerGroup.sortable({
onUpdate: function () {
updateValue();
}
});
});
});
|
export class App {
constructor (router) {
this.router = router;
}
configureRouter (config, router) {
this.router = router;
config.map([
{ name: 'orders', route: ['', 'orders'], moduleId: 'modules/orders/index', nav: true, title: "Orders" }
, { name: 'order', route: 'order/:name', moduleId: 'modules/order/index' }
]);
}
}
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import '../resources/fonts/fonts.global.css';
import './app.global.css';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
function solve(input){
let result=input.toString();
let sum=0;
let count=0;
while(input>=1){
sum+=input%10;
count++;
input=Math.floor(input/10);
}
while(sum/count<=5){
sum+=9;
count++;
result+='9';
}
console.log(result)
}
solve(101);
|
import Zip from 'adm-zip';
/**
* @param {Type}
* @return {Type}
*/
export default function (filePath) {
let courseZip = new Zip(filePath);
let courseFileScanner = {
getZipObject: () => {
return courseZip;
},
getCourseFiles: () => {
return courseZip.getEntries().filter(courseFileScanner._isCourseFile).map(courseFileScanner._getCourseFileId);
},
_isCourseFile: (file) => {
return file.entryName.match(/^(?=.*\bcsfiles\/home_dir\b)(?!.*\b.xml\b).*$/ig);
},
_getCourseFileId: (file) => {
let fileName = file.entryName;
let startIndex = fileName.lastIndexOf('xid-') + 4;
let endIndex = fileName.indexOf('_', startIndex);
file.courseFileId = fileName.substring(startIndex, endIndex);
return file;
},
getDatFiles: () => {
return courseZip.getEntries().filter(courseFileScanner._isDatFile);
},
_isDatFile: (file) => {
return file.entryName.match(/^(?=.*res)(?=.*\b\.dat\b).*$/g);
}
};
return courseFileScanner;
}
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
// ESLint configuration
// http://eslint.org/docs/user-guide/configuring
module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:flowtype/recommended',
'plugin:css-modules/recommended',
'prettier',
'prettier/flowtype',
'prettier/react',
],
plugins: ['flowtype', 'css-modules', 'prettier'],
globals: {
__DEV__: true,
},
env: {
browser: true,
},
rules: {
// `js` and `jsx` are common extensions
// `mjs` is for `universal-router` only, for now
'import/extensions': [
'error',
'always',
{
js: 'never',
jsx: 'never',
mjs: 'never',
},
],
// Not supporting nested package.json yet
// https://github.com/benmosher/eslint-plugin-import/issues/458
'import/no-extraneous-dependencies': 'off',
// Recommend not to leave any console.log in your code
// Use console.error, console.warn and console.info instead
'no-console': [
'error',
{
allow: ['warn', 'error', 'info'],
},
],
// a11y removed rule, ignore them
'jsx-a11y/href-no-hash': 'off',
// https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/308#issuecomment-322954274
'jsx-a11y/label-has-for': 'warn',
// Allow js files to use jsx syntax, too
'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }],
// Automatically convert pure class to function by
// babel-plugin-transform-react-pure-class-to-function
// https://github.com/kriasoft/react-starter-kit/pull/961
'react/prefer-stateless-function': 'off',
// ESLint plugin for prettier formatting
// https://github.com/prettier/eslint-plugin-prettier
'prettier/prettier': [
'error',
{
// https://github.com/prettier/prettier#options
singleQuote: true,
trailingComma: 'all',
},
],
},
settings: {
// Allow absolute paths in imports, e.g. import Button from 'components/Button'
// https://github.com/benmosher/eslint-plugin-import/tree/master/resolvers
'import/resolver': {
node: {
moduleDirectory: ['node_modules', 'src'],
},
},
},
};
|
function getShortMessages(messages) {
return messages.map(function(m) {
return m.message;
}).filter(function(message) { return message.length < 50; })
}
module.exports = getShortMessages;
|
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
$scope.authentication = Authentication;
// If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/');
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
console.log(response);
// And redirect to the index page
$location.path('/');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]);
|
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
$("#slide0").addClass("active");
$("#data0").addClass("active");
// JavaScript to be fired on the about us page
}
},
'process': {
init: function() {
$("#design_slide0").addClass("active");
$("#design_data0").addClass("active");
$("#construction_slide0").addClass("active");
$("#administration_slide0").addClass("active");
// JavaScript to be fired on the about us page
}
},
// About us page, note the change from about-us to about_us.
'single_project': {
init: function() {
$("#slide0").addClass("active");
$("#data0").addClass("active");
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
$(function(){
$('#carousel-project-page').carousel({
interval:false
});
});
})(jQuery); // Fully reference jQuery after this point.
|
//{block name="backend/connect/store/import/local_products"}
Ext.define('Shopware.apps.Connect.store.import.LocalProducts', {
extend : 'Ext.data.Store',
autoLoad: false,
pageSize: 10,
fields: [
{ name: 'Article_id', type: 'integer' },
{ name: 'Detail_number', type: 'string' },
{ name: 'Article_name', type: 'string' },
{ name: 'Supplier_name', type: 'string' },
{ name: 'Article_active', type: 'boolean' },
{ name: 'Detail_purchasePrice', type: 'float' },
{ name: 'Price_price', type: 'float' },
{ name: 'Tax_name', type: 'string' },
{ name: 'Attribute_connectMappedCategory', type: 'int' }
],
proxy : {
type : 'ajax',
api : {
read : '{url controller=Import action=loadBothArticleTypes}'
},
reader : {
type : 'json',
root: 'data',
totalProperty:'total'
}
}
});
//{/block}
|
import Microcosm from 'microcosm'
describe('History node children', function() {
const action = n => n
it('can determine children', function() {
const repo = new Microcosm()
const a = repo.append(action)
const b = repo.append(action)
repo.checkout(a)
const c = repo.append(action)
expect(a.children.map(n => n.id)).toEqual([b.id, c.id])
})
it('does not lose children when checking out nodes on the left', function() {
const repo = new Microcosm()
repo.append(action)
const b = repo.append(action)
const c = repo.append(action)
repo.checkout(b)
const d = repo.append(action)
expect(b.children).toEqual([c, d])
})
it('does not lose children when checking out nodes on the right', function() {
const repo = new Microcosm()
repo.append(action)
const b = repo.append(action)
const c = repo.append(action)
repo.checkout(b)
const d = repo.append(action)
repo.checkout(c)
expect(b.children).toEqual([c, d])
})
})
|
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
import {Parser} from "./state"
import {types as tt} from "./tokentype"
import {lineBreak} from "./whitespace"
export class TokContext {
constructor(token, isExpr, preserveSpace, override) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override
}
}
export const types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, p => p.readTmplToken()),
new TokContext("function", true);
}
const pp = Parser.prototype;
pp.initialContext = function() {
return [types.b_stat]
};
pp.braceIsBlock = function(prevType) {
if (prevType === tt.colon) {
let parent = this.curContext();
if (parent === types.b_stat || parent === types.b_expr)
return !parent.isExpr
}
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR)
return true;
if (prevType == tt.braceL)
return this.curContext() === types.b_stat;
return !this.exprAllowed
};
pp.updateContext = function(prevType) {
let update, type = this.type;
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false;
else if (update = type.updateContext)
update.call(this, prevType);
else
this.exprAllowed = type.beforeExpr
};
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true;
return
}
let out = this.context.pop();
if (out === types.b_stat && this.curContext() === types.f_expr) {
this.context.pop();
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
};
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
this.exprAllowed = true
};
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl);
this.exprAllowed = true
};
tt.parenL.updateContext = function(prevType) {
let statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
this.context.push(statementParens ? types.p_stat : types.p_expr);
this.exprAllowed = true
};
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
};
tt._function.updateContext = function() {
if (this.curContext() !== types.b_stat)
this.context.push(types.f_expr);
this.exprAllowed = false
};
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop();
else
this.context.push(types.q_tmpl);
this.exprAllowed = false
};
|
import {eventMixin} from "./event"
export class MarkedRange {
constructor(from, to, options) {
this.options = options || {}
this.from = from
this.to = to
}
clear() {
this.signal("removed", this.from)
this.from = this.to = null
}
}
eventMixin(MarkedRange)
class RangeSorter {
constructor() {
this.sorted = []
}
find(at) {
let min = 0, max = this.sorted.length
for (;;) {
if (max < min + 10) {
for (let i = min; i < max; i++)
if (this.sorted[i].at.cmp(at) >= 0) return i
return max
}
let mid = (min + max) >> 1
if (this.sorted[mid].at.cmp(at) > 0) max = mid
else min = mid
}
}
insert(obj) {
this.sorted.splice(this.find(obj.at), 0, obj)
}
remove(at, range) {
let pos = this.find(at)
for (let dist = 0;; dist++) {
let leftPos = pos - dist - 1, rightPos = pos + dist
if (leftPos >= 0 && this.sorted[leftPos].range == range) {
this.sorted.splice(leftPos, 1)
return
} else if (rightPos < this.sorted.length && this.sorted[rightPos].range == range) {
this.sorted.splice(rightPos, 1)
return
}
}
}
resort() {
for (let i = 0; i < this.sorted.length; i++) {
let cur = this.sorted[i]
let at = cur.at = cur.type == "open" ? cur.range.from : cur.range.to
let pos = i
while (pos > 0 && this.sorted[pos - 1].at.cmp(at) > 0) {
this.sorted[pos] = this.sorted[pos - 1]
this.sorted[--pos] = cur
}
}
}
}
export class RangeStore {
constructor(pm) {
this.pm = pm
this.ranges = []
this.sorted = new RangeSorter
}
addRange(range) {
this.ranges.push(range)
this.sorted.insert({type: "open", at: range.from, range: range})
this.sorted.insert({type: "close", at: range.to, range: range})
this.pm.markRangeDirty(range)
}
removeRange(range) {
let found = this.ranges.indexOf(range)
if (found > -1) {
this.ranges.splice(found, 1)
this.sorted.remove(range.from, range)
this.sorted.remove(range.to, range)
this.pm.markRangeDirty(range)
range.clear()
}
}
transform(mapping) {
for (let i = 0; i < this.ranges.length; i++) {
let range = this.ranges[i]
range.from = mapping.map(range.from, range.options.inclusiveLeft ? -1 : 1).pos
range.to = mapping.map(range.to, range.options.inclusiveRight ? 1 : -1).pos
let diff = range.from.cmp(range.to)
if (range.options.clearWhenEmpty !== false && diff >= 0) {
this.removeRange(range)
i--
} else if (diff > 0) {
range.to = range.from
}
}
this.sorted.resort()
}
activeRangeTracker() {
return new RangeTracker(this.sorted.sorted)
}
}
class RangeTracker {
constructor(sorted) {
this.sorted = sorted
this.pos = 0
this.current = []
}
advanceTo(pos) {
let next
while (this.pos < this.sorted.length && (next = this.sorted[this.pos]).at.cmp(pos) <= 0) {
let className = next.range.options.className
if (!className) continue
if (next.type == "open")
this.current.push(className)
else
this.current.splice(this.current.indexOf(className), 1)
this.pos++
}
}
nextChangeBefore(pos) {
for (;;) {
if (this.pos == this.sorted.length) return null
let next = this.sorted[this.pos]
if (!next.range.options.className)
this.pos++
else if (next.at.cmp(pos) >= 0)
return null
else
return next.at.offset
}
}
}
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('receive-for', 'Integration | Component | receive for', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });"
this.render(hbs`{{receive-for}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:"
this.render(hbs`
{{#receive-for}}
{{else}}
template block text
{{/receive-for}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
// Invoke 'strict' JavaScript mode
'use strict';
var app = angular.module('dashboards', ['ngMaterial']);
// Create the 'Dashboards' controller
angular.module('dashboards').controller('DashboardsController', ['$scope','$http','$q','$mdDialog','$window','$timeout' ,'$routeParams', '$location', 'Authentication', 'Dashboards','Powers','Devices','SmartPlugs','ngDialog','$interval', 'roundProgressService',
function($scope,$http,$q,$mdDialog,$window,$timeout, $routeParams, $location, Authentication, Dashboards,Powers,Devices,SmartPlugs,ngDialog,$interval, roundProgressService) {
// Expose the Authentication service
$scope.authentication = Authentication;
var dashboardList ={};
dashboardList._id='';
dashboardList.creator ='';
dashboardList.devices='';
dashboardList.smartplugs='';
dashboardList.consumption='';
dashboardList.pid='';
dashboardList.created='';
$scope.dashboards= dashboardList;
$scope.search_date_range='';
///////////////////////////////////////////////
//device list and functions
$scope.switchdata = {
cb1: true,
cb4: true,
cb5: false
};
///////////////////////////////////////////////
///////////////////////////////////////////////////
//angular material table
$scope.data = {
selectedIndex: 0,
secondLocked: false,
secondLabel: "Item Two",
bottom: false
};
$scope.next = function() {
$scope.data.selectedIndex = Math.min($scope.data.selectedIndex + 1, 2) ;
};
$scope.previous = function() {
$scope.data.selectedIndex = Math.max($scope.data.selectedIndex - 1, 0);
};
////////////////////////////////////////////////
//table 2 template start
//angular material alert box start
$scope.status = ' ';
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,//DialogController
templateUrl: 'dialog1.tmpl.html',
//scope:$scope,
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
//angular material alert box ends
$scope.isDeviceSelected =false;
//table 2 template ends
/////////////////////////////////////////////////////
var mainList =[{id:0,name:'Yesterday'},{id:1,name:'Today'},{id:2,name:'Current Month'},{id:3,name:'Last Month'},{id:4,name:'Overall'}];
$scope.filterOption = mainList[4].id;
$scope.mainListItems = mainList;
//setting main views on and off start
$scope.costOfOneKWh = parseFloat(2.50);
$scope.basic = true;
$scope.analytics =true;
$scope.analytics_name='Analytics';
$scope.todayGraph=true;
$scope.yesterdayGraph = true;
$scope.lastMonthGraph = true;
$scope.setAnalyticView = function(){
$scope.setStreamLineChartData();
if($scope.analytics==false){
$scope.analytics=true;
$scope.basic=false;
$scope.analytics_name='Basic';
console.log($scope.attrs);
console.log($scope.categories);
console.log($scope.dataset)
}else{
$scope.analytics=false;
$scope.basic=true;
$scope.analytics_name='Analytics';
}
};
$scope.getMonthGraph = function(){
//$scope.setThisMonthGraphData();
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerDayGraph(dateString);
if($scope.analytics==true){
$scope.analytics=false;
$scope.lastMonthGraph=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}else{
$scope.analytics=true;
$scope.lastMonthGraph=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}
};
$scope.getLastMonthGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerDayGraph(dateString);
if($scope.lastMonthGraph==true){
$scope.lastMonthGraph=false;
$scope.analytics=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}else{
$scope.lastMonthGraph=true;
$scope.analytics=true;
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
}
};
$scope.getTodayGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// var dateString = yy+"-"+mm+"-"+dd;
// var dateString = '2015-11-05'
// $scope.getPowerPerHourGraph(dateString);
if($scope.todayGraph==true){
$scope.todayGraph=false;
$scope.yesterdayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}else{
$scope.todayGraph=true;
$scope.yesterdayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}
};
$scope.getYesterdayGraph = function(){
// var date = new Date();
// var dd = date.getDate();
// var mm = date.getMonth();
// var yy = date.getFullYear();
// date = date.toLocaleDateString();
// var dateString = date
//var dateString = yy+"-"+mm+"-"+dd;
// dateString = '2015-11-05'
// $scope.getPowerPerHourGraph(dateString);
if($scope.yesterdayGraph==true){
$scope.yesterdayGraph=false;
$scope.todayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}else{
$scope.yesterdayGraph=true;
$scope.todayGraph=true;
$scope.lastMonthGraph=true;
$scope.analytics=true;
}
};
$scope.setGraphViews = function(){
// $scope.getMonthGraph();
// $scope.getLastMonthGraph();
// $scope.getTodayGraph();
// $scope.getYesterdayGraph();
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
date = date.toLocaleDateString();
var dateString = date
//var dateString = yy+"-"+mm+"-"+dd;
// dateString = '2015-11-05'
$scope.getPowerPerHourGraph(dateString);
$scope.getPowerPerDayGraph(dateString);
};
//setting main views on and off end
//set graph data holding variables start
//this month power
$scope.categories2=[];
$scope.attrs2={};
$scope.dataset2=[];
//this month cost
$scope.categories3=[];
$scope.attrs3={};
$scope.dataset3=[];
//last month power
$scope.categories4=[];
$scope.attrs4={};
$scope.dataset4=[];
//last month cost
$scope.categories5=[];
$scope.attrs5={};
$scope.dataset5=[];
//today power
$scope.categories6=[];
$scope.attrs6={};
$scope.dataset6=[];
//yesterday power
$scope.categories7=[];
$scope.attrs7={};
$scope.dataset7=[];
//today cost
$scope.categories8=[];
$scope.attrs8={};
$scope.dataset8=[];
//yesterday cost
$scope.categories9=[];
$scope.attrs9={};
$scope.dataset9=[];
//set graph data holding variables end
$scope.setGraphAttributes = function(){
//for this month graph
$scope.attrs2 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories2 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//for cost section
$scope.attrs3 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories3 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//last month cost and power section
$scope.attrs4 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories4 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//for cost section
$scope.attrs5 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories5 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
//today and yesterday
$scope.attrs6 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories6 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
$scope.attrs8 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories8 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
//for yesterday
$scope.attrs7 = {
"caption": "",
"numberprefix": " KWh ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories7 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
$scope.attrs9 = {
"caption": "",
"numberprefix": " LKR ",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories9 = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
}
]
}
];
};
$scope.setGraphAttributes();
//calculation constants for power consumption cost end
$scope.init = function(){
$scope.getPatternForHourAll();
$scope.getDataOfCostofPastYears();
$scope.predictionOfCostNextYear();
$scope.setGraphViews();
};
// Create a new controller method for creating new Dashboards
$scope.create = function() {
// Use the form fields to create a new Dashboard $resource object
var Dashboard = new Dashboards({
pid: this.pid,
name: this.name,
consumption: this.consumption,
devices: this.devices,
smartplugs: this.smartplugs
});
// Use the Dashboard '$save' method to send an appropriate POST request
Dashboard.$save(function(response) {
// If an Dashboard was created successfully, redirect the user to the Dashboard's page
$location.path('dashboards/' + response._id);
console.log("Saved Dashboard");
console.log(response);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for retrieving a list of Dashboards
$scope.find = function() {
// Use the Dashboard 'query' method to send an appropriate GET request
var dashboards=[];
$scope.dashboards = Dashboards.query({}, function() {
var count=0;
angular.forEach($scope.dashboards, function(dashboard, key) {
var idevice = Devices.get({deviceId:dashboard.devices},function(){
dashboard.devices=idevice.name;
});
var ismartplug = SmartPlugs.get({smartplugId:dashboard.smartplugs},function(){
dashboard.smartplugs=ismartplug.name;
});
count++;
});//end of loop
dashboards = $scope.dashboards;
});//end of query
return dashboards;
};
// Create a new controller method for retrieving a single Dashboard
$scope.findOne = function() {
// Use the Dashboard 'get' method to send an appropriate GET request
$scope.dashboard = Dashboards.get({dashboardId: $routeParams.dashboardId});
};
///////////////////////////////////////////////
//get the prediction results
$scope.identify = function() {
// Use the Dashboard 'get' method to send an appropriate GET request
$scope.dashboard = Dashboards.get({identity: $routeParams.identity});
console.log('identify');
};
//////////////////////////////////
// Create a new controller method for updating a single Dashboard
$scope.update = function() {
// Use the device '$update' method to send an appropriate PUT request
$scope.dashboard.$update(function() {
// If an device was updated successfully, redirect the user to the device's page
$location.path('dashboards/' + $scope.dashboard._id);
}, function(errorResponse) {
// Otherwise, present the user with the error message
$scope.error = errorResponse.data.message;
});
};
// Create a new controller method for deleting a single Dashboard
$scope.delete = function(dashboard) {
// If an Dashboard was sent to the method, delete it
if (dashboard) {
// Use the Dashboard '$remove' method to delete the Dashboard
Dashboard.$remove(function() {
// Remove the Dashboard from the Dashboards list
for (var i in $scope.dashboards) {
if ($scope.dashboards[i] === dashboard) {
$scope.dashboards.splice(i, 1);
}
}
});
} else {
// Otherwise, use the Dashboard '$remove' method to delete the Dashboard
$scope.dashboard.$remove(function() {
$location.path('dashboards');
});
}
};
//retrieving all the Smart Plugs currently created
$scope.findDevices = function() {
// Use the Dashboard 'query' method to send an appropriate GET request
$scope.deviceList = Devices.query();
$scope.devices = $scope.deviceList[1];
};
$scope.findDevices();
$scope.findSmartPlugs = function() {
// Use the device 'query' method to send an appropriate GET request
$scope.smartplugList = SmartPlugs.query();
$scope.smartplugs = $scope.smartplugList[1];
};
$scope.findSmartPlugs();
//ngDialog Controlling Section Start
$scope.jsonData = '{"foo": "bar"}';
$scope.theme = 'ngdialog-theme-default';
$scope.clickToOpen = function () {
ngDialog.open(
{ template: 'templateId' ,
className: 'ngdialog-theme-flat',
plain: false,
showClose: true,
closeByDocument: true,
closeByEscape: true
});
};
//power calculation functions start
$scope.power_per_device =0;
$scope.getTotalPowerConsumedPerDevice = function(deviceId){
var powersPerDevice=[];
var totalPower=0;
var deviceList = Powers.query({devices:deviceId},function(){
angular.forEach(deviceList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPower+=(consN*10/3600/1000);
//console.log(deviceId);
});//end of foreach
totalPower = parseFloat(totalPower).toFixed(2);
$scope.power_per_device=totalPower;
$scope.power_per_device = parseFloat($scope.power_per_device);
console.log("Total Power Per Device: "+totalPower+" KWh");
$scope.setDataForNgDialog1();
console.log("Power of Device :"+ $scope.power_per_device)
$scope.setGaugeMeterForDevice();
});//end of query
return totalPower;
};
// power per smartplug start
$scope.power_per_smartplug =0;
$scope.getTotalPowerConsumedPerSmartPlug = function(smartplugId){
console.log("smartplug Id: "+smartplugId);
var powersPerSmartPlug=[];
var totalPowerSmartPlug=0;
var smartplugList = Powers.query({smartplugs:smartplugId},function(){
angular.forEach(smartplugList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPowerSmartPlug+=(consN*10/3600/1000);
console.log(smartplugId);
});//end of foreach
totalPowerSmartPlug = parseFloat(totalPowerSmartPlug).toFixed(2);
$scope.power_per_smartplug=totalPowerSmartPlug;
$scope.power_per_smartplug = parseFloat($scope.power_per_smartplug);
console.log("Total Power Per Smartplug: "+totalPowerSmartPlug+" KWh");
$scope.setDataForNgDialog2();
console.log("Power of SmartPlug :"+ $scope.power_per_smartplug)
$scope.setGaugeMeterForSmartPlug();
});//end of query
return totalPowerSmartPlug;
};
//power per smart plug end
$scope.total_power_consumption=0;
$scope.no_of_days_for_total_power=0;
//get power consumption for all devices
$scope.getTotalPowerConsumptionFromEachDevice =function(){
var power=0;
var powers=[];
Devices.query({},function(data){
var totalPower=0;
angular.forEach(data, function(device,key){
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
totalPower+=(consN*10/3600/1000);
// console.log(device._id);
});//end of foreach powerList
console.log("Power :"+totalPower);
$scope.total_power_consumption=parseFloat(totalPower).toFixed(2);
$scope.setGuageMeterForOverall();
$scope.setGaugeMeterForDevice();
$scope.setGaugeMeterForSmartPlug();
});//end of query powerList
//retrieve power for each device start
console.log("Power All: "+power);
}); //end of angular foreach
});//end of query
};
$scope.getTotalPowerConsumptionFromEachDevice();
//power calculation functions end
//get results
$scope.getPowerByDevice = function(){
$scope.getTotalPowerConsumedPerDevice($scope.devices);
};
$scope.getPowerBySmartPlug = function(){
$scope.getTotalPowerConsumedPerSmartPlug($scope.smartplugs);
};
//date range power calculation
$scope.total_power_consumption_per_date_range=0;
$scope.date_range_device_wise_power_list=[];
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice =[];
$scope.dateRangemaxPowerUserInfo=[];
$scope.dateRangeminPowerUserInfo=[];
$scope.dateRangeDateInfo=[];
$scope.getTotalPowerConsumptionFromEachDeviceByDayRange =function(start_date,end_date){
var powerData=[];
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice=[];
$scope.date_range_device_wise_power_list=[];
$scope.dateRangemaxPowerUserInfo=[];
$scope.dateRangeminPowerUserInfo=[];
$scope.dateRangeDateInfo=[];
var mm1 = start_date.split('-')[1];
var dd1 = start_date.split('-')[2];
var yy1 = start_date.split('-')[0];
$scope.dateRangeDateInfo.push({start_date:start_date,end_date:end_date});
var mm2 = end_date.split('-')[1];
var dd2 = end_date.split('-')[2];
var yy2 = end_date.split('-')[0];
Devices.query({},function(data){
var max=0;
var maxDevice='';
var min=10000000000000;
var minDevice='';
angular.forEach(data, function(device,key){
//retrieve power for each device start
var totalPower=0;
var powerList = Powers.query({devices:device._id},function(){
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
var milli = date.getTime();
// console.log("Time: "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());
// console.log("Day : "+date.getDay()+"/ Year: "+date.getFullYear()+" / Month : "+date.getMonth()+"");
var condition1 = (date.getFullYear()>=yy1 && date.getFullYear()<=yy2 );
var condition2 = ((date.getMonth()+1>=mm1) && (date.getMonth()+1<=mm2)) ;
var condition3 = (date.getMonth()>=dd1 && date.getMonth()<=dd2) ;
// console.log(condition1+" "+condition2+" "+condition3);
if( condition1==true && condition2==true && condition3==true ){
totalPower+=(consN*10/3600/1000);
}
// console.log(device._id);
});//end of foreach powerList
//console.log("Total Power Per Device: "+totalPower+" KWh Based On: Day Range: "+yy1+"/"+mm1+"/"+dd1+" - "+yy2+"/"+mm2+"/"+dd2);
totalPower = parseFloat(totalPower);
powerData.push(totalPower);
console.log("device : "+device.name);
console.log("total power: "+totalPower);
//calculate max and min power summary starts
if(max<totalPower){
$scope.dateRangemaxPowerUserInfo.splice(0,1);
max=totalPower.toFixed(2);
maxDevice=device.name;
$scope.dateRangemaxPowerUserInfo.push({maxDevice:maxDevice,max:max});
console.log(max+" <max> "+totalPower)
}
//min power using device
if(min>totalPower){
$scope.dateRangeminPowerUserInfo.splice(0,1);
min=totalPower.toFixed(2);
minDevice=device.name;
$scope.dateRangeminPowerUserInfo.push({minDevice:minDevice,min:min});
console.log(min+" <min> "+totalPower)
}
//calculate the cost for power consumption start
var start= new Date($scope.start_date);
var end= new Date($scope.end_date);
var diff = Math.round((end-start)/(1000*60*60*24));
// console.log('no of days : '+diff);
var cost=[];
cost= $scope.calculateCostPerMonth(totalPower.toFixed(2),diff,0);
//console.log('Cost Array')
//console.log(cost);
//calculate the cost for power consumption end
$scope.dateRangesummaryOnMaximumPowerUsagePerDevice.push({device:device.name, power:totalPower.toFixed(2),cost:cost[0].energy_cost});
//calculate max and min power summary ends
$scope.date_range_device_wise_power_list.push({device:device.name,power:totalPower});
console.log(powerData.length+"/"+data.length);
if(powerData.length==data.length){
var power1=0;
angular.forEach(powerData,function(value,key){
power1+=parseFloat(value);
});
power1= parseFloat(power1).toFixed(2)
$scope.total_power_consumption_per_date_range=power1;
$scope.search_date_range=start_date+"-"+end_date;
console.log("Power Of All Devices: "+ $scope.total_power_consumption_per_date_range);
$scope.dialogModel1 = {
message : power1
};
$scope.setDataForNgDialog();
}
});//end of query powerList
//retrieve power for each device start
// console.log("total power c: "+power);
}); //end of angular foreach
});//end of query
};
$scope.getTotalPowerConsumptionByDateRange = function(start_date,end_date){
var mm1 = start_date.split('-')[1];
var dd1 = start_date.split('-')[2];
var yy1 = start_date.split('-')[0];
var mm2 = end_date.split('-')[1];
var dd2 = end_date.split('-')[2];
var yy2 = end_date.split('-')[0];
start_date = new Date(start_date);
end_date = new Date(end_date);
var totalPower=0;
var powers = Powers.query({},function(data){
angular.forEach(data,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
var milli = date.getTime();
if(date>=start_date && date <= end_date){
totalPower+=(consN*10/3600/1000);
}
});
$scope.totalPowerByDateRange = totalPower.toFixed(2);
});
};
//ngDialog code
$scope.dialogModel = {
message : 'message from passed scope'
};
$scope.openSecond = function () {
ngDialog.open({
template: '<h3><a href="" ng-click="closeSecond()">Close all by click here!</a></h3>',
plain: true,
closeByEscape: false,
controller: 'SecondModalCtrl',
data: $scope.total_power_consumption_per_date_range,
scope:$scope
});
};
$scope.openFirst = function () {
console.log("Power : "+$scope.total_power_consumption_per_date_range);
$scope.jsonData1 = {foo: $scope.total_power_consumption_per_date_range};
console.log('Form Json data: ')
console.log( $scope.jsonData1.foo);
ngDialog.open({
template: '<h2>Value: <code>{{total_power_consumption_per_date_range}}</code></h2>',
plain: true,
closeByEscape: false,
controller: 'DashboardsController',
data: $scope.jsonData1,
scope:$scope
});
};
$scope.setDataForNgDialog = function(){
var start= new Date($scope.start_date);
var end= new Date($scope.end_date);
//console.log('start: '+start);
// console.log('end: '+end);
var diff = Math.round((end-start)/(1000*60*60*24));
// console.log('no of days : '+diff);
$scope.calculateCostPerMonth($scope.total_power_consumption_per_date_range,diff,0);
var cost = $scope.costOfConsumptionPerDateRange;
$scope.jsonData1 = {power: $scope.total_power_consumption_per_date_range,daterange: $scope.search_date_range, moreinfo:$scope.date_range_device_wise_power_list,summary:$scope.dateRangesummaryOnMaximumPowerUsagePerDevice,maxInfo: $scope.dateRangemaxPowerUserInfo,minInfo:$scope.dateRangeminPowerUserInfo,dateRange:$scope.dateRangeDateInfo,totalCost:cost};
};
$scope.setDataForNgDialog1 = function(){
$scope.jsonData2 = {power: $scope.power_per_device,totalpower: $scope.total_power_consumption};
console.log("jsondata2.power : "+$scope.jsonData2.power)
$scope.setGaugeMeterForDevice();
};
$scope.setDataForNgDialog2 = function(){
$scope.jsonData3 = {power: $scope.power_per_smartplug,totalpower: $scope.total_power_consumption};
console.log("jsondata2.power : "+$scope.jsonData3.power)
$scope.setGaugeMeterForSmartPlug();
};
$scope.setDataForNgDialogActivationTime = function(){
var active_time= $scope.processAcivationDeviceTime($scope.deviceActivateTime);
var deviceInfo = $scope.deviceProfile_SelectedDevice;
$scope.jsonData4 = {list: $scope.deviceActivateTime,len: $scope.deviceActivateTime.length,active:active_time,deviceInfo:deviceInfo};
};
$scope.setDataForNgDialogGraphDetails = function(){
$scope.setAnalyticChartInfo();
console.log('My Data Source');
console.log($scope.myDataSource);
$scope.jsonData8 = {dataSource:$scope.myDataSource};
};
//get the time ranges and make prediction start
$scope.processAcivationDeviceTime = function(list){
//data
var on_off_set=[];
var block=[];
console.log('===========Activation Time Process==========');
for(var i=list.length-1;i>0;i--){
var t1 = list[i].time;
var t2 = list[i-1].time;
var t = t2-t1;
if(t<=180000 ){
console.log(i+"->"+t1);
block.push({index:i,date:t1});
//this condition detects if the last data set contains a block or not
if(block.length>0 && i==1){
//console.log("block:");
//console.log(block);
on_off_set.push(block);
block=[];
}
}
else{
if(block.length>0){
//console.log("block:");
// console.log(block);
on_off_set.push(block);
block=[];
}
}
// console.log("diff :"+t+" ==>"+t1+"---"+t2);
}
console.log("array length blcok: "+on_off_set.length)
for(var k=0;k<on_off_set.length;k++){
console.log(on_off_set[k]);
}
return on_off_set;
};
//get the time ranges and make prediction end
//gauge meter per device start
$scope.setGaugeMeterForDevice = function(){
//ng Guage Meter Start - For Device Overall Consumption
var meter_reading_device = parseFloat($scope.power_per_device);
console.log("meter reading devices: "+meter_reading_device);
$scope.value1 = meter_reading_device ;
$scope.upperLimit1 = Math.ceil($scope.total_power_consumption);
$scope.lowerLimit1 = 0;
$scope.unit1= "kWh";
$scope.precision1 = 2;
$scope.ranges1 = [
{
min: 0,
max: $scope.upperLimit1/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit1/5,
max: 2*$scope.upperLimit1/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit1/5,
max: 3*$scope.upperLimit1/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit1/5,
max: 4*$scope.upperLimit1/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit1/5,
max: $scope.upperLimit1,
color: '#C50200'
}
];
//ng Gauge Meter For Overall Device Consumption End
console.log("setGaugeMeterForDevice");
};
//gauge meter per smartplug start
$scope.setGaugeMeterForSmartPlug = function(){
//ng Guage Meter Start - For Device Overall Consumption
var meter_reading_smartplug = parseFloat($scope.power_per_smartplug);
console.log("meter reading devices: "+meter_reading_smartplug);
$scope.value2 = meter_reading_smartplug ;
$scope.upperLimit2 = Math.ceil($scope.total_power_consumption);
$scope.lowerLimit2 = 0;
$scope.unit2= "kWh";
$scope.precision2 = 2;
$scope.ranges2 = [
{
min: 0,
max: $scope.upperLimit2/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit2/5,
max: 2*$scope.upperLimit2/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit2/5,
max: 3*$scope.upperLimit2/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit2/5,
max: 4*$scope.upperLimit2/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit2/5,
max: $scope.upperLimit2,
color: '#C50200'
}
];
//ng Gauge Meter For Overall Device Consumption End
console.log("setGaugeMeterForSmartPlug");
};
//for device update gauge start
function update1() {
$timeout(function() {
if($scope.power_per_device!=0){
$scope.value1= $scope.power_per_device;
$scope.upperLimit1= $scope.power_per_device + 10;
console.log("Upper limit: "+$scope.upperLimit1);
console.log($scope.value1+"**"+$scope.upperLimit1+"##"+$scope.power_per_device);
if ($scope.value1 > $scope.upperLimit1) {
$scope.value1=$scope.lowerLimit1;
}
}
update1();
}, 1000);
}
update1();
//device update gauge ends
//smartplug update gauge start
function update2() {
$timeout(function() {
if($scope.power_per_smartplug!=0){
$scope.value2= $scope.power_per_smartplug;
$scope.upperLimit2= $scope.power_per_smartplug + 10;
console.log("Upper limit: "+$scope.upperLimit1);
console.log($scope.value2+"**"+$scope.upperLimit2+"##"+$scope.power_per_smartplug);
if ($scope.value2 > $scope.upperLimit2) {
$scope.value2=$scope.lowerLimit2;
}
}
update2();
}, 1000);
}
update2();
//smartplug update gauge ends
///////////////////////////////////////////////////////////////////////////////
$scope.current = 27;
$scope.max = 50;
$scope.timerCurrent = 0;
$scope.uploadCurrent = 0;
$scope.stroke = 15;
$scope.radius = 60;
$scope.isSemi = false;
$scope.rounded = false;
$scope.responsive = false;
$scope.clockwise = true;
$scope.currentColor = '#45ccce';
$scope.bgColor = '#eaeaea';
$scope.duration = 800;
$scope.currentAnimation = 'easeOutCubic';
$scope.increment = function(amount){
$scope.current+=(amount || 1);
};
$scope.decrement = function(amount){
$scope.current-=(amount || 1);
};
$scope.animations = [];
angular.forEach(roundProgressService.animations, function(value, key){
$scope.animations.push(key);
});
$scope.getStyle = function(){
var transform = ($scope.isSemi ? '' : 'translateY(-50%) ') + 'translateX(-50%)';
return {
'top': $scope.isSemi ? 'auto' : '50%',
'bottom': $scope.isSemi ? '5%' : 'auto',
'left': '50%',
'transform': transform,
'-moz-transform': transform,
'-webkit-transform': transform,
'font-size': $scope.radius/3.5 + 'px'
};
};
$scope.getColor = function(){
return $scope.gradient ? 'url(#gradient)' : $scope.currentColor;
};
var getPadded = function(val){
return val < 10 ? ('0' + val) : val;
};
$interval(function(){
var date = new Date();
var secs = date.getSeconds();
$scope.timerCurrent = secs;
$scope.time = getPadded(date.getHours()) + ':' + getPadded(date.getMinutes()) + ':' + getPadded(secs);
}, 1000);
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//angular gauge meter panels
$scope.openGauages = function () {
ngDialog.open({
template: 'views/popupTmpl.html',
plain: true,
closeByEscape: false,
controller: 'DashboardsController',
scope:$scope
});
};
//angular gauge meter code start
//ng Guage Meter Start - For Overall Consumption
$scope.setGuageMeterForOverall = function(){
var meter_reading = parseFloat($scope.total_power_consumption);
console.log("meter reading: "+meter_reading)
var meter_reading1 = 3;
$scope.value = meter_reading;
$scope.upperLimit = meter_reading + 20.00;
$scope.lowerLimit = 0;
$scope.unit = "kWh";
$scope.precision = 2;
$scope.ranges = [
{
min: 0,
max: $scope.upperLimit/5,
color: '#DEDEDE'
},
{
min: $scope.upperLimit/5,
max: 2*$scope.upperLimit/5,
color: '#8DCA2F'
},
{
min: 2*$scope.upperLimit/5,
max: 3*$scope.upperLimit/5,
color: '#FDC702'
},
{
min: 3*$scope.upperLimit/5,
max: 4*$scope.upperLimit/5,
color: '#FF7700'
},
{
min: 4*$scope.upperLimit/5,
max: $scope.upperLimit,
color: '#C50200'
}
];
};
function update() {
$timeout(function() {
$scope.value= $scope.value;
//console.log($scope.value+" "+$scope.upperLimit);
if ($scope.value > $scope.upperLimit) {
$scope.value=$scope.lowerLimit;
}
update();
}, 1000);
}
update();
//////////////////////////////////////////////////////////////
//calculate the on of times of a device start
$scope.deviceActivateTime =[];
$scope.deviceProfile_SelectedDevice='';
$scope.getActivationDetails = function(device){
if($scope.isDeviceSelected==false){
$scope.isDeviceSelected=true;
}
$scope.getActivatedTimeOfDevice(device);
};
$scope.getActivatedTimeOfDevice = function(device){
var i=0;
$scope.deviceActivateTime =[];
$scope.deviceProfile_SelectedDevice=device;
var powerlist = Powers.query({devices:device._id},function(){//start of power loop
angular.forEach(powerlist,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
$scope.deviceActivateTime.push({id:i,time:date});
i++;
});
if($scope.deviceActivateTime.length>0){
console.log("Length of activate time : "+$scope.deviceActivateTime.length)
$scope.dialogModelActivationTime = {
message : $scope.deviceActivateTime.length
};
$scope.setDataForNgDialogActivationTime();
}
});//end of power loop
};
//calculate the on of times of device end
/////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the summary starts
$scope.summaryOnMaximumPowerUsagePerDevice =[];
$scope.maxPowerUserInfo=[];
$scope.minPowerUserInfo=[];
$scope.getSummaryOnMaximumPowerUsagePerDevice = function(){//function start
var infoList=[];
var deviceList = Devices.query({},function(){//start device list
var powerPerDevice=0;
var max=0;
var maxDevice='';
var min=10000000000000;
var minDevice='';
angular.forEach(deviceList,function(device,key){//devicelist for loop start
var powerList = Powers.query({devices:device._id},function(){//powerlist for loop start
powerPerDevice=0;
angular.forEach(powerList,function(power,key){//power for loop start
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseFloat(consumSplit[0]);
powerPerDevice+=(consN*10/3600/1000);
}); //power for loop end
console.log("Device: "+device.name+" , Power Consumption : "+powerPerDevice.toFixed(2));
//max power using device
if(max<powerPerDevice){
$scope.maxPowerUserInfo.splice(0,1);
max=powerPerDevice.toFixed(2);
maxDevice=device.name;
$scope.maxPowerUserInfo.push({maxDevice:maxDevice,max:max});
console.log(max+" <max> "+powerPerDevice)
}
//min power using device
if(min>powerPerDevice){
$scope.minPowerUserInfo.splice(0,1);
min=powerPerDevice.toFixed(2);
minDevice=device.name;
$scope.minPowerUserInfo.push({minDevice:minDevice,min:min});
console.log(min+" <min> "+powerPerDevice)
}
$scope.summaryOnMaximumPowerUsagePerDevice.push({device:device.name, power:powerPerDevice.toFixed(2)});
});//powerlist for loop end
//get max power usage device
});//devicelist for loop ends
});//end device list
};//function ends
$scope.getSummaryOnMaximumPowerUsagePerDevice();
//summary ends
//cost calculation algorithm start
//calculation constants for power consumption cost start
//information url:
//http://leco.lk/?page_id=549
$scope.price_per_kwh=parseFloat(5.00);
var domesticCalculationBelow60={};
domesticCalculationBelow60.level=60;
domesticCalculationBelow60.range1_low=0;
domesticCalculationBelow60.range1_high=30;
domesticCalculationBelow60.range2_low=31;
domesticCalculationBelow60.range2_high=60;
domesticCalculationBelow60.range1_energy_charge=parseFloat(2.50);
domesticCalculationBelow60.range1_fixed_charge=parseFloat(30.00);
domesticCalculationBelow60.range2_energy_charge=parseFloat(4.85);
domesticCalculationBelow60.range2_fixed_charge=parseFloat(60.00);
domesticCalculationBelow60.ranges_energy_charge=[2.50,4.85,0,0,0];
domesticCalculationBelow60.ranges_fixed_charge=[30,60,0,0,0];
// 61-90 10.00 90
// 91-120 27.75 480
// 121-180 32.00 480
// >180 45.00 540
var domesticCalculationOver60={};
domesticCalculationOver60.level=60;
domesticCalculationOver60.range1_low=61;
domesticCalculationOver60.range1_high=90;
domesticCalculationOver60.range2_low=91;
domesticCalculationOver60.range2_high=120;
domesticCalculationOver60.range3_low=121;
domesticCalculationOver60.range3_high=180;
domesticCalculationOver60.range4_low=181;
domesticCalculationOver60.range4_high=100000;
domesticCalculationOver60.range1_energy_charge=parseFloat(10.00);
domesticCalculationOver60.range1_fixed_charge=parseFloat(90.00);
domesticCalculationOver60.range2_energy_charge=parseFloat(27.75);
domesticCalculationOver60.range2_fixed_charge=parseFloat(480.00);
domesticCalculationOver60.range3_energy_charge=parseFloat(32);
domesticCalculationOver60.range3_fixed_charge=parseFloat(480.00);
domesticCalculationOver60.range4_energy_charge=parseFloat(45.00);
domesticCalculationOver60.range4_fixed_charge=parseFloat(540.00);
domesticCalculationOver60.ranges_energy_charge=[7.85,10.00,27.75,32.00,45.00];
domesticCalculationOver60.ranges_fixed_charge=[0,90,480,480,540];
domesticCalculationOver60.ranges_fixed_charge_cut_off=[60,90,120,180,181];
$scope.costOfConsumptionPerDateRange = 0;
//calculating cost per month start
$scope.calculateCostPerMonth = function(units,days,type){
console.log('Bill Calculating');
console.log('=========================================');
var cost=0;
var costs=[];
//domestic type =0;
if(type==0){
console.log('This is domestic billing...');
if(units<=domesticCalculationBelow60.level){
var blocksize = days *2;
var currentUnit=units;
var block=[];
if(days<units){//block check if start
var no_of_blocks = Math.floor(units/days) ;
for(var i=0;i<5;i++){
if(currentUnit>=0 && i<4){
if(i==0 && currentUnit-blocksize>0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(i==3 && currentUnit-blocksize>=0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(currentUnit-days<=0){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}else{
block.push({id:i,val:days});
currentUnit-=days;
}
}
}
}else if(currentUnit>=0 && i==4){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}
}
console.log('no of blocks :'+no_of_blocks);
var cost=0;
for(var i=0;i<5;i++){
console.log(block[i].id+' - '+block[i].val);
cost+= block[i].val * domesticCalculationBelow60.ranges_energy_charge[i];
}
costs.push({id:'energy_cost',energy_cost:cost});
if(units>domesticCalculationBelow60.ranges_fixed_charge[0] ){
cost+=domesticCalculationBelow60.ranges_fixed_charge[1];
}else{
cost+=domesticCalculationBelow60.ranges_fixed_charge[0];
}
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',fixed_cost:cost});
}else{
costs.push({id:'energy_cost',energy_cost:(units*parseFloat(2.50)).toFixed(2)});
cost=((units*parseFloat(2.50) +parseFloat(30.00)).toFixed(2));
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',fixed_cost:cost});
}
}
if(units>domesticCalculationOver60.level){
var blocksize = days *2;
var currentUnit=units;
var block=[];
if(days<units){//block check if start
var no_of_blocks = Math.floor(units/days) ;
for(var i=0;i<5;i++){
if(currentUnit>=0 && i<4){
if(i==0 && currentUnit-blocksize>0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(i==3 && currentUnit-blocksize>=0){
block.push({id:i,val:blocksize});
currentUnit-=blocksize;
}else{
if(currentUnit-days<=0){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}else{
block.push({id:i,val:days});
currentUnit-=days;
}
}
}
}else if(currentUnit>=0 && i==4){
block.push({id:i,val:currentUnit});
currentUnit-=currentUnit;
}
}
console.log('no of blocks :'+no_of_blocks);
for(var i=0;i<5;i++){
console.log(block[i].id+' - '+block[i].val);
cost+= block[i].val * domesticCalculationOver60.ranges_energy_charge[i];
}
console.log('Cost : '+cost);
costs.push({id:'energy_cost',energy_cost:cost});
if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[0] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[0];
}else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[1] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[1];
}
else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[2] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[2];
}
else if(units<domesticCalculationOver60.ranges_fixed_charge_cut_off[3] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[3];
}
else if(units>domesticCalculationOver60.ranges_fixed_charge_cut_off[4] ){
cost+=domesticCalculationOver60.ranges_fixed_charge[4];
}
console.log('Cost : '+cost);
costs.push({id:'fixed_cost',energy_cost:cost});
}
}
}//type 0 ends domestic
if(type='religious'){
}
if(type='hotel'){
}
if(type='industrial'){
}
console.log('=========================================');
$scope.costOfConsumptionPerDateRange=cost;
return costs;
};
//calculating cost per month end
//calculating cost per month start
$scope.calculateCostPerDay = function(units,days){
};
//calculating cost per month end
//calculating cost per month start
$scope.calculateCostPerYear = function(units,days){
};
//calculating cost per month end
//cost calculation algorithm ends
//get main list selected item and process data start
$scope.mainTodayOverallPower=[];
$scope.mainTodayTotalPower=0;
$scope.mainTodayTotalPowerCost=0;
$scope.mainTodayCostOfKWH= parseFloat(2.50);
$scope.isToday=false;
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
$scope.isYesterday=false;
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
$scope.isThisMonth=false;
$scope.mainLastMonthOverallPower=[];
$scope.mainLastMonthTotalPower=0;
$scope.mainLastMonthTotalPowerCost=0;
$scope.mainLastMonthCostOfKWH= parseFloat(2.50);
$scope.isLastMonth=false;
$scope.getMainListSearch = function(item){
if($scope.mainListItems[item].id==0){
//yesterday
$scope.isYesterday=true;
$scope.isToday=false;
$scope.isThisMonth=false;
$scope.isLastMonth=false;
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
//var tempDateString ="2015-11-25";
dateString = date.toLocaleDateString();
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==1){
//today
$scope.isToday=true;
$scope.isYesterday=false;
$scope.isThisMonth=false;
$scope.isLastMonth=false;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
// $window.alert($scope.mainListItems[item].name+"**"+'today :'+date);
// var tempDateString ="2015-09-16";
dateString = date.toLocaleDateString();
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==2){
//current month
$scope.isThisMonth=true;
$scope.isLastMonth=false;
$scope.isToday=false;
$scope.isYesterday=false;
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==3){
//last month
$scope.isThisMonth=false;
$scope.isLastMonth=true;
$scope.isToday=false;
$scope.isYesterday=false;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
if($scope.mainListItems[item].id==4){
//overall
$scope.isToday=true;
$scope.isYesterday=true;
$scope.isThisMonth=true;
$scope.isLastMonth=true;
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth();
var yy = date.getFullYear();
var dateString = yy+"-"+(mm+1)+"-"+dd;
dateString = date.toLocaleDateString();
// var tempDateString ="2015-09-16";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(dateString);
}
}
//get main list selected item and process data end
//
//get total power consumption per device per day
$scope.getTotalPowerConsumptionFromEachDeviceByDay =function(start_date){
$scope.mainTodayOverallPower=[];
$scope.mainTodayTotalPower=0;
$scope.mainTodayTotalPowerCost=0;
$scope.mainTodayCostOfKWH= parseFloat(2.50);
$scope.mainTodayOverallPowerCost=[];
$scope.mainYesterdayOverallPower=[];
$scope.mainYesterdayTotalPower=0;
$scope.mainYesterdayTotalPowerCost=0;
$scope.mainYesterdayCostOfKWH= parseFloat(2.50);
$scope.mainYesterdayOverallPowerCost=[];
$scope.mainThisMonthOverallPower=[];
$scope.mainThisMonthTotalPower=0;
$scope.mainThisMonthTotalPowerCost=0;
$scope.mainThisMonthCostOfKWH= parseFloat(2.50);
$scope.mainThisMonthOverallPowerCost=[];
$scope.mainLastMonthOverallPower=[];
$scope.mainLastMonthTotalPower=0;
$scope.mainLastMonthTotalPowerCost=0;
$scope.mainLastMonthCostOfKWH= parseFloat(2.50);
$scope.mainLastMonthOverallPowerCost=[];
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
var powerOfAllDevices=0;
console.log(yy+"-"+mm+"-"+dd);
Devices.query({},function(data){
angular.forEach(data, function(device,key){
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
var totalPower=0;
var totalPowerYesterday=0;
var totalPowerThisMonth=0;
var totalPowerLastMonth=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
// console.log(device.name+'-'+date);
// console.log("Time: "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());
console.log("Day : "+date.getDate()+"/ Year: "+date.getFullYear()+" / Month : "+(date.getMonth()+1)+"");
//get today power
if(mm==(date.getMonth()+1) && (dd)==date.getDate() && yy==date.getFullYear()){
totalPower+=(consN*10/3600/1000);
}
//get yesterday power
if(mm==(date.getMonth()+1) && (dd-1)==(date.getDate()) && yy==date.getFullYear()){
totalPowerYesterday+=(consN*10/3600/1000);
}
//get this month power
if((mm-1)==(date.getMonth()) && yy==date.getFullYear()){
totalPowerThisMonth+=(consN*10/3600/1000);
}
//get last month power
if((mm-2)==(date.getMonth()) && yy==date.getFullYear()){
totalPowerLastMonth+=(consN*10/3600/1000);
}
// console.log(device._id);
});//end of foreach powerList
console.log(device.name+" : "+totalPower+" KWh Based On: "+mm+"/"+dd+"/"+yy);
powerOfAllDevices+=totalPower;
$scope.mainTodayOverallPower.push({device:device.name,power:totalPower});
$scope.mainTodayTotalPower +=totalPower;
var costOfTodayPower = $scope.mainTodayCostOfKWH * totalPower;
$scope.mainTodayOverallPowerCost.push({device:device.name,cost:costOfTodayPower});
console.log($scope.mainTodayOverallPowerCost);
$scope.mainYesterdayOverallPower.push({device:device.name,power:totalPowerYesterday});
$scope.mainYesterdayTotalPower +=totalPowerYesterday;
var costOfYesterdayPower = $scope.mainYesterdayCostOfKWH * totalPowerYesterday;
$scope.mainYesterdayOverallPowerCost.push({device:device.name,cost:costOfYesterdayPower});
$scope.mainThisMonthOverallPower.push({device:device.name,power:totalPowerThisMonth});
$scope.mainThisMonthTotalPower +=totalPowerThisMonth;
var costsThisMonth= $scope.calculateCostPerMonth(totalPowerThisMonth,30,0);
$scope.mainThisMonthOverallPowerCost.push({device:device.name,cost:costsThisMonth});
$scope.mainLastMonthOverallPower.push({device:device.name,power:totalPowerLastMonth});
$scope.mainLastMonthTotalPower +=totalPowerLastMonth;
var costsLastMonth= $scope.calculateCostPerMonth(totalPowerLastMonth,30,0);
$scope.mainLastMonthOverallPowerCost.push({device:device.name,cost:costsLastMonth});
if(data.length==$scope.mainTodayOverallPower.length){
var val = ($scope.mainTodayTotalPower * $scope.mainTodayCostOfKWH);
//val = parseFloat(val).toFixed(2);
$scope.mainTodayTotalPowerCost=val;
}
if(data.length==$scope.mainYesterdayOverallPower.length){
var val = ($scope.mainYesterdayTotalPower * $scope.mainYesterdayCostOfKWH);
//val = parseFloat(val).toFixed(2);
$scope.mainYesterdayTotalPowerCost=val;
}
if(data.length==$scope.mainThisMonthOverallPower.length){
var val = ($scope.mainThisMonthTotalPower);
var pow=0;
angular.forEach($scope.mainThisMonthOverallPower,function(value,key){
pow+=value.power;
});
$scope.mainThisMonthTotalPower=pow;
var costs= $scope.calculateCostPerMonth($scope.mainThisMonthTotalPower,30,0);
var energy_cost = costs[0].energy_cost;
var fixed_cost = costs[1].fixed_cost;
console.log('this month fixed cost: '+fixed_cost);
console.log('this month energy cost: '+energy_cost);
$scope.mainThisMonthTotalPowerCost=energy_cost;
console.log($scope.mainThisMonthTotalPowerCost);
}
if(data.length==$scope.mainLastMonthOverallPower.length){
if(totalPowerLastMonth==0){
$scope.mainLastMonthTotalPower=parseFloat(0.00);
}
var pow=0;
angular.forEach($scope.mainLastMonthOverallPower,function(value,key){
pow+=value.power;
});
$scope.mainLastMonthTotalPower=pow;
var costs= $scope.calculateCostPerMonth($scope.mainLastMonthTotalPower,30,0);
var energy_cost = costs[0].energy_cost;
var fixed_cost = costs[1].fixed_cost;
console.log('last month fixed cost: '+fixed_cost);
console.log('last month energy cost: '+energy_cost);
$scope.mainLastMonthTotalPowerCost=energy_cost;
console.log($scope.mainLastMonthTotalPowerCost);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//draw chart
$scope.myDataSource={};
$scope.setAnalyticChartInfo = function(){
};
$scope.myDataSource = {
chart: {
caption: "Harry's SuperMart",
subCaption: "Top 5 stores in last month by revenue",
numberPrefix: "$",
theme: "fint"
},
data: [{
label: "Bakersfield Central",
value: "880000"
}, {
label: "Garden Groove harbour",
value: "730000"
}, {
label: "Los Angeles Topanga",
value: "590000"
}, {
label: "Compton-Rancho Dom",
value: "520000"
}, {
label: "Daly City Serramonte",
value: "330000"
}]
};
$scope.myDataSourcePie = {
chart: {
caption: "Age profile of website visitors",
subcaption: "Last Year",
startingangle: "120",
showlabels: "0",
showlegend: "1",
enablemultislicing: "0",
slicingdistance: "15",
showpercentvalues: "1",
showpercentintooltip: "0",
plottooltext: "Age group : $label Total visit : $datavalue",
theme: "fint"
},
data: [
{
label: "Teenage",
value: "1250400"
},
{
label: "Adult",
value: "1463300"
},
{
label: "Mid-age",
value: "1050700"
},
{
label: "Senior",
value: "491000"
}
]
};
/* $scope.attrs={};
$scope.categories=[];
$scope.dataset=[];*/
//stream line char data
$scope.setStreamLineChartData = function(){
$scope.attrs = {
"caption": "Sales Comparison: 2013 versus 2014",
"subCaption": "Harry's SuperMart",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categories = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.dataset = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "21800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "27600"
}, {
"value": "26800"
}, {
"value": "27700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
//this month Graph Data Set
$scope.setThisMonthGraphData = function(){
$scope.attrsThisMonth = {
"caption": "This Month",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesThisMonth = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetThisMonth = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
//set last month graph data
$scope.setLastMonthGraphData =function(){
$scope.attrsLastMonth = {
"caption": "Last Month",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesLastMonth = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetLastMonth = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setTodayGraphData = function(){
$scope.attrsToday = {
"caption": "Today",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesToday = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetToday = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setYesterdayGraphData = function(){
$scope.attrsYesterday = {
"caption": "Yesterday",
"subCaption": "Gasta Homes ",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesYesterday = [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}];
$scope.datasetYesterday = [{
"seriesname": "2013",
"data": [{
"value": "22400"
}, {
"value": "24800"
}, {
"value": "1800"
}, {
"value": "21800"
}, {
"value": "24600"
}, {
"value": "600"
}, {
"value": "26800"
}, {
"value": "20700"
}, {
"value": "23700"
}, {
"value": "25900"
}, {
"value": "26800"
}, {
"value": "24800"
}]
},
{
"seriesname": "2012",
"data": [{
"value": "10000"
}, {
"value": "11500"
}, {
"value": "12500"
}, {
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17600"
}, {
"value": "18800"
}, {
"value": "19700"
}, {
"value": "21700"
}, {
"value": "21900"
}, {
"value": "22900"
}, {
"value": "20800"
}]
}
];
};
$scope.setStreamLineChartData();
$scope.setThisMonthGraphData();
$scope.setLastMonthGraphData();
$scope.setTodayGraphData();
$scope.setYesterdayGraphData();
//generate data dynamically for graphs
$scope.getPowerPerDayGraph = function(start_date){
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
var selectedMonth ;
$scope.dataset2=[];
$scope.dataset3=[];
$scope.dataset4=[];
$scope.dataset5=[];
var maxPar =0;
var maxParLastMonth=0;
var days = [];
for (var i=1; i<=31; i++) {
days.push({day:i});
}
var data=[];
var dataLastMonth=[];
var monthlist = [{key:'1',month:'1',days:31},{key:'2',month:'2',days:31},{key:'3',month:'3',days:31},{key:'4',month:'4',days:31},{key:'5',month:'5',days:31},{key:'6',month:'6',days:31},{key:'7',month:'7',days:31},{key:'8',month:'8',days:31},{key:'9',month:'9',days:31},{key:'10',month:'10',days:31},{key:'11',month:'11',days:31},{key:'12',month:'12',days:31}];
var powerOfAllDevices=0;
Devices.query({},function(devicesData){
angular.forEach(devicesData, function(device,key){
var plotData = [];
var plotDataLastMonth=[];
var plotObject=[];
var plotObjectLastMonth=[];
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
// console.log(device._id)
// console.log(device._id+" "+(key+1))
angular.forEach(days,function(val1,key){//days loop start
var totalPower=0;
var totalPowerLastMonth=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
// console.log(date);
// console.log(date+"===>"+date.getFullYear()+"-"+((date.getMonth())+1)+"-"+date.getDate())
//calculation for this month
if( mm==((date.getMonth())+1) && yy==date.getFullYear() && (val1.day)==date.getDate() ){
totalPower+=(consN*10/3600/1000);
powerOfAllDevices+=(consN*10/3600/1000);
selectedMonth=date;
}
//calculation for last month
if( (mm-2)==((date.getMonth())) && yy==date.getFullYear() && (val1.day)==date.getDate() ){
totalPowerLastMonth+=(consN*10/3600/1000);
selectedMonth=date;
}
});//end of foreach powerList
plotData.push({value:totalPower});
plotDataLastMonth.push({value:totalPowerLastMonth});
if(maxPar==0){
maxPar=totalPower;
}else if(totalPower>maxPar){
maxPar=totalPower;
}else{
maxPar=maxPar;
}
if(maxParLastMonth==0){
maxParLastMonth=totalPowerLastMonth;
}else if(totalPowerLastMonth>maxParLastMonth){
maxParLastMonth=totalPowerLastMonth;
}else{
maxParLastMonth=maxParLastMonth;
}
});//days loop end
// var month = selectedMonth.toString().split(' ')[1];
plotObject.push({seriesname:device.name,data:plotData});
plotObjectLastMonth.push({seriesname:device.name,data:plotDataLastMonth});
data.push(plotObject);
dataLastMonth.push(plotObjectLastMonth);
/* $scope.dataset2.push({seriesname:device.name,data:plotData});
$scope.attrs2.caption='Power Consumption of Month - '+mm;
// console.log("maxPar: "+maxPar)
$scope.attrs2.yaxismaxvalue = Math.ceil(maxPar);*/
if(data.length==devicesData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var monthdata=[];
var monthdataCost=[];
for(var j=0;j<data[data.length-1][0].data.length;j++){
var val=0;
var cost=0;
for(var i=0;i<data.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
val+=data[i][0].data[j].value;
}
cost = val * $scope.costOfOneKWh;
monthdataCost.push({value:cost});
monthdata.push({value:val});
}
$scope.dataset2.push({seriesname:'Current Month ',data:monthdata});
$scope.dataset3.push({seriesname:'Current Month ',data:monthdataCost});
$scope.attrs2.caption='Power Consumption of Month - '+mm;
$scope.attrs3.caption='Cost of Consumption on Month - '+mm;
// console.log("maxPar: "+maxPar)
$scope.attrs2.yaxismaxvalue = Math.ceil(maxPar);
$scope.attrs3.yaxismaxvalue = Math.ceil(maxPar*$scope.costOfOneKWh);
}
if(dataLastMonth.length==devicesData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var monthdataLastMonth=[];
var monthdataCostLastMonth=[];
for(var j=0;j<dataLastMonth[dataLastMonth.length-1][0].data.length;j++){
var valLastMonth=0;
var costLastMonth=0;
for(var i=0;i<dataLastMonth.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
valLastMonth+=dataLastMonth[i][0].data[j].value;
}
costLastMonth = valLastMonth * $scope.costOfOneKWh;
monthdataCostLastMonth.push({value:costLastMonth});
monthdataLastMonth.push({value:valLastMonth});
}
$scope.dataset4.push({seriesname:'Last Month ',data:monthdataLastMonth});
$scope.dataset5.push({seriesname:'Last Month ',data:monthdataCostLastMonth});
$scope.attrs4.caption='Power Consumption of Month - '+(parseInt(mm)-1);
$scope.attrs5.caption='Cost of Consumption on Month - '+(parseInt(mm)-1);
// console.log("maxPar: "+maxPar)
$scope.attrs4.yaxismaxvalue = Math.ceil(maxParLastMonth);
$scope.attrs5.yaxismaxvalue = Math.ceil(maxParLastMonth*$scope.costOfOneKWh);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
//////////////////////////////////////////////////////////////////////////////////
// generating graphs for today and yesterday
$scope.getPowerPerHourGraph = function(start_date){
var mm = start_date.split('-')[1];
var dd = start_date.split('-')[2];
var yy = start_date.split('-')[0];
// var str = start_time.toString().split(' ')[4];
// var time = str.split(':');
// var hour = time[0];
// var minute = time[1];
// var second = time[2];
var selectedMonth ;
$scope.dataset6=[];//today
$scope.dataset7=[];//tommorrow
$scope.dataset8=[];//today
$scope.dataset9=[];//tommorrow
var maxPar =0;
var maxParYesterday=0;
var hours =[];
for(var j=0; j<=23 ; j++){
hours.push({hour:j});
}
var data=[];
var dataYesterday=[];
var monthlist = [{key:'1',month:'1',days:31},{key:'2',month:'2',days:31},{key:'3',month:'3',days:31},{key:'4',month:'4',days:31},{key:'5',month:'5',days:31},{key:'6',month:'6',days:31},{key:'7',month:'7',days:31},{key:'8',month:'8',days:31},{key:'9',month:'9',days:31},{key:'10',month:'10',days:31},{key:'11',month:'11',days:31},{key:'12',month:'12',days:31}];
Devices.query({},function(deviceData){
angular.forEach(deviceData, function(device,key){
var plotData = [];
var plotObject=[];
var plotDataYesterday = [];
var plotObjectYesterday=[];
//retrieve power for each device start
var powerList = Powers.query({devices:device._id},function(){
// console.log(device._id)
angular.forEach(hours,function(val1,key){//days loop start
var totalPower=0;
var totalPowerYesterday=0;
angular.forEach(powerList,function(power,key){
var date = new Date(power.created);
var consumption = power.consumption;
var consumSplit = consumption.split('W');
var consN = parseInt(consumSplit[0]);
var milli = date.getTime();
var str1 = date.toString().split(' ')[4];
str1= date.toTimeString().split(' ')[0]
var time1 = str1.split(':');
var hour1 = time1[0];
var minute1 = time1[1];
var second1 = time1[2];
// console.log(str);
// console.log(hour1+" "+minute1+" "+second1);
var condition1 =(mm==((date.getMonth())+1) && yy==date.getFullYear() && dd==date.getDate());
var condition2 = (hour1==val1.hour);
var condition3 = (mm==((date.getMonth())+1) && yy==date.getFullYear() && ((dd-1)==(date.getDate())));
// console.log(hour1+"--"+val1.hour)
// console.log(date+"===>"+date.getFullYear()+"-"+((date.getMonth())+1)+"-"+date.getDate())
if( condition1==true && condition2==true){
totalPower+=(consN*10/3600/1000);
selectedMonth=date;
}
if( condition3==true && condition2==true){
totalPowerYesterday+=(consN*10/3600/1000);
selectedMonth=date;
}
});//end of foreach powerList
plotData.push({value:totalPower});
if(maxPar==0){
maxPar=totalPower;
}else if(totalPower>maxPar){
maxPar=totalPower;
}else{
maxPar=maxPar;
}
plotDataYesterday.push({value:totalPowerYesterday});
if(maxParYesterday==0){
maxParYesterday=totalPowerYesterday;
}else if(totalPowerYesterday>maxParYesterday){
maxParYesterday=totalPowerYesterday;
}else{
maxParYesterday=maxParYesterday;
}
});//days loop end
// var month = selectedMonth.toString().split(' ')[1];
plotObject.push({seriesname:device.name,data:plotData});
plotObjectYesterday.push({seriesname:device.name,data:plotDataYesterday});
data.push(plotObject);
dataYesterday.push(plotObjectYesterday);
/* $scope.dataset6.push({seriesname:device.name,data:plotData});
$scope.attrs6.caption='Power Consumption of Day - '+start_date;
// console.log("maxPar: "+maxPar)
$scope.attrs6.yaxismaxvalue = Math.ceil(maxPar);
$scope.dataset7.push({seriesname:device.name,data:plotDataYesterday});
$scope.attrs7.caption='Power Consumption of Day - '+start_date;
// console.log("maxPar: "+maxPar)
$scope.attrs7.yaxismaxvalue = Math.ceil(maxParYesterday);*/
if(data.length==deviceData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var todaydata=[];
var todaydataCost=[];
var tempTodayPower=0;
var tempTodayPowerCost=0;
for(var j=0;j<data[data.length-1][0].data.length;j++){
var val=0;
var cost=0;
for(var i=0;i<data.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
val+=data[i][0].data[j].value;
}
cost = val * $scope.costOfOneKWh;
todaydataCost.push({value:cost});
todaydata.push({value:val});
tempTodayPower+=val;
tempTodayPowerCost+=cost;
}
$scope.tempTodayTotalPower = tempTodayPower;
$scope.tempTodayTotalPowerCost = tempTodayPowerCost;
$scope.dataset6.push({seriesname:'Today ',data:todaydata});
$scope.dataset8.push({seriesname:'Today ',data:todaydataCost});
$scope.attrs6.caption='Power Consumption of Today - '+dd;
$scope.attrs8.caption='Cost of Consumption on Today - '+dd;
// console.log("maxPar: "+maxPar)
$scope.attrs6.yaxismaxvalue = Math.ceil(maxPar);
$scope.attrs8.yaxismaxvalue = Math.ceil(maxPar*$scope.costOfOneKWh);
}
if(dataYesterday.length==deviceData.length){
// console.log(' :Total power of all devices: '+powerOfAllDevices);
// console.log('Plot data analysis:');
// console.log('Plot data length : '+data.length);
// console.log(data[0][0].data);
var yesterdaydata=[];
var yesterdaydatacost=[];
var tempYesterdayPower=0;
var tempYesterdayPowerCost=0;
for(var j=0;j<dataYesterday[dataYesterday.length-1][0].data.length;j++){
var valYesterday=0;
var costYesterday=0;
for(var i=0;i<dataYesterday.length;i++){
// console.log(data[i][0].seriesname+" - "+data[i][0].data[j].value);
valYesterday+=dataYesterday[i][0].data[j].value;
}
costYesterday = valYesterday * $scope.costOfOneKWh;
tempYesterdayPower+=valYesterday;
tempYesterdayPowerCost+=costYesterday;
yesterdaydatacost.push({value:costYesterday});
yesterdaydata.push({value:valYesterday});
}
$scope.tempYesterdayTotalPower = tempYesterdayPower;
$scope.tempYesterdayTotalPowerCost = tempYesterdayPowerCost;
$scope.dataset7.push({seriesname:'Yesterday ',data:yesterdaydata});
$scope.dataset9.push({seriesname:'Yesterday ',data:yesterdaydatacost});
$scope.attrs7.caption='Power Consumption of Yesterday - '+(parseInt(dd)-1);
$scope.attrs9.caption='Cost of Consumption on Yesterday - '+(parseInt(dd)-1);
// console.log("maxPar: "+maxPar)
$scope.attrs7.yaxismaxvalue = Math.ceil(maxParYesterday);
$scope.attrs9.yaxismaxvalue = Math.ceil(maxParYesterday*$scope.costOfOneKWh);
}
});//end of query powerList
//retrieve power for each device start
}); //end of angular foreach
});//end of query
};
//call daily, monthly past and current data and load data to scope
var currentDate = new Date();
currentDate = currentDate.toLocaleDateString();
var demodata="2015-11-04";
$scope.getTotalPowerConsumptionFromEachDeviceByDay(currentDate)
//$scope.setAnalyticChartInfo();
////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//predictions START
//reading from file START
$scope.showContent = function($fileContent){
$scope.content = $fileContent;
var data_string = $scope.content;
var data = data_string.split(',')
console.log('Plotting Pattern')
console.log(data);
};
//reading from file END
$scope.hour_data=[];
$scope.getPatternForHourAll = function(){
console.log('Hour Pattern Plotting');
var devices = Devices.query({},function(data){
angular.forEach(data,function(device,key){
console.log(device.name);
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+device.name+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.hour_data.push({seriesname:device.name,data:responses});
}).error(function(error){
$scope.hour_data.push({});
});
});
});
};
$scope.hour_data_per_device=[];
$scope.showHourDevicePatternGraph=false;
$scope.getPatternForHourPerDevice= function(deviceName){
$scope.showHourDevicePatternGraph=true;
$scope.hour_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+deviceName+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.hour_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.hour_data_per_device = [];
});
};
//month data extraction starts
$scope.month_data_per_device=[];
$scope.showMonthDevicePatternGraph=false;
$scope.getPatternForMonthPerDevice= function(deviceName){
$scope.showMonthDevicePatternGraph=true;
$scope.month_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/month/'+deviceName+'MonthX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.month_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.month_data_per_device = [];
});
};
//month data extraction ends
//week data extraction starts
$scope.week_data_per_device=[];
$scope.showWeekDevicePatternGraph=false;
$scope.getPatternForWeekPerDevice= function(deviceName){
$scope.showWeekDevicePatternGraph=true;
$scope.week_data_per_device=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/week/'+deviceName+'WeekX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push({value:val});
});
$scope.week_data_per_device.push({seriesname:deviceName,data:responses});
}).error(function(error){
$scope.week_data_per_device = [];
});
};
//week data extraction ends
//get all pattern data start
$scope.getAllPatternData = function(deviceName){
$scope.getPatternForHourPerDevice(deviceName);
$scope.getPatternForMonthPerDevice(deviceName);
$scope.getPatternForWeekPerDevice(deviceName);
};
// get all pattern data end
$scope.predictionGraphPerHourDevices = function(){
$scope.attrsPredictionHour = {
"caption": "Hour Based",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.attrsPredictionHour1 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionHour = [
{
"category": [
{
"label": "0"
},
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},
{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
}
]
}
];
$scope.dataset = [];
};
//per week analysis
$scope.predictionGraphPerWeekDevices = function(){
$scope.attrsPredictionWeek1 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#69f0ae",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionWeek = [
{
"category": [
{
"label": "Monday"
},
{
"label": "Tuesday"
},
{
"label": "Wednesday"
},
{
"label": "Thursday"
},
{
"label": "Friday"
},
{
"label": "Saturday"
},
{
"label": "Sunday"
}
]
}
];
$scope.dataset = [];
};
//per week analysis ends
//per month analysis starts
$scope.predictionGraphPerMonthDevices = function(){
$scope.attrsPredictionMonth = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.categoriesPredictionMonth = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},
{
"label": "13"
},
{
"label": "14"
},
{
"label": "15"
},
{
"label": "16"
},
{
"label": "17"
},
{
"label": "18"
},
{
"label": "19"
},
{
"label": "20"
},
{
"label": "21"
},
{
"label": "22"
},
{
"label": "23"
},
{
"label": "24"
},
{
"label": "25"
},
{
"label": "26"
},
{
"label": "27"
},
{
"label": "28"
},
{
"label": "29"
},
{
"label": "30"
},
{
"label": "31"
}
]
}
];
$scope.dataset = [];
};
//per month analysis ends
$scope.predictionGraphPerHourDevices();
$scope.predictionGraphPerWeekDevices();
$scope.predictionGraphPerMonthDevices();
//visible prediction and patterns start
$scope.prediction = true;
$scope.pattern = false;
$scope.cost_prediction=false;
// visible prediction and patterns end
$scope.showPredictionTab = function(){
$scope.prediction = true;
$scope.pattern = false;
$scope.cost_prediction=false;
};
$scope.showPatternTab = function(){
$scope.pattern = true;
$scope.prediction = false;
$scope.cost_prediction=false;
};
$scope.showCostPredictionTab =function(){
$scope.pattern = false;
$scope.prediction = false;
$scope.cost_prediction=true;
};
//prediction of usage start
$scope.peak_usage_cost_per_unit = 60.0;
$scope.off_peak_usage_cost_per_unit = 45.0;
$scope.predictionOfUsagePerDevice = function(deviceName){
console.log('Device Name :'+deviceName);
$scope.usage_data=[];
$http({
url: 'http://localhost:3000/data/multi-pattern/hour/'+deviceName+'HourX.txt',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
var responses=[];
// response = response.split('\n')
response = response.split(',');
angular.forEach(response,function(val,key){
responses.push(val);
});
$scope.usage_data.push(responses);
var usage_in_peak=0;
var usage_in_off_peak=0;
var capacity_peak=0;
var capacity_off_peak=0;
//process data start
var off_peak_lower1=18;
var off_peak_upper1=23;
var off_peak_lower2=0;
var off_peak_upper2=6;
var peak_lower=7;
var peak_upper=17;
console.log('Prediction of Usage Per Device');
console.log('==================================');
var length_of_data = responses.length;
console.log('length :'+length_of_data);
for(var i=0;i<length_of_data;i++){
var check_peak = (i>=peak_lower && i<=peak_upper) ;
var check_off_peak1 =(i>=off_peak_lower1 && i<=off_peak_upper1);
var check_off_peak2 =(i>=off_peak_lower2 && i<=off_peak_upper2);
if(check_peak){
if(responses[i]==1){
usage_in_peak= usage_in_peak +1;
capacity_peak= capacity_peak +1;
}
}
if(check_off_peak1){
if(responses[i]==1){
usage_in_off_peak= usage_in_off_peak +1;
capacity_off_peak= capacity_off_peak +1;
}
}
if(check_off_peak2){
if(responses[i]==1){
usage_in_off_peak= usage_in_off_peak +1;
capacity_off_peak= capacity_off_peak +1;
}
}
}
console.log('Peak Hour Usage : '+usage_in_peak);
console.log('Off-Peak Hour Usage : '+usage_in_off_peak);
$scope.usage_in_peak = usage_in_peak;
$scope.usage_in_off_peak = usage_in_off_peak;
//////////////////////////////
var cost_peak = $scope.usage_in_peak * $scope.peak_usage_cost_per_unit;
var cost_off_peak = $scope.usage_in_off_peak * $scope.off_peak_usage_cost_per_unit;
$scope.cost_peak=cost_peak;
$scope.cost_off_peak = cost_off_peak;
$scope.costOptimization($scope.usage_in_peak,$scope.usage_in_off_peak);
$scope.capacityShiftingCapability($scope.usage_in_peak,$scope.usage_in_off_peak);
//process data end
}).error(function(error){
$scope.usage_data = [];
});
};
$scope.cost_saving = 0.0;
$scope.costOptimization = function(usage_peak, usage_off_peak){
var total_cost = usage_peak*$scope.peak_usage_cost_per_unit + usage_off_peak*$scope.off_peak_usage_cost_per_unit;
var new_saving = $scope.off_peak_usage_cost_per_unit*(usage_peak+usage_off_peak);
var cost_saving = total_cost - new_saving;
$scope.cost_saving = cost_saving;
};
$scope.shifting_possible=false;
$scope.capacityShiftingCapability = function(capacity_peak, capacity_off_peak){
var off_peak_lower1=18;
var off_peak_upper1=24;
var off_peak_lower2=0;
var off_peak_upper2=6;
var peak_lower=6;
var peak_upper=18;
var status=false;
var total_off_peak_capacity = (off_peak_upper1 - off_peak_lower1) + (off_peak_upper2-off_peak_lower2);
var total_peak_capacity = (peak_upper-peak_lower);
var capacity_ratio = capacity_peak/capacity_off_peak;
var off_peak_capacity_remainder = total_off_peak_capacity - capacity_off_peak;
var peak_capacity_remainder = total_peak_capacity - capacity_peak;
$scope.peak_capacity_remainder = peak_capacity_remainder;
$scope.off_peak_capacity_remainder = off_peak_capacity_remainder;
console.log('remainder : '+off_peak_capacity_remainder);
console.log('peak capacity : '+capacity_peak);
if(off_peak_capacity_remainder>capacity_peak && capacity_peak>0){
status=true; //resembles cost can be minimized
}else{
status=false; //resembles cost cannot be minimized
}
$scope.shifting_possible=status;
console.log(status);
};
//prediction of usage ends
//prediction of cost STARTS
$scope.getDataOfCostofPastYears = function(){
var units_2014=[65,60,66,103,89,70,68,65,43,44,55,111];
var cost_2014=[521,220,531,1131,761,571,551,521,138,142,196,1353];
var units_2013=[118,88,68,90,71,78,58,58,65,56,74,80];
var cost_2013=[1548,751,551,771,581,651,210,210,521,201,611,671];
var units_2012=[119,108,96,127,113,127,131,145,119,123,100,90];
var cost_2012=[1575,1270,937,1827,1409,1827,1955,2403,1575,1699,1048,771];
var units_2011=[99,96,90,98,126,120,122,141,129,120,121,116];
var cost_2011=[1020,937,771,993,1795,1603,1667,2275,1891,1603,1635,1492];
var units_2010=[134,87,67,124,97,99,81,116,103,90,104,108];
var cost_2010=[2051,741,541,1731,965,1020,681,1492,1131,771,1159,1270];
$scope.attrsPredictionCostOfYear = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.attrsPredictionCostOfYear1 = {
"caption": "Electricty Bills",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesPredictionCostOfYear = [
{
"category": [
{
"label": "1"
},
{
"label": "2"
},
{
"label": "3"
},
{
"label": "4"
},
{
"label": "5"
},
{
"label": "6"
},
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
}
]
}
];
$scope.dataset_cost_past_years = [
{
"seriesname": "2014",
"data": [
{
"value": "521"
},
{
"value": "220"
},
{
"value": "531"
},
{
"value": "1131"
},
{
"value": "761"
},
{
"value": "571"
},
{
"value": "551"
},
{
"value": "521"
},
{
"value": "138"
},
{
"value": "142"
},
{
"value": "196"
},
{
"value": "1353"
}
]
},
{
"seriesname": "2013",
"data": [
{
"value": "1548"
},
{
"value": "751"
},
{
"value": "551"
},
{
"value": "771"
},
{
"value": "581"
},
{
"value": "651"
},
{
"value": "210"
},
{
"value": "210"
},
{
"value": "521"
},
{
"value": "201"
},
{
"value": "611"
},
{
"value": "671"
}
]
},
{
"seriesname": "2012",
"data": [
{
"value": "1575"
},
{
"value": "1270"
},
{
"value": "937"
},
{
"value": "1827"
},
{
"value": "1409"
},
{
"value": "1827"
},
{
"value": "1955"
},
{
"value": "2403"
},
{
"value": "1575"
},
{
"value": "1699"
},
{
"value": "1048"
},
{
"value": "771"
}
]
},
{
"seriesname": "2011",
"data": [
{
"value": "1020"
},
{
"value": "937"
},
{
"value": "771"
},
{
"value": "993"
},
{
"value": "1795"
},
{
"value": "1603"
},
{
"value": "1667"
},
{
"value": "2275"
},
{
"value": "1891"
},
{
"value": "1603"
},
{
"value": "1635"
},
{
"value": "1492"
}
]
},
{
"seriesname": "2010",
"data": [
{
"value": "2051"
},
{
"value": "741"
},
{
"value": "541"
},
{
"value": "1731"
},
{
"value": "965"
},
{
"value": "1020"
},
{
"value": "681"
},
{
"value": "1492"
},
{
"value": "1131"
},
{
"value": "771"
},
{
"value": "1159"
},
{
"value": "1270"
}
]
}
];
};
$scope.predictionOfCostNextYear = function(){
$scope.attrsPredictionCostOfYear2014 = {
"caption": "Device Usage ",
"subCaption": "Hour Based",
"xAxisName": "Hour",
"yAxisName": "Status",
"numberPrefix": "",
"paletteColors": "#0075c2",
"bgColor": "#607d8b",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"plotFillAlpha": "50",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"divLineAlpha": "10",
"showValues": "1",
"showAlternateHGridColor": "0",
/* "bgImage": "img/background/elec1.jpg",
"baseFontColor": "red",*/
"captionFontSize": "18",
"subcaptionFontSize": "16",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"toolTipPadding": "5"
}
$scope.attrsPredictionCostOfYear12014 = {
"caption": "Electricty Bills",
"numberprefix": "",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "1",
"captionpadding": "30",
"linethickness": "3",
"yaxisvaluespadding": "1",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showborder": "0"
};
$scope.categoriesPredictionCostOfYear2014 = [
{
"category": [
{
"label": "July"
},
{
"label": "August"
},
{
"label": "Sepetember"
},
{
"label": "October"
},
{
"label": "November"
},
{
"label": "December"
}
]
}
];
$scope.dataset_cost_past_years2014 = [
{
"seriesname": "2015 Prediction Bill",
"data": [
{
"value": "70"
},
{
"value": "65"
},
{
"value": "66"
},
{
"value": "103"
},
{
"value": "65"
},
{
"value": "65"
}
]
},
{
"seriesname": "2015 Real Bill",
"data": [
{
"value": "68"
},
{
"value": "65"
},
{
"value": "43"
},
{
"value": "44"
},
{
"value": "55"
},
{
"value": "111"
}
]
}
];
};
//prediction of cost ENDS
//predictions END
//
$scope.init();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
]).config( function($mdThemingProvider){
// Configure a dark theme with primary foreground yellow
$mdThemingProvider.theme('docs-dark', 'default')
.primaryPalette('yellow')
.dark();
});
angular.module('dashboards').controller('InsideCtrl', function ($scope, ngDialog) {
$scope.dialogModel = {
message : 'message from passed scope'
};
$scope.openSecond = function () {
ngDialog.open({
template: '<h3><a href="" ng-click="closeSecond()">Close all by click here!</a></h3>',
plain: true,
closeByEscape: false,
controller: 'SecondModalCtrl'
});
};
});
angular.module('dashboards').controller('InsideCtrlAs', function () {
this.value = 'value from controller';
});
angular.module('dashboards').controller('SecondModalCtrl', function ($scope, ngDialog) {
$scope.closeSecond = function () {
ngDialog.close();
};
});
//ngDialog Controlling Section End
////////////////////////////////////////////
//angular tables
app.directive('mdTable', function () {
return {
restrict: 'E',
scope: {
headers: '=',
content: '=',
sortable: '=',
filters: '=',
customClass: '=customClass',
thumbs:'=',
count: '='
},
controller: function ($scope,$filter,$window) {
var orderBy = $filter('orderBy');
$scope.tablePage = 0;
$scope.nbOfPages = function () {
return Math.ceil($scope.content.length / $scope.count);
},
$scope.handleSort = function (field) {
if ($scope.sortable.indexOf(field) > -1) { return true; } else { return false; }
};
$scope.order = function(predicate, reverse) {
$scope.content = orderBy($scope.content, predicate, reverse);
$scope.predicate = predicate;
};
$scope.order($scope.sortable[0],false);
$scope.getNumber = function (num) {
return new Array(num);
};
$scope.goToPage = function (page) {
$scope.tablePage = page;
};
},
template: angular.element(document.querySelector('#md-table-template')).html()
}
});
app.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
/*app.directive('mdColresize', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$evalAsync(function () {
$timeout(function(){ $(element).colResizable({
liveDrag: true,
fixed: true
});},100);
});
}
}
});*/
app.filter('startFrom', function() {
return function(input, start) {
if (!input || !input.length) { return; }
start = +start; //parse to int
return input.slice(start);
}
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
$scope.devicename="Name of the device";
$scope.deviceDetails= $scope.deviceProfile_SelectedDevice;
}
|
var process = function (json) {
var x = 0,
r = Raphael("chart", 2350, 550),
labels = {},
textattr = {"font": '9px "Arial"', stroke: "none", fill: "#fff"},
pathes = {},
nmhldr = $("#name")[0],
nmhldr2 = $("#name2")[0],
lgnd = $("#legend")[0],
usrnm = $("#username")[0],
lgnd2 = $("#legend2")[0],
usrnm2 = $("#username2")[0],
plchldr = $("#placeholder")[0];
function finishes() {
for (var i in json.authors) {
var start, end;
for (var j = json.buckets.length - 1; j >= 0; j--) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
}
if (isin) {
end = j;
break;
}
}
for (var j = 0, jj = json.buckets.length; j < jj; j++) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
};
if (isin) {
start = j;
break;
}
}
for (var j = start, jj = end; j < jj; j++) {
var isin = false;
for (var k = 0, kk = json.buckets[j].i.length; k < kk; k++) {
isin = isin || (json.buckets[j].i[k][0] == i);
}
if (!isin) {
json.buckets[j].i.push([i, 0]);
}
}
}
}
function block() {
var p, h;
finishes();
for (var j = 0, jj = json.buckets.length; j < jj; j++) {
var users = json.buckets[j].i;
h = 0;
for (var i = 0, ii = users.length; i < ii; i++) {
p = pathes[users[i][0]];
if (!p) {
p = pathes[users[i][0]] = {f:[], b:[]};
}
p.f.push([x, h, users[i][1]]);
p.b.unshift([x, h += Math.max(Math.round(Math.log(users[i][1]) / Math.log(1.2) * 2.5), 1)]);
h += 2;
}
var dt = new Date(json.buckets[j].d * 1000);
var dtext = dt.getDate() + "." + (dt.getMonth()+1) + "." + dt.getFullYear();
r.text(x + 25, h + 10, dtext).attr({"font": '9px "Arial"', stroke: "none", fill: "#aaa"});
x += 100;
}
var c = 0;
for (var i in pathes) {
labels[i] = r.set();
var clr = Raphael.getColor();
pathes[i].p = r.path().attr({fill: clr, stroke: clr});
var path = "M".concat(pathes[i].f[0][0], ",", pathes[i].f[0][1], "L", pathes[i].f[0][0] + 50, ",", pathes[i].f[0][1]);
var th = Math.round(pathes[i].f[0][1] + (pathes[i].b[pathes[i].b.length - 1][1] - pathes[i].f[0][1]) / 2 + 3);
labels[i].push(r.text(pathes[i].f[0][0] + 25, th, pathes[i].f[0][2]).attr(textattr));
var X = pathes[i].f[0][0] + 50,
Y = pathes[i].f[0][1];
for (var j = 1, jj = pathes[i].f.length; j < jj; j++) {
path = path.concat("C", X + 20, ",", Y, ",");
X = pathes[i].f[j][0];
Y = pathes[i].f[j][1];
path = path.concat(X - 20, ",", Y, ",", X, ",", Y, "L", X += 50, ",", Y);
th = Math.round(Y + (pathes[i].b[pathes[i].b.length - 1 - j][1] - Y) / 2 + 3);
if (th - 9 > Y) {
labels[i].push(r.text(X - 25, th, pathes[i].f[j][2]).attr(textattr));
}
}
path = path.concat("L", pathes[i].b[0][0] + 50, ",", pathes[i].b[0][1], ",", pathes[i].b[0][0], ",", pathes[i].b[0][1]);
for (var j = 1, jj = pathes[i].b.length; j < jj; j++) {
path = path.concat("C", pathes[i].b[j][0] + 70, ",", pathes[i].b[j - 1][1], ",", pathes[i].b[j][0] + 70, ",", pathes[i].b[j][1], ",", pathes[i].b[j][0] + 50, ",", pathes[i].b[j][1], "L", pathes[i].b[j][0], ",", pathes[i].b[j][1]);
}
pathes[i].p.attr({path: path + "z"});
labels[i].hide();
var current = null;
(function (i) {
pathes[i].p.mouseover(function () {
if (current != null) {
labels[current].hide();
}
current = i;
labels[i].show();
pathes[i].p.toFront();
labels[i].toFront();
usrnm2.innerHTML = json.authors[i].n + " <em>(" + json.authors[i].c + " votes, " + json.authors[i].a + " for, " + json.authors[i].d + " against)</em>";
lgnd2.style.backgroundColor = pathes[i].p.attr("fill");
nmhldr2.className = "";
plchldr.className = "hidden";
});
})(i);
}
}
if (json.error) {
alert("Project not found. Try again.");
} else {
block();
}
};
$(function () {
process(json);
});
|
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import mutations from './mutations';
import state from './state';
Vue.use(Vuex);
export default () =>
new Vuex.Store({
actions,
mutations,
state,
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'km', {
button: 'ពុម្ពគំរូ',
emptyListMsg: '(មិនមានពុម្ពគំរូត្រូវបានកំណត់)',
insertOption: 'ជំនួសក្នុងមាតិកាបច្ចុប្បន្ន',
options: 'ជម្រើសពុម្ពគំរូ',
selectPromptMsg: 'សូមរើសពុម្ពគំរូដើម្បីបើកក្នុងកម្មវិធីសរសេរអត្ថបទ',
title: 'ពុម្ពគំរូមាតិកា'
});
|
var twimap;
twimap = require("twimap");
var Twit = require("twit");
var util = require("util");
var _current_index = -1;
var _followers_list ;
var thanks_temp;
thanks_temp = [
"Dear %s, thank you for following :)",
"%s = awesome. Me = grateful for following :)",
"Is there no limit to your awesomeness %s? Thank you for following!",
"You can’t see me %s! but I’m totally doing a happy dance! Big thanks for following me on twitter :)",
"hey %s!Do you practice being so wonderful? Thank you kindly for following."
];
// create twitter client
twit_cli = new Twit({
consumer_key: "---consumer-key---"
, consumer_secret: "---consumer-secret---"
, access_token: "---access-token---"
, access_token_secret: "---access-token-secret---"
});
//config TWIMAP imap account
twimap.configImap({
user : '---username---@gmail.com',
password : '---password---',
host : 'imap.gmail.com',
port : 993,
secure : true
});
// stores last imap try
var last_check = now();
//call this function periodically to get new followers
//callback is called when new information is available
function load_followers_priodically() {
try{
twimap.followersAsync(last_check, function(result) {
if(typeof result != "undefined" && result.length >=1){
//save it in our variable
_followers_list = result;
last_check = now();
msg_followers_thanks();
}
},function (err){
// I command you to stay silent
reset_values();
});
}catch(e){
//still...
reset_values();
console.log(e);
}
}
//this function iterates through followers listed in variable
//_followers_list
function msg_followers_thanks(){
//move cursor
_current_index++;
//if there is no followers OR finished messaging followers stop
if(_current_index >= _followers_list.length ){
_current_index = -1;
_followe_list = null;
return;
}
//otherwise get user name from twitter
twit_cli.get("users/show",{screen_name:_followers_list[_current_index]}, function (err,dt){
//clean up the name
var dude = filter_name(dt.name);
//message the user
twit_cli.post("direct_messages/new" , {screen_name:_followers_list[_current_index],text:random_msg(dude)}, function (err,dt){
if(!err) console.log("done...");
//go for another round
msg_followers_thanks();
});
});
}
//cut names bigger that 40 characters
function filter_name(name){
if ( typeof name == "undefined" || name=="" || name==null) name = "my friend";
if(name.length > 40 ) name = name.substr(0,40);
return name;
}
//generate a random message
function random_msg(name){
name = filter_name(name);
return util.format(thanks_temp[Math.floor(Math.random()*10)%(thanks_temp.length-1)] , name);
}
//return current day
function now() {
var d;
d = new Date();
return d.toUTCString();
}
//reset values on error
function reset_values(){
_current_index = -1;
_followers_list = null;
}
// run safe and sound :|
function run(){
_interval = setInterval(load_followers_priodically,1000*60*30);
//run now , I can't wait ;)
load_followers_priodically();
}
//cheers to a happy running ;)
run();
|
import { expect } from 'chai';
import { validateRegister, validateLogin } from '../../src/universal/validation/authValidation';
describe('validation', () => {
describe('validateRegister', () => {
it('passes for acceptable details', () => {
const username = 'username';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors).to.be.empty;
});
it('fails with no username', () => {
const username = '';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Please provide a username');
});
it('fails for a username with non alpha numeric or hypen', () => {
const username = 'B4D4$$!!!!';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen');
});
it('fails for a username with spaces', () => {
const username = 'bad username';
const password = 'password';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.username).to.equal('Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen');
});
it('fails with no password', () => {
const username = 'username';
const password = '';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.password).to.equal('Please supply a password');
});
it('fails for a password under 6 characters', () => {
const username = 'username';
const password = 'passw';
const email = 'valid@example.com';
const errors = validateRegister(username, password, email);
expect(errors.password).to.equal('Please supply a password over 6 characters');
});
it('fails with no email', () => {
const username = 'username';
const password = 'password';
const email = '';
const errors = validateRegister(username, password, email);
expect(errors.email).to.equal('Please provide an email');
});
it('fails with an invalid email', () => {
const username = 'username';
const password = 'password';
const email = '234567';
const errors = validateRegister(username, password, email);
expect(errors.email).to.equal('Please provide a valid email address');
});
});
describe('validateLogin', () => {
it('passes with both username and password', () => {
const username = 'username';
const password = 'password';
const errors = validateLogin(username, password);
expect(errors).to.be.empty;
});
it('fails with no username', () => {
const username = '';
const password = 'password';
const errors = validateLogin(username, password);
expect(errors.username).to.equal('Please provide a username');
});
it('fails with no password', () => {
const username = 'username';
const password = '';
const errors = validateLogin(username, password);
expect(errors.password).to.equal('Please supply a password');
});
});
});
|
const NUM_HASHES = HASHES.length;
function verify(id, accessCode) {
var token = id.replace(/\s+/g, '').toLowerCase() + accessCode;
for (var i = 0; i < NUM_HASHES; ++i) {
var result = CryptoJS.AES.decrypt(HASHES[i], token).toString(CryptoJS.enc.Latin1);
if (/^https?:\/\/[^\s]+$/.test(result)) {
window.location = result;
return true;
}
}
// Display denial
$("#lit-header").removeClass("power-on");
document.getElementById("go").className = "denied";
document.getElementById("go").value = "Access Denied";
return false;
}
$(document).ready(function() {
var state = false;
var numAttempts = 0;
$('#access-panel').on('submit', function(evt) {
evt.preventDefault();
if (!state && numAttempts < 10) {
state = true;
$("#lit-header").addClass("power-on");
document.getElementById("go").className = "";
document.getElementById("go").value = "Verifying...";
numAttempts += 1;
setTimeout(function() {
verify($('#name').val(), $('#password').val());
state = false;
}, 2000);
}
});
});
|
const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');
const CMD = 'MODE';
describe(CMD, function () {
let sandbox;
const mockClient = {
reply: () => Promise.resolve()
};
const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);
beforeEach(() => {
sandbox = sinon.sandbox.create().usingPromise(Promise);
sandbox.spy(mockClient, 'reply');
});
afterEach(() => {
sandbox.restore();
});
it('S // successful', () => {
return cmdFn({command: {arg: 'S'}})
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(200);
});
});
it('Q // unsuccessful', () => {
return cmdFn({command: {arg: 'Q'}})
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(504);
});
});
});
|
export { default } from './BottomNavigation';
export { default as BottomNavigationAction } from './BottomNavigationAction';
|
// @flow
import * as React from 'react'
import {StyleSheet, Image, Alert} from 'react-native'
import {Column, Row} from '../components/layout'
import {ListRow, Detail, Title} from '../components/list'
import type {StoryType} from './types'
type Props = {
onPress: string => any,
story: StoryType,
thumbnail: false | number,
}
export class NewsRow extends React.PureComponent<Props> {
_onPress = () => {
if (!this.props.story.link) {
Alert.alert('There is nowhere to go for this story')
return
}
this.props.onPress(this.props.story.link)
}
render() {
const {story} = this.props
const thumb =
this.props.thumbnail !== false
? story.featuredImage
? {uri: story.featuredImage}
: this.props.thumbnail
: null
return (
<ListRow arrowPosition="top" onPress={this._onPress}>
<Row alignItems="center">
{thumb !== null ? (
<Image source={thumb} style={styles.image} />
) : null}
<Column flex={1}>
<Title lines={2}>{story.title}</Title>
<Detail lines={3}>{story.excerpt}</Detail>
</Column>
</Row>
</ListRow>
)
}
}
const styles = StyleSheet.create({
image: {
borderRadius: 5,
marginRight: 15,
height: 70,
width: 70,
},
})
|
{
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== "unknown") {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
}
|
// saskavi.js
// client side script for calling saskavi functions
//
(function() {
"use strict";
var Saskavi = function(fbRoot, uid) {
if (!uid)
throw new Error("uid not supplied, an authenticated user id is required");
this.rpcBus = fbRoot.child("__saskavi-rpc").child(uid);
};
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
Saskavi.prototype.call = function() {
var params = Array.prototype.slice.call(arguments, 0);
var funcName = params[0];
if (!isFunction(params[params.length - 1]))
throw new Error("Callback function as last parameter is required, promises may come soon");
var cb = params[params.length - 1];
console.log(params);
var ps = params.slice(1, params.length - 1);
console.log(ps);
var rpcData = {
"function": funcName,
"args": ps
};
var rpcRef = this.rpcBus.push(rpcData);
var resultRef = rpcRef.child('result');
resultRef.on('value', function(snapshot) {
if (snapshot !== null && snapshot.val() !== null) {
resultRef.off('value');
cb(null, snapshot.val());
}
});
};
window.Saskavi = Saskavi;
})();
|
function checkNeighbours(arr, i) {
var result,
inputArray,
position;
if (arr == null) {
inputArray = document.getElementById('numbersArray2').value.split(' '),
position = +document.getElementById('num6').value;
} else {
inputArray = arr,
position = i;
}
if ((position === 0 || position === inputArray.length) && arr == null) {
result = 'Not enough neighbours!';
document.getElementById('result6').innerHTML = result;
return result;
}
if ((+inputArray[position] > +inputArray[position - 1]) && (+inputArray[position] > +inputArray[position + 1])) result = true;
else result = false;
if (arr == null) document.getElementById('result6').innerHTML = result;
return result;
}
|
'use strict';
var $ = require('./main')
, getViewportRect = require('./get-viewport-rect')
, getElementRect = require('./get-element-rect');
module.exports = $.showInViewport = function (el/*, options*/) {
var vpRect = getViewportRect()
, elRect = getElementRect(el)
, options = Object(arguments[1])
, padding = isNaN(options.padding) ? 0 : Number(options.padding)
, elTopLeft = { x: elRect.left, y: elRect.top }
, elBottomRight = { x: elRect.left + elRect.width, y: elRect.top + elRect.height }
, vpTopLeft = { x: vpRect.left + padding, y: vpRect.top + padding }
, vpBottomRight = { x: vpRect.left + vpRect.width - padding,
y: vpRect.top + vpRect.height - padding }
, diffPoint = { x: 0, y: 0 }, diff;
if (elBottomRight.x > vpBottomRight.x) {
// right beyond
diff = elBottomRight.x - vpBottomRight.x;
elTopLeft.x -= diff;
elBottomRight.x -= diff;
diffPoint.x -= diff;
}
if (elBottomRight.y > vpBottomRight.y) {
// bottom beyond
diff = elBottomRight.y - vpBottomRight.y;
elTopLeft.y -= diff;
elBottomRight.y -= diff;
diffPoint.y -= diff;
}
if (elTopLeft.x < vpTopLeft.x) {
// left beyond
diff = vpTopLeft.x - elTopLeft.x;
elTopLeft.x += diff;
elBottomRight.x += diff;
diffPoint.x += diff;
}
if (elTopLeft.y < vpTopLeft.y) {
// top beyond
diff = vpTopLeft.y - elTopLeft.y;
elTopLeft.y += diff;
elBottomRight.y += diff;
diffPoint.y += diff;
}
if (diffPoint.x) el.style.left = (el.offsetLeft + diffPoint.x) + "px";
if (diffPoint.y) el.style.top = (el.offsetTop + diffPoint.y) + "px";
};
|
'use strict';
require('babel/register');
// controls application file
let app = require('app');
// control main window
let BrowserWindow = require('browser-window');
let mainWindow = null;
// quite when all windows are closed
app.on('window-all-closed', () => {
if (process.platform != 'darwin') {
app.quit();
}
});
// This is called when Electron is ready to create windows
app.on('ready', () => {
// create the main window
mainWindow = new BrowserWindow({ width: 800, height: 600 });
// load main file
mainWindow.loadUrl(`file://${__dirname}/index.html`);
// open dev tools
mainWindow.openDevTools();
// when the window is closed
mainWindow.on('close', () => {
// clean the window object for garbage collector
mainWindow = null;
});
});
|
[comment /**]
[comment Plain text doesn't have any special ]
[comment indentation. {][comment&tag @link][comment foo}]
[comment&tag @fileoverview][comment Doesn't have any special]
[comment indentation.]
[comment&tag @see][comment https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler]
[comment&tag @constructor]
[comment&tag @foo]
[comment&tag @param][comment {]
[comment * ][comment&type !Foo][comment } ]
[comment * ][comment&def param][comment Some ]
[comment description.]
[comment&tag @param][comment {][comment&type {]
[comment ][comment&type foo: objectRulesApplyAndParamNameIsRequired}][comment }]
[comment ][comment&def Desc]
[comment */]
[string "use strict"]
|
var path = require('path')
var AtomicFile = require('atomic-file')
function id (e) { return e }
var none = {
encode: id, decode: id
}
module.exports = function (dir, name, codec) {
codec = codec || require('flumecodec/json')
var af = AtomicFile(path.join(dir, name+'.json'), '~', none)
var self
return self = {
size: null,
get: function (cb) {
af.get(function (err, value) {
if(err) return cb(err)
if(value == null) return cb()
try {
self.size = value.length
value = codec.decode(value)
value.size = self.size
} catch(err) {
return cb(err)
}
cb(null, value)
})
},
set: function (value, cb) {
value = codec.encode(value)
self.size = value.length
af.set(value, cb)
},
destroy: function (cb) {
value = null
self.size = 0
af.destroy(cb)
}
}
}
|
angular.module('ModuleGlobal').service('LoginService', ['$http', 'urlService', function($http, urlService) {
var self = this;
var url = urlService.getLoginUrl();
var connected = false;
self.identifier = '';
self.isConnected = function() {
return connected;
};
self.connect = function(identifier, password, remember) {
var logs = {
login : identifier,
mdp : password,
};
return $http.post(url, logs).then(function(response) {
connected = true;
if (remember)
self.identifier = identifier;
else
self.identifier = '';
return {connected: true, status: response.status};
},
function(response) {
return {connected: false, status: response.status};
});
};
self.disconnect = function() {
connected = false;
};
}]);
|
import React from 'react';
import {Link} from "react-router";
import Subheading from '../components/Subheading';
import Portfolio4col from '../components/Portfolio/Portfolio4col';
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome to Momoware!",
};
}
changeTitle(title){
this.setState({title});
}
navigate() {
console.log(this.props);
}
render() {
return(
<div>
<Subheading title="Portfolio4col"/>
<Portfolio4col
projectImgPic1="http://placehold.it/700x300"
projectImgPic2="http://placehold.it/700x300"
projectImgPic3="http://placehold.it/700x300"
projectImgPic4="http://placehold.it/700x300"
/>
<Portfolio4col
projectImgPic1="http://placehold.it/700x300"
projectImgPic2="http://placehold.it/700x300"
projectImgPic3="http://placehold.it/700x300"
projectImgPic4="http://placehold.it/700x300"
/>
<Portfolio4col
projectImgPic1="http://placehold.it/700x300"
projectImgPic2="http://placehold.it/700x300"
projectImgPic3="http://placehold.it/700x300"
projectImgPic4="http://placehold.it/700x300"
/>
</div>
);
}
}
|
/*****************************************************************************/
/* PayRunResultModal: Event Handlers */
/*****************************************************************************/
import Ladda from 'ladda';
Template.PayRunResultModal.events({
});
/*****************************************************************************/
/* PayRunResultModal: Helpers */
/*****************************************************************************/
Template.PayRunResultModal.helpers({
});
/*****************************************************************************/
/* PayRunResultModal: Lifecycle Hooks */
/*****************************************************************************/
Template.PayRunResultModal.onCreated(function () {
let self = this;
});
Template.PayRunResultModal.onRendered(function () {
});
Template.PayRunResultModal.onDestroyed(function () {
});
|
/* global Mousetrap */
import { typeOf } from '@ember/utils';
import { get } from "@ember/object";
export function bindKeyboardShortcuts(context) {
const shortcuts = get(context, 'keyboardShortcuts');
if (typeOf(shortcuts) !== 'object') {
return;
}
context._mousetraps = [];
Object.keys(shortcuts).forEach(function(shortcut) {
const actionObject = shortcuts[shortcut];
let mousetrap;
let preventDefault = true;
function invokeAction(action, eventType) {
let type = typeOf(action);
let callback;
if (type === 'string') {
callback = function() {
context.send(action);
return preventDefault !== true;
};
} else if (type === 'function') {
callback = action.bind(context);
} else {
throw new Error('Invalid value for keyboard shortcut: ' + action);
}
mousetrap.bind(shortcut, callback, eventType);
}
if (typeOf(actionObject) === 'object') {
if (actionObject.global === false) {
mousetrap = new Mousetrap(document);
} else if (actionObject.scoped) {
if (typeOf(actionObject.scoped) === 'boolean') {
mousetrap = new Mousetrap(get(context, 'element'));
} else if (typeOf(actionObject.scoped) === 'string') {
mousetrap = new Mousetrap(
document.querySelector(actionObject.scoped)
);
}
} else if (actionObject.targetElement) {
mousetrap = new Mousetrap(actionObject.targetElement);
} else {
mousetrap = new Mousetrap(document.body);
}
if (actionObject.preventDefault === false) {
preventDefault = false;
}
invokeAction(actionObject.action, actionObject.eventType);
} else {
mousetrap = new Mousetrap(document.body);
invokeAction(actionObject);
}
context._mousetraps.push(mousetrap);
});
}
export function unbindKeyboardShortcuts(context) {
const _removeEvent = (object, type, callback) => {
if (object.removeEventListener) {
object.removeEventListener(type, callback, false);
return;
}
object.detachEvent('on' + type, callback);
};
Array.isArray(context._mousetraps) && context._mousetraps.forEach(mousetrap => {
// manually unbind JS event
_removeEvent(mousetrap.target, 'keypress', mousetrap._handleKeyEvent);
_removeEvent(mousetrap.target, 'keydown', mousetrap._handleKeyEvent);
_removeEvent(mousetrap.target, 'keyup', mousetrap._handleKeyEvent);
mousetrap.reset();
});
context._mousetraps = [];
}
|
/**
* Transforms __ref to ref
* @param {object} props
* @returns {object}
* @private
*/
export default (oldProps = {}) => {
const { __ref, ...props } = oldProps
if (!__ref) return oldProps
return { ...props, ref: __ref }
}
|
sdkaskdj
|
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import {
getDatePicker,
selectDateTime,
} from 'ember-date-components/test-support/helpers/date-picker';
import { selectTime } from 'ember-date-components/test-support/helpers/time-picker';
import moment from 'moment';
module('Integration | Component | date-time-picker', function (hooks) {
setupRenderingTest(hooks);
test('time picker is disabled if no value is set', async function (assert) {
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@onChange={{this.onChange}}
/>
`);
assert.dom('[data-time-picker-toggle-button] button').isDisabled();
});
test('selecting a time works with a value pre-set', async function (assert) {
let today = moment();
this.onChange = function (val) {
assert.equal(val.hours(), 14, 'hours are correct');
assert.equal(val.minutes(), 30, 'minutes are correct');
assert.equal(val.seconds(), 0, 'seconds are correct');
assert.equal(val.milliseconds(), 0, 'ms are correct');
assert.equal(val.year(), today.year(), 'year remains the same');
assert.equal(val.month(), today.month(), 'month remains the same');
assert.equal(val.date(), today.date(), 'date remains the same');
assert.equal(this.value, today, 'the value is not modified');
assert.step('onChange is called');
};
this.value = today;
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
await selectTime(this.element, '14:30');
assert.verifySteps(['onChange is called']);
});
test('time picker is disabled if disabled=true', async function (assert) {
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@onChange={{this.onChange}}
@disabled={{true}}
/>
`);
assert.dom('[data-time-picker-toggle-button] button').isDisabled();
});
test('time-picker value is pre-filled', async function (assert) {
let today = moment().hours(14).minutes(30).seconds(0).milliseconds(0);
this.value = today;
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
assert.dom('[data-time-picker-toggle-button]').hasText('02:30 pm');
});
test('ignoreZeroTime works', async function (assert) {
let today = moment();
today.hours(0);
today.minutes(0);
today.seconds(0);
today.milliseconds(0);
this.value = today;
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
assert
.dom('[data-time-picker-toggle-button]')
.hasText('Enter time...', 'value is empty if time is 00:00');
});
test('ignoreZeroTime can be disabled', async function (assert) {
let today = moment();
today.hours(0);
today.minutes(0);
today.seconds(0);
today.milliseconds(0);
this.value = today;
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@value={{this.value}}
@ignoreZeroTime={{false}}
@onChange={{this.onChange}}
/>
`);
assert
.dom('[data-time-picker-toggle-button]')
.hasText('12:00 am', 'value is 00:00 if ignoreZeroTime=false');
});
test('date picker is not disabled if no value is set', async function (assert) {
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@onChange={{this.onChange}}
/>
`);
let datePicker = getDatePicker(this.element);
assert.dom(datePicker.buttonElement).isNotDisabled();
});
test('date picker is disabled if disabled=true', async function (assert) {
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@disabled={{true}}
@value={{now}}
@onChange={{this.onChange}}
/>
`);
let datePicker = getDatePicker(this.element);
assert.dom(datePicker.buttonElement).hasAttribute('disabled');
});
test('selecting a date works without a value pre-set', async function (assert) {
let today = moment('2017-05-13');
this.onChange = function (val) {
assert.equal(val.hours(), today.hours(), 'hours remain the same');
assert.equal(val.minutes(), today.minutes(), 'minutes remain the same');
assert.equal(val.seconds(), today.seconds(), 'seconds remain the same');
assert.equal(
val.milliseconds(),
today.milliseconds(),
'ms remain the same'
);
assert.equal(val.year(), 2017, 'year is correct');
assert.equal(val.month(), 4, 'month is correct');
assert.equal(val.date(), 6, 'date is correct');
assert.equal(this.value, today, 'the value is not modified');
assert.step('onChange is called');
};
this.value = today;
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
let datePicker = getDatePicker(this.element);
await datePicker.toggle();
await datePicker.selectDate(moment('2017-05-06'));
assert.verifySteps(['onChange is called']);
});
test('selecting a date works with a value pre-set', async function (assert) {
let today = moment();
this.onChange = function (val) {
assert.equal(val.hours(), 0, 'hours defaults to 0');
assert.equal(val.minutes(), 0, 'minutes defaults to 0');
assert.equal(val.seconds(), 0, 'seconds defaults to 0');
assert.equal(val.milliseconds(), 0, 'ms defaults to 0');
assert.equal(val.year(), today.year(), 'year is correct');
assert.equal(val.month(), today.month(), 'month is correct');
assert.equal(val.date(), today.date(), 'date is correct');
assert.step('onChange is called');
};
await render(hbs`
<DateTimePicker
@onChange={{this.onChange}}
/>
`);
let datePicker = getDatePicker(this.element);
await datePicker.toggle();
await datePicker.selectDate(today);
assert.verifySteps(['onChange is called']);
});
test('date-picker value is pre-filled', async function (assert) {
let today = moment('2017-05-13');
this.value = today;
this.onChange = () => {};
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
let datePicker = getDatePicker(this.element);
assert.equal(datePicker.buttonText(), today.format('L'));
});
test('setDateTime test helpers works', async function (assert) {
this.onChange = (val) => {
this.set('value', val);
assert.step('onChange is called');
};
this.value = null;
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
/>
`);
let targetDate = moment().add(2, 'day').hours(5).minutes(30);
await selectDateTime(this.element, targetDate);
assert.ok(
this.value.format('YYYY-MM-DD HH:mm'),
targetDate.format('YYYY-MM-DD HH:mm'),
'date is correctly updated'
);
assert.verifySteps(['onChange is called', 'onChange is called']);
});
module('named blocks', function () {
test('it allows to yield the components', async function (assert) {
let today = moment('2017-05-13');
this.onChange = function (val) {
assert.equal(val.hours(), today.hours(), 'hours remain the same');
assert.equal(val.minutes(), today.minutes(), 'minutes remain the same');
assert.equal(val.seconds(), today.seconds(), 'seconds remain the same');
assert.equal(
val.milliseconds(),
today.milliseconds(),
'ms remain the same'
);
assert.equal(val.year(), 2017, 'year is correct');
assert.equal(val.month(), 4, 'month is correct');
assert.equal(val.date(), 6, 'date is correct');
assert.equal(this.value, today, 'the value is not modified');
assert.step('onChange is called');
};
this.value = today;
await render(hbs`
<DateTimePicker
@value={{this.value}}
@onChange={{this.onChange}}
>
<:date as |DatePicker|>
<DatePicker />
</:date>
<:time as |TimePicker|>
<TimePicker />
</:time>
</DateTimePicker>
`);
let datePicker = getDatePicker(this.element);
await datePicker.toggle();
await datePicker.selectDate(moment('2017-05-06'));
assert.verifySteps(['onChange is called']);
});
test('it allows to pass arguments to yielded components', async function (assert) {
this.onChange = function () {};
await render(hbs`
<DateTimePicker
@onChange={{this.onChange}}
>
<:date as |DatePicker|>
<DatePicker @placeholder='test 1' />
</:date>
<:time as |TimePicker|>
<TimePicker @placeholder='test 2' />
</:time>
</DateTimePicker>
`);
assert.dom('[data-time-picker-toggle-button]').hasText('test 2');
});
});
});
|
export var SKIP_DJ_START = 'moderation/SKIP_DJ_START';
export var SKIP_DJ_COMPLETE = 'moderation/SKIP_DJ_COMPLETE';
export var MOVE_USER_START = 'moderation/MOVE_USER_START';
export var MOVE_USER_COMPLETE = 'moderation/MOVE_USER_COMPLETE';
export var REMOVE_USER_START = 'moderation/REMOVE_USER_START';
export var REMOVE_USER_COMPLETE = 'moderation/REMOVE_USER_COMPLETE';
export var MUTE_USER_START = 'moderation/MUTE_USER_START';
export var MUTE_USER_COMPLETE = 'moderation/MUTE_USER_COMPLETE';
export var UNMUTE_USER_START = 'moderation/UNMUTE_USER_START';
export var UNMUTE_USER_COMPLETE = 'moderation/UNMUTE_USER_COMPLETE';
export var BAN_USER_START = 'moderation/BAN_USER_START';
export var BAN_USER_COMPLETE = 'moderation/BAN_USER_COMPLETE';
export var ADD_USER_ROLES_START = 'moderation/ADD_USER_ROLES_START';
export var ADD_USER_ROLES_COMPLETE = 'moderation/ADD_USER_ROLES_COMPLETE';
export var REMOVE_USER_ROLES_START = 'moderation/REMOVE_USER_ROLES_START';
export var REMOVE_USER_ROLES_COMPLETE = 'moderation/REMOVE_USER_ROLES_COMPLETE';
//# sourceMappingURL=moderation.js.map
|
export { default } from 'supertree-auth/login/serializer';
|
import Ember from 'ember';
import DS from 'ember-data';
import ModelDefinition from './model-definition';
import FixtureBuilderFactory from './fixture-builder-factory';
var FactoryGuy = function () {
var modelDefinitions = {};
var store = null;
var fixtureBuilderFactory = null;
var fixtureBuilder = null;
/**
```javascript
Person = DS.Model.extend({
type: DS.attr('string'),
name: DS.attr('string')
})
FactoryGuy.define('person', {
sequences: {
personName: function(num) {
return 'person #' + num;
},
personType: function(num) {
return 'person type #' + num;
}
},
default: {
type: 'normal',
name: FactoryGuy.generate('personName')
},
dude: {
type: FactoryGuy.generate('personType')
},
});
```
For the Person model, you can define named fixtures like 'dude' or
just use 'person' and get default values.
And to get those fixtures you would call them this way:
FactoryGuy.build('dude') or FactoryGuy.build('person')
@param {String} model the model to define
@param {Object} config your model definition
*/
this.define = function (model, config) {
modelDefinitions[model] = new ModelDefinition(model, config);
};
/*
@param model name of named fixture type like: 'admin' or model name like 'user'
@returns {ModelDefinition} if there is one matching that name
*/
this.findModelDefinition = function (model) {
return modelDefinitions[model];
};
/*
Using JSONAPI style data?
*/
this.useJSONAPI = function () {
return fixtureBuilderFactory.useJSONAPI();
};
/**
Setting the store so FactoryGuy can do some model introspection.
Also setting the correct fixtureBuilderFactory and fixtureBuilder.
*/
this.setStore = function (aStore) {
Ember.assert("FactoryGuy#setStore needs a valid store instance.You passed in [" + aStore + "]", aStore instanceof DS.Store);
store = aStore;
fixtureBuilderFactory = new FixtureBuilderFactory(store);
fixtureBuilder = fixtureBuilderFactory.getFixtureBuilder();
};
this.getStore = function () {
return store;
};
this.getFixtureBuilder = function () {
return fixtureBuilder;
};
/**
Used in model definitions to declare use of a sequence. For example:
```
FactoryGuy.define('person', {
sequences: {
personName: function(num) {
return 'person #' + num;
}
},
default: {
name: FactoryGuy.generate('personName')
}
});
```
@param {String|Function} value previously declared sequence name or
an inline function to use as the sequence
@returns {Function} wrapper function that is called by the model
definition containing the sequence
*/
this.generate = function (nameOrFunction) {
var sortaRandomName = Math.floor((1 + Math.random()) * 65536).toString(16) + Date.now();
return function () {
// this function will be called by ModelDefinition, which has it's own generate method
if (Ember.typeOf(nameOrFunction) === 'function') {
return this.generate(sortaRandomName, nameOrFunction);
} else {
return this.generate(nameOrFunction);
}
};
};
/**
Used in model definitions to define a belongsTo association attribute.
For example:
```
FactoryGuy.define('project', {
default: {
title: 'Project'
},
// setup named project with built in associated user
project_with_admin: {
user: FactoryGuy.belongsTo('admin')
}
// or use as a trait
traits: {
with_admin: {
user: FactoryGuy.belongsTo('admin')
}
}
})
```
@param {String} fixtureName fixture name
@param {Object} opts options
@returns {Function} wrapper function that will build the association json
*/
this.belongsTo = function (fixtureName, opts) {
var self = this;
return function () {
return self.buildSingle(fixtureName, opts);
};
};
/**
Used in model definitions to define a hasMany association attribute.
For example:
```
FactoryGuy.define('user', {
default: {
name: 'Bob'
},
// define the named user type that will have projects
user_with_projects: { FactoryGuy.hasMany('project', 2) }
// or use as a trait
traits: {
with_projects: {
projects: FactoryGuy.hasMany('project', 2)
}
}
})
```
@param {String} fixtureName fixture name
@param {Number} number of hasMany association items to build
@param {Object} opts options
@returns {Function} wrapper function that will build the association json
*/
this.hasMany = function (fixtureName, number, opts) {
return function () {
return buildSingleList(fixtureName, number, opts);
};
};
/**
Given a fixture name like 'person' or 'dude' determine what model this name
refers to. In this case it's 'person' for each one.
@param {String} name a fixture name could be model name like 'person'
or a named person in model definition like 'dude'
@returns {String} model name associated with fixture name or undefined if not found
*/
var lookupModelForFixtureName = function (name) {
var definition = lookupDefinitionForFixtureName(name);
if (definition) {
return definition.modelName;
}
};
/**
@param {String} name a fixture name could be model name like 'person'
or a named person in model definition like 'dude'
@returns {ModelDefinition} ModelDefinition associated with model or undefined if not found
*/
var lookupDefinitionForFixtureName = function (name) {
for (var model in modelDefinitions) {
var definition = modelDefinitions[model];
if (definition.matchesName(name)) {
return definition;
}
}
};
/**
extract arguments for build and make function
@param {String} name fixture name
@param {String} trait optional trait names ( one or more )
@param {Object} opts optional fixture options that will override default fixture values
@returns {Object} json fixture
*/
var extractArguments = function () {
var args = Array.prototype.slice.call(arguments);
var opts = {};
var name = args.shift();
if (!name) {
throw new Error('Build needs a factory name to build');
}
if (Ember.typeOf(args[args.length - 1]) === 'object') {
opts = args.pop();
}
// whatever is left are traits
var traits = Ember.A(args).compact();
return {name: name, opts: opts, traits: traits};
};
/**
Build fixtures for model or specific fixture name.
For example:
```
FactoryGuy.build('user') for User model
FactoryGuy.build('bob') for a 'bob' User
FactoryGuy.build('bob', 'dude') for a 'bob' User with dude traits
FactoryGuy.build('bob', 'dude', 'funny') for a 'bob' User with dude and funny traits
FactoryGuy.build('bob', 'dude', {name: 'wombat'}) for a 'bob' User with dude trait and custom attribute name of 'wombat'
```
@param {String} name fixture name
@param {String} trait optional trait names ( one or more )
@param {Object} opts optional fixture options that will override default fixture values
@returns {Object} json fixture
*/
this.build = function () {
var args = extractArguments.apply(this, arguments);
var fixture = this.buildSingle.apply(this, arguments);
var modelName = lookupModelForFixtureName(args.name);
return fixtureBuilder.convertForBuild(modelName, fixture);
};
this.buildSingle = function () {
var args = extractArguments.apply(this, arguments);
var definition = lookupDefinitionForFixtureName(args.name);
if (!definition) {
throw new Error('Can\'t find that factory named [' + args.name + ']');
}
return definition.build(args.name, args.opts, args.traits);
};
/**
Build list of fixtures for model or specific fixture name. For example:
```
FactoryGuy.buildList('user', 2) for 2 User models
FactoryGuy.build('bob', 2) for 2 User model with bob attributes
```
@param {String} name fixture name
@param {Number} number number of fixtures to create
@param {String} trait optional traits (one or more)
@param {Object} opts optional fixture options that will override default fixture values
@returns {Array} list of fixtures
*/
this.buildList = function () {
var args = Array.prototype.slice.call(arguments);
var name = args.shift();
var list = buildSingleList.apply(this, arguments);
var modelName = lookupModelForFixtureName(name);
return fixtureBuilder.convertForBuild(modelName, list);
};
var buildSingleList = function () {
var args = Array.prototype.slice.call(arguments);
var name = args.shift();
var number = args.shift();
if (!name || Ember.isEmpty(number)) {
throw new Error('buildList needs a name and a number ( at least ) to build with');
}
var opts = {};
if (Ember.typeOf(args[args.length - 1]) === 'object') {
opts = args.pop();
}
// whatever is left are traits
var traits = Ember.A(args).compact();
var definition = lookupDefinitionForFixtureName(name);
if (!definition) {
throw new Error("Can't find that factory named [" + name + "]");
}
return definition.buildList(name, number, traits, opts);
};
/**
Make new fixture and save to store.
@param {String} name fixture name
@param {String} trait optional trait names ( one or more )
@param {Object} options optional fixture options that will override default fixture values
@returns {DS.Model} record
*/
this.make = function () {
var args = extractArguments.apply(this, arguments);
Ember.assert(
"FactoryGuy does not have the application's store." +
" Use FactoryGuy.setStore(store) before making any fixtures", store
);
var modelName = lookupModelForFixtureName(args.name);
var fixture = this.buildSingle.apply(this, arguments);
var data = fixtureBuilder.convertForMake(modelName, fixture);
var model = makeModel.call(this, modelName, data);
var definition = lookupDefinitionForFixtureName(args.name);
if (definition.hasAfterMake()) {
definition.applyAfterMake(model, args.opts);
}
return model;
};
/**
Push JSONAPI formatted data into the store to make the model.
@param modelName
@param data which might or might not be formatted in JSONAPI style
@returns {DS.Model} instance of DS.Model
*/
var makeModel = function (modelName, data) {
var model;
Ember.run(function () {
model = store.push(data);
});
return model;
};
/**
Make a list of Fixtures
@param {String} name name of fixture
@param {Number} number number to create
@param {String} trait optional trait names ( one or more )
@param {Object} options optional fixture options that will override default fixture values
@returns {Array} list of json fixtures or records depending on the adapter type
*/
this.makeList = function () {
Ember.assert("FactoryGuy does not have the application's store. Use FactoryGuy.setStore(store) before making any fixtures", store);
var arr = [];
var args = Array.prototype.slice.call(arguments);
Ember.assert("makeList needs at least 2 arguments, a name and a number", args.length >= 2);
var number = args.splice(1, 1)[0];
Ember.assert("Second argument to makeList should be a number (of fixtures to make.)", typeof number === 'number');
for (var i = 0; i < number; i++) {
arr.push(this.make.apply(this, args));
}
return arr;
};
/**
Clear model instances from store cache.
Reset the id sequence for the models back to zero.
*/
this.clearStore = function () {
this.resetDefinitions();
this.clearModels();
};
/**
Reset the id sequence for the models back to zero.
*/
this.resetDefinitions = function () {
for (var model in modelDefinitions) {
var definition = modelDefinitions[model];
definition.reset();
}
};
/**
Clear model instances from store cache.
*/
this.clearModels = function () {
store.unloadAll();
};
/**
Push fixture to model's FIXTURES array.
Used when store's adapter is a DS.FixtureAdapter.
@param {DS.Model} modelClass
@param {Object} fixture the fixture to add
@returns {Object} json fixture data
*/
this.pushFixture = function (modelClass, fixture) {
var index;
if (!modelClass.FIXTURES) {
modelClass.FIXTURES = [];
}
index = this.indexOfFixture(modelClass.FIXTURES, fixture);
if (index > -1) {
modelClass.FIXTURES.splice(index, 1);
}
modelClass.FIXTURES.push(fixture);
return fixture;
};
/**
Used in compliment with pushFixture in order to
ensure we don't push duplicate fixtures
@private
@param {Array} fixtures
@param {String|Integer} id of fixture to find
@returns {Object} fixture
*/
this.indexOfFixture = function (fixtures, fixture) {
var index = -1,
id = fixture.id + '';
Ember.A(fixtures).find(function (r, i) {
if ('' + Ember.get(r, 'id') === id) {
index = i;
return true;
} else {
return false;
}
});
return index;
};
/**
Clears all model definitions
*/
this.clearDefinitions = function (opts) {
if (!opts) {
modelDefinitions = {};
}
};
};
var factoryGuy = new FactoryGuy();
//To accomodate for phantomjs ( older versions do not recognise bind method )
var make = function () {
return factoryGuy.make.apply(factoryGuy, arguments);
};
var makeList = function () {
return factoryGuy.makeList.apply(factoryGuy, arguments);
};
var build = function () {
return factoryGuy.build.apply(factoryGuy, arguments);
};
var buildList = function () {
return factoryGuy.buildList.apply(factoryGuy, arguments);
};
var clearStore = function () {
return factoryGuy.clearStore.apply(factoryGuy, arguments);
};
export { make, makeList, build, buildList, clearStore };
export default factoryGuy;
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './GridItem.css';
const placeholder = require('../../assets/imgholder.png');
class GridItem extends Component {
static defaultProps = {
aspect: "cover",
};
constructor(props) {
super(props);
// Check if the img value is null; if so we need to input placeholder
let img = this.props.img;
let empty = false;
if(img == null) {
img = placeholder;
empty = true;
}
this.state = {
imageStyle: {
backgroundImage: "url(" + img + ")",
// Use the given backgroundSize unless using placeholder
backgroundSize: empty ? "cover" : this.props.aspect
}
}
}
render() {
return (
<Link to={ this.props.url } className="grid-item">
<div className="grid-item-container">
<div className="cover-image" style={this.state.imageStyle}>
<div className="item-detail-list">
{
this.props.details.map( d =>
<div key={d.title} className="item">
<div className="item-detail-title">{d.title}</div>
<div className="item-detail-content">{d.content}</div>
</div>
)
}
</div>
</div>
<div className="item-detail">
<div className="item-title">{ this.props.name.length > 23 ? this.props.name.substring(0, 20) + "..." : this.props.name }</div>
</div>
</div>
</Link>
);
}
}
export default GridItem;
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('wpsite generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
const jwt = require("jsonwebtoken");
module.exports = (UserModel, Config, CryptoHelper) => {
function _transformUser (user) {
return {
"id": user._id,
"name": user.name,
"isAdmin": user.isAdmin,
"created": user.createdAt,
"updated": user.updatedAt
}
}
async function signIn (username, userpassword) {
// search for username
const foundUser = await UserModel.findOne({ name: username }).lean();
// validate founduser
if (!foundUser) throw new Error("Authentication failed. User not found.")
if (userpassword !== CryptoHelper.decrypt(foundUser.passwordHash)) throw new Error("Authentication failed. Wrong password.");
// create a token
const token = await jwt.sign(foundUser, Config.tokenSecret, {
expiresIn: Config.tokenExpires,
issuer: Config.tokenIssuer
});
// delete password before return the user
delete foundUser.passwordHash;
// return token and user
return {
token: token,
user: this._transformUser(foundUser)
}
}
async function signUp (username, userpassword, isAdmin) {
// try to find the user
const foundUser = await UserModel.findOne({name: username}).lean();
// check if user is available
if (foundUser) throw new Error("Username is already registered. Please use another Username.");
// create new User object
const newUser = new UserModel({
name: username,
passwordHash: CryptoHelper.encrypt(userpassword),
isAdmin: isAdmin
});
// save new User object
const createdUser = await newUser.save();
// delete password before return the user
delete createdUser.passwordHash;
// return user
return {
user: this._transformUser(createdUser)
}
}
return {
_transformUser,
signIn,
signUp
}
}
|
var express = require('express');
var app = express();
app.use(function(req,res,next){
console.log(req.url);
next();
});
app.all('/jsonp',function(req,res){
var data = req.query;
var callback = data.cb;
res.send(callback+'({s:["a","a2","a3"]})');
});
app.listen(8080);
|
var EpubParser;
//var sax = require('./sax');
EpubParser = (function() {
var jszip = require('node-zip');
var zip, zipEntries;
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var request = require('request');
var fs = require('fs');
function extractText(filename) {
//console.log('extracting '+filename);
var file = zip.file(filename);
if(typeof file !== 'undefined' || file !== null) {
return file.asText();
} else {
throw 'file '+filename+' not found in zip';
}
}
function extractBinary(filename) {
var file = zip.file(filename);
if(typeof file !== 'undefined') {
return file.asBinary();
} else {
return '';
}
}
function safeAccess(supposedArray) {
// a quick bandaid to handle undefined lists
// coming back from the parser - poor fix TODO
if(typeof supposedArray === 'undefined') {
return new Array();
} else {
return supposedArray;
}
}
function open(filename, cb) {
/*
"filename" is still called "filename" but now it can be
a full file path, a full URL, or a Buffer object
we should eventually change its name...
*/
var epubdata = {};
var md5hash;
var htmlNav = '<ul>';
var container, opf, ncx,
opfPath, ncxPath, opsRoot,
uniqueIdentifier, uniqueIdentifierValue, uniqueIdentifierScheme = null,
opfDataXML, ncxDataXML,
opfPrefix = '', dcPrefix = '', ncxPrefix = '',
metadata, manifest, spine, guide, nav,
root, ns, ncxId,
epub3CoverId, epub3NavId, epub3NavHtml, epub2CoverUrl = null,
isEpub3, epubVersion;
var itemlist, itemreflist;
var itemHashById = {};
var itemHashByHref = {};
var linearSpine = {};
var spineOrder = [];
var simpleMeta = [];
function readAndParseData(/* Buffer */ data, cb) {
md5hash = require('crypto').createHash('md5').update(data).digest("hex");
zip = new jszip(data.toString('binary'), {binary:true, base64: false, checkCRC32: true});
var containerData = extractText('META-INF/container.xml');
parseEpub(containerData, function (err,epubData) {
if(err) return cb(err);
cb(null,epubData);
});
}
function parseEpub(containerDataXML, finalCallback) {
/*
Parsing chain walking down the metadata of an epub,
and storing it in the JSON config object
*/
parser.parseString(containerDataXML, function (err, containerJSON) {
parseContainer(err, containerJSON, finalCallback);
});
}
function parseContainer(err, containerJSON, finalCallback) {
var cb = finalCallback;
if(err) return cb(err);
container = containerJSON.container;
// determine location of OPF
opfPath = root = container.rootfiles[0].rootfile[0]["$"]["full-path"];
// console.log('opfPath is:'+opfPath);
// set the opsRoot for resolving paths
if(root.match(/\//)) { // not at top level
opsRoot = root.replace(/\/([^\/]+)\.opf/i, '');
if(!opsRoot.match(/\/$/)) { // does not end in slash, but we want it to
opsRoot += '/';
}
if(opsRoot.match(/^\//)) {
opsRoot = opsRoot.replace(/^\//, '');
}
} else { // at top level
opsRoot = '';
}
console.log('opsRoot is:'+opsRoot+' (derived from '+root+')');
// get the OPF data and parse it
console.log('parsing OPF data');
opfDataXML = extractText(root);
parser.parseString(opfDataXML.toString(), function (err, opfJSON) {
if(err) return cb(err);
// store opf data
opf = (opfJSON["opf:package"]) ? opfJSON["opf:package"] : opfJSON["package"];
uniqueIdentifier = opf["$"]["unique-identifier"];
epubVersion = opf["$"]["version"][0];
isEpub3 = (epubVersion=='3'||epubVersion=='3.0') ? true : false;
// console.log('epub version:'+epubVersion);
for(att in opf["$"]) {
if(att.match(/^xmlns\:/)) {
ns = att.replace(/^xmlns\:/,'');
if(opf["$"][att]=='http://www.idpf.org/2007/opf') opfPrefix = ns+':';
if(opf["$"][att]=='http://purl.org/dc/elements/1.1/') dcPrefix = ns+':';
}
}
parsePackageElements();
// spine
itemlist = manifest.item;
itemreflist = spine.itemref;
buildItemHashes();
buildLinearSpine();
// metadata
buildMetadataLists();
if(!ncxId) { // assume epub 3 navigation doc
if(!isEpub3) cb(new Error('ncx id not found but package indicates epub 2'));
ncxDataXML = '';
ncx = {};
ncxPath = '';
htmlNav = null;
if(!epub3NavHtml) return cb(new Error('epub 3 with no nav html'));
parser.parseString(epub3NavHtml, function (err, navJSON) {
if(err) return cb(err);
nav = navJSON;
epubdata = getEpubDataBlock();
cb(null, epubdata);
});
} else { // epub 2, use ncx doc
for(item in manifest[opfPrefix+"item"]) {
if(manifest[opfPrefix+"item"][item]["$"].id==ncxId) {
ncxPath = opsRoot + manifest[opfPrefix+"item"][item]["$"].href;
}
}
//console.log('determined ncxPath:'+ncxPath);
ncxDataXML = extractText(ncxPath);
parser.parseString(ncxDataXML.toString(), function (err, ncxJSON) {
if(err) return cb(err);
function setPrefix(ncxJSON) {
for(att in ncxJSON["$"]) {
//console.log(att);
if(att.match(/^xmlns\:/)) {
var ns = att.replace(/^xmlns\:/,'');
if(ncxJSON["$"][att]=='http://www.daisy.org/z3986/2005/ncx/') ncxPrefix = ns+':';
}
}
}
// grab the correct ns prefix for ncx
for(prop in ncxJSON) {
//console.log(prop);
if(prop === '$') { // normal parse result
setPrefix(ncxJSON);
} else {
if(typeof ncxJSON[prop]['$'] !== 'undefined') {
//console.log(ncxJSON[prop]['$']);
setPrefix(ncxJSON[prop]);
}
}
}
ncx = ncxJSON[ncxPrefix+"ncx"];
var navPoints = ncx[ncxPrefix+"navMap"][0][ncxPrefix+"navPoint"];
for(var i = 0; i < safeAccess(navPoints).length; i++) {
processNavPoint(navPoints[i]);
}
htmlNav += '</ul>'+"\n";
epubdata = getEpubDataBlock();
cb(null,epubdata);
});
}
});
}
function processNavPoint(np) {
var text = 'Untitled';
var src = "#";
if(typeof np.navLabel !== 'undefined') {
text = np.navLabel[0].text[0];
}
if(typeof np.content !== 'undefined') {
src = np.content[0]["$"].src;
}
htmlNav += '<li><a href="'+src+'">'+text+'</a>';
if(typeof np.navPoint !== 'undefined') {
htmlNav += '<ul>';
for(var i = 0; i < safeAccess(np.navPoint).length; i++) {
processNavPoint(np.navPoint[i]);
}
htmlNav += '</ul>'+"\n";
}
htmlNav += '</li>'+"\n";
}
function buildItemHashes() {
for(item in itemlist) {
var href = itemlist[item].$.href;
var id = itemlist[item].$.id;
var mediaType = itemlist[item].$['media-type'];
var properties = itemlist[item].$['properties'];
if(typeof properties !== 'undefined') {
if(properties == 'cover-image') {
epub3CoverId = id;
} else if (properties == 'nav') {
epub3NavId = id;
epub3NavHtml = extractText(opsRoot+href);
}
}
itemHashByHref[href] = itemlist[item];
itemHashById[id] = itemlist[item];
}
var itemrefs = itemreflist;
try {
ncxId = spine.$.toc;
} catch(e) {
;
}
}
function buildLinearSpine() {
for(itemref in itemreflist) {
var id = itemreflist[itemref].$.idref;
spineOrder.push(itemreflist[itemref].$);
if(itemreflist[itemref].$.linear=='yes' || typeof itemreflist[itemref].$.linear == 'undefined') {
itemreflist[itemref].$.item = itemHashById[id];
linearSpine[id] = itemreflist[itemref].$;
}
}
}
function buildMetadataLists() {
var metas = metadata;
for(prop in metas) {
if(prop == 'meta') { // process a list of meta tags
for(var i = 0; i < safeAccess(metas[prop]).length; i++) {
var m = metas[prop][i].$;
if(typeof m.name !== 'undefined') {
var md = {};
md[m.name] = m.content;
simpleMeta.push(md);
} else if (typeof m.property !== 'undefined') {
var md = {};
md[m.property] = metas[prop][i]._;
simpleMeta.push(md);
}
if(m.name == 'cover') {
if (typeof itemHashById[m.content] !== 'undefined') {
epub2CoverUrl = opsRoot + itemHashById[m.content].$.href;
}
}
}
} else if(prop != '$') {
var content = '';
var atts = {};
if(metas[prop][0]) {
if(metas[prop][0].$ || metas[prop][0]._) { // complex tag
content = (metas[prop][0]._) ?
metas[prop][0]._ :
metas[prop][0];
if(metas[prop][0].$) { // has attributes
for(att in metas[prop][0].$) {
atts[att]=metas[prop][0].$[att];
}
}
} else { // simple one, if object, assume empty
content = (typeof metas[prop][0] == 'object') ? '' : metas[prop][0];
}
}
if(typeof prop !== 'undefined') {
var md = {};
md[prop] = content;
simpleMeta.push(md);
}
if(prop.match(/identifier$/i)) {
if(typeof metas[prop][0].$.id) {
if(metas[prop][0].$.id==uniqueIdentifier) {
if(typeof content == 'object') {
console.log('warning - content not fully parsed');
console.log(content);
console.log(metas[prop][0].$.id);
} else {
uniqueIdentifierValue = content;
if(typeof metas[prop][0].$.scheme !== 'undefined') {
uniqueIdentifierScheme= metas[prop][0].$.scheme;
}
}
}
};
}
}
}
}
function parsePackageElements() {
// operates on global vars
if(typeof opf[opfPrefix+"manifest"] === 'undefined') {
// it's a problem
// gutenberg files, for example will lead to this condition
// we must assume that tags are not actually namespaced
opfPrefix = '';
}
try {
metadata = opf[opfPrefix+"metadata"][0];
} catch(e) {
console.log('metadata element error: '+e.message);
console.log('are the tags really namespaced with '+opfPrefix+' or not? file indicates they should be.');
}
try {
manifest = opf[opfPrefix+"manifest"][0];
} catch (e) {
console.log('manifest element error: '+e.message);
console.log('are the tags really namespaced with '+opfPrefix+' or not? file indicates they should be.');
console.log(opfDataXML);
console.log(opf);
console.log('must throw this - unrecoverable');
throw (e);
}
try {
spine = opf[opfPrefix+"spine"][0];
} catch(e) {
console.log('spine element error: '+e.message);
console.log('must throw this');
throw (e);
}
try {
guide = opf[opfPrefix+"guide"][0];
} catch (e) {
;
}
}
function getEpubDataBlock()
{
return {
easy: {
primaryID: {
name:uniqueIdentifier,
value:uniqueIdentifierValue,
scheme:uniqueIdentifierScheme
},
epubVersion: epubVersion,
isEpub3: isEpub3,
md5: md5hash,
epub3NavHtml: epub3NavHtml,
navMapHTML: htmlNav,
linearSpine: linearSpine,
itemHashById: itemHashById,
itemHashByHref: itemHashByHref,
linearSpine: linearSpine,
simpleMeta: simpleMeta,
epub3CoverId: epub3CoverId,
epub3NavId: epub3NavId,
epub2CoverUrl: epub2CoverUrl
},
paths: {
opfPath: opfPath,
ncxPath: ncxPath,
opsRoot: opsRoot
},
raw: {
json: {
prefixes: {
opfPrefix:opfPrefix,
dcPrefix:dcPrefix,
ncxPrefix:ncxPrefix
},
container: container,
opf: opf,
ncx: ncx,
nav: nav
},
xml: {
opfXML: opfDataXML,
ncxXML: ncxDataXML
}
}
};
}
if(Buffer.isBuffer(filename)) {
console.log('epub-parser parsing from buffer, not file');
readAndParseData(filename, cb);
} else if(filename.match(/^https?:\/\//i)) { // is a URL
request({
uri:filename,
encoding:null /* sets the response to be a buffer */
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var b = body;
readAndParseData(b, cb);
} else {
cb(error,null);
}
});
} else { // assume local full path to file
fs.readFile(filename, 'binary', function (err, data) {
if(err) return cb(err);
readAndParseData(data, cb);
});
}
} // end #open function definition block
return {
open:open,
getZip:function () { return zip; },
getJsZip: function () { return jszip; },
extractBinary: extractBinary,
extractText: extractText
};
})();
module.exports = EpubParser;
|
class Button {
constructor(arg) {
arg.type = 'button'
this.element = buildElement(arg)
this.addTo = function(parentId) {
var parent = document.getElementById(parentId)
parent.appendChild(this.element)
}
}
}
class Input {
constructor(arg) {
arg.type = 'input'
this.element = buildElement(arg)
this.addTo = function(parentId) {
var parent = document.getElementById(parentId)
parent.appendChild(this.element)
}
}
}
class Header {
constructor(arg) {
var headerWrapping = buildElement({type: 'div', attributes: {id: 'header-wrapping'}})
headerWrapping.appendChild(buildElement({type: 'h1', attributes: {id: 'header-title'}, innerHTML: arg.title || 'Titel'}))
headerWrapping.appendChild(buildElement({type: 'div', attributes: {id: 'header-actions'}}))
document.body.appendChild(headerWrapping)
this.setTitle = function(newTitle) {
document.getElementById('header-title').innerHTML = newTitle
}
this.remove = function() {
this.parentNode.removeChild(this)
}
}
}
function buildElement(arg) {
if(typeof arg.type == 'undefined') {throw new Error(['Missing build arguments'])}
var element = document.createElement(arg.type)
element.appendChild(document.createTextNode(arg.innerHTML || ''))
for(var key in arg.attributes) {
element.setAttribute(key, arg.attributes[key])
}
var style = ""
for(var key in arg.styles) {
style = style + key + ': ' + arg.styles[key] + '; '
}
if(style.length > 0) { element.setAttribute('style', style) }
return element
}
|
var group__eth__mac__interface__gr =
[
[ "Ethernet MAC Events", "group__ETH__MAC__events.html", "group__ETH__MAC__events" ],
[ "Ethernet MAC Control Codes", "group__eth__mac__control.html", "group__eth__mac__control" ],
[ "Ethernet MAC Timer Control Codes", "group__eth__mac__time__control.html", "group__eth__mac__time__control" ],
[ "Ethernet MAC Frame Transmit Flags", "group__eth__mac__frame__transmit__ctrls.html", "group__eth__mac__frame__transmit__ctrls" ],
[ "ARM_ETH_MAC_CAPABILITIES", "group__eth__mac__interface__gr.html#structARM__ETH__MAC__CAPABILITIES", [
[ "checksum_offload_rx_ip4", "group__eth__mac__interface__gr.html#a0051111be2e389c3161da1c444746216", null ],
[ "checksum_offload_rx_ip6", "group__eth__mac__interface__gr.html#a674b2306c64901e924b3cb7bb882f32f", null ],
[ "checksum_offload_rx_udp", "group__eth__mac__interface__gr.html#a5a447f05a5fbfd35896aad9cd769511c", null ],
[ "checksum_offload_rx_tcp", "group__eth__mac__interface__gr.html#a730d6be6a7b868e0690d9548e77b7aae", null ],
[ "checksum_offload_rx_icmp", "group__eth__mac__interface__gr.html#a142179445bfdbaaaf0d451f277fb0e96", null ],
[ "checksum_offload_tx_ip4", "group__eth__mac__interface__gr.html#ac787d70407ce70e28724932fb32ef0ba", null ],
[ "checksum_offload_tx_ip6", "group__eth__mac__interface__gr.html#a8f7a154565e652d976b9e65bf3516504", null ],
[ "checksum_offload_tx_udp", "group__eth__mac__interface__gr.html#ab3f9560668a087606c40cd81b935396b", null ],
[ "checksum_offload_tx_tcp", "group__eth__mac__interface__gr.html#a6c2b80bbfe520f3e7808cf3d4aaedb45", null ],
[ "checksum_offload_tx_icmp", "group__eth__mac__interface__gr.html#a7b701bac9d66886b5c6964b20c6ca55a", null ],
[ "media_interface", "group__eth__mac__interface__gr.html#a3c5cb74e086417a01d0079f847a3fc8d", null ],
[ "mac_address", "group__eth__mac__interface__gr.html#a7fdea04bacd9c0e12792751055ef6238", null ],
[ "event_rx_frame", "group__eth__mac__interface__gr.html#a8c8f1ac2bf053a9bac98c476646a6018", null ],
[ "event_tx_frame", "group__eth__mac__interface__gr.html#a1b4af3590d59ea4f8e845b4239a4e445", null ],
[ "event_wakeup", "group__eth__mac__interface__gr.html#a7536d9b9818b20b6974a712e0449439b", null ],
[ "precision_timer", "group__eth__mac__interface__gr.html#a881a863974d32f95d7829f768ac47aa2", null ],
[ "reserved", "group__eth__mac__interface__gr.html#aa43c4c21b173ada1b6b7568956f0d650", null ]
] ],
[ "ARM_DRIVER_ETH_MAC", "group__eth__mac__interface__gr.html#structARM__DRIVER__ETH__MAC", [
[ "GetVersion", "group__eth__mac__interface__gr.html#a8834b281da48583845c044a81566c1b3", null ],
[ "GetCapabilities", "group__eth__mac__interface__gr.html#a9fd725bb058c584a9ced9c579561cdf1", null ],
[ "Initialize", "group__eth__mac__interface__gr.html#aa34417c70cb8b43567c59aa530866cc7", null ],
[ "Uninitialize", "group__eth__mac__interface__gr.html#adcf20681a1402869ecb5c6447fada17b", null ],
[ "PowerControl", "group__eth__mac__interface__gr.html#aba8f1c8019af95ffe19c32403e3240ef", null ],
[ "GetMacAddress", "group__eth__mac__interface__gr.html#a02837059933cd04b04bf795a7138f218", null ],
[ "SetMacAddress", "group__eth__mac__interface__gr.html#ac640f929dc4d5bde3e4282c75b25c00d", null ],
[ "SetAddressFilter", "group__eth__mac__interface__gr.html#a45b879a6df608f582d1866daff715798", null ],
[ "SendFrame", "group__eth__mac__interface__gr.html#ac095aea379f23e30a0e51b1f3518ad37", null ],
[ "ReadFrame", "group__eth__mac__interface__gr.html#a466b724be2167ea7d9a14569062a8fa8", null ],
[ "GetRxFrameSize", "group__eth__mac__interface__gr.html#a3286cc9c7624168b162aa3ce3cbe135e", null ],
[ "GetRxFrameTime", "group__eth__mac__interface__gr.html#a8ae5a588bf4055bba3de73cfba78f7e8", null ],
[ "GetTxFrameTime", "group__eth__mac__interface__gr.html#acf081f5020f4ef1435bcff7333a70b93", null ],
[ "ControlTimer", "group__eth__mac__interface__gr.html#ab6bdbdc7fdfcc52e027201738b88b431", null ],
[ "Control", "group__eth__mac__interface__gr.html#a6e0f47a92f626a971c5197fca6545505", null ],
[ "PHY_Read", "group__eth__mac__interface__gr.html#a0f2ddb734e4242077275761400b26e35", null ],
[ "PHY_Write", "group__eth__mac__interface__gr.html#ac3efe9bdc31c3b1d7fd8eb82bbfb4c13", null ]
] ],
[ "ARM_ETH_MAC_TIME", "group__eth__mac__interface__gr.html#structARM__ETH__MAC__TIME", [
[ "ns", "group__eth__mac__interface__gr.html#a048317f84621fb38ed0bf8c8255e26f0", null ],
[ "sec", "group__eth__mac__interface__gr.html#aaf5f5a3fa5d596a9136b4331f2b54bfc", null ]
] ],
[ "ARM_ETH_MAC_SignalEvent_t", "group__eth__mac__interface__gr.html#gadfc95cb09c541a29a72da86963668726", null ],
[ "ARM_ETH_MAC_GetVersion", "group__eth__mac__interface__gr.html#ga86b15062c297384ad5842dd57b9d6b1d", null ],
[ "ARM_ETH_MAC_GetCapabilities", "group__eth__mac__interface__gr.html#ga2b13b230502736d8c7679b359dff20d0", null ],
[ "ARM_ETH_MAC_Initialize", "group__eth__mac__interface__gr.html#gacf42d11b171cd032f0ec1de6db2b6832", null ],
[ "ARM_ETH_MAC_Uninitialize", "group__eth__mac__interface__gr.html#gacb2c2ae06f32328775bffbdeaaabfb5d", null ],
[ "ARM_ETH_MAC_PowerControl", "group__eth__mac__interface__gr.html#ga346fef040a0e9bac5762a04a306b1be7", null ],
[ "ARM_ETH_MAC_GetMacAddress", "group__eth__mac__interface__gr.html#ga66308c1e791952047e974bd653037fae", null ],
[ "ARM_ETH_MAC_SetMacAddress", "group__eth__mac__interface__gr.html#ga7cc3d17c7312c5032202dfd9a915f24a", null ],
[ "ARM_ETH_MAC_SetAddressFilter", "group__eth__mac__interface__gr.html#ga150fe30290275a4b32756f94208124e8", null ],
[ "ARM_ETH_MAC_SendFrame", "group__eth__mac__interface__gr.html#ga5bf58defdb239ed7dc948f1da147a1c3", null ],
[ "ARM_ETH_MAC_ReadFrame", "group__eth__mac__interface__gr.html#ga4b79f57d8624bb4410ee12c73a483993", null ],
[ "ARM_ETH_MAC_GetRxFrameSize", "group__eth__mac__interface__gr.html#ga5ee86d6b0efab5329b9bc191c23a466d", null ],
[ "ARM_ETH_MAC_GetRxFrameTime", "group__eth__mac__interface__gr.html#gaa7c6865fb09754be869778142466c5e4", null ],
[ "ARM_ETH_MAC_GetTxFrameTime", "group__eth__mac__interface__gr.html#ga115b5c7e149aec2b181de760f5d83f60", null ],
[ "ARM_ETH_MAC_Control", "group__eth__mac__interface__gr.html#gac3e90c66058d20077f04ac8e8b8d0536", null ],
[ "ARM_ETH_MAC_ControlTimer", "group__eth__mac__interface__gr.html#ga85d9dc865af3702b71a514b18a588643", null ],
[ "ARM_ETH_MAC_PHY_Read", "group__eth__mac__interface__gr.html#gaded29ad58366e9222487db9944373c29", null ],
[ "ARM_ETH_MAC_PHY_Write", "group__eth__mac__interface__gr.html#ga79dd38672749aeebd28f39d9b4f813ce", null ],
[ "ARM_ETH_MAC_SignalEvent", "group__eth__mac__interface__gr.html#gae0697be4c4229601f3bfc17e2978ada6", null ]
];
|
(function($){
$(document).ready(function(){
/**
* @type {Object}
*/
var app = {
delay_before_gridSquares_animation: 365,
gridSquares_AnimationTiming: 350,
btwEach_gridSquares_animationDelay: 50,
/**
* Init the app.
*/
init: function() {
// Display the best score of the player or save the default value if it is not set.
if(!localStorage.getItem('best'))
localStorage.setItem('best', 0);
// Display the best score of the player.
$('#best').find('.value').html(localStorage.getItem('best'));
// Get the score.
app.getPlayerScore();
// Display the username.
if(localStorage.getItem('username'))
$('.settings-wrapper', '#rules').find('.username').find('span').html(localStorage.getItem('username'));
// Display the game key.
if(localStorage.getItem('gamekey'))
$('.settings-wrapper', '#rules').find('.gamekey').find('span').html(localStorage.getItem('gamekey').toUpperCase());
// Hide the loader and display the controls screen if the player has not yet played.
setTimeout(function(){
if(!localStorage.getItem('best') || parseInt(localStorage.getItem('best'), 10) == 0)
$('#overlay').addClass('controls').find('.loader').addClass('hide').siblings('div').removeClass('hide');
else
$('#overlay').removeClass('show').find('.loader').addClass('hide');
}, 200);
// Show the "How to" text if the player has not yet played.
if(!localStorage.getItem('best') || parseInt(localStorage.getItem('best'), 10) == 0)
$('#how-to').removeClass('hide');
// Display the game in the language of the player or save the default value if it is not set.
if(!localStorage.getItem('lang'))
localStorage.setItem('lang', 'en');
else if(localStorage.getItem('lang') != 'en')
app.changeLanguage(localStorage.getItem('lang'));
// Display the game with the theme selected by the player or save the default value if it is not set.
if(!localStorage.getItem('theme'))
localStorage.setItem('theme', 'light');
else if(localStorage.getItem('theme') != 'light')
app.changeTheme(localStorage.getItem('theme'));
},
/**
* Change the language of the application.
* @param {str} lang
*/
changeLanguage: function(lang) {
$('html').attr('lang', lang);
},
/**
* Change the theme of the application.
* @param {str} theme
*/
changeTheme: function(theme) {
// Change the value of the toggle
$('.settings', '#rules').find('.theme')
.attr('data-theme-toggle', ((theme == 'light') ? 'dark' : 'light'));
// Change the elements for the theme.
$('*', document).filter('[data-theme]').addClass('hide')
$('*', document).filter('[data-theme=' + theme + ']').removeClass('hide');
// Change the theme of the application.
$('link', 'head').filter('.app-theme').attr('href', 'css/app-' + theme + '.css');
},
/**
* Run the animation of the grid.
*/
animateGrid: function() {
for(var i=1; i<=9; i++) {
setTimeout(function(i){
var $square = $('.square', '#grid')
.find('span:contains(' + i + ')')
.parents('.square');
$square.addClass('rotate');
setTimeout(function(){
$square.addClass('back')
}, 90);
setTimeout(function(){
$square.removeClass('active right not-found back')
}, 225);
if(i == 9) {
setTimeout(function(){
$('.square', '#grid').removeClass('rotate');
}, app.gridSquares_AnimationTiming);
}
}, this.btwEach_gridSquares_animationDelay * i, i);
}
},
/**
* Save the score in the leaderboard.
* @param {str} username The username of the player.
*/
saveScore: function(username) {
var data = {
username: username,
gamekey: localStorage.getItem('gamekey'),
score: parseInt(localStorage.getItem('best'), 10),
device: 'desktop',
lang: localStorage.getItem('lang'),
theme: localStorage.getItem('theme'),
foundsquaresstyle: 'icons',
details: localStorage.getItem('details')
};
$.ajax({
url: 'server/saveScore.php',
type: 'post',
data: data
})
.done(function(data){
$('form', '#username-modal-box').find('.username').removeClass('error');
$('form', '#username-modal-box').find('.alert').addClass('hide').filter('.success').removeClass('hide');
localStorage.setItem('username', username);
localStorage.setItem('gamekey', data);
$('.settings-wrapper', '#rules').find('.username').find('span').html(username);
$('.settings-wrapper', '#rules').find('.gamekey').find('span').html(data.toUpperCase());
setTimeout(function(){
$('form', '#username-modal-box').find('.form-buttons').find('.button').removeClass('disabled').removeAttr('disabled');
// Close the username modal box if displayed.
if($('#username-modal-box').hasClass('show'))
$('#username-modal-box').click();
}, 1000);
})
.fail(function(data){
$('form', '#username-modal-box').find('.form-buttons').find('.button').removeClass('disabled').removeAttr('disabled');
// Display the gamekey modal box if the username already exists, or else display the error.
if(data.status === 401) {
app.username = username;
$('form', '#gamekey-modal-box').find('.gamekey').focus();
$('#username-modal-box').removeClass('show');
$('#gamekey-modal-box').addClass('show');
} else {
$('form', '#username-modal-box').find('.username').addClass('error').focus();
$('form', '#username-modal-box').find('.alert').addClass('hide').filter('.http-' + data.status).removeClass('hide');
}
})
.always(function(data){
// Get the old score.
var old_score = (data.responseText !== undefined) ? data.responseText : data;
// Define the format of the number for displaying the old score.
var score_format = (localStorage.getItem('lang') == 'en') ? '$1,' : '$1 ';
$('form', '#username-modal-box')
.find('p').filter('.alert').find('span')
.html(old_score.replace(/(\d)(?=(\d{3})+$)/g, score_format));
});
},
/**
* Get the score of all the players.
*/
getScores: function() {
app.getPlayerScore();
// Hide the old content and display the loader.
$('.modal-box', '#leaderboard').addClass('loading').find('.leaderboard-content').not('.no-entries').html('');
$.ajax({
url: 'server/getScores.php?v=' + Date.now(),
type: 'get',
cache: false
})
.done(function(data){
var playersScores = JSON.parse(data);
var playersScores_html = '';
var rank = 1;
// Display the number of players (not implemented in the final version at the moment).
$('.players-count', '#show-leaderboard').find('span').html(playersScores.length);
// If there is no score yet.
if(playersScores.length == 0) {
$('.modal-box', '#leaderboard').removeClass('loading');
return false;
}
// Hide the old content.
$('.modal-box', '#leaderboard').find('.leaderboard-content').removeClass('no-entries').html('');
$('#best').find('.rank').addClass('hide');
$.each(playersScores, function(username, score){
// Whether the player is the current player.
var isCurrentPlayer = (localStorage.getItem('username') == username) ? true : false;
// Define the format of the number for displaying the score.
var score_format = (localStorage.getItem('lang') == 'en') ? '$1,' : '$1 ';
// Build the HTML of the entry.
playersScores_html+= '<div class="entry ' + ((isCurrentPlayer) ? 'active' : '') + '">' +
'<div class="rank-wrapper">' +
((rank >= 1 && rank <= 3) ? '<div class="rank rank-' + rank + '">' + rank + '</div>' : rank) +
'</div>' +
'<div class="username">' + username + '</div>' +
'<div class="score">' + score.replace(/(\d)(?=(\d{3})+$)/g, score_format) + '<span>pts</span></div>' +
'</div>';
// Display the rank of the player next to the best score.
if(rank >= 1 && rank <= 3 && localStorage.getItem('username') == username)
$('#best').find('.rank').removeClass('hide').removeClass('rank-1 rank-2 rank-3').addClass('rank-' + rank).html(rank);
rank++;
});
setTimeout(function(){
// Inject the HTML on the leaderboard and remove the loader.
$('.modal-box', '#leaderboard').removeClass('loading').find('.leaderboard-content').append(playersScores_html);
// Get the position of the entry corresponding to the current player.
var activeEntry_position = $('.modal-box', '#leaderboard').find('.leaderboard-content').children('.entry').filter('.active').position();
var leaderboardModalBox_height = $('.modal-box', '#leaderboard').outerHeight();
// Set the scroll on the entry corresponding to the current player.
if(activeEntry_position !== undefined)
$('.modal-box', '#leaderboard').find('.leaderboard-content').scrollTop(activeEntry_position.top - (leaderboardModalBox_height / 1.6));
}, 500);
});
},
/**
* Get the score of the player.
* @param {username}
*/
getPlayerScore: function(username) {
if(!localStorage.getItem('username'))
return false;
var username = localStorage.getItem('username');
$.ajax({
url: 'server/getPlayerScore.php?v=' + Date.now(),
type: 'get',
data: {
username: username,
gamekey: localStorage.getItem('gamekey')
},
cache: false
}).done(function(data){
if(data === '')
return false;
if(parseInt(data, 10) > localStorage.getItem('best')) {
$('#best').find('.value').html(data);
localStorage.setItem('best', data);
} else {
app.saveScore(localStorage.getItem('username'));
}
});
},
/**
* Check the game data entered by the player.
* @param {str} username The username previously entered by the player.
* @param {str} gameKey The game key entered by the player.
*/
checkGameData: function(username, gameKey) {
$.ajax({
url: 'server/checkGameData.php?v=' + Date.now(),
type: 'get',
data: {
username: username,
gamekey: gameKey
},
cache: false
}).done(function(data){
localStorage.setItem('username', app.username);
localStorage.setItem('gamekey', gameKey);
$('.settings-wrapper', '#rules').find('.username').find('span').html(app.username);
$('.settings-wrapper', '#rules').find('.gamekey').find('span').html(gameKey.toUpperCase());
$('form', '#gamekey-modal-box').find('.gamekey').removeClass('error');
$('form', '#gamekey-modal-box').find('.alert').addClass('hide').filter('.success').removeClass('hide');
setTimeout(function(){
$('form', '#gamekey-modal-box').find('.form-buttons').find('.button').removeClass('disabled').removeAttr('disabled');
// Close the gamekey modal box if displayed.
if($('#gamekey-modal-box').hasClass('show'))
$('#gamekey-modal-box').click();
app.getPlayerScore();
app.resetGridAndTimer();
}, 1000);
}).fail(function(data){
$('form', '#gamekey-modal-box').find('.gamekey').addClass('error').focus();
$('form', '#gamekey-modal-box').find('.form-buttons').find('.button').removeClass('disabled').removeAttr('disabled');
$('form', '#gamekey-modal-box').find('.alert').addClass('hide').filter('.http-' + data.status).removeClass('hide');
});
},
/**
* Reset the grid and the timer.
*/
resetGridAndTimer: function() {
setTimeout(function(){
$('html').css('overflow', 'auto');
app.animateGrid();
timer.reset();
}, 200);
},
/**
* Run a bot to simulate a perfect game.
*/
runBot: function() {
setInterval(function(){
$.each(game.rightSquares, function(index, square){
$('.square', '#grid').children('.square-content').find('span').filter(':contains(' + square + ')').click();
});
}, 4);
}
};
/**
* @type {Object}
*/
var timer = {
id: 0,
time: 90000,
lasted: 0,
container: null,
progress_bar: null,
reset_interval_id: 0,
/**
* Run the timer.
* @param {obj} $container The container of the digital timer.
* @param {obj} $progress_bar The progress bar of the timer.
*/
run: function($container, $progress_bar) {
this.lasted = this.time;
this.container = $container;
this.progress_bar = $progress_bar;
this.id = setInterval(function(){
if(timer.lasted <= 0)
game.end();
timer.update(timer.lasted);
timer.lasted-= 10;
}, 10);
},
/**
* Stop the timer.
*/
stop: function() {
clearInterval(this.id);
},
/**
* Reset the timer.
*/
reset: function() {
// Animate the reset.
this.reset_interval_id = setInterval(function(){
timer.lasted+= 1000;
if(timer.lasted >= timer.time)
timer.lasted = timer.time;
timer.update(timer.lasted);
// Stop the animation when the timer is reset.
if(timer.lasted >= timer.time)
clearInterval(timer.reset_interval_id);
}, (app.btwEach_gridSquares_animationDelay * 9 + app.gridSquares_AnimationTiming) * 1000 / timer.time);
},
/**
* Update the display for each change.
* @param {int} lasted The time lasted.
*/
update: function(lasted) {
var time = (lasted / 1000).toFixed(2);
time = ((lasted < 10000) ? '0' : '') + time;
this.container.html(time);
this.progress_bar.css('width', ((lasted / timer.time) * 100) + '%');
}
};
/**
* @type {Object}
*/
var score = {
total: 0,
/**
* Set the points earned for each round won.
* @param {int} time The time spent to win the round.
* @param {int} attempts The number of attempts made to win the round.
* @return {int} The points earned.
*/
set: function(time, attempts) {
var points = (timer.time - time) / 10;
points-= ((attempts - 1) * 200);
points = Math.ceil(points);
// Set a minimum number of points if the player didn't earn many.
if(points < 1500)
points = 1500;
this.add(points, false);
return points;
},
/**
* Add points to the score.
* @param {int} points
*/
add: function(points) {
$('.update', '#score')
.filter('.add').html('+' + points).addClass('show');
setTimeout(function(){
$('.update', '#score').html('').removeClass('show');
}, 400);
this.total+= points;
this.update(800);
},
/**
* Substract points to the score.
* @param {int} points
*/
sub: function(points) {
$('.update', '#score')
.filter('.sub').html('-' + points).addClass('show');
setTimeout(function(){
$('.update', '#score').html('').removeClass('show');
}, 400);
this.total-= points;
this.update(100);
},
/**
* Reset the score.
*/
reset: function() {
this.total = 0;
this.update(0);
},
/**
* Update the display for each change.
* @param {int} animationTiming The time the animation of the score must last (in ms), 0 for no animation.
*/
update: function(animationTiming) {
var score_delta = this.total - parseInt($('#score').find('.value').html(), 10);
var points_toAdd_atEachLoop = Math.ceil(score_delta * 10 / animationTiming);
if(this.total <= 0)
this.total = 0;
// If it must be animated.
if(animationTiming != 0) {
var scoreAnimation_interval_id = setInterval(function(){
var new_score = parseInt($('#score').find('.value').html(), 10) + points_toAdd_atEachLoop;
if(new_score < 0)
new_score = score.total;
$('#score').find('.value').html(new_score);
}, 10);
setTimeout(function(){
clearInterval(scoreAnimation_interval_id);
$('#score').find('.value').html(score.total);
}, animationTiming)
} else
$('#score').find('.value').html(this.total);
},
/**
* Save the new best score and display the username modal box if necessary.
* @return {bool} Whether the username modal box must be displayed or not.
*/
saveBest: function() {
if(this.total > localStorage.getItem('best')) {
localStorage.setItem('best', this.total);
localStorage.setItem('details', JSON.stringify(game.currentGame));
$('#best').addClass('new-best').find('.value').html(this.total);
// Display the username modal box if it is not saved, or save the new best score directly.
if(!localStorage.getItem('username')) {
setTimeout(function(){
// Define the format of the number for displaying the score.
var score_format = (localStorage.getItem('lang') == 'en') ? '$1,' : '$1 ';
$('html').css('overflow', 'hidden');
$('#overlay').addClass('show lower-opacity');
$('#username-modal-box')
.addClass('show')
.find('p').not('.alert').find('span')
.html(localStorage.getItem('best').replace(/(\d)(?=(\d{3})+$)/g, score_format));
$('form', '#username-modal-box').find('.username').removeClass('error').focus();
$('form', '#username-modal-box').find('.alert').addClass('hide');
$('form', '#username-modal-box').find('.form-buttons').find('.button').removeClass('disabled').removeAttr('disabled');
}, 2000);
return true;
} else {
var username = localStorage.getItem('username');
app.saveScore(username);
}
}
return false;
}
};
/**
* @type {Object}
*/
var game = {
squares: [],
rightSquares: [],
rights: 0,
attempts: 0,
rounds: 0,
currentAttempt_time: timer.time,
currentAttempt_interval_id: 0,
currentRound_time: timer.time,
currentRound_attempts: [],
currentGame: {},
areInputsBlocked: false,
isGameRunning: false,
isGameReady: true,
/**
* Start a new game.
*/
start: function() {
if(!this.isGameReady || this.isGameRunning || this.areInputsBlocked)
return false;
this.isGameRunning = true;
this.rights = 0;
this.attempts = 0;
this.rounds = 0;
this.currentGame = {};
this.currentGame.rounds = {};
this.currentGame.rounds.each = [];
this.currentGame.timestamp = {};
this.currentGame.timestamp.start = Math.floor(Date.now() / 1000);
$('#best').removeClass('new-best');
// Get the 3 random squares.
this.getRandomSquares();
// Run the timer.
timer.run($('#timer').find('span'), $('#progress-bar'));
// Reset the old score.
score.reset();
// app.runBot();
// Remove points if an attempt is too long.
this.currentAttempt_interval_id = setInterval(function(){
if(game.currentAttempt_time > timer.lasted + 4500 & score.total !== 0 & timer.lasted > 500)
score.sub(200);
}, 1000);
this.updateRights();
this.updateAttempts();
this.updateRounds();
this.nextRound();
},
/**
* End the current game.
*/
end: function() {
this.squares = [];
this.currentAttempt_time = timer.time;
this.currentRound_time = timer.time;
this.currentRound_attempts = [];
this.currentGame.timestamp.end = Math.floor(Date.now() / 1000);
this.currentGame.rounds.count = this.rounds - 1;
this.isGameReady = false;
this.isGameRunning = false;
this.areInputsBlocked = true;
$('#grid').addClass('disabled');
$('.square', '#grid').removeClass('active');
$('#rights', '#outputs').removeClass('right');
// Clear the setInterval() which removes points if an attempt is too long.
clearInterval(this.currentAttempt_interval_id);
// Stop the timer.
timer.stop();
// Add points to the score as a rounds bonus (+500 points per round won)
score.add($('#rounds').find('.value').html() * 500, true);
// Display the rights squares.
$.each(this.rightSquares, function(id, square){
$('.square', '#grid')
.find('span:contains(' + square + ')')
.parents('.square').addClass('not-found');
});
// Save the score if it is the best.
var mustUsernameModalBoxBeDisplayed = score.saveBest();
// Prepare the next game with the animation.
setTimeout(function(mustUsernameModalBoxBeDisplayed){
if(!mustUsernameModalBoxBeDisplayed) {
app.animateGrid();
timer.reset();
}
setTimeout(function(){
$('#grid').removeClass('disabled');
game.isGameReady = true;
game.areInputsBlocked = false;
// Display the Google Play modal box if necessary.
if(!localStorage.getItem('googleplay-modal-box') && navigator.userAgent.match(/(android|symbian|symbianos|symbos|netfront|model-orange|javaplatform|samsung|htc|opera mobile|opera mobi|opera mini|presto|huawei|blazer|bolt|doris|fennec|gobrowser|iris|maemo browser|mib|cldc|minimo|semc-browser|skyfire|teashark|teleca|uzard|uzardweb|meego|nokia|playbook)/gi)) {
localStorage.setItem('googleplay-modal-box', true);
$('html').css('overflow', 'hidden');
$('#overlay').addClass('show lower-opacity');
$('#googleplay-modal-box').addClass('show');
}
}, app.btwEach_gridSquares_animationDelay * 9 + app.gridSquares_AnimationTiming);
}, 3000, mustUsernameModalBoxBeDisplayed);
},
/**
* Get the 3 random squares.
*/
getRandomSquares: function() {
game.rightSquares = [];
for(var i=0; i<3; i++) {
do {
var square = Math.floor(Math.random() * 9) + 1;
} while($.inArray(square, game.rightSquares) !== -1);
game.rightSquares.push(square);
}
},
/**
* Save each square selected by the player.
* @param {int} square
*/
squareSelected: function(square) {
if(!this.isGameRunning || this.areInputsBlocked)
return false;
// If the square was already selected before.
if($.inArray(square, this.squares) !== -1) {
$('.square', '#grid')
.find('span:contains(' + square + ')')
.parents('.square').removeClass('active');
this.squares = $.grep(this.squares, function(squareNumber) {
return squareNumber != square;
});
return false;
}
$('.square', '#grid')
.find('span:contains(' + square + ')')
.parents('.square').addClass('active');
this.squares.push(square);
// When 3 squares are selected by the player.
if(this.squares.length === 3)
this.checkSquares();
},
/**
* Check the squares selected by the player.
*/
checkSquares: function() {
var currentAttempt = [];
this.areInputsBlocked = true;
// Count the right squares found.
$.each(this.squares, function(id, square){
currentAttempt.push(square);
if($.inArray(square, game.rightSquares) !== -1)
game.rights++;
});
// Remove points when same squares are selected more than once.
$.each(game.currentRound_attempts, function(id, attempt){
var nbOf_squaresMatched = 0;
$.each(currentAttempt, function(id, square){
if($.inArray(square, attempt) !== -1)
nbOf_squaresMatched++;
});
if(nbOf_squaresMatched === 3) {
score.sub(500);
return false;
}
});
this.currentRound_attempts.push(currentAttempt);
this.updateRights();
// When the 3 squares are found.
if(this.rights === 3)
shouldNextRoundBeRun = true;
else
shouldNextRoundBeRun = false;
this.nextAttempt(shouldNextRoundBeRun);
},
/**
* Set the next attempt.
* @param {bool} shouldNextRoundBeRun Whether the next run should be run or not.
*/
nextAttempt: function(shouldNextRoundBeRun) {
this.squares = [];
this.rights = 0;
this.attempts++;
this.currentAttempt_time = timer.lasted;
this.updateAttempts();
// If a new round must be run or not.
if(shouldNextRoundBeRun) {
game.nextRound();
} else {
// Blink the panel of rights cases as a tip for the player.
$('#rights', '#outputs').addClass('blink');
setTimeout(function(){
$('.square', '#grid').removeClass('active');
$('#rights', '#outputs').removeClass('blink');
game.areInputsBlocked = false;
}, 200);
}
},
/**
* Set the next round.
*/
nextRound: function() {
// Between each round (so not for the first round).
if(this.rounds !== 0) {
// Set the new score.
var points = score.set(this.currentRound_time - timer.lasted, this.attempts);
// Save the current round.
this.saveCurrentRound(
this.currentRound_time - timer.lasted,
points,
this.attempts,
this.currentRound_attempts,
this.rightSquares,
$('.square', '#grid').filter('.active')
);
this.rightSquares = [];
this.attempts = 0;
this.currentRound_attempts = [];
$('#grid').addClass('disabled');
$('.square', '#grid').filter('.active').addClass('right');
$('#rights', '#outputs').addClass('right');
// Prepare the next round with the animation.
setTimeout(function(){
if(!game.isGameRunning)
return false;
app.animateGrid();
// When the animation is over.
setTimeout(function(){
$('#grid').removeClass('disabled');
$('#rights', '#outputs').removeClass('right');
// Get the 3 random squares.
game.getRandomSquares();
game.areInputsBlocked = false;
game.currentRound_time = timer.lasted;
game.updateRights();
}, app.btwEach_gridSquares_animationDelay * 9 + app.gridSquares_AnimationTiming);
}, app.delay_before_gridSquares_animation);
}
this.updateAttempts();
this.updateRounds();
this.rounds++;
},
/**
* Save the time spent for the current round, the number of the attempts made during this round, the details of each attempt, the right squares, and the squares selected by the user.
* @param {int} time
* @param {int} points
* @param {obj} attempts
* @param {arr} currentRound_attempts
* @param {arr} rightSquares
* @param {obj} $activeSquares
*/
saveCurrentRound: function(time, points, attempts, currentRound_attempts, rightSquares, $activeSquares) {
this.currentGame.rounds.each.push({
time: time,
points: points,
attempts: {
count: attempts,
each: currentRound_attempts
},
squares: {
rights: rightSquares,
displayedAsRights: $.map($activeSquares, function(element){
return parseInt(element.innerText, 10);
})
}
});
},
/**
* Update the display of the right squares found for each change.
*/
updateRights: function() {
var rights_html = '';
if(this.rights === 0) {
rights_html = '<span class="square-thumb null"></span>';
} else {
$.each(new Array(this.rights), function(){
rights_html+= '<span class="square-thumb"></span>';
});
}
$('#rights', '#outputs')
.find('.value').html(rights_html);
},
/**
* Update the display of the attempts for each change.
*/
updateAttempts: function() {
$('#attempts', '#outputs')
.find('.value').html(this.attempts);
},
/**
* Update the display of the rounds for each change.
*/
updateRounds: function() {
$('#rounds', '#outputs')
.find('.value').html(this.rounds);
}
};
/* - - - - - - */
/* E V E N T S */
/* - - - - - - */
// When a key is pressed.
$(document).on('keydown', function(key) {
// Escape key.
if(key.which == 27) {
// If the controls screen, the rules or a modal box are displayed, close the content.
if($('#overlay').hasClass('controls'))
$('#overlay').click();
else if($('#rules').hasClass('show'))
$('.close', '#rules').click();
else if($('#username-modal-box').hasClass('show'))
$('.close', '#username-modal-box').click();
else if($('#leaderboard').hasClass('show'))
$('.close', '#leaderboard').click();
// Or else, reload the document.
else
setTimeout(function(){
document.location.reload();
});
}
// If there is no overlay displayed.
if(!$('#overlay').hasClass('show')) {
// Enter or space or numeric keys.
if(key.which == 13 || key.which == 32 || (key.which >= 97 && key.which <= 105)) {
key.preventDefault();
game.start();
// Only numeric keys.
if(key.which >= 97 && key.which <= 105)
game.squareSelected(key.which - 96);
}
}
});
// When the controls screen is pressed.
$(document).on('click', '#overlay.controls', function(event){
$(this).removeClass('show controls').children('div').fadeOut(100);
});
// When a square is selected.
$('.square', '#grid').on('click', function() {
game.start();
game.squareSelected(parseInt($(this).find('span').html(), 10));
});
// When the "Show rules" button or the "See the rules" link is pressed.
$('#show-rules, #how-to a').on('click', function(event){
event.preventDefault();
$('#rules, #overlay').addClass('show').removeClass('lower-opacity');
$('html').css('overflow', 'hidden');
});
// When the rules or the close button of the rules are pressed.
$('#rules, #rules .close').on('click', function(){
$('#rules, #overlay').removeClass('show');
setTimeout(function(){
$('html').css('overflow', 'auto');
}, 500);
});
// When the language button is pressed.
$('.settings', '#rules').find('.language').on('click', function(event){
event.preventDefault();
var lang = $(this).attr('data-lang-toggle');
localStorage.setItem('lang', lang);
app.changeLanguage(lang);
});
// When the theme button is pressed.
$('.settings', '#rules').find('.theme').on('click', function(event){
event.preventDefault();
var theme = $(this).attr('data-theme-toggle');
localStorage.setItem('theme', theme);
app.changeTheme(theme);
});
// When the "Leaderboard" button is pressed.
$('button').filter('#show-leaderboard').on('click', function(){
$('#leaderboard, #overlay').addClass('show').filter('#overlay').addClass('lower-opacity');
$('html').css('overflow', 'hidden');
app.getScores();
});
// When the area outside the leaderboard modal box or the close button of the modal box is pressed.
$('#leaderboard, #leaderboard .close').on('click', function(){
$('#leaderboard, #overlay').removeClass('show');
setTimeout(function(){
$('.modal-box', '#leaderboard').find('.leaderboard-content').scrollTop(0);
$('html').css('overflow', 'auto');
}, 200);
});
// When the area outside a modal box, the close button or the later button of modal boxes is pressed.
$('#username-modal-box, #username-modal-box .close, #username-modal-box .later, #gamekey-modal-box, #gamekey-modal-box .close, #gamekey-modal-box .later, #googleplay-modal-box, #googleplay-modal-box .close').on('click', function(){
$('#username-modal-box').removeClass('show');
$('#gamekey-modal-box').removeClass('show');
$('#googleplay-modal-box').removeClass('show');
$('#overlay').removeClass('show');
app.resetGridAndTimer();
});
// When the username modal box form is submitted.
$('form', '#username-modal-box').on('submit', function(event){
event.preventDefault();
var username = $(this).find('div').filter(':visible').children('.username').val();
app.saveScore(username);
$(this).find('.form-buttons').find('.button').addClass('disabled').attr('disabled', true);
});
// When the gamekey modal box form is submitted.
$('form', '#gamekey-modal-box').on('submit', function(event){
event.preventDefault();
var username = app.username;
var gamekey = $(this).find('div').filter(':visible').children('.gamekey').val();
app.checkGameData(username, gamekey);
$(this).find('.form-buttons').find('.button').addClass('disabled').attr('disabled', true);
});
// When the settings section or a link on the rules, or a modal box is pressed.
$('#rules .settings, #rules a, .modal-box', document).on('click', function(event){
// Stop the propagation to prevent the rules or the modal squares from closing.
event.stopPropagation();
});
// When a button link is pressed.
$('button, input').filter('.link').on('click', function(){
var link = $(this).data('href');
window.open(link, '_blank');
});
app.init();
});
})(jQuery);
|
var mongo = require('../');
var db = mongo.db('192.168.0.103/test');
// var db = mongo.db('127.0.0.1/test');
var myconsole = require('myconsole');
var foo = db.collection('foo');
setInterval(function() {
foo.insert({foo:'foo'}, function(err, result){
if(err) return myconsole.error(err);
foo.count(function(err, count){
if(err) return myconsole.error(err);
myconsole.log('count: %d', count);
foo.find().limit(10).toArray(function(err, arr) {
if(err) return myconsole.error(err);
myconsole.log('arr: %d', arr.length);
})
})
})
}, 500);
process.on('SIGINT', function(){
myconsole.log('SIGINT')
foo.drop(function(err){
if(err) myconsole.error(err);
process.exit();
})
})
|
// Only publish invitation codes for the logged in user
Meteor.publish("invitations", function (all) {
if(!this.userId)
return [];
// XXX in the future the admin page requires to fetch
// all invitations. Then do somehting with 'all'.
return Invitations.find({$or: [ {broadcastUser: this.userId},
{receivingUser: this.userId} ]});
});
|
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var React = require('react');
var classes = require('classnames');
var Option = React.createClass({
displayName: 'Option',
propTypes: {
addLabelText: React.PropTypes.string, // string rendered in case of allowCreate option passed to ReactSelect
className: React.PropTypes.string, // className (based on mouse position)
click: React.PropTypes.func, // method to handle click events
mouseDown: React.PropTypes.func, // method to handle click on option element
mouseEnter: React.PropTypes.func, // method to handle mouseEnter on option element
mouseLeave: React.PropTypes.func, // method to handle mouseLeave on option element
option: React.PropTypes.object.isRequired, // object that is base for that option
renderFunc: React.PropTypes.func // method passed to ReactSelect component to render label text
},
blockEvent: function blockEvent(event) {
event.preventDefault();
if (event.target.tagName !== 'A' || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href);
} else {
window.location.href = event.target.href;
}
},
render: function render() {
var obj = this.props.option;
var renderedLabel = this.props.renderFunc(obj);
var optionClasses = classes(this.props.className, obj.className);
return obj.disabled ? React.createElement(
'div',
{ className: optionClasses,
onMouseDown: this.blockEvent,
onClick: this.blockEvent },
renderedLabel
) : React.createElement(
'div',
{ className: optionClasses,
style: obj.style,
onMouseEnter: this.props.mouseEnter,
onMouseLeave: this.props.mouseLeave,
onMouseDown: this.props.mouseDown,
onClick: this.props.click,
title: obj.title },
React.createElement(
'span',
null,
obj.create ? this.props.addLabelText.replace('{label}', obj.label) : renderedLabel
)
);
}
});
module.exports = Option;
},{"classnames":undefined,"react":undefined}],2:[function(require,module,exports){
'use strict';
var React = require('react');
var classes = require('classnames');
var SingleValue = React.createClass({
displayName: 'SingleValue',
propTypes: {
placeholder: React.PropTypes.string, // this is default value provided by React-Select based component
value: React.PropTypes.object // selected option
},
render: function render() {
var classNames = classes('Select-placeholder', this.props.value && this.props.value.className);
return React.createElement(
'div',
{
className: classNames,
style: this.props.value && this.props.value.style,
title: this.props.value && this.props.value.title
},
this.props.placeholder
);
}
});
module.exports = SingleValue;
},{"classnames":undefined,"react":undefined}],3:[function(require,module,exports){
'use strict';
var React = require('react');
var classes = require('classnames');
var Value = React.createClass({
displayName: 'Value',
propTypes: {
disabled: React.PropTypes.bool, // disabled prop passed to ReactSelect
onOptionLabelClick: React.PropTypes.func, // method to handle click on value label
onRemove: React.PropTypes.func, // method to handle remove of that value
option: React.PropTypes.object.isRequired, // option passed to component
optionLabelClick: React.PropTypes.bool, // indicates if onOptionLabelClick should be handled
renderer: React.PropTypes.func // method to render option label passed to ReactSelect
},
blockEvent: function blockEvent(event) {
event.stopPropagation();
},
handleOnRemove: function handleOnRemove(event) {
if (!this.props.disabled) {
this.props.onRemove(event);
}
},
render: function render() {
var label = this.props.option.label;
if (this.props.renderer) {
label = this.props.renderer(this.props.option);
}
if (!this.props.onRemove && !this.props.optionLabelClick) {
return React.createElement(
'div',
{
className: classes('Select-value', this.props.option.className),
style: this.props.option.style,
title: this.props.option.title
},
label
);
}
if (this.props.optionLabelClick) {
label = React.createElement(
'a',
{ className: classes('Select-item-label__a', this.props.option.className),
onMouseDown: this.blockEvent,
onTouchEnd: this.props.onOptionLabelClick,
onClick: this.props.onOptionLabelClick,
style: this.props.option.style,
title: this.props.option.title },
label
);
}
return React.createElement(
'div',
{ className: classes('Select-item', this.props.option.className),
style: this.props.option.style,
title: this.props.option.title },
React.createElement(
'span',
{ className: 'Select-item-icon',
onMouseDown: this.blockEvent,
onClick: this.handleOnRemove,
onTouchEnd: this.handleOnRemove },
'×'
),
React.createElement(
'span',
{ className: 'Select-item-label' },
label
)
);
}
});
module.exports = Value;
},{"classnames":undefined,"react":undefined}],"react-select":[function(require,module,exports){
/* disable some rules until we refactor more completely; fixing them now would
cause conflicts with some open PRs unnecessarily. */
/* eslint react/jsx-sort-prop-types: 0, react/sort-comp: 0, react/prop-types: 0 */
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = require('react');
var ReactDOM = require('react-dom');
var Input = require('react-input-autosize');
var classes = require('classnames');
var Value = require('./Value');
var SingleValue = require('./SingleValue');
var Option = require('./Option');
var requestId = 0;
var Select = React.createClass({
displayName: 'Select',
propTypes: {
addLabelText: React.PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input
allowCreate: React.PropTypes.bool, // whether to allow creation of new entries
asyncOptions: React.PropTypes.func, // function to call to get options
autoload: React.PropTypes.bool, // whether to auto-load the default async options set
backspaceRemoves: React.PropTypes.bool, // whether backspace removes an item if there is no text input
cacheAsyncResults: React.PropTypes.bool, // whether to allow cache
className: React.PropTypes.string, // className for the outer element
clearAllText: React.PropTypes.string, // title for the "clear" control when multi: true
clearValueText: React.PropTypes.string, // title for the "clear" control
clearable: React.PropTypes.bool, // should it be possible to reset value
delimiter: React.PropTypes.string, // delimiter to use to join multiple values
disabled: React.PropTypes.bool, // whether the Select is disabled or not
filterOption: React.PropTypes.func, // method to filter a single option (option, filterString)
filterOptions: React.PropTypes.func, // method to filter the options array: function ([options], filterString, [values])
ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering
inputProps: React.PropTypes.object, // custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
isLoading: React.PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded)
labelKey: React.PropTypes.string, // path of the label value in option objects
matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering
matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on
multi: React.PropTypes.bool, // multi-value input
multiSum: React.PropTypes.bool, // multiSum option enabler
multiSumLimit: React.PropTypes.number, // limit for the number of options before it summarizes to x of y
name: React.PropTypes.string, // field name, for hidden <input /> tag
newOptionCreator: React.PropTypes.func, // factory to create new options when allowCreate set
noResultsText: React.PropTypes.string, // placeholder displayed when there are no matching search results
onBlur: React.PropTypes.func, // onBlur handler: function (event) {}
onChange: React.PropTypes.func, // onChange handler: function (newValue) {}
onFocus: React.PropTypes.func, // onFocus handler: function (event) {}
onInputChange: React.PropTypes.func, // onInputChange handler: function (inputValue) {}
onOptionLabelClick: React.PropTypes.func, // onCLick handler for value labels: function (value, event) {}
optionComponent: React.PropTypes.func, // option component to render in dropdown
optionRenderer: React.PropTypes.func, // optionRenderer: function (option) {}
options: React.PropTypes.array, // array of options
placeholder: React.PropTypes.string, // field placeholder, displayed when there's no value
searchable: React.PropTypes.bool, // whether to enable searching feature or not
searchingText: React.PropTypes.string, // message to display whilst options are loading via asyncOptions
searchPromptText: React.PropTypes.string, // label to prompt for search input
singleValueComponent: React.PropTypes.func, // single value component when multiple is set to false
value: React.PropTypes.any, // initial field value
valueComponent: React.PropTypes.func, // value component to render in multiple mode
valueKey: React.PropTypes.string, // path of the label value in option objects
valueRenderer: React.PropTypes.func // valueRenderer: function (option) {}
},
getDefaultProps: function getDefaultProps() {
return {
addLabelText: 'Add "{label}"?',
allowCreate: false,
asyncOptions: undefined,
autoload: true,
backspaceRemoves: true,
cacheAsyncResults: true,
className: undefined,
clearAllText: 'Clear all',
clearValueText: 'Clear value',
clearable: true,
delimiter: ',',
disabled: false,
ignoreCase: true,
inputProps: {},
isLoading: false,
labelKey: 'label',
matchPos: 'any',
matchProp: 'any',
multiSumLimit: 3,
name: undefined,
newOptionCreator: undefined,
noResultsText: 'No results found',
onChange: undefined,
onInputChange: undefined,
onOptionLabelClick: undefined,
optionComponent: Option,
options: undefined,
placeholder: 'Select...',
searchable: true,
searchingText: 'Searching...',
searchPromptText: 'Type to search',
singleValueComponent: SingleValue,
value: undefined,
valueComponent: Value,
valueKey: 'value'
};
},
getInitialState: function getInitialState() {
return {
/*
* set by getStateFromValue on componentWillMount:
* - value
* - values
* - filteredOptions
* - inputValue
* - placeholder
* - focusedOption
*/
isFocused: false,
isLoading: false,
isOpen: false,
options: this.props.options
};
},
componentWillMount: function componentWillMount() {
var _this = this;
this._optionsCache = {};
this._optionsFilterString = '';
this._closeMenuIfClickedOutside = function (event) {
if (!_this.state.isOpen) {
return;
}
var menuElem = ReactDOM.findDOMNode(_this.refs.selectMenuContainer);
var controlElem = ReactDOM.findDOMNode(_this.refs.control);
var eventOccuredOutsideMenu = _this.clickedOutsideElement(menuElem, event);
var eventOccuredOutsideControl = _this.clickedOutsideElement(controlElem, event);
// Hide dropdown menu if click occurred outside of menu
if (eventOccuredOutsideMenu && eventOccuredOutsideControl) {
_this.setState({
isOpen: false
}, _this._unbindCloseMenuIfClickedOutside);
}
};
this._bindCloseMenuIfClickedOutside = function () {
if (!document.addEventListener && document.attachEvent) {
document.attachEvent('onclick', _this._closeMenuIfClickedOutside);
} else {
document.addEventListener('click', _this._closeMenuIfClickedOutside);
}
};
this._unbindCloseMenuIfClickedOutside = function () {
if (!document.removeEventListener && document.detachEvent) {
document.detachEvent('onclick', _this._closeMenuIfClickedOutside);
} else {
document.removeEventListener('click', _this._closeMenuIfClickedOutside);
}
};
this.setState(this.getStateFromValue(this.props.value));
},
componentDidMount: function componentDidMount() {
if (this.props.asyncOptions && this.props.autoload) {
this.autoloadAsyncOptions();
}
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this._blurTimeout);
clearTimeout(this._focusTimeout);
if (this.state.isOpen) {
this._unbindCloseMenuIfClickedOutside();
}
},
componentWillReceiveProps: function componentWillReceiveProps(newProps) {
var _this2 = this;
var optionsChanged = false;
if (JSON.stringify(newProps.options) !== JSON.stringify(this.props.options)) {
optionsChanged = true;
this.setState({
options: newProps.options,
filteredOptions: this.filterOptions(newProps.options)
});
}
if (newProps.value !== this.state.value || newProps.placeholder !== this.props.placeholder || optionsChanged) {
var setState = function setState(newState) {
_this2.setState(_this2.getStateFromValue(newProps.value, newState && newState.options || newProps.options, newProps.placeholder));
};
if (this.props.asyncOptions) {
this.loadAsyncOptions(newProps.value, {}, setState);
} else {
setState();
}
}
},
componentDidUpdate: function componentDidUpdate() {
var _this3 = this;
if (!this.props.disabled && this._focusAfterUpdate) {
clearTimeout(this._blurTimeout);
clearTimeout(this._focusTimeout);
this._focusTimeout = setTimeout(function () {
if (!_this3.isMounted()) return;
_this3.getInputNode().focus();
_this3._focusAfterUpdate = false;
}, 50);
}
if (this._focusedOptionReveal) {
if (this.refs.focused && this.refs.menu) {
var focusedDOM = ReactDOM.findDOMNode(this.refs.focused);
var menuDOM = ReactDOM.findDOMNode(this.refs.menu);
var focusedRect = focusedDOM.getBoundingClientRect();
var menuRect = menuDOM.getBoundingClientRect();
if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) {
menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight;
}
}
this._focusedOptionReveal = false;
}
},
focus: function focus() {
this.getInputNode().focus();
},
clickedOutsideElement: function clickedOutsideElement(element, event) {
var eventTarget = event.target ? event.target : event.srcElement;
while (eventTarget != null) {
if (eventTarget === element) return false;
eventTarget = eventTarget.offsetParent;
}
return true;
},
getStateFromValue: function getStateFromValue(value, options, placeholder) {
var _this4 = this;
if (!options) {
options = this.state.options;
}
if (!placeholder) {
placeholder = this.props.placeholder;
}
// reset internal filter string
this._optionsFilterString = '';
var values = this.initValuesArray(value, options);
var filteredOptions = this.filterOptions(options, values);
var focusedOption;
var valueForState = null;
if (!this.props.multi && values.length) {
focusedOption = values[0];
valueForState = values[0][this.props.valueKey];
} else {
focusedOption = this.getFirstFocusableOption(filteredOptions);
valueForState = values.map(function (v) {
return v[_this4.props.valueKey];
}).join(this.props.delimiter);
}
return {
value: valueForState,
values: values,
inputValue: '',
filteredOptions: filteredOptions,
placeholder: !this.props.multi && values.length ? values[0][this.props.labelKey] : placeholder,
focusedOption: focusedOption
};
},
getFirstFocusableOption: function getFirstFocusableOption(options) {
for (var optionIndex = 0; optionIndex < options.length; ++optionIndex) {
if (!options[optionIndex].disabled) {
return options[optionIndex];
}
}
},
initValuesArray: function initValuesArray(values, options) {
var _this5 = this;
if (!Array.isArray(values)) {
if (typeof values === 'string') {
values = values === '' ? [] : this.props.multi ? values.split(this.props.delimiter) : [values];
} else {
values = values !== undefined && values !== null ? [values] : [];
}
}
return values.map(function (val) {
if (typeof val === 'string' || typeof val === 'number') {
for (var key in options) {
if (options.hasOwnProperty(key) && options[key] && (options[key][_this5.props.valueKey] === val || typeof options[key][_this5.props.valueKey] === 'number' && options[key][_this5.props.valueKey].toString() === val)) {
return options[key];
}
}
return { value: val, label: val };
} else {
return val;
}
});
},
setValue: function setValue(value, focusAfterUpdate) {
if (focusAfterUpdate || focusAfterUpdate === undefined) {
this._focusAfterUpdate = true;
}
var newState = this.getStateFromValue(value);
if (this.props.multi) {
newState.isOpen = true;
} else {
newState.isOpen = false;
}
this.fireChangeEvent(newState);
this.setState(newState);
},
selectValue: function selectValue(value) {
if (!this.props.multi) {
this.setValue(value);
} else if (value) {
this.addValue(value);
}
this._unbindCloseMenuIfClickedOutside();
},
addValue: function addValue(value) {
this.setValue(this.state.values.concat(value));
},
popValue: function popValue() {
this.setValue(this.state.values.slice(0, this.state.values.length - 1));
},
removeValue: function removeValue(valueToRemove) {
this.setValue(this.state.values.filter(function (value) {
return value.value !== valueToRemove.value;
}));
},
clearValue: function clearValue(event) {
// if the event was triggered by a mousedown and not the primary
// button, ignore it.
if (event && event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this.setValue(null);
},
resetValue: function resetValue() {
this.setValue(this.state.value === '' ? null : this.state.value);
},
getInputNode: function getInputNode() {
var input = this.refs.input;
return this.props.searchable ? input : ReactDOM.findDOMNode(input);
},
fireChangeEvent: function fireChangeEvent(newState) {
if (newState.value !== this.state.value && this.props.onChange) {
this.props.onChange(newState.value, newState.values);
}
},
handleMouseDown: function handleMouseDown(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
// for the non-searchable select, close the dropdown when button is clicked
if (this.state.isOpen && !this.props.searchable) {
this.setState({
isOpen: false
}, this._unbindCloseMenuIfClickedOutside);
return;
}
if (this.state.isFocused) {
this.setState({
isOpen: true
}, this._bindCloseMenuIfClickedOutside);
} else {
this._openAfterFocus = true;
this.getInputNode().focus();
}
},
handleMouseDownOnMenu: function handleMouseDownOnMenu(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
},
handleMouseDownOnArrow: function handleMouseDownOnArrow(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
// If not focused, handleMouseDown will handle it
if (!this.state.isOpen) {
return;
}
event.stopPropagation();
event.preventDefault();
this.setState({
isOpen: false
}, this._unbindCloseMenuIfClickedOutside);
},
handleInputFocus: function handleInputFocus(event) {
var _this6 = this;
var newIsOpen = this.state.isOpen || this._openAfterFocus;
this.setState({
isFocused: true,
isOpen: newIsOpen
}, function () {
if (newIsOpen) {
_this6._bindCloseMenuIfClickedOutside();
} else {
_this6._unbindCloseMenuIfClickedOutside();
}
});
this._openAfterFocus = false;
if (this.props.onFocus) {
this.props.onFocus(event);
}
},
handleInputBlur: function handleInputBlur(event) {
var _this7 = this;
this._blurTimeout = setTimeout(function () {
if (_this7._focusAfterUpdate || !_this7.isMounted()) return;
_this7.setState({
isFocused: false,
isOpen: false
});
}, 50);
if (this.props.onBlur) {
this.props.onBlur(event);
}
},
handleKeyDown: function handleKeyDown(event) {
if (this.props.disabled) return;
switch (event.keyCode) {
case 8:
// backspace
if (!this.state.inputValue && this.props.backspaceRemoves) {
event.preventDefault();
this.popValue();
}
return;
case 9:
// tab
if (event.shiftKey || !this.state.isOpen || !this.state.focusedOption) {
return;
}
this.selectFocusedOption();
break;
case 13:
// enter
if (!this.state.isOpen) return;
this.selectFocusedOption();
break;
case 27:
// escape
if (this.state.isOpen) {
this.resetValue();
} else if (this.props.clearable) {
this.clearValue(event);
}
break;
case 38:
// up
this.focusPreviousOption();
break;
case 40:
// down
this.focusNextOption();
break;
case 188:
// ,
if (this.props.allowCreate && this.props.multi) {
event.preventDefault();
event.stopPropagation();
this.selectFocusedOption();
} else {
return;
}
break;
default:
return;
}
event.preventDefault();
},
// Ensures that the currently focused option is available in filteredOptions.
// If not, returns the first available option.
_getNewFocusedOption: function _getNewFocusedOption(filteredOptions) {
for (var key in filteredOptions) {
if (filteredOptions.hasOwnProperty(key) && filteredOptions[key] === this.state.focusedOption) {
return filteredOptions[key];
}
}
return this.getFirstFocusableOption(filteredOptions);
},
handleInputChange: function handleInputChange(event) {
// assign an internal variable because we need to use
// the latest value before setState() has completed.
this._optionsFilterString = event.target.value;
if (this.props.onInputChange) {
this.props.onInputChange(event.target.value);
}
if (this.props.asyncOptions) {
this.setState({
isLoading: true,
inputValue: event.target.value
});
this.loadAsyncOptions(event.target.value, {
isLoading: false,
isOpen: true
}, this._bindCloseMenuIfClickedOutside);
} else {
var filteredOptions = this.filterOptions(this.state.options);
this.setState({
isOpen: true,
inputValue: event.target.value,
filteredOptions: filteredOptions,
focusedOption: this._getNewFocusedOption(filteredOptions)
}, this._bindCloseMenuIfClickedOutside);
}
},
autoloadAsyncOptions: function autoloadAsyncOptions() {
var _this8 = this;
this.setState({
isLoading: true
});
this.loadAsyncOptions(this.props.value || '', { isLoading: false }, function () {
// update with new options but don't focus
_this8.setValue(_this8.props.value, false);
});
},
loadAsyncOptions: function loadAsyncOptions(input, state, callback) {
var _this9 = this;
var thisRequestId = this._currentRequestId = requestId++;
if (this.props.cacheAsyncResults) {
for (var i = 0; i <= input.length; i++) {
var cacheKey = input.slice(0, i);
if (this._optionsCache[cacheKey] && (input === cacheKey || this._optionsCache[cacheKey].complete)) {
var options = this._optionsCache[cacheKey].options;
var filteredOptions = this.filterOptions(options);
var newState = {
options: options,
filteredOptions: filteredOptions,
focusedOption: this._getNewFocusedOption(filteredOptions)
};
for (var key in state) {
if (state.hasOwnProperty(key)) {
newState[key] = state[key];
}
}
this.setState(newState);
if (callback) callback.call(this, newState);
return;
}
}
}
this.props.asyncOptions(input, function (err, data) {
if (err) throw err;
if (_this9.props.cacheAsyncResults) {
_this9._optionsCache[input] = data;
}
if (thisRequestId !== _this9._currentRequestId) {
return;
}
var filteredOptions = _this9.filterOptions(data.options);
var newState = {
options: data.options,
filteredOptions: filteredOptions,
focusedOption: _this9._getNewFocusedOption(filteredOptions)
};
for (var key in state) {
if (state.hasOwnProperty(key)) {
newState[key] = state[key];
}
}
_this9.setState(newState);
if (callback) {
callback.call(_this9, newState);
}
});
},
filterOptions: function filterOptions(options, values) {
var filterValue = this._optionsFilterString;
var exclude = (values || this.state.values).map(function (i) {
return i.value;
});
if (this.props.filterOptions) {
return this.props.filterOptions.call(this, options, filterValue, exclude);
} else {
var filterOption = function filterOption(op) {
if (this.props.filterOption) return this.props.filterOption.call(this, op, filterValue);
var valueTest = String(op[this.props.valueKey]);
var labelTest = String(op[this.props.labelKey]);
if (this.props.ignoreCase) {
valueTest = valueTest.toLowerCase();
labelTest = labelTest.toLowerCase();
filterValue = filterValue.toLowerCase();
}
return !filterValue || this.props.matchPos === 'start' ? this.props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || this.props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : this.props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || this.props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0;
};
return (options || []).filter(filterOption, this);
}
},
selectFocusedOption: function selectFocusedOption() {
if (this.props.allowCreate && !this.state.focusedOption) {
return this.selectValue(this.state.inputValue);
}
if (this.state.focusedOption) {
return this.selectValue(this.state.focusedOption);
}
},
focusOption: function focusOption(op) {
this.setState({
focusedOption: op
});
},
focusNextOption: function focusNextOption() {
this.focusAdjacentOption('next');
},
focusPreviousOption: function focusPreviousOption() {
this.focusAdjacentOption('previous');
},
focusAdjacentOption: function focusAdjacentOption(dir) {
this._focusedOptionReveal = true;
var ops = this.state.filteredOptions.filter(function (op) {
return !op.disabled;
});
if (!this.state.isOpen) {
this.setState({
isOpen: true,
inputValue: '',
focusedOption: this.state.focusedOption || ops[dir === 'next' ? 0 : ops.length - 1]
}, this._bindCloseMenuIfClickedOutside);
return;
}
if (!ops.length) {
return;
}
var focusedIndex = -1;
for (var i = 0; i < ops.length; i++) {
if (this.state.focusedOption === ops[i]) {
focusedIndex = i;
break;
}
}
var focusedOption = ops[0];
if (dir === 'next' && focusedIndex > -1 && focusedIndex < ops.length - 1) {
focusedOption = ops[focusedIndex + 1];
} else if (dir === 'previous') {
if (focusedIndex > 0) {
focusedOption = ops[focusedIndex - 1];
} else {
focusedOption = ops[ops.length - 1];
}
}
this.setState({
focusedOption: focusedOption
});
},
unfocusOption: function unfocusOption(op) {
if (this.state.focusedOption === op) {
this.setState({
focusedOption: null
});
}
},
buildMenu: function buildMenu() {
var focusedValue = this.state.focusedOption ? this.state.focusedOption[this.props.valueKey] : null;
var renderLabel = this.props.optionRenderer || function (op) {
return op.label;
};
if (this.state.filteredOptions.length > 0) {
focusedValue = focusedValue == null ? this.state.filteredOptions[0] : focusedValue;
}
// Add the current value to the filtered options in last resort
var options = this.props.searchable && this.state.filteredOptions.length > 0 ? this.state.filteredOptions : this.state.options;
var valueNames = this.state.values.map(function (o) {
return o.value;
});
if (this.props.allowCreate && this.state.inputValue.trim()) {
var inputValue = this.state.inputValue;
options = options.slice();
var newOption = this.props.newOptionCreator ? this.props.newOptionCreator(inputValue) : {
value: inputValue,
label: inputValue,
create: true
};
options.unshift(newOption);
}
if (this.props.multi && this.props.multiSum) {
options = options.map(function (opt) {
if (valueNames.indexOf(opt.value) === -1) {
opt.type = 'opt';
opt.isMulti = false;
opt.renderLabel = undefined;
opt.selectValue = undefined;
} else {
opt.type = 'multiSum';
opt.isMulti = true;
var optionRenderer = this.props.optionRenderer;
opt.renderLabel = function (op) {
var label = op.label;
if (optionRenderer) {
label = optionRenderer(op);
}
return 'x ' + label;
};
opt.selectValue = this.removeValue.bind(this, opt);
}
return opt;
}, this);
}
var ops = options.map(function (op) {
var isSelected = this.state.value === op.value;
var isFocused = focusedValue === op.value;
var optionClass = classes({
'Select-option': true,
'is-selected': isSelected,
'is-focused': isFocused,
'is-disabled': op.disabled,
'is-multiSum': op.isMulti
});
var ref = isFocused ? 'focused' : null;
var mouseEnter = this.focusOption.bind(this, op);
var mouseLeave = this.unfocusOption.bind(this, op);
var click = op.selectValue || this.selectValue.bind(this, op);
var optionResult = React.createElement(this.props.optionComponent, {
key: 'option-' + op[this.props.valueKey],
className: optionClass,
renderFunc: op.renderLabel || renderLabel,
mouseEnter: mouseEnter,
mouseLeave: mouseLeave,
mouseDown: undefined,
click: click,
addLabelText: this.props.addLabelText,
option: op,
ref: ref
});
return optionResult;
}, this);
if (ops.length) {
return ops;
} else {
var noResultsText, promptClass;
if (this.isLoading()) {
promptClass = 'Select-searching';
noResultsText = this.props.searchingText;
} else if (this.state.inputValue || !this.props.asyncOptions) {
promptClass = 'Select-noresults';
noResultsText = this.props.noResultsText;
} else {
promptClass = 'Select-search-prompt';
noResultsText = this.props.searchPromptText;
}
return React.createElement(
'div',
{ className: promptClass },
noResultsText
);
}
},
handleOptionLabelClick: function handleOptionLabelClick(value, event) {
if (this.props.onOptionLabelClick) {
this.props.onOptionLabelClick(value, event);
}
},
summarizeValues: function summarizeValues(values) {
var summary = '';
if (values.length < this.props.multiSumLimit) {
this.state.values.forEach(function (opt, i) {
summary = summary + opt.label;
if (i < values.length - 1) {
summary = summary + ', ';
}
});
return summary;
} else if (values.length === this.props.options.length) {
return 'All';
} else if (values.length >= this.props.options.length - 2) {
var valueKeys = values.map(function (v) {
return v.props.option.value;
});
this.state.options.filter(function (o) {
return valueKeys.indexOf(o.value) === -1;
}).forEach(function (opt) {
summary = summary + ', ' + opt.label;
});
return 'All except' + summary;
}
return summary = values.length + ' of ' + this.props.options.length + ' selected';
},
isLoading: function isLoading() {
return this.props.isLoading || this.state.isLoading;
},
addAll: function addAll() {
this.props.onChange(this.state.options.map(function (d) {
return d.value;
}).toString(), this.state.options);
},
render: function render() {
var selectClass = classes('Select', this.props.className, {
'is-multi': this.props.multi,
'is-searchable': this.props.searchable,
'is-open': this.state.isOpen,
'is-focused': this.state.isFocused,
'is-loading': this.isLoading(),
'is-disabled': this.props.disabled,
'has-value': this.state.value !== undefined && this.state.value !== null
});
var value = [];
if (this.props.multi) {
this.state.values.forEach(function (val) {
var onOptionLabelClick = this.handleOptionLabelClick.bind(this, val);
var onRemove = this.removeValue.bind(this, val);
var valueComponent = React.createElement(this.props.valueComponent, {
key: val.value,
option: val,
renderer: this.props.valueRenderer,
optionLabelClick: !!this.props.onOptionLabelClick,
onOptionLabelClick: onOptionLabelClick,
onRemove: onRemove,
disabled: this.props.disabled
});
value.push(valueComponent);
}, this);
if (this.props.multiSum && value.length > 0) {
value = this.summarizeValues(value);
}
}
if (!this.state.inputValue && (!this.props.multi || !value.length)) {
var val = this.state.values[0] || null;
if (this.props.valueRenderer && !!this.state.values.length) {
value.push(React.createElement(Value, {
key: 0,
option: val,
renderer: this.props.valueRenderer,
disabled: this.props.disabled }));
} else {
var singleValueComponent = React.createElement(this.props.singleValueComponent, {
key: 'placeholder',
value: val,
placeholder: this.state.placeholder
});
value.push(singleValueComponent);
}
}
var loading = this.isLoading() ? React.createElement('span', { className: 'Select-loading', 'aria-hidden': 'true' }) : null;
var clear = this.props.clearable && this.state.value && !this.props.disabled ? React.createElement('span', { className: 'Select-clear', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchEnd: this.clearValue, onClick: this.clearValue, dangerouslySetInnerHTML: { __html: '×' } }) : null;
var menu;
var menuProps;
if (this.state.isOpen) {
menuProps = {
ref: 'menu',
className: 'Select-menu',
onMouseDown: this.handleMouseDownOnMenu
};
var addRemoveButtons;
if (this.props.multi) {
addRemoveButtons = React.createElement(
'div',
null,
React.createElement(
'p',
{ onClick: this.addAll, className: 'Select-option addAll' },
'Add All'
),
this.props.clearable && !this.props.disabled ? React.createElement(
'p',
{ onClick: this.clearValue, className: 'Select-option removeAll ' + (this.state.value ? '' : 'disabled') },
'Remove All'
) : undefined
);
}
menu = React.createElement(
'div',
{ ref: 'selectMenuContainer', className: 'Select-menu-outer' },
React.createElement(
'div',
menuProps,
addRemoveButtons,
this.buildMenu()
)
);
}
var input;
var inputProps = {
ref: 'input',
className: 'Select-input ' + (this.props.inputProps.className || ''),
tabIndex: this.props.tabIndex || 0,
onFocus: this.handleInputFocus,
onBlur: this.handleInputBlur
};
for (var key in this.props.inputProps) {
if (this.props.inputProps.hasOwnProperty(key) && key !== 'className') {
inputProps[key] = this.props.inputProps[key];
}
}
if (!this.props.disabled) {
if (this.props.searchable) {
input = React.createElement(Input, _extends({ value: this.state.inputValue, onChange: this.handleInputChange, minWidth: '5' }, inputProps));
} else {
input = React.createElement(
'div',
inputProps,
' '
);
}
} else if (!this.props.multi || !this.state.values.length) {
input = React.createElement(
'div',
{ className: 'Select-input' },
' '
);
}
return React.createElement(
'div',
{ ref: 'wrapper', className: selectClass },
React.createElement('input', { type: 'hidden', ref: 'value', name: this.props.name, value: this.state.value, disabled: this.props.disabled }),
React.createElement(
'div',
{ className: 'Select-control', ref: 'control', onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown },
value,
input,
React.createElement('span', { className: 'Select-arrow-zone', onMouseDown: this.handleMouseDownOnArrow }),
React.createElement('span', { className: 'Select-arrow', onMouseDown: this.handleMouseDownOnArrow }),
loading,
clear
),
menu
);
}
});
module.exports = Select;
},{"./Option":1,"./SingleValue":2,"./Value":3,"classnames":undefined,"react":undefined,"react-dom":undefined,"react-input-autosize":undefined}]},{},[]);
|
const {CookieJar} = require('tough-cookie');
const {cookieToString, jarFromCookies, cookiesFromJar} = require('..');
describe('jarFromCookies()', () => {
it('returns valid cookies', done => {
const jar = jarFromCookies([{
key: 'foo',
value: 'bar',
domain: 'google.com'
}]);
jar.store.getAllCookies((err, cookies) => {
expect(err).toBeNull();
expect(cookies[0].domain).toEqual('google.com');
expect(cookies[0].key).toEqual('foo');
expect(cookies[0].value).toEqual('bar');
expect(cookies[0].creation instanceof Date).toEqual(true);
expect(cookies[0].expires).toEqual('Infinity');
done();
});
});
it('handles malformed JSON', () => {
const jar = jarFromCookies('not a jar');
expect(jar.constructor.name).toBe('CookieJar');
});
});
describe('cookiesFromJar()', () => {
it('returns valid jar', async () => {
const d = new Date();
const initialCookies = [{
key: 'bar',
value: 'baz',
domain: 'insomnia.rest',
expires: d
}, {
// This one will fail to parse, and be skipped
bad: 'cookie'
}];
const jar = CookieJar.fromJSON({cookies: initialCookies});
const cookies = await cookiesFromJar(jar);
expect(cookies[0].domain).toBe('insomnia.rest');
expect(cookies[0].key).toBe('bar');
expect(cookies[0].value).toBe('baz');
expect(cookies[0].creation).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/);
expect(cookies[0].expires).toEqual(d.toISOString());
});
it('handles bad jar', async () => {
const jar = CookieJar.fromJSON({cookies: []});
// MemoryStore never actually throws errors, so lets mock the
// function to force it to this time.
jar.store.getAllCookies = cb => cb(new Error('Dummy Error'));
const cookies = await cookiesFromJar(jar);
// Cookies failed to p
expect(cookies.length).toBe(0);
});
});
|
import React from 'react';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';
import { recosActions } from '../../core/recos';
import { getRecommenders, getReco } from '../../core/recos';
import { isEditing } from '../../core/loading';
import Header from '../Header';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { Card, CardText } from 'material-ui/Card';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import FlatButton from 'material-ui/FlatButton';
import AutoComplete from 'material-ui/AutoComplete';
import LoadingIndicator from '../../components/LoadingIndicator';
import CategorySelector from '../../components/CategorySelector';
const blockStyle = {
display: 'block'
}
class EditReco extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super();
this.state = {
...props.reco
};
this.handleNameChange = this.handleNameChange.bind(this);
this.handleRecommenderChange = this.handleRecommenderChange.bind(this);
this.handleCategoryChange = this.handleCategoryChange.bind(this);
this.saveButtonClicked = this.saveButtonClicked.bind(this);
this.dispatchSaveButtonClicked = props.dispatchSaveButtonClicked; //Probably there is a better way to have evrything being into this.
this.recommenders = props.recommenders;
this.props = props;
}
handleNameChange(event) {
this.setState({ name: event.target.value });
}
handleRecommenderChange(value) {
this.setState({ recommender: value });
}
handleCategoryChange(newCategory) {
if(this.state.category === newCategory) {
newCategory = null;
}
this.setState({ category: newCategory });
}
saveButtonClicked() {
this.dispatchSaveButtonClicked(this.state.key, {
name: this.state.name,
recommender: this.state.recommender,
category: this.state.category,
});
}
closeButtonClicked() {
browserHistory.goBack();
}
getHeaderSaveButton() {
if(this.state.name) {
return <FlatButton label="Save" />;
} else {
return null;
}
}
render() {
if(this.props.isLoading) {
return <LoadingIndicator />;
}
return (
<div>
<Header
title={'Edit Reco'}
iconElementLeft={<IconButton><NavigationClose /></IconButton>}
onLeftIconButtonTouchTap={this.closeButtonClicked}
/>
<Card>
<CardText>
<TextField
hintText={'Recommendation name'}
style={blockStyle}
type='text'
value={this.state.name}
onChange={this.handleNameChange}
/>
<AutoComplete
hintText='Who recommended it?'
searchText={this.state.recommender}
dataSource={this.recommenders}
onUpdateInput={this.handleRecommenderChange}
onNewRequest={this.handleRecommenderChange}
style={blockStyle}
filter={AutoComplete.fuzzyFilter}
maxSearchResults={5}
/>
<CategorySelector
value={this.state.category}
onChange={this.handleCategoryChange}/>
<RaisedButton
label={'Save'}
style={blockStyle}
primary={true}
onClick={this.saveButtonClicked}
disabled={!this.state.name} />
</CardText>
</Card>
</div>
);
}
}
const mapStateToProps = (state, { params }) => {
return {
recommenders: getRecommenders(state).map( reco => reco.name),
reco: getReco(state, params.recoId),
isLoading: isEditing(state)
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatchSaveButtonClicked: (id, reco) => {
dispatch(recosActions.editReco(id, reco))
.then(() => {
browserHistory.goBack();
});
}
};
};
const EditRecoContainer = connect(mapStateToProps, mapDispatchToProps)(EditReco);
export default EditRecoContainer;
|
var fs = require('fs')
var path = require('path')
module.exports.getConfig = getConfig
var env = process.env.NODE_ENV || 'development'
var configDirs = fs.readdirSync(path.resolve(__dirname, '../config'))
var configObj = {}
configDirs.forEach(function(dirName) {
if (dirName.indexOf('.') !== 0) {
// skip hidden folder like .DS_Store in Mac
var config = require('../config/' + dirName + '/' + env)
configObj[dirName] = config
}
})
function getConfig() {
return configObj
}
|
'use strict'
const { test } = require('tap')
const Fastify = require('..')
const {
codes: {
FST_ERR_DEC_ALREADY_PRESENT,
FST_ERR_MISSING_MIDDLEWARE
}
} = require('../lib/errors')
test('Should throw if the basic use API has not been overridden', t => {
t.plan(1)
const fastify = Fastify()
try {
fastify.use()
t.fail('Should throw')
} catch (err) {
t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE)
}
})
test('Should be able to override the default use API', t => {
t.plan(1)
const fastify = Fastify()
fastify.decorate('use', () => true)
t.strictEqual(fastify.use(), true)
})
test('Cannot decorate use twice', t => {
t.plan(1)
const fastify = Fastify()
fastify.decorate('use', () => true)
try {
fastify.decorate('use', () => true)
} catch (err) {
t.ok(err instanceof FST_ERR_DEC_ALREADY_PRESENT)
}
})
test('Encapsulation works', t => {
t.plan(2)
const fastify = Fastify()
fastify.register((instance, opts, next) => {
instance.decorate('use', () => true)
t.strictEqual(instance.use(), true)
next()
})
fastify.register((instance, opts, next) => {
try {
instance.use()
t.fail('Should throw')
} catch (err) {
t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE)
}
next()
})
fastify.ready()
})
|
import React from "react";
import { storiesOf } from "@storybook/react";
import { withKnobs, boolean } from "@storybook/addon-knobs";
import centered from "@storybook/addon-centered/react";
import DarkModeKnobWrapper from "./DarkModeKnobWrapper";
import Heart from "../components/dots/Heart";
import Pride from "../components/dots/Pride";
import Triangle from "../components/dots/Triangle";
import Vroom from "../components/dots/Vroom";
import Pulse from "../components/dots/Pulse";
storiesOf("Dots", module)
.addDecorator(withKnobs)
.addDecorator(centered)
.add("Heart", () => {
const on = boolean("On", false);
return (
<div>
<Heart on={on} />
<Heart on={!on} />
</div>
);
})
.add("Pride", () => (
<DarkModeKnobWrapper>
<Pride on={boolean("On", false)} />
</DarkModeKnobWrapper>
))
.add("Triangle", () => <Triangle on={boolean("On", false)} />)
.add("Vroom", () => <Vroom on={boolean("On", false)} />)
.add("Pulse", () => <Pulse on={boolean("On", false)} />);
|
define(function(require) {
/**
* The Promises/A+ compliance test suite
*
* Converted from https://github.com/promises-aplus/promises-tests
* Thanks @domenic and A+ team for this massive work!
**/
require('spec/base/promiseSpec/aplus/2.1.2');
require('spec/base/promiseSpec/aplus/2.1.3');
require('spec/base/promiseSpec/aplus/2.2.1');
require('spec/base/promiseSpec/aplus/2.2.2');
require('spec/base/promiseSpec/aplus/2.2.3');
require('spec/base/promiseSpec/aplus/2.2.4');
require('spec/base/promiseSpec/aplus/2.2.5');
require('spec/base/promiseSpec/aplus/2.2.6');
require('spec/base/promiseSpec/aplus/2.2.7');
require('spec/base/promiseSpec/aplus/2.3.1');
require('spec/base/promiseSpec/aplus/2.3.2');
require('spec/base/promiseSpec/aplus/2.3.3');
require('spec/base/promiseSpec/aplus/2.3.4');
});
|
import React from 'react'
import { Image, Reveal } from 'shengnian-ui-react'
const RevealExampleHidden = () => (
<Reveal animated='small fade'>
<Reveal.Content visible>
<Image src='/assets/images/wireframe/square-image.png' size='small' />
</Reveal.Content>
<Reveal.Content hidden>
<Image src='/assets/images/avatar/large/ade.jpg' size='small' />
</Reveal.Content>
</Reveal>
)
export default RevealExampleHidden
|
/* global appSettings */
var
$result,
$resultContainer,
$resultsButton,
$resultsPane,
$renderingLabel,
$window = $(window),
path = require('path'),
_ = require('lodash'),
isEnabled = true,
messenger = require(path.resolve(__dirname, '../messenger')),
renderer = require(path.resolve(__dirname, './asciidoc.js')).get(),
formats = require(path.resolve(__dirname, '../formats')),
source = '',
shell = require('shell'),
formatter = null,
subscriptions = [],
_fileInfo,
_buildFlags = [];
var detectRenderer = function (fileInfo) {
var rendererPath, currentFormatter;
currentFormatter = formats.getByFileExtension(fileInfo.ext);
if (formatter === null || currentFormatter.name !== formatter.name) {
formatter = currentFormatter;
rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase());
renderer = require(rendererPath).get();
messenger.publish.file('formatChanged', formatter);
}
};
var handlers = {
opened: function(fileInfo){
refreshSubscriptions();
$result.animate({
scrollTop: $result.offset().top
}, 10);
},
sourceChanged: function(fileInfo){
handlers.contentChanged(fileInfo);
},
contentChanged: function (fileInfo) {
if (isEnabled && $result) {
_fileInfo = fileInfo;
if (!_.isUndefined(_fileInfo)) {
if (_fileInfo.isBlank) {
$result.html('');
} else {
if(_fileInfo.contents.length > 0){
var flags = '';
detectRenderer(_fileInfo);
source = _fileInfo.contents;
_buildFlags.forEach(function (buildFlag) {
flags += ':' + buildFlag + ':\n'
});
source = flags + source;
if(!$renderingLabel.is(':visible')){
$renderingLabel.fadeIn('fast');
}
renderer(source, function (e) {
$result.html(e.html);
if($renderingLabel.is(':visible')){
$renderingLabel.fadeOut('fast');
}
});
}
}
}
}
},
clearBuildFlags: function (params) {
_buildFlags = [];
},
buildFlags: function (buildFlags) {
_buildFlags = buildFlags;
handlers.contentChanged(_fileInfo);
},
showResults: function() {
subscribe();
$resultsPane.css('visibility', 'visible');
$resultsButton
.removeClass('fa-chevron-left')
.addClass('fa-chevron-right')
.one('click', handlers.hideResults);
messenger.publish.layout('showResults');
},
hideResults: function () {
unsubscribe();
$resultsPane.css('visibility', 'hidden');
$resultsButton
.removeClass('fa-chevron-right')
.addClass('fa-chevron-left')
.one('click', handlers.showResults);
messenger.publish.layout('hideResults');
},
fileSelected: function(){
refreshSubscriptions();
_buildFlags = [];
},
allFilesClosed: function () {
$result.html('');
$renderingLabel.fadeOut('fast');
}
};
var subscribe = function () {
isEnabled = true;
subscriptions.push(messenger.subscribe.file('new', handlers.opened));
subscriptions.push(messenger.subscribe.file('opened', handlers.opened));
subscriptions.push(messenger.subscribe.file('contentChanged', handlers.contentChanged));
subscriptions.push(messenger.subscribe.file('sourceChange', handlers.sourceChanged));
subscriptions.push(messenger.subscribe.file('allFilesClosed', handlers.allFilesClosed));
subscriptions.push(messenger.subscribe.format('buildFlags', handlers.buildFlags));
subscriptions.push(messenger.subscribe.metadata('buildFlags.clear', handlers.clearBuildFlags));
};
var unsubscribe = function () {
isEnabled = false;
subscriptions.forEach(function (subscription) {
messenger.unsubscribe(subscription);
});
subscriptions = [];
};
var refreshSubscriptions = function(){
unsubscribe();
subscribe();
};
subscribe();
messenger.subscribe.file('selected', handlers.fileSelected);
messenger.subscribe.file('rerender', function (data, envelope) {
renderer(source, function (e) {
$result.html(e.html);
});
});
var openExternalLinksInBrowser = function (e) {
var href;
var element = e.target;
if (element.nodeName === 'A') {
href = element.getAttribute('href');
shell.openExternal(href);
e.preventDefault();
}
};
document.addEventListener('click', openExternalLinksInBrowser, false);
var setHeight = function (offSetValue) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
$window.on('resize', function (e) {
$resultsPane.css('height', $window.height() - offSetValue + 'px');
});
};
$(function () {
$result = $('#result');
$resultContainer = $('#result-container');
$resultsPane = $('#result-pane');
$resultsButton = $('#result-button');
$renderingLabel = $('#rendering-label');
$resultsPane
.css('left', appSettings.split())
.css('width', appSettings.resultsWidth());
$resultsButton.one('click', handlers.hideResults);
setHeight(appSettings.editingContainerOffset());
});
|
/**
* @license Angular v4.2.6
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/core'), require('rxjs/BehaviorSubject'), require('rxjs/Subject'), require('rxjs/observable/from'), require('rxjs/observable/of'), require('rxjs/operator/concatMap'), require('rxjs/operator/every'), require('rxjs/operator/first'), require('rxjs/operator/map'), require('rxjs/operator/mergeMap'), require('rxjs/operator/reduce'), require('rxjs/Observable'), require('rxjs/operator/catch'), require('rxjs/operator/concatAll'), require('rxjs/util/EmptyError'), require('rxjs/observable/fromPromise'), require('rxjs/operator/last'), require('rxjs/operator/mergeAll'), require('@angular/platform-browser'), require('rxjs/operator/filter')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/common', '@angular/core', 'rxjs/BehaviorSubject', 'rxjs/Subject', 'rxjs/observable/from', 'rxjs/observable/of', 'rxjs/operator/concatMap', 'rxjs/operator/every', 'rxjs/operator/first', 'rxjs/operator/map', 'rxjs/operator/mergeMap', 'rxjs/operator/reduce', 'rxjs/Observable', 'rxjs/operator/catch', 'rxjs/operator/concatAll', 'rxjs/util/EmptyError', 'rxjs/observable/fromPromise', 'rxjs/operator/last', 'rxjs/operator/mergeAll', '@angular/platform-browser', 'rxjs/operator/filter'], factory) :
(factory((global.ng = global.ng || {}, global.ng.router = global.ng.router || {}),global.ng.common,global.ng.core,global.Rx,global.Rx,global.Rx.Observable,global.Rx.Observable,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx,global.Rx.Observable,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.ng.platformBrowser,global.Rx.Observable.prototype));
}(this, (function (exports,_angular_common,_angular_core,rxjs_BehaviorSubject,rxjs_Subject,rxjs_observable_from,rxjs_observable_of,rxjs_operator_concatMap,rxjs_operator_every,rxjs_operator_first,rxjs_operator_map,rxjs_operator_mergeMap,rxjs_operator_reduce,rxjs_Observable,rxjs_operator_catch,rxjs_operator_concatAll,rxjs_util_EmptyError,rxjs_observable_fromPromise,rxjs_operator_last,rxjs_operator_mergeAll,_angular_platformBrowser,rxjs_operator_filter) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* @license Angular v4.2.6
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Represents an event triggered when a navigation starts.
*
* \@stable
*/
var NavigationStart = (function () {
/**
* @param {?} id
* @param {?} url
*/
function NavigationStart(id, url) {
this.id = id;
this.url = url;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationStart.prototype.toString = function () { return "NavigationStart(id: " + this.id + ", url: '" + this.url + "')"; };
return NavigationStart;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation ends successfully.
*
* \@stable
*/
var NavigationEnd = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
*/
function NavigationEnd(id, url, urlAfterRedirects) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationEnd.prototype.toString = function () {
return "NavigationEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "')";
};
return NavigationEnd;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation is canceled.
*
* \@stable
*/
var NavigationCancel = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} reason
*/
function NavigationCancel(id, url, reason) {
this.id = id;
this.url = url;
this.reason = reason;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationCancel.prototype.toString = function () { return "NavigationCancel(id: " + this.id + ", url: '" + this.url + "')"; };
return NavigationCancel;
}());
/**
* \@whatItDoes Represents an event triggered when a navigation fails due to an unexpected error.
*
* \@stable
*/
var NavigationError = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} error
*/
function NavigationError(id, url, error) {
this.id = id;
this.url = url;
this.error = error;
}
/**
* \@docsNotRequired
* @return {?}
*/
NavigationError.prototype.toString = function () {
return "NavigationError(id: " + this.id + ", url: '" + this.url + "', error: " + this.error + ")";
};
return NavigationError;
}());
/**
* \@whatItDoes Represents an event triggered when routes are recognized.
*
* \@stable
*/
var RoutesRecognized = (function () {
/**
* @param {?} id
* @param {?} url
* @param {?} urlAfterRedirects
* @param {?} state
*/
function RoutesRecognized(id, url, urlAfterRedirects, state) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
/**
* \@docsNotRequired
* @return {?}
*/
RoutesRecognized.prototype.toString = function () {
return "RoutesRecognized(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
};
return RoutesRecognized;
}());
/**
* \@whatItDoes Represents an event triggered before lazy loading a route config.
*
* \@experimental
*/
var RouteConfigLoadStart = (function () {
/**
* @param {?} route
*/
function RouteConfigLoadStart(route) {
this.route = route;
}
/**
* @return {?}
*/
RouteConfigLoadStart.prototype.toString = function () { return "RouteConfigLoadStart(path: " + this.route.path + ")"; };
return RouteConfigLoadStart;
}());
/**
* \@whatItDoes Represents an event triggered when a route has been lazy loaded.
*
* \@experimental
*/
var RouteConfigLoadEnd = (function () {
/**
* @param {?} route
*/
function RouteConfigLoadEnd(route) {
this.route = route;
}
/**
* @return {?}
*/
RouteConfigLoadEnd.prototype.toString = function () { return "RouteConfigLoadEnd(path: " + this.route.path + ")"; };
return RouteConfigLoadEnd;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Name of the primary outlet.
*
* \@stable
*/
var PRIMARY_OUTLET = 'primary';
var ParamsAsMap = (function () {
/**
* @param {?} params
*/
function ParamsAsMap(params) {
this.params = params || {};
}
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.has = function (name) { return this.params.hasOwnProperty(name); };
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.get = function (name) {
if (this.has(name)) {
var /** @type {?} */ v = this.params[name];
return Array.isArray(v) ? v[0] : v;
}
return null;
};
/**
* @param {?} name
* @return {?}
*/
ParamsAsMap.prototype.getAll = function (name) {
if (this.has(name)) {
var /** @type {?} */ v = this.params[name];
return Array.isArray(v) ? v : [v];
}
return [];
};
Object.defineProperty(ParamsAsMap.prototype, "keys", {
/**
* @return {?}
*/
get: function () { return Object.keys(this.params); },
enumerable: true,
configurable: true
});
return ParamsAsMap;
}());
/**
* Convert a {\@link Params} instance to a {\@link ParamMap}.
*
* \@stable
* @param {?} params
* @return {?}
*/
function convertToParamMap(params) {
return new ParamsAsMap(params);
}
var NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
/**
* @param {?} message
* @return {?}
*/
function navigationCancelingError(message) {
var /** @type {?} */ error = Error('NavigationCancelingError: ' + message);
((error))[NAVIGATION_CANCELING_ERROR] = true;
return error;
}
/**
* @param {?} error
* @return {?}
*/
function isNavigationCancelingError(error) {
return ((error))[NAVIGATION_CANCELING_ERROR];
}
/**
* @param {?} segments
* @param {?} segmentGroup
* @param {?} route
* @return {?}
*/
function defaultUrlMatcher(segments, segmentGroup, route) {
var /** @type {?} */ parts = ((route.path)).split('/');
if (parts.length > segments.length) {
// The actual URL is shorter than the config, no match
return null;
}
if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || parts.length < segments.length)) {
// The config is longer than the actual URL but we are looking for a full match, return null
return null;
}
var /** @type {?} */ posParams = {};
// Check each config part against the actual URL
for (var /** @type {?} */ index = 0; index < parts.length; index++) {
var /** @type {?} */ part = parts[index];
var /** @type {?} */ segment = segments[index];
var /** @type {?} */ isParameter = part.startsWith(':');
if (isParameter) {
posParams[part.substring(1)] = segment;
}
else if (part !== segment.path) {
// The actual URL part does not match the config, no match
return null;
}
}
return { consumed: segments.slice(0, parts.length), posParams: posParams };
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var LoadedRouterConfig = (function () {
/**
* @param {?} routes
* @param {?} module
*/
function LoadedRouterConfig(routes, module) {
this.routes = routes;
this.module = module;
}
return LoadedRouterConfig;
}());
/**
* @param {?} config
* @param {?=} parentPath
* @return {?}
*/
function validateConfig(config, parentPath) {
if (parentPath === void 0) { parentPath = ''; }
// forEach doesn't iterate undefined values
for (var /** @type {?} */ i = 0; i < config.length; i++) {
var /** @type {?} */ route = config[i];
var /** @type {?} */ fullPath = getFullPath(parentPath, route);
validateNode(route, fullPath);
}
}
/**
* @param {?} route
* @param {?} fullPath
* @return {?}
*/
function validateNode(route, fullPath) {
if (!route) {
throw new Error("\n Invalid configuration of route '" + fullPath + "': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");
}
if (Array.isArray(route)) {
throw new Error("Invalid configuration of route '" + fullPath + "': Array cannot be specified");
}
if (!route.component && (route.outlet && route.outlet !== PRIMARY_OUTLET)) {
throw new Error("Invalid configuration of route '" + fullPath + "': a componentless route cannot have a named outlet set");
}
if (route.redirectTo && route.children) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and children cannot be used together");
}
if (route.redirectTo && route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and loadChildren cannot be used together");
}
if (route.children && route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "': children and loadChildren cannot be used together");
}
if (route.redirectTo && route.component) {
throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and component cannot be used together");
}
if (route.path && route.matcher) {
throw new Error("Invalid configuration of route '" + fullPath + "': path and matcher cannot be used together");
}
if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) {
throw new Error("Invalid configuration of route '" + fullPath + "'. One of the following must be provided: component, redirectTo, children or loadChildren");
}
if (route.path === void 0 && route.matcher === void 0) {
throw new Error("Invalid configuration of route '" + fullPath + "': routes must have either a path or a matcher specified");
}
if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
throw new Error("Invalid configuration of route '" + fullPath + "': path cannot start with a slash");
}
if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
var /** @type {?} */ exp = "The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.";
throw new Error("Invalid configuration of route '{path: \"" + fullPath + "\", redirectTo: \"" + route.redirectTo + "\"}': please provide 'pathMatch'. " + exp);
}
if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') {
throw new Error("Invalid configuration of route '" + fullPath + "': pathMatch can only be set to 'prefix' or 'full'");
}
if (route.children) {
validateConfig(route.children, fullPath);
}
}
/**
* @param {?} parentPath
* @param {?} currentRoute
* @return {?}
*/
function getFullPath(parentPath, currentRoute) {
if (!currentRoute) {
return parentPath;
}
if (!parentPath && !currentRoute.path) {
return '';
}
else if (parentPath && !currentRoute.path) {
return parentPath + "/";
}
else if (!parentPath && currentRoute.path) {
return currentRoute.path;
}
else {
return parentPath + "/" + currentRoute.path;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqualArrays(a, b) {
if (a.length !== b.length)
return false;
for (var /** @type {?} */ i = 0; i < a.length; ++i) {
if (!shallowEqual(a[i], b[i]))
return false;
}
return true;
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function shallowEqual(a, b) {
var /** @type {?} */ k1 = Object.keys(a);
var /** @type {?} */ k2 = Object.keys(b);
if (k1.length != k2.length) {
return false;
}
var /** @type {?} */ key;
for (var /** @type {?} */ i = 0; i < k1.length; i++) {
key = k1[i];
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
/**
* @template T
* @param {?} arr
* @return {?}
*/
function flatten(arr) {
return Array.prototype.concat.apply([], arr);
}
/**
* @template T
* @param {?} a
* @return {?}
*/
function last$1(a) {
return a.length > 0 ? a[a.length - 1] : null;
}
/**
* @param {?} bools
* @return {?}
*/
/**
* @template K, V
* @param {?} map
* @param {?} callback
* @return {?}
*/
function forEach(map$$1, callback) {
for (var /** @type {?} */ prop in map$$1) {
if (map$$1.hasOwnProperty(prop)) {
callback(map$$1[prop], prop);
}
}
}
/**
* @template A, B
* @param {?} obj
* @param {?} fn
* @return {?}
*/
function waitForMap(obj, fn) {
if (Object.keys(obj).length === 0) {
return rxjs_observable_of.of({});
}
var /** @type {?} */ waitHead = [];
var /** @type {?} */ waitTail = [];
var /** @type {?} */ res = {};
forEach(obj, function (a, k) {
var /** @type {?} */ mapped = rxjs_operator_map.map.call(fn(k, a), function (r) { return res[k] = r; });
if (k === PRIMARY_OUTLET) {
waitHead.push(mapped);
}
else {
waitTail.push(mapped);
}
});
var /** @type {?} */ concat$ = rxjs_operator_concatAll.concatAll.call(rxjs_observable_of.of.apply(void 0, waitHead.concat(waitTail)));
var /** @type {?} */ last$ = rxjs_operator_last.last.call(concat$);
return rxjs_operator_map.map.call(last$, function () { return res; });
}
/**
* @param {?} observables
* @return {?}
*/
function andObservables(observables) {
var /** @type {?} */ merged$ = rxjs_operator_mergeAll.mergeAll.call(observables);
return rxjs_operator_every.every.call(merged$, function (result) { return result === true; });
}
/**
* @template T
* @param {?} value
* @return {?}
*/
function wrapIntoObservable(value) {
if (_angular_core.ɵisObservable(value)) {
return value;
}
if (_angular_core.ɵisPromise(value)) {
// Use `Promise.resolve()` to wrap promise-like instances.
// Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
// change detection.
return rxjs_observable_fromPromise.fromPromise(Promise.resolve(value));
}
return rxjs_observable_of.of(value);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @return {?}
*/
function createEmptyUrlTree() {
return new UrlTree(new UrlSegmentGroup([], {}), {}, null);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} exact
* @return {?}
*/
function containsTree(container, containee, exact) {
if (exact) {
return equalQueryParams(container.queryParams, containee.queryParams) &&
equalSegmentGroups(container.root, containee.root);
}
return containsQueryParams(container.queryParams, containee.queryParams) &&
containsSegmentGroup(container.root, containee.root);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalQueryParams(container, containee) {
return shallowEqual(container, containee);
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function equalSegmentGroups(container, containee) {
if (!equalPath(container.segments, containee.segments))
return false;
if (container.numberOfChildren !== containee.numberOfChildren)
return false;
for (var /** @type {?} */ c in containee.children) {
if (!container.children[c])
return false;
if (!equalSegmentGroups(container.children[c], containee.children[c]))
return false;
}
return true;
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsQueryParams(container, containee) {
return Object.keys(containee).length <= Object.keys(container).length &&
Object.keys(containee).every(function (key) { return containee[key] === container[key]; });
}
/**
* @param {?} container
* @param {?} containee
* @return {?}
*/
function containsSegmentGroup(container, containee) {
return containsSegmentGroupHelper(container, containee, containee.segments);
}
/**
* @param {?} container
* @param {?} containee
* @param {?} containeePaths
* @return {?}
*/
function containsSegmentGroupHelper(container, containee, containeePaths) {
if (container.segments.length > containeePaths.length) {
var /** @type {?} */ current = container.segments.slice(0, containeePaths.length);
if (!equalPath(current, containeePaths))
return false;
if (containee.hasChildren())
return false;
return true;
}
else if (container.segments.length === containeePaths.length) {
if (!equalPath(container.segments, containeePaths))
return false;
for (var /** @type {?} */ c in containee.children) {
if (!container.children[c])
return false;
if (!containsSegmentGroup(container.children[c], containee.children[c]))
return false;
}
return true;
}
else {
var /** @type {?} */ current = containeePaths.slice(0, container.segments.length);
var /** @type {?} */ next = containeePaths.slice(container.segments.length);
if (!equalPath(container.segments, current))
return false;
if (!container.children[PRIMARY_OUTLET])
return false;
return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next);
}
}
/**
* \@whatItDoes Represents the parsed URL.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree =
* router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
* const f = tree.fragment; // return 'fragment'
* const q = tree.queryParams; // returns {debug: 'true'}
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
* g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
* g.children['support'].segments; // return 1 segment 'help'
* }
* }
* ```
*
* \@description
*
* Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
* serialized tree.
* UrlTree is a data structure that provides a lot of affordances in dealing with URLs
*
* \@stable
*/
var UrlTree = (function () {
/**
* \@internal
* @param {?} root
* @param {?} queryParams
* @param {?} fragment
*/
function UrlTree(root, queryParams, fragment) {
this.root = root;
this.queryParams = queryParams;
this.fragment = fragment;
}
Object.defineProperty(UrlTree.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlTree.prototype.toString = function () { return DEFAULT_SERIALIZER.serialize(this); };
return UrlTree;
}());
/**
* \@whatItDoes Represents the parsed URL segment group.
*
* See {\@link UrlTree} for more information.
*
* \@stable
*/
var UrlSegmentGroup = (function () {
/**
* @param {?} segments
* @param {?} children
*/
function UrlSegmentGroup(segments, children) {
var _this = this;
this.segments = segments;
this.children = children;
/**
* The parent node in the url tree
*/
this.parent = null;
forEach(children, function (v, k) { return v.parent = _this; });
}
/**
* Whether the segment has child segments
* @return {?}
*/
UrlSegmentGroup.prototype.hasChildren = function () { return this.numberOfChildren > 0; };
Object.defineProperty(UrlSegmentGroup.prototype, "numberOfChildren", {
/**
* Number of child segments
* @return {?}
*/
get: function () { return Object.keys(this.children).length; },
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlSegmentGroup.prototype.toString = function () { return serializePaths(this); };
return UrlSegmentGroup;
}());
/**
* \@whatItDoes Represents a single URL segment.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const tree: UrlTree = router.parseUrl('/team;id=33');
* const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
* const s: UrlSegment[] = g.segments;
* s[0].path; // returns 'team'
* s[0].parameters; // returns {id: 33}
* }
* }
* ```
*
* \@description
*
* A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
* parameters associated with the segment.
*
* \@stable
*/
var UrlSegment = (function () {
/**
* @param {?} path
* @param {?} parameters
*/
function UrlSegment(path, parameters) {
this.path = path;
this.parameters = parameters;
}
Object.defineProperty(UrlSegment.prototype, "parameterMap", {
/**
* @return {?}
*/
get: function () {
if (!this._parameterMap) {
this._parameterMap = convertToParamMap(this.parameters);
}
return this._parameterMap;
},
enumerable: true,
configurable: true
});
/**
* \@docsNotRequired
* @return {?}
*/
UrlSegment.prototype.toString = function () { return serializePath(this); };
return UrlSegment;
}());
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalSegments(as, bs) {
return equalPath(as, bs) && as.every(function (a, i) { return shallowEqual(a.parameters, bs[i].parameters); });
}
/**
* @param {?} as
* @param {?} bs
* @return {?}
*/
function equalPath(as, bs) {
if (as.length !== bs.length)
return false;
return as.every(function (a, i) { return a.path === bs[i].path; });
}
/**
* @template T
* @param {?} segment
* @param {?} fn
* @return {?}
*/
function mapChildrenIntoArray(segment, fn) {
var /** @type {?} */ res = [];
forEach(segment.children, function (child, childOutlet) {
if (childOutlet === PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
});
forEach(segment.children, function (child, childOutlet) {
if (childOutlet !== PRIMARY_OUTLET) {
res = res.concat(fn(child, childOutlet));
}
});
return res;
}
/**
* \@whatItDoes Serializes and deserializes a URL string into a URL tree.
*
* \@description The url serialization strategy is customizable. You can
* make all URLs case insensitive by providing a custom UrlSerializer.
*
* See {\@link DefaultUrlSerializer} for an example of a URL serializer.
*
* \@stable
* @abstract
*/
var UrlSerializer = (function () {
function UrlSerializer() {
}
/**
* Parse a url into a {\@link UrlTree}
* @abstract
* @param {?} url
* @return {?}
*/
UrlSerializer.prototype.parse = function (url) { };
/**
* Converts a {\@link UrlTree} into a url
* @abstract
* @param {?} tree
* @return {?}
*/
UrlSerializer.prototype.serialize = function (tree) { };
return UrlSerializer;
}());
/**
* \@whatItDoes A default implementation of the {\@link UrlSerializer}.
*
* \@description
*
* Example URLs:
*
* ```
* /inbox/33(popup:compose)
* /inbox/33;open=true/messages/44
* ```
*
* DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
* colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
* specify route specific parameters.
*
* \@stable
*/
var DefaultUrlSerializer = (function () {
function DefaultUrlSerializer() {
}
/**
* Parses a url into a {\@link UrlTree}
* @param {?} url
* @return {?}
*/
DefaultUrlSerializer.prototype.parse = function (url) {
var /** @type {?} */ p = new UrlParser(url);
return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
};
/**
* Converts a {\@link UrlTree} into a url
* @param {?} tree
* @return {?}
*/
DefaultUrlSerializer.prototype.serialize = function (tree) {
var /** @type {?} */ segment = "/" + serializeSegment(tree.root, true);
var /** @type {?} */ query = serializeQueryParams(tree.queryParams);
var /** @type {?} */ fragment = typeof tree.fragment === "string" ? "#" + encodeURI(/** @type {?} */ ((tree.fragment))) : '';
return "" + segment + query + fragment;
};
return DefaultUrlSerializer;
}());
var DEFAULT_SERIALIZER = new DefaultUrlSerializer();
/**
* @param {?} segment
* @return {?}
*/
function serializePaths(segment) {
return segment.segments.map(function (p) { return serializePath(p); }).join('/');
}
/**
* @param {?} segment
* @param {?} root
* @return {?}
*/
function serializeSegment(segment, root) {
if (!segment.hasChildren()) {
return serializePaths(segment);
}
if (root) {
var /** @type {?} */ primary = segment.children[PRIMARY_OUTLET] ?
serializeSegment(segment.children[PRIMARY_OUTLET], false) :
'';
var /** @type {?} */ children_1 = [];
forEach(segment.children, function (v, k) {
if (k !== PRIMARY_OUTLET) {
children_1.push(k + ":" + serializeSegment(v, false));
}
});
return children_1.length > 0 ? primary + "(" + children_1.join('//') + ")" : primary;
}
else {
var /** @type {?} */ children = mapChildrenIntoArray(segment, function (v, k) {
if (k === PRIMARY_OUTLET) {
return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
}
return [k + ":" + serializeSegment(v, false)];
});
return serializePaths(segment) + "/(" + children.join('//') + ")";
}
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "\@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* @param {?} s
* @return {?}
*/
function encode(s) {
return encodeURIComponent(s)
.replace(/%40/g, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';');
}
/**
* @param {?} s
* @return {?}
*/
function decode(s) {
return decodeURIComponent(s);
}
/**
* @param {?} path
* @return {?}
*/
function serializePath(path) {
return "" + encode(path.path) + serializeParams(path.parameters);
}
/**
* @param {?} params
* @return {?}
*/
function serializeParams(params) {
return Object.keys(params).map(function (key) { return ";" + encode(key) + "=" + encode(params[key]); }).join('');
}
/**
* @param {?} params
* @return {?}
*/
function serializeQueryParams(params) {
var /** @type {?} */ strParams = Object.keys(params).map(function (name) {
var /** @type {?} */ value = params[name];
return Array.isArray(value) ? value.map(function (v) { return encode(name) + "=" + encode(v); }).join('&') :
encode(name) + "=" + encode(value);
});
return strParams.length ? "?" + strParams.join("&") : '';
}
var SEGMENT_RE = /^[^\/()?;=&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchSegments(str) {
var /** @type {?} */ match = str.match(SEGMENT_RE);
return match ? match[0] : '';
}
var QUERY_PARAM_RE = /^[^=?&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchQueryParams(str) {
var /** @type {?} */ match = str.match(QUERY_PARAM_RE);
return match ? match[0] : '';
}
var QUERY_PARAM_VALUE_RE = /^[^?&#]+/;
/**
* @param {?} str
* @return {?}
*/
function matchUrlQueryParamValue(str) {
var /** @type {?} */ match = str.match(QUERY_PARAM_VALUE_RE);
return match ? match[0] : '';
}
var UrlParser = (function () {
/**
* @param {?} url
*/
function UrlParser(url) {
this.url = url;
this.remaining = url;
}
/**
* @return {?}
*/
UrlParser.prototype.parseRootSegment = function () {
this.consumeOptional('/');
if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
return new UrlSegmentGroup([], {});
}
// The root segment group never has segments
return new UrlSegmentGroup([], this.parseChildren());
};
/**
* @return {?}
*/
UrlParser.prototype.parseQueryParams = function () {
var /** @type {?} */ params = {};
if (this.consumeOptional('?')) {
do {
this.parseQueryParam(params);
} while (this.consumeOptional('&'));
}
return params;
};
/**
* @return {?}
*/
UrlParser.prototype.parseFragment = function () {
return this.consumeOptional('#') ? decodeURI(this.remaining) : null;
};
/**
* @return {?}
*/
UrlParser.prototype.parseChildren = function () {
if (this.remaining === '') {
return {};
}
this.consumeOptional('/');
var /** @type {?} */ segments = [];
if (!this.peekStartsWith('(')) {
segments.push(this.parseSegment());
}
while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
this.capture('/');
segments.push(this.parseSegment());
}
var /** @type {?} */ children = {};
if (this.peekStartsWith('/(')) {
this.capture('/');
children = this.parseParens(true);
}
var /** @type {?} */ res = {};
if (this.peekStartsWith('(')) {
res = this.parseParens(false);
}
if (segments.length > 0 || Object.keys(children).length > 0) {
res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
}
return res;
};
/**
* @return {?}
*/
UrlParser.prototype.parseSegment = function () {
var /** @type {?} */ path = matchSegments(this.remaining);
if (path === '' && this.peekStartsWith(';')) {
throw new Error("Empty path url segment cannot have parameters: '" + this.remaining + "'.");
}
this.capture(path);
return new UrlSegment(decode(path), this.parseMatrixParams());
};
/**
* @return {?}
*/
UrlParser.prototype.parseMatrixParams = function () {
var /** @type {?} */ params = {};
while (this.consumeOptional(';')) {
this.parseParam(params);
}
return params;
};
/**
* @param {?} params
* @return {?}
*/
UrlParser.prototype.parseParam = function (params) {
var /** @type {?} */ key = matchSegments(this.remaining);
if (!key) {
return;
}
this.capture(key);
var /** @type {?} */ value = '';
if (this.consumeOptional('=')) {
var /** @type {?} */ valueMatch = matchSegments(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
params[decode(key)] = decode(value);
};
/**
* @param {?} params
* @return {?}
*/
UrlParser.prototype.parseQueryParam = function (params) {
var /** @type {?} */ key = matchQueryParams(this.remaining);
if (!key) {
return;
}
this.capture(key);
var /** @type {?} */ value = '';
if (this.consumeOptional('=')) {
var /** @type {?} */ valueMatch = matchUrlQueryParamValue(this.remaining);
if (valueMatch) {
value = valueMatch;
this.capture(value);
}
}
var /** @type {?} */ decodedKey = decode(key);
var /** @type {?} */ decodedVal = decode(value);
if (params.hasOwnProperty(decodedKey)) {
// Append to existing values
var /** @type {?} */ currentVal = params[decodedKey];
if (!Array.isArray(currentVal)) {
currentVal = [currentVal];
params[decodedKey] = currentVal;
}
currentVal.push(decodedVal);
}
else {
// Create a new value
params[decodedKey] = decodedVal;
}
};
/**
* @param {?} allowPrimary
* @return {?}
*/
UrlParser.prototype.parseParens = function (allowPrimary) {
var /** @type {?} */ segments = {};
this.capture('(');
while (!this.consumeOptional(')') && this.remaining.length > 0) {
var /** @type {?} */ path = matchSegments(this.remaining);
var /** @type {?} */ next = this.remaining[path.length];
// if is is not one of these characters, then the segment was unescaped
// or the group was not closed
if (next !== '/' && next !== ')' && next !== ';') {
throw new Error("Cannot parse url '" + this.url + "'");
}
var /** @type {?} */ outletName = ((undefined));
if (path.indexOf(':') > -1) {
outletName = path.substr(0, path.indexOf(':'));
this.capture(outletName);
this.capture(':');
}
else if (allowPrimary) {
outletName = PRIMARY_OUTLET;
}
var /** @type {?} */ children = this.parseChildren();
segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
new UrlSegmentGroup([], children);
this.consumeOptional('//');
}
return segments;
};
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.peekStartsWith = function (str) { return this.remaining.startsWith(str); };
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.consumeOptional = function (str) {
if (this.peekStartsWith(str)) {
this.remaining = this.remaining.substring(str.length);
return true;
}
return false;
};
/**
* @param {?} str
* @return {?}
*/
UrlParser.prototype.capture = function (str) {
if (!this.consumeOptional(str)) {
throw new Error("Expected \"" + str + "\".");
}
};
return UrlParser;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var NoMatch = (function () {
/**
* @param {?=} segmentGroup
*/
function NoMatch(segmentGroup) {
this.segmentGroup = segmentGroup || null;
}
return NoMatch;
}());
var AbsoluteRedirect = (function () {
/**
* @param {?} urlTree
*/
function AbsoluteRedirect(urlTree) {
this.urlTree = urlTree;
}
return AbsoluteRedirect;
}());
/**
* @param {?} segmentGroup
* @return {?}
*/
function noMatch(segmentGroup) {
return new rxjs_Observable.Observable(function (obs) { return obs.error(new NoMatch(segmentGroup)); });
}
/**
* @param {?} newTree
* @return {?}
*/
function absoluteRedirect(newTree) {
return new rxjs_Observable.Observable(function (obs) { return obs.error(new AbsoluteRedirect(newTree)); });
}
/**
* @param {?} redirectTo
* @return {?}
*/
function namedOutletsRedirect(redirectTo) {
return new rxjs_Observable.Observable(function (obs) { return obs.error(new Error("Only absolute redirects can have named outlets. redirectTo: '" + redirectTo + "'")); });
}
/**
* @param {?} route
* @return {?}
*/
function canLoadFails(route) {
return new rxjs_Observable.Observable(function (obs) { return obs.error(navigationCancelingError("Cannot load children because the guard of the route \"path: '" + route.path + "'\" returned false")); });
}
/**
* Returns the `UrlTree` with the redirection applied.
*
* Lazy modules are loaded along the way.
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
* @return {?}
*/
function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply();
}
var ApplyRedirects = (function () {
/**
* @param {?} moduleInjector
* @param {?} configLoader
* @param {?} urlSerializer
* @param {?} urlTree
* @param {?} config
*/
function ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
this.configLoader = configLoader;
this.urlSerializer = urlSerializer;
this.urlTree = urlTree;
this.config = config;
this.allowRedirects = true;
this.ngModule = moduleInjector.get(_angular_core.NgModuleRef);
}
/**
* @return {?}
*/
ApplyRedirects.prototype.apply = function () {
var _this = this;
var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET);
var /** @type {?} */ urlTrees$ = rxjs_operator_map.map.call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, _this.urlTree.queryParams, /** @type {?} */ ((_this.urlTree.fragment))); });
return rxjs_operator_catch._catch.call(urlTrees$, function (e) {
if (e instanceof AbsoluteRedirect) {
// after an absolute redirect we do not apply any more redirects!
_this.allowRedirects = false;
// we need to run matching, so we can fetch all lazy-loaded modules
return _this.match(e.urlTree);
}
if (e instanceof NoMatch) {
throw _this.noMatchError(e);
}
throw e;
});
};
/**
* @param {?} tree
* @return {?}
*/
ApplyRedirects.prototype.match = function (tree) {
var _this = this;
var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET);
var /** @type {?} */ mapped$ = rxjs_operator_map.map.call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, tree.queryParams, /** @type {?} */ ((tree.fragment))); });
return rxjs_operator_catch._catch.call(mapped$, function (e) {
if (e instanceof NoMatch) {
throw _this.noMatchError(e);
}
throw e;
});
};
/**
* @param {?} e
* @return {?}
*/
ApplyRedirects.prototype.noMatchError = function (e) {
return new Error("Cannot match any routes. URL Segment: '" + e.segmentGroup + "'");
};
/**
* @param {?} rootCandidate
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
ApplyRedirects.prototype.createUrlTree = function (rootCandidate, queryParams, fragment) {
var /** @type {?} */ root = rootCandidate.segments.length > 0 ?
new UrlSegmentGroup([], (_a = {}, _a[PRIMARY_OUTLET] = rootCandidate, _a)) :
rootCandidate;
return new UrlTree(root, queryParams, fragment);
var _a;
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentGroup = function (ngModule, routes, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return rxjs_operator_map.map.call(this.expandChildren(ngModule, routes, segmentGroup), function (children) { return new UrlSegmentGroup([], children); });
}
return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true);
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} segmentGroup
* @return {?}
*/
ApplyRedirects.prototype.expandChildren = function (ngModule, routes, segmentGroup) {
var _this = this;
return waitForMap(segmentGroup.children, function (childOutlet, child) { return _this.expandSegmentGroup(ngModule, routes, child, childOutlet); });
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} segments
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
ApplyRedirects.prototype.expandSegment = function (ngModule, segmentGroup, routes, segments, outlet, allowRedirects) {
var _this = this;
var /** @type {?} */ routes$ = rxjs_observable_of.of.apply(void 0, routes);
var /** @type {?} */ processedRoutes$ = rxjs_operator_map.map.call(routes$, function (r) {
var /** @type {?} */ expanded$ = _this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects);
return rxjs_operator_catch._catch.call(expanded$, function (e) {
if (e instanceof NoMatch) {
return rxjs_observable_of.of(null);
}
throw e;
});
});
var /** @type {?} */ concattedProcessedRoutes$ = rxjs_operator_concatAll.concatAll.call(processedRoutes$);
var /** @type {?} */ first$ = rxjs_operator_first.first.call(concattedProcessedRoutes$, function (s) { return !!s; });
return rxjs_operator_catch._catch.call(first$, function (e, _) {
if (e instanceof rxjs_util_EmptyError.EmptyError) {
if (_this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return rxjs_observable_of.of(new UrlSegmentGroup([], {}));
}
throw new NoMatch(segmentGroup);
}
throw e;
});
};
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} paths
* @param {?} outlet
* @param {?} allowRedirects
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentAgainstRoute = function (ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) {
if (getOutlet(route) !== outlet) {
return noMatch(segmentGroup);
}
if (route.redirectTo === undefined) {
return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths);
}
if (allowRedirects && this.allowRedirects) {
return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet);
}
return noMatch(segmentGroup);
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
if (route.path === '**') {
return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet);
}
return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet);
};
/**
* @param {?} ngModule
* @param {?} routes
* @param {?} route
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect = function (ngModule, routes, route, outlet) {
var _this = this;
var /** @type {?} */ newTree = this.applyRedirectCommands([], /** @type {?} */ ((route.redirectTo)), {});
if (((route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return rxjs_operator_mergeMap.mergeMap.call(this.lineralizeSegments(route, newTree), function (newSegments) {
var /** @type {?} */ group = new UrlSegmentGroup(newSegments, {});
return _this.expandSegment(ngModule, group, routes, newSegments, outlet, false);
});
};
/**
* @param {?} ngModule
* @param {?} segmentGroup
* @param {?} routes
* @param {?} route
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
ApplyRedirects.prototype.expandRegularSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
var _this = this;
var _a = match(segmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild, positionalParamSegments = _a.positionalParamSegments;
if (!matched)
return noMatch(segmentGroup);
var /** @type {?} */ newTree = this.applyRedirectCommands(consumedSegments, /** @type {?} */ ((route.redirectTo)), /** @type {?} */ (positionalParamSegments));
if (((route.redirectTo)).startsWith('/')) {
return absoluteRedirect(newTree);
}
return rxjs_operator_mergeMap.mergeMap.call(this.lineralizeSegments(route, newTree), function (newSegments) {
return _this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false);
});
};
/**
* @param {?} ngModule
* @param {?} rawSegmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
ApplyRedirects.prototype.matchSegmentAgainstRoute = function (ngModule, rawSegmentGroup, route, segments) {
var _this = this;
if (route.path === '**') {
if (route.loadChildren) {
return rxjs_operator_map.map.call(this.configLoader.load(ngModule.injector, route), function (cfg) {
route._loadedConfig = cfg;
return new UrlSegmentGroup(segments, {});
});
}
return rxjs_observable_of.of(new UrlSegmentGroup(segments, {}));
}
var _a = match(rawSegmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild;
if (!matched)
return noMatch(rawSegmentGroup);
var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild);
var /** @type {?} */ childConfig$ = this.getChildConfig(ngModule, route);
return rxjs_operator_mergeMap.mergeMap.call(childConfig$, function (routerConfig) {
var /** @type {?} */ childModule = routerConfig.module;
var /** @type {?} */ childConfig = routerConfig.routes;
var _a = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
var /** @type {?} */ expanded$_1 = _this.expandChildren(childModule, childConfig, segmentGroup);
return rxjs_operator_map.map.call(expanded$_1, function (children) { return new UrlSegmentGroup(consumedSegments, children); });
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return rxjs_observable_of.of(new UrlSegmentGroup(consumedSegments, {}));
}
var /** @type {?} */ expanded$ = _this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true);
return rxjs_operator_map.map.call(expanded$, function (cs) { return new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children); });
});
};
/**
* @param {?} ngModule
* @param {?} route
* @return {?}
*/
ApplyRedirects.prototype.getChildConfig = function (ngModule, route) {
var _this = this;
if (route.children) {
// The children belong to the same module
return rxjs_observable_of.of(new LoadedRouterConfig(route.children, ngModule));
}
if (route.loadChildren) {
// lazy children belong to the loaded module
if (route._loadedConfig !== undefined) {
return rxjs_observable_of.of(route._loadedConfig);
}
return rxjs_operator_mergeMap.mergeMap.call(runCanLoadGuard(ngModule.injector, route), function (shouldLoad) {
if (shouldLoad) {
return rxjs_operator_map.map.call(_this.configLoader.load(ngModule.injector, route), function (cfg) {
route._loadedConfig = cfg;
return cfg;
});
}
return canLoadFails(route);
});
}
return rxjs_observable_of.of(new LoadedRouterConfig([], ngModule));
};
/**
* @param {?} route
* @param {?} urlTree
* @return {?}
*/
ApplyRedirects.prototype.lineralizeSegments = function (route, urlTree) {
var /** @type {?} */ res = [];
var /** @type {?} */ c = urlTree.root;
while (true) {
res = res.concat(c.segments);
if (c.numberOfChildren === 0) {
return rxjs_observable_of.of(res);
}
if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
return namedOutletsRedirect(/** @type {?} */ ((route.redirectTo)));
}
c = c.children[PRIMARY_OUTLET];
}
};
/**
* @param {?} segments
* @param {?} redirectTo
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.applyRedirectCommands = function (segments, redirectTo, posParams) {
return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
};
/**
* @param {?} redirectTo
* @param {?} urlTree
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.applyRedirectCreatreUrlTree = function (redirectTo, urlTree, segments, posParams) {
var /** @type {?} */ newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
};
/**
* @param {?} redirectToParams
* @param {?} actualParams
* @return {?}
*/
ApplyRedirects.prototype.createQueryParams = function (redirectToParams, actualParams) {
var /** @type {?} */ res = {};
forEach(redirectToParams, function (v, k) {
var /** @type {?} */ copySourceValue = typeof v === 'string' && v.startsWith(':');
if (copySourceValue) {
var /** @type {?} */ sourceName = v.substring(1);
res[k] = actualParams[sourceName];
}
else {
res[k] = v;
}
});
return res;
};
/**
* @param {?} redirectTo
* @param {?} group
* @param {?} segments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.createSegmentGroup = function (redirectTo, group, segments, posParams) {
var _this = this;
var /** @type {?} */ updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
var /** @type {?} */ children = {};
forEach(group.children, function (child, name) {
children[name] = _this.createSegmentGroup(redirectTo, child, segments, posParams);
});
return new UrlSegmentGroup(updatedSegments, children);
};
/**
* @param {?} redirectTo
* @param {?} redirectToSegments
* @param {?} actualSegments
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.createSegments = function (redirectTo, redirectToSegments, actualSegments, posParams) {
var _this = this;
return redirectToSegments.map(function (s) { return s.path.startsWith(':') ? _this.findPosParam(redirectTo, s, posParams) :
_this.findOrReturn(s, actualSegments); });
};
/**
* @param {?} redirectTo
* @param {?} redirectToUrlSegment
* @param {?} posParams
* @return {?}
*/
ApplyRedirects.prototype.findPosParam = function (redirectTo, redirectToUrlSegment, posParams) {
var /** @type {?} */ pos = posParams[redirectToUrlSegment.path.substring(1)];
if (!pos)
throw new Error("Cannot redirect to '" + redirectTo + "'. Cannot find '" + redirectToUrlSegment.path + "'.");
return pos;
};
/**
* @param {?} redirectToUrlSegment
* @param {?} actualSegments
* @return {?}
*/
ApplyRedirects.prototype.findOrReturn = function (redirectToUrlSegment, actualSegments) {
var /** @type {?} */ idx = 0;
for (var _i = 0, actualSegments_1 = actualSegments; _i < actualSegments_1.length; _i++) {
var s = actualSegments_1[_i];
if (s.path === redirectToUrlSegment.path) {
actualSegments.splice(idx);
return s;
}
idx++;
}
return redirectToUrlSegment;
};
return ApplyRedirects;
}());
/**
* @param {?} moduleInjector
* @param {?} route
* @return {?}
*/
function runCanLoadGuard(moduleInjector, route) {
var /** @type {?} */ canLoad = route.canLoad;
if (!canLoad || canLoad.length === 0)
return rxjs_observable_of.of(true);
var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(canLoad), function (injectionToken) {
var /** @type {?} */ guard = moduleInjector.get(injectionToken);
return wrapIntoObservable(guard.canLoad ? guard.canLoad(route) : guard(route));
});
return andObservables(obs);
}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match(segmentGroup, route, segments) {
if (route.path === '') {
if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) {
return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
}
var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher;
var /** @type {?} */ res = matcher(segments, segmentGroup, route);
if (!res) {
return {
matched: false, consumedSegments: /** @type {?} */ ([]), lastChild: 0, positionalParamSegments: {},
};
}
return {
matched: true,
consumedSegments: /** @type {?} */ ((res.consumed)),
lastChild: /** @type {?} */ ((res.consumed.length)),
positionalParamSegments: /** @type {?} */ ((res.posParams)),
};
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @return {?}
*/
function split(segmentGroup, consumedSegments, slicedSegments, config) {
if (slicedSegments.length > 0 &&
containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
return { segmentGroup: mergeTrivialChildren(s), slicedSegments: slicedSegments };
}
return { segmentGroup: segmentGroup, slicedSegments: slicedSegments };
}
/**
* @param {?} s
* @return {?}
*/
function mergeTrivialChildren(s) {
if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
var /** @type {?} */ c = s.children[PRIMARY_OUTLET];
return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
}
return s;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @return {?}
*/
function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
var /** @type {?} */ res = {};
for (var _i = 0, routes_1 = routes; _i < routes_1.length; _i++) {
var r = routes_1[_i];
if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
res[getOutlet(r)] = new UrlSegmentGroup([], {});
}
}
return Object.assign({}, children, res);
}
/**
* @param {?} routes
* @param {?} primarySegmentGroup
* @return {?}
*/
function createChildrenForEmptySegments(routes, primarySegmentGroup) {
var /** @type {?} */ res = {};
res[PRIMARY_OUTLET] = primarySegmentGroup;
for (var _i = 0, routes_2 = routes; _i < routes_2.length; _i++) {
var r = routes_2[_i];
if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
res[getOutlet(r)] = new UrlSegmentGroup([], {});
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) {
return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET; });
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathRedirects(segmentGroup, segments, routes) {
return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r); });
}
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} r
* @return {?}
*/
function isEmptyPathRedirect(segmentGroup, segments, r) {
if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo !== undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Tree = (function () {
/**
* @param {?} root
*/
function Tree(root) {
this._root = root;
}
Object.defineProperty(Tree.prototype, "root", {
/**
* @return {?}
*/
get: function () { return this._root.value; },
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.parent = function (t) {
var /** @type {?} */ p = this.pathFromRoot(t);
return p.length > 1 ? p[p.length - 2] : null;
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.children = function (t) {
var /** @type {?} */ n = findNode(t, this._root);
return n ? n.children.map(function (t) { return t.value; }) : [];
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.firstChild = function (t) {
var /** @type {?} */ n = findNode(t, this._root);
return n && n.children.length > 0 ? n.children[0].value : null;
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.siblings = function (t) {
var /** @type {?} */ p = findPath(t, this._root);
if (p.length < 2)
return [];
var /** @type {?} */ c = p[p.length - 2].children.map(function (c) { return c.value; });
return c.filter(function (cc) { return cc !== t; });
};
/**
* \@internal
* @param {?} t
* @return {?}
*/
Tree.prototype.pathFromRoot = function (t) { return findPath(t, this._root).map(function (s) { return s.value; }); };
return Tree;
}());
/**
* @template T
* @param {?} value
* @param {?} node
* @return {?}
*/
function findNode(value, node) {
if (value === node.value)
return node;
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var child = _a[_i];
var /** @type {?} */ node_1 = findNode(value, child);
if (node_1)
return node_1;
}
return null;
}
/**
* @template T
* @param {?} value
* @param {?} node
* @return {?}
*/
function findPath(value, node) {
if (value === node.value)
return [node];
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var child = _a[_i];
var /** @type {?} */ path = findPath(value, child);
if (path.length) {
path.unshift(node);
return path;
}
}
return [];
}
var TreeNode = (function () {
/**
* @param {?} value
* @param {?} children
*/
function TreeNode(value, children) {
this.value = value;
this.children = children;
}
/**
* @return {?}
*/
TreeNode.prototype.toString = function () { return "TreeNode(" + this.value + ")"; };
return TreeNode;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Represents the state of the router.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const root: ActivatedRoute = state.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* \@description
* RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL
* segments, the extracted parameters, and the resolved data.
*
* See {\@link ActivatedRoute} for more information.
*
* \@stable
*/
var RouterState = (function (_super) {
__extends(RouterState, _super);
/**
* \@internal
* @param {?} root
* @param {?} snapshot
*/
function RouterState(root, snapshot) {
var _this = _super.call(this, root) || this;
_this.snapshot = snapshot;
setRouterState(_this, root);
return _this;
}
/**
* @return {?}
*/
RouterState.prototype.toString = function () { return this.snapshot.toString(); };
return RouterState;
}(Tree));
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyState(urlTree, rootComponent) {
var /** @type {?} */ snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
var /** @type {?} */ emptyUrl = new rxjs_BehaviorSubject.BehaviorSubject([new UrlSegment('', {})]);
var /** @type {?} */ emptyParams = new rxjs_BehaviorSubject.BehaviorSubject({});
var /** @type {?} */ emptyData = new rxjs_BehaviorSubject.BehaviorSubject({});
var /** @type {?} */ emptyQueryParams = new rxjs_BehaviorSubject.BehaviorSubject({});
var /** @type {?} */ fragment = new rxjs_BehaviorSubject.BehaviorSubject('');
var /** @type {?} */ activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
activated.snapshot = snapshot.root;
return new RouterState(new TreeNode(activated, []), snapshot);
}
/**
* @param {?} urlTree
* @param {?} rootComponent
* @return {?}
*/
function createEmptyStateSnapshot(urlTree, rootComponent) {
var /** @type {?} */ emptyParams = {};
var /** @type {?} */ emptyData = {};
var /** @type {?} */ emptyQueryParams = {};
var /** @type {?} */ fragment = '';
var /** @type {?} */ activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {});
return new RouterStateSnapshot('', new TreeNode(activated, []));
}
/**
* \@whatItDoes Contains the information about a route associated with a component loaded in an
* outlet.
* An `ActivatedRoute` can also be used to traverse the router state tree.
*
* \@howToUse
*
* ```
* \@Component({...})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: Observable<string> = route.params.map(p => p.id);
* const url: Observable<string> = route.url.map(segments => segments.join(''));
* // route.data includes both `data` and `resolve`
* const user = route.data.map(d => d.user);
* }
* }
* ```
*
* \@stable
*/
var ActivatedRoute = (function () {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} futureSnapshot
*/
function ActivatedRoute(url, params, queryParams, fragment, data, outlet, component, futureSnapshot) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this._futureSnapshot = futureSnapshot;
}
Object.defineProperty(ActivatedRoute.prototype, "routeConfig", {
/**
* The configuration used to match this route
* @return {?}
*/
get: function () { return this._futureSnapshot.routeConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "root", {
/**
* The root of the router state
* @return {?}
*/
get: function () { return this._routerState.root; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "parent", {
/**
* The parent of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.parent(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "firstChild", {
/**
* The first child of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.firstChild(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "children", {
/**
* The children of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.children(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "pathFromRoot", {
/**
* The path from the root of the router state tree to this route
* @return {?}
*/
get: function () { return this._routerState.pathFromRoot(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "paramMap", {
/**
* @return {?}
*/
get: function () {
if (!this._paramMap) {
this._paramMap = rxjs_operator_map.map.call(this.params, function (p) { return convertToParamMap(p); });
}
return this._paramMap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRoute.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap =
rxjs_operator_map.map.call(this.queryParams, function (p) { return convertToParamMap(p); });
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ActivatedRoute.prototype.toString = function () {
return this.snapshot ? this.snapshot.toString() : "Future(" + this._futureSnapshot + ")";
};
return ActivatedRoute;
}());
/**
* \@internal
* @param {?} route
* @return {?}
*/
function inheritedParamsDataResolve(route) {
var /** @type {?} */ pathToRoot = route.pathFromRoot;
var /** @type {?} */ inhertingStartingFrom = pathToRoot.length - 1;
while (inhertingStartingFrom >= 1) {
var /** @type {?} */ current = pathToRoot[inhertingStartingFrom];
var /** @type {?} */ parent = pathToRoot[inhertingStartingFrom - 1];
// current route is an empty path => inherits its parent's params and data
if (current.routeConfig && current.routeConfig.path === '') {
inhertingStartingFrom--;
// parent is componentless => current route should inherit its params and data
}
else if (!parent.component) {
inhertingStartingFrom--;
}
else {
break;
}
}
return pathToRoot.slice(inhertingStartingFrom).reduce(function (res, curr) {
var /** @type {?} */ params = Object.assign({}, res.params, curr.params);
var /** @type {?} */ data = Object.assign({}, res.data, curr.data);
var /** @type {?} */ resolve = Object.assign({}, res.resolve, curr._resolvedData);
return { params: params, data: data, resolve: resolve };
}, /** @type {?} */ ({ params: {}, data: {}, resolve: {} }));
}
/**
* \@whatItDoes Contains the information about a route associated with a component loaded in an
* outlet
* at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router
* state tree.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'./my-component.html'})
* class MyComponent {
* constructor(route: ActivatedRoute) {
* const id: string = route.snapshot.params.id;
* const url: string = route.snapshot.url.join('');
* const user = route.snapshot.data.user;
* }
* }
* ```
*
* \@stable
*/
var ActivatedRouteSnapshot = (function () {
/**
* \@internal
* @param {?} url
* @param {?} params
* @param {?} queryParams
* @param {?} fragment
* @param {?} data
* @param {?} outlet
* @param {?} component
* @param {?} routeConfig
* @param {?} urlSegment
* @param {?} lastPathIndex
* @param {?} resolve
*/
function ActivatedRouteSnapshot(url, params, queryParams, fragment, data, outlet, component, routeConfig, urlSegment, lastPathIndex, resolve) {
this.url = url;
this.params = params;
this.queryParams = queryParams;
this.fragment = fragment;
this.data = data;
this.outlet = outlet;
this.component = component;
this._routeConfig = routeConfig;
this._urlSegment = urlSegment;
this._lastPathIndex = lastPathIndex;
this._resolve = resolve;
}
Object.defineProperty(ActivatedRouteSnapshot.prototype, "routeConfig", {
/**
* The configuration used to match this route
* @return {?}
*/
get: function () { return this._routeConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "root", {
/**
* The root of the router state
* @return {?}
*/
get: function () { return this._routerState.root; },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "parent", {
/**
* The parent of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.parent(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "firstChild", {
/**
* The first child of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.firstChild(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "children", {
/**
* The children of this route in the router state tree
* @return {?}
*/
get: function () { return this._routerState.children(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "pathFromRoot", {
/**
* The path from the root of the router state tree to this route
* @return {?}
*/
get: function () { return this._routerState.pathFromRoot(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "paramMap", {
/**
* @return {?}
*/
get: function () {
if (!this._paramMap) {
this._paramMap = convertToParamMap(this.params);
}
return this._paramMap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActivatedRouteSnapshot.prototype, "queryParamMap", {
/**
* @return {?}
*/
get: function () {
if (!this._queryParamMap) {
this._queryParamMap = convertToParamMap(this.queryParams);
}
return this._queryParamMap;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
ActivatedRouteSnapshot.prototype.toString = function () {
var /** @type {?} */ url = this.url.map(function (segment) { return segment.toString(); }).join('/');
var /** @type {?} */ matched = this._routeConfig ? this._routeConfig.path : '';
return "Route(url:'" + url + "', path:'" + matched + "')";
};
return ActivatedRouteSnapshot;
}());
/**
* \@whatItDoes Represents the state of the router at a moment in time.
*
* \@howToUse
*
* ```
* \@Component({templateUrl:'template.html'})
* class MyComponent {
* constructor(router: Router) {
* const state: RouterState = router.routerState;
* const snapshot: RouterStateSnapshot = state.snapshot;
* const root: ActivatedRouteSnapshot = snapshot.root;
* const child = root.firstChild;
* const id: Observable<string> = child.params.map(p => p.id);
* //...
* }
* }
* ```
*
* \@description
* RouterStateSnapshot is a tree of activated route snapshots. Every node in this tree knows about
* the "consumed" URL segments, the extracted parameters, and the resolved data.
*
* \@stable
*/
var RouterStateSnapshot = (function (_super) {
__extends(RouterStateSnapshot, _super);
/**
* \@internal
* @param {?} url
* @param {?} root
*/
function RouterStateSnapshot(url, root) {
var _this = _super.call(this, root) || this;
_this.url = url;
setRouterState(_this, root);
return _this;
}
/**
* @return {?}
*/
RouterStateSnapshot.prototype.toString = function () { return serializeNode(this._root); };
return RouterStateSnapshot;
}(Tree));
/**
* @template U, T
* @param {?} state
* @param {?} node
* @return {?}
*/
function setRouterState(state, node) {
node.value._routerState = state;
node.children.forEach(function (c) { return setRouterState(state, c); });
}
/**
* @param {?} node
* @return {?}
*/
function serializeNode(node) {
var /** @type {?} */ c = node.children.length > 0 ? " { " + node.children.map(serializeNode).join(", ") + " } " : '';
return "" + node.value + c;
}
/**
* The expectation is that the activate route is created with the right set of parameters.
* So we push new values into the observables only when they are not the initial values.
* And we detect that by checking if the snapshot field is set.
* @param {?} route
* @return {?}
*/
function advanceActivatedRoute(route) {
if (route.snapshot) {
var /** @type {?} */ currentSnapshot = route.snapshot;
var /** @type {?} */ nextSnapshot = route._futureSnapshot;
route.snapshot = nextSnapshot;
if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
((route.queryParams)).next(nextSnapshot.queryParams);
}
if (currentSnapshot.fragment !== nextSnapshot.fragment) {
((route.fragment)).next(nextSnapshot.fragment);
}
if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
((route.params)).next(nextSnapshot.params);
}
if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
((route.url)).next(nextSnapshot.url);
}
if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
((route.data)).next(nextSnapshot.data);
}
}
else {
route.snapshot = route._futureSnapshot;
// this is for resolved data
((route.data)).next(route._futureSnapshot.data);
}
}
/**
* @param {?} a
* @param {?} b
* @return {?}
*/
function equalParamsAndUrlSegments(a, b) {
var /** @type {?} */ equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
var /** @type {?} */ parentsMismatch = !a.parent !== !b.parent;
return equalUrlParams && !parentsMismatch &&
(!a.parent || equalParamsAndUrlSegments(a.parent, /** @type {?} */ ((b.parent))));
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createRouterState(routeReuseStrategy, curr, prevState) {
var /** @type {?} */ root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
return new RouterState(root, curr);
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?=} prevState
* @return {?}
*/
function createNode(routeReuseStrategy, curr, prevState) {
// reuse an activated route that is currently displayed on the screen
if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
var /** @type {?} */ value = prevState.value;
value._futureSnapshot = curr.value;
var /** @type {?} */ children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
return new TreeNode(value, children);
// retrieve an activated route that is used to be displayed, but is not currently displayed
}
else if (routeReuseStrategy.retrieve(curr.value)) {
var /** @type {?} */ tree_1 = ((routeReuseStrategy.retrieve(curr.value))).route;
setFutureSnapshotsOfActivatedRoutes(curr, tree_1);
return tree_1;
}
else {
var /** @type {?} */ value = createActivatedRoute(curr.value);
var /** @type {?} */ children = curr.children.map(function (c) { return createNode(routeReuseStrategy, c); });
return new TreeNode(value, children);
}
}
/**
* @param {?} curr
* @param {?} result
* @return {?}
*/
function setFutureSnapshotsOfActivatedRoutes(curr, result) {
if (curr.value.routeConfig !== result.value.routeConfig) {
throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route');
}
if (curr.children.length !== result.children.length) {
throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children');
}
result.value._futureSnapshot = curr.value;
for (var /** @type {?} */ i = 0; i < curr.children.length; ++i) {
setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]);
}
}
/**
* @param {?} routeReuseStrategy
* @param {?} curr
* @param {?} prevState
* @return {?}
*/
function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
return curr.children.map(function (child) {
for (var _i = 0, _a = prevState.children; _i < _a.length; _i++) {
var p = _a[_i];
if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) {
return createNode(routeReuseStrategy, child, p);
}
}
return createNode(routeReuseStrategy, child);
});
}
/**
* @param {?} c
* @return {?}
*/
function createActivatedRoute(c) {
return new ActivatedRoute(new rxjs_BehaviorSubject.BehaviorSubject(c.url), new rxjs_BehaviorSubject.BehaviorSubject(c.params), new rxjs_BehaviorSubject.BehaviorSubject(c.queryParams), new rxjs_BehaviorSubject.BehaviorSubject(c.fragment), new rxjs_BehaviorSubject.BehaviorSubject(c.data), c.outlet, c.component, c);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} route
* @param {?} urlTree
* @param {?} commands
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function createUrlTree(route, urlTree, commands, queryParams, fragment) {
if (commands.length === 0) {
return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment);
}
var /** @type {?} */ nav = computeNavigation(commands);
if (nav.toRoot()) {
return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment);
}
var /** @type {?} */ startingPosition = findStartingPosition(nav, urlTree, route);
var /** @type {?} */ segmentGroup = startingPosition.processChildren ?
updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) :
updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands);
return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment);
}
/**
* @param {?} command
* @return {?}
*/
function isMatrixParams(command) {
return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
}
/**
* @param {?} oldSegmentGroup
* @param {?} newSegmentGroup
* @param {?} urlTree
* @param {?} queryParams
* @param {?} fragment
* @return {?}
*/
function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) {
var /** @type {?} */ qp = {};
if (queryParams) {
forEach(queryParams, function (value, name) {
qp[name] = Array.isArray(value) ? value.map(function (v) { return "" + v; }) : "" + value;
});
}
if (urlTree.root === oldSegmentGroup) {
return new UrlTree(newSegmentGroup, qp, fragment);
}
return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment);
}
/**
* @param {?} current
* @param {?} oldSegment
* @param {?} newSegment
* @return {?}
*/
function replaceSegment(current, oldSegment, newSegment) {
var /** @type {?} */ children = {};
forEach(current.children, function (c, outletName) {
if (c === oldSegment) {
children[outletName] = newSegment;
}
else {
children[outletName] = replaceSegment(c, oldSegment, newSegment);
}
});
return new UrlSegmentGroup(current.segments, children);
}
var Navigation = (function () {
/**
* @param {?} isAbsolute
* @param {?} numberOfDoubleDots
* @param {?} commands
*/
function Navigation(isAbsolute, numberOfDoubleDots, commands) {
this.isAbsolute = isAbsolute;
this.numberOfDoubleDots = numberOfDoubleDots;
this.commands = commands;
if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
throw new Error('Root segment cannot have matrix parameters');
}
var cmdWithOutlet = commands.find(function (c) { return typeof c === 'object' && c != null && c.outlets; });
if (cmdWithOutlet && cmdWithOutlet !== last$1(commands)) {
throw new Error('{outlets:{}} has to be the last command');
}
}
/**
* @return {?}
*/
Navigation.prototype.toRoot = function () {
return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
};
return Navigation;
}());
/**
* Transforms commands to a normalized `Navigation`
* @param {?} commands
* @return {?}
*/
function computeNavigation(commands) {
if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
return new Navigation(true, 0, commands);
}
var /** @type {?} */ numberOfDoubleDots = 0;
var /** @type {?} */ isAbsolute = false;
var /** @type {?} */ res = commands.reduce(function (res, cmd, cmdIdx) {
if (typeof cmd === 'object' && cmd != null) {
if (cmd.outlets) {
var /** @type {?} */ outlets_1 = {};
forEach(cmd.outlets, function (commands, name) {
outlets_1[name] = typeof commands === 'string' ? commands.split('/') : commands;
});
return res.concat([{ outlets: outlets_1 }]);
}
if (cmd.segmentPath) {
return res.concat([cmd.segmentPath]);
}
}
if (!(typeof cmd === 'string')) {
return res.concat([cmd]);
}
if (cmdIdx === 0) {
cmd.split('/').forEach(function (urlPart, partIndex) {
if (partIndex == 0 && urlPart === '.') {
// skip './a'
}
else if (partIndex == 0 && urlPart === '') {
isAbsolute = true;
}
else if (urlPart === '..') {
numberOfDoubleDots++;
}
else if (urlPart != '') {
res.push(urlPart);
}
});
return res;
}
return res.concat([cmd]);
}, []);
return new Navigation(isAbsolute, numberOfDoubleDots, res);
}
var Position = (function () {
/**
* @param {?} segmentGroup
* @param {?} processChildren
* @param {?} index
*/
function Position(segmentGroup, processChildren, index) {
this.segmentGroup = segmentGroup;
this.processChildren = processChildren;
this.index = index;
}
return Position;
}());
/**
* @param {?} nav
* @param {?} tree
* @param {?} route
* @return {?}
*/
function findStartingPosition(nav, tree, route) {
if (nav.isAbsolute) {
return new Position(tree.root, true, 0);
}
if (route.snapshot._lastPathIndex === -1) {
return new Position(route.snapshot._urlSegment, true, 0);
}
var /** @type {?} */ modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
var /** @type {?} */ index = route.snapshot._lastPathIndex + modifier;
return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots);
}
/**
* @param {?} group
* @param {?} index
* @param {?} numberOfDoubleDots
* @return {?}
*/
function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
var /** @type {?} */ g = group;
var /** @type {?} */ ci = index;
var /** @type {?} */ dd = numberOfDoubleDots;
while (dd > ci) {
dd -= ci;
g = ((g.parent));
if (!g) {
throw new Error('Invalid number of \'../\'');
}
ci = g.segments.length;
}
return new Position(g, false, ci - dd);
}
/**
* @param {?} command
* @return {?}
*/
function getPath(command) {
if (typeof command === 'object' && command != null && command.outlets) {
return command.outlets[PRIMARY_OUTLET];
}
return "" + command;
}
/**
* @param {?} commands
* @return {?}
*/
function getOutlets(commands) {
if (!(typeof commands[0] === 'object'))
return _a = {}, _a[PRIMARY_OUTLET] = commands, _a;
if (commands[0].outlets === undefined)
return _b = {}, _b[PRIMARY_OUTLET] = commands, _b;
return commands[0].outlets;
var _a, _b;
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroup(segmentGroup, startIndex, commands) {
if (!segmentGroup) {
segmentGroup = new UrlSegmentGroup([], {});
}
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
}
var /** @type {?} */ m = prefixedWith(segmentGroup, startIndex, commands);
var /** @type {?} */ slicedCommands = commands.slice(m.commandIndex);
if (m.match && m.pathIndex < segmentGroup.segments.length) {
var /** @type {?} */ g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
g.children[PRIMARY_OUTLET] =
new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
return updateSegmentGroupChildren(g, 0, slicedCommands);
}
else if (m.match && slicedCommands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else if (m.match && !segmentGroup.hasChildren()) {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
else if (m.match) {
return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
}
else {
return createNewSegmentGroup(segmentGroup, startIndex, commands);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
if (commands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
}
else {
var /** @type {?} */ outlets_2 = getOutlets(commands);
var /** @type {?} */ children_2 = {};
forEach(outlets_2, function (commands, outlet) {
if (commands !== null) {
children_2[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
}
});
forEach(segmentGroup.children, function (child, childOutlet) {
if (outlets_2[childOutlet] === undefined) {
children_2[childOutlet] = child;
}
});
return new UrlSegmentGroup(segmentGroup.segments, children_2);
}
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function prefixedWith(segmentGroup, startIndex, commands) {
var /** @type {?} */ currentCommandIndex = 0;
var /** @type {?} */ currentPathIndex = startIndex;
var /** @type {?} */ noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
while (currentPathIndex < segmentGroup.segments.length) {
if (currentCommandIndex >= commands.length)
return noMatch;
var /** @type {?} */ path = segmentGroup.segments[currentPathIndex];
var /** @type {?} */ curr = getPath(commands[currentCommandIndex]);
var /** @type {?} */ next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
if (currentPathIndex > 0 && curr === undefined)
break;
if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
if (!compare(curr, next, path))
return noMatch;
currentCommandIndex += 2;
}
else {
if (!compare(curr, {}, path))
return noMatch;
currentCommandIndex++;
}
currentPathIndex++;
}
return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
}
/**
* @param {?} segmentGroup
* @param {?} startIndex
* @param {?} commands
* @return {?}
*/
function createNewSegmentGroup(segmentGroup, startIndex, commands) {
var /** @type {?} */ paths = segmentGroup.segments.slice(0, startIndex);
var /** @type {?} */ i = 0;
while (i < commands.length) {
if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) {
var /** @type {?} */ children = createNewSegmentChildren(commands[i].outlets);
return new UrlSegmentGroup(paths, children);
}
// if we start with an object literal, we need to reuse the path part from the segment
if (i === 0 && isMatrixParams(commands[0])) {
var /** @type {?} */ p = segmentGroup.segments[startIndex];
paths.push(new UrlSegment(p.path, commands[0]));
i++;
continue;
}
var /** @type {?} */ curr = getPath(commands[i]);
var /** @type {?} */ next = (i < commands.length - 1) ? commands[i + 1] : null;
if (curr && next && isMatrixParams(next)) {
paths.push(new UrlSegment(curr, stringify(next)));
i += 2;
}
else {
paths.push(new UrlSegment(curr, {}));
i++;
}
}
return new UrlSegmentGroup(paths, {});
}
/**
* @param {?} outlets
* @return {?}
*/
function createNewSegmentChildren(outlets) {
var /** @type {?} */ children = {};
forEach(outlets, function (commands, outlet) {
if (commands !== null) {
children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
}
});
return children;
}
/**
* @param {?} params
* @return {?}
*/
function stringify(params) {
var /** @type {?} */ res = {};
forEach(params, function (v, k) { return res[k] = "" + v; });
return res;
}
/**
* @param {?} path
* @param {?} params
* @param {?} segment
* @return {?}
*/
function compare(path, params, segment) {
return path == segment.path && shallowEqual(params, segment.parameters);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var NoMatch$1 = (function () {
function NoMatch$1() {
}
return NoMatch$1;
}());
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
* @return {?}
*/
function recognize(rootComponentType, config, urlTree, url) {
return new Recognizer(rootComponentType, config, urlTree, url).recognize();
}
var Recognizer = (function () {
/**
* @param {?} rootComponentType
* @param {?} config
* @param {?} urlTree
* @param {?} url
*/
function Recognizer(rootComponentType, config, urlTree, url) {
this.rootComponentType = rootComponentType;
this.config = config;
this.urlTree = urlTree;
this.url = url;
}
/**
* @return {?}
*/
Recognizer.prototype.recognize = function () {
try {
var /** @type {?} */ rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config).segmentGroup;
var /** @type {?} */ children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
var /** @type {?} */ root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
var /** @type {?} */ rootNode = new TreeNode(root, children);
var /** @type {?} */ routeState = new RouterStateSnapshot(this.url, rootNode);
this.inheritParamsAndData(routeState._root);
return rxjs_observable_of.of(routeState);
}
catch (e) {
return new rxjs_Observable.Observable(function (obs) { return obs.error(e); });
}
};
/**
* @param {?} routeNode
* @return {?}
*/
Recognizer.prototype.inheritParamsAndData = function (routeNode) {
var _this = this;
var /** @type {?} */ route = routeNode.value;
var /** @type {?} */ i = inheritedParamsDataResolve(route);
route.params = Object.freeze(i.params);
route.data = Object.freeze(i.data);
routeNode.children.forEach(function (n) { return _this.inheritParamsAndData(n); });
};
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegmentGroup = function (config, segmentGroup, outlet) {
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return this.processChildren(config, segmentGroup);
}
return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet);
};
/**
* @param {?} config
* @param {?} segmentGroup
* @return {?}
*/
Recognizer.prototype.processChildren = function (config, segmentGroup) {
var _this = this;
var /** @type {?} */ children = mapChildrenIntoArray(segmentGroup, function (child, childOutlet) { return _this.processSegmentGroup(config, child, childOutlet); });
checkOutletNameUniqueness(children);
sortActivatedRouteSnapshots(children);
return children;
};
/**
* @param {?} config
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegment = function (config, segmentGroup, segments, outlet) {
for (var _i = 0, config_1 = config; _i < config_1.length; _i++) {
var r = config_1[_i];
try {
return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet);
}
catch (e) {
if (!(e instanceof NoMatch$1))
throw e;
}
}
if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
return [];
}
throw new NoMatch$1();
};
/**
* @param {?} segmentGroup
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
return segments.length === 0 && !segmentGroup.children[outlet];
};
/**
* @param {?} route
* @param {?} rawSegment
* @param {?} segments
* @param {?} outlet
* @return {?}
*/
Recognizer.prototype.processSegmentAgainstRoute = function (route, rawSegment, segments, outlet) {
if (route.redirectTo)
throw new NoMatch$1();
if ((route.outlet || PRIMARY_OUTLET) !== outlet)
throw new NoMatch$1();
if (route.path === '**') {
var /** @type {?} */ params = segments.length > 0 ? ((last$1(segments))).parameters : {};
var /** @type {?} */ snapshot_1 = new ActivatedRouteSnapshot(segments, params, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route));
return [new TreeNode(snapshot_1, [])];
}
var _a = match$1(rawSegment, route, segments), consumedSegments = _a.consumedSegments, parameters = _a.parameters, lastChild = _a.lastChild;
var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild);
var /** @type {?} */ childConfig = getChildConfig(route);
var _b = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _b.segmentGroup, slicedSegments = _b.slicedSegments;
var /** @type {?} */ snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route));
if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
var /** @type {?} */ children_3 = this.processChildren(childConfig, segmentGroup);
return [new TreeNode(snapshot, children_3)];
}
if (childConfig.length === 0 && slicedSegments.length === 0) {
return [new TreeNode(snapshot, [])];
}
var /** @type {?} */ children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET);
return [new TreeNode(snapshot, children)];
};
return Recognizer;
}());
/**
* @param {?} nodes
* @return {?}
*/
function sortActivatedRouteSnapshots(nodes) {
nodes.sort(function (a, b) {
if (a.value.outlet === PRIMARY_OUTLET)
return -1;
if (b.value.outlet === PRIMARY_OUTLET)
return 1;
return a.value.outlet.localeCompare(b.value.outlet);
});
}
/**
* @param {?} route
* @return {?}
*/
function getChildConfig(route) {
if (route.children) {
return route.children;
}
if (route.loadChildren) {
return ((route._loadedConfig)).routes;
}
return [];
}
/**
* @param {?} segmentGroup
* @param {?} route
* @param {?} segments
* @return {?}
*/
function match$1(segmentGroup, route, segments) {
if (route.path === '') {
if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
throw new NoMatch$1();
}
return { consumedSegments: [], lastChild: 0, parameters: {} };
}
var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher;
var /** @type {?} */ res = matcher(segments, segmentGroup, route);
if (!res)
throw new NoMatch$1();
var /** @type {?} */ posParams = {};
forEach(/** @type {?} */ ((res.posParams)), function (v, k) { posParams[k] = v.path; });
var /** @type {?} */ parameters = Object.assign({}, posParams, res.consumed[res.consumed.length - 1].parameters);
return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters: parameters };
}
/**
* @param {?} nodes
* @return {?}
*/
function checkOutletNameUniqueness(nodes) {
var /** @type {?} */ names = {};
nodes.forEach(function (n) {
var /** @type {?} */ routeWithSameOutletName = names[n.value.outlet];
if (routeWithSameOutletName) {
var /** @type {?} */ p = routeWithSameOutletName.url.map(function (s) { return s.toString(); }).join('/');
var /** @type {?} */ c = n.value.url.map(function (s) { return s.toString(); }).join('/');
throw new Error("Two segments cannot have the same outlet name: '" + p + "' and '" + c + "'.");
}
names[n.value.outlet] = n.value;
});
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getSourceSegmentGroup(segmentGroup) {
var /** @type {?} */ s = segmentGroup;
while (s._sourceSegment) {
s = s._sourceSegment;
}
return s;
}
/**
* @param {?} segmentGroup
* @return {?}
*/
function getPathIndexShift(segmentGroup) {
var /** @type {?} */ s = segmentGroup;
var /** @type {?} */ res = (s._segmentIndexShift ? s._segmentIndexShift : 0);
while (s._sourceSegment) {
s = s._sourceSegment;
res += (s._segmentIndexShift ? s._segmentIndexShift : 0);
}
return res - 1;
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} slicedSegments
* @param {?} config
* @return {?}
*/
function split$1(segmentGroup, consumedSegments, slicedSegments, config) {
if (slicedSegments.length > 0 &&
containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s_1 = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
s_1._sourceSegment = segmentGroup;
s_1._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s_1, slicedSegments: [] };
}
if (slicedSegments.length === 0 &&
containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
var /** @type {?} */ s_2 = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
s_2._sourceSegment = segmentGroup;
s_2._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s_2, slicedSegments: slicedSegments };
}
var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
return { segmentGroup: s, slicedSegments: slicedSegments };
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @param {?} children
* @return {?}
*/
function addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
var /** @type {?} */ res = {};
for (var _i = 0, routes_3 = routes; _i < routes_3.length; _i++) {
var r = routes_3[_i];
if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) {
var /** @type {?} */ s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
s._segmentIndexShift = segmentGroup.segments.length;
res[getOutlet$1(r)] = s;
}
}
return Object.assign({}, children, res);
}
/**
* @param {?} segmentGroup
* @param {?} consumedSegments
* @param {?} routes
* @param {?} primarySegment
* @return {?}
*/
function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) {
var /** @type {?} */ res = {};
res[PRIMARY_OUTLET] = primarySegment;
primarySegment._sourceSegment = segmentGroup;
primarySegment._segmentIndexShift = consumedSegments.length;
for (var _i = 0, routes_4 = routes; _i < routes_4.length; _i++) {
var r = routes_4[_i];
if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) {
var /** @type {?} */ s = new UrlSegmentGroup([], {});
s._sourceSegment = segmentGroup;
s._segmentIndexShift = consumedSegments.length;
res[getOutlet$1(r)] = s;
}
}
return res;
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET; });
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} routes
* @return {?}
*/
function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r); });
}
/**
* @param {?} segmentGroup
* @param {?} slicedSegments
* @param {?} r
* @return {?}
*/
function emptyPathMatch(segmentGroup, slicedSegments, r) {
if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
return false;
}
return r.path === '' && r.redirectTo === undefined;
}
/**
* @param {?} route
* @return {?}
*/
function getOutlet$1(route) {
return route.outlet || PRIMARY_OUTLET;
}
/**
* @param {?} route
* @return {?}
*/
function getData(route) {
return route.data || {};
}
/**
* @param {?} route
* @return {?}
*/
function getResolve(route) {
return route.resolve || {};
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Provides a way to customize when activated routes get reused.
*
* \@experimental
* @abstract
*/
var RouteReuseStrategy = (function () {
function RouteReuseStrategy() {
}
/**
* Determines if this route (and its subtree) should be detached to be reused later
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.shouldDetach = function (route) { };
/**
* Stores the detached route.
*
* Storing a `null` value should erase the previously stored value.
* @abstract
* @param {?} route
* @param {?} handle
* @return {?}
*/
RouteReuseStrategy.prototype.store = function (route, handle) { };
/**
* Determines if this route (and its subtree) should be reattached
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.shouldAttach = function (route) { };
/**
* Retrieves the previously stored route
* @abstract
* @param {?} route
* @return {?}
*/
RouteReuseStrategy.prototype.retrieve = function (route) { };
/**
* Determines if a route should be reused
* @abstract
* @param {?} future
* @param {?} curr
* @return {?}
*/
RouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) { };
return RouteReuseStrategy;
}());
/**
* Does not detach any subtrees. Reuses routes as long as their route config is the same.
*/
var DefaultRouteReuseStrategy = (function () {
function DefaultRouteReuseStrategy() {
}
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldDetach = function (route) { return false; };
/**
* @param {?} route
* @param {?} detachedTree
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.store = function (route, detachedTree) { };
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldAttach = function (route) { return false; };
/**
* @param {?} route
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.retrieve = function (route) { return null; };
/**
* @param {?} future
* @param {?} curr
* @return {?}
*/
DefaultRouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) {
return future.routeConfig === curr.routeConfig;
};
return DefaultRouteReuseStrategy;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@docsNotRequired
* \@experimental
*/
var ROUTES = new _angular_core.InjectionToken('ROUTES');
var RouterConfigLoader = (function () {
/**
* @param {?} loader
* @param {?} compiler
* @param {?=} onLoadStartListener
* @param {?=} onLoadEndListener
*/
function RouterConfigLoader(loader, compiler, onLoadStartListener, onLoadEndListener) {
this.loader = loader;
this.compiler = compiler;
this.onLoadStartListener = onLoadStartListener;
this.onLoadEndListener = onLoadEndListener;
}
/**
* @param {?} parentInjector
* @param {?} route
* @return {?}
*/
RouterConfigLoader.prototype.load = function (parentInjector, route) {
var _this = this;
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
var /** @type {?} */ moduleFactory$ = this.loadModuleFactory(/** @type {?} */ ((route.loadChildren)));
return rxjs_operator_map.map.call(moduleFactory$, function (factory) {
if (_this.onLoadEndListener) {
_this.onLoadEndListener(route);
}
var /** @type {?} */ module = factory.create(parentInjector);
return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)), module);
});
};
/**
* @param {?} loadChildren
* @return {?}
*/
RouterConfigLoader.prototype.loadModuleFactory = function (loadChildren) {
var _this = this;
if (typeof loadChildren === 'string') {
return rxjs_observable_fromPromise.fromPromise(this.loader.load(loadChildren));
}
else {
return rxjs_operator_mergeMap.mergeMap.call(wrapIntoObservable(loadChildren()), function (t) {
if (t instanceof _angular_core.NgModuleFactory) {
return rxjs_observable_of.of(t);
}
else {
return rxjs_observable_fromPromise.fromPromise(_this.compiler.compileModuleAsync(t));
}
});
}
};
return RouterConfigLoader;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Provides a way to migrate AngularJS applications to Angular.
*
* \@experimental
* @abstract
*/
var UrlHandlingStrategy = (function () {
function UrlHandlingStrategy() {
}
/**
* Tells the router if this URL should be processed.
*
* When it returns true, the router will execute the regular navigation.
* When it returns false, the router will set the router state to an empty state.
* As a result, all the active components will be destroyed.
*
* @abstract
* @param {?} url
* @return {?}
*/
UrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { };
/**
* Extracts the part of the URL that should be handled by the router.
* The rest of the URL will remain untouched.
* @abstract
* @param {?} url
* @return {?}
*/
UrlHandlingStrategy.prototype.extract = function (url) { };
/**
* Merges the URL fragment with the rest of the URL.
* @abstract
* @param {?} newUrlPart
* @param {?} rawUrl
* @return {?}
*/
UrlHandlingStrategy.prototype.merge = function (newUrlPart, rawUrl) { };
return UrlHandlingStrategy;
}());
/**
* \@experimental
*/
var DefaultUrlHandlingStrategy = (function () {
function DefaultUrlHandlingStrategy() {
}
/**
* @param {?} url
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { return true; };
/**
* @param {?} url
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.extract = function (url) { return url; };
/**
* @param {?} newUrlPart
* @param {?} wholeUrl
* @return {?}
*/
DefaultUrlHandlingStrategy.prototype.merge = function (newUrlPart, wholeUrl) { return newUrlPart; };
return DefaultUrlHandlingStrategy;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} error
* @return {?}
*/
function defaultErrorHandler(error) {
throw error;
}
/**
* \@internal
* @param {?} snapshot
* @return {?}
*/
function defaultRouterHook(snapshot) {
return (rxjs_observable_of.of(null));
}
/**
* \@whatItDoes Provides the navigation and url manipulation capabilities.
*
* See {\@link Routes} for more details and examples.
*
* \@ngModule RouterModule
*
* \@stable
*/
var Router = (function () {
/**
* @param {?} rootComponentType
* @param {?} urlSerializer
* @param {?} rootContexts
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
*/
function Router(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) {
var _this = this;
this.rootComponentType = rootComponentType;
this.urlSerializer = urlSerializer;
this.rootContexts = rootContexts;
this.location = location;
this.config = config;
this.navigations = new rxjs_BehaviorSubject.BehaviorSubject(/** @type {?} */ ((null)));
this.routerEvents = new rxjs_Subject.Subject();
this.navigationId = 0;
/**
* Error handler that is invoked when a navigation errors.
*
* See {\@link ErrorHandler} for more information.
*/
this.errorHandler = defaultErrorHandler;
/**
* Indicates if at least one navigation happened.
*/
this.navigated = false;
/**
* Used by RouterModule. This allows us to
* pause the navigation either before preactivation or after it.
* \@internal
*/
this.hooks = {
beforePreactivation: defaultRouterHook,
afterPreactivation: defaultRouterHook
};
/**
* Extracts and merges URLs. Used for AngularJS to Angular migrations.
*/
this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
this.routeReuseStrategy = new DefaultRouteReuseStrategy();
var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); };
var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); };
this.ngModule = injector.get(_angular_core.NgModuleRef);
this.resetConfig(config);
this.currentUrlTree = createEmptyUrlTree();
this.rawUrlTree = this.currentUrlTree;
this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType);
this.processNavigations();
}
/**
* \@internal
* TODO: this should be removed once the constructor of the router made internal
* @param {?} rootComponentType
* @return {?}
*/
Router.prototype.resetRootComponentType = function (rootComponentType) {
this.rootComponentType = rootComponentType;
// TODO: vsavkin router 4.0 should make the root component set to null
// this will simplify the lifecycle of the router.
this.currentRouterState.root.component = this.rootComponentType;
};
/**
* Sets up the location change listener and performs the initial navigation.
* @return {?}
*/
Router.prototype.initialNavigation = function () {
this.setUpLocationChangeListener();
if (this.navigationId === 0) {
this.navigateByUrl(this.location.path(true), { replaceUrl: true });
}
};
/**
* Sets up the location change listener.
* @return {?}
*/
Router.prototype.setUpLocationChangeListener = function () {
var _this = this;
// Zone.current.wrap is needed because of the issue with RxJS scheduler,
// which does not work properly with zone.js in IE and Safari
if (!this.locationSubscription) {
this.locationSubscription = (this.location.subscribe(Zone.current.wrap(function (change) {
var /** @type {?} */ rawUrlTree = _this.urlSerializer.parse(change['url']);
var /** @type {?} */ source = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
setTimeout(function () { _this.scheduleNavigation(rawUrlTree, source, { replaceUrl: true }); }, 0);
})));
}
};
Object.defineProperty(Router.prototype, "routerState", {
/**
* The current route state
* @return {?}
*/
get: function () { return this.currentRouterState; },
enumerable: true,
configurable: true
});
Object.defineProperty(Router.prototype, "url", {
/**
* The current url
* @return {?}
*/
get: function () { return this.serializeUrl(this.currentUrlTree); },
enumerable: true,
configurable: true
});
Object.defineProperty(Router.prototype, "events", {
/**
* An observable of router events
* @return {?}
*/
get: function () { return this.routerEvents; },
enumerable: true,
configurable: true
});
/**
* \@internal
* @param {?} e
* @return {?}
*/
Router.prototype.triggerEvent = function (e) { this.routerEvents.next(e); };
/**
* Resets the configuration used for navigation and generating links.
*
* ### Usage
*
* ```
* router.resetConfig([
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ]}
* ]);
* ```
* @param {?} config
* @return {?}
*/
Router.prototype.resetConfig = function (config) {
validateConfig(config);
this.config = config;
};
/**
* \@docsNotRequired
* @return {?}
*/
Router.prototype.ngOnDestroy = function () { this.dispose(); };
/**
* Disposes of the router
* @return {?}
*/
Router.prototype.dispose = function () {
if (this.locationSubscription) {
this.locationSubscription.unsubscribe();
this.locationSubscription = ((null));
}
};
/**
* Applies an array of commands to the current url tree and creates a new url tree.
*
* When given an activate route, applies the given commands starting from the route.
* When not given a route, applies the given command starting from the root.
*
* ### Usage
*
* ```
* // create /team/33/user/11
* router.createUrlTree(['/team', 33, 'user', 11]);
*
* // create /team/33;expand=true/user/11
* router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
*
* // you can collapse static segments like this (this works only with the first passed-in value):
* router.createUrlTree(['/team/33/user', userId]);
*
* // If the first segment can contain slashes, and you do not want the router to split it, you
* // can do the following:
*
* router.createUrlTree([{segmentPath: '/one/two'}]);
*
* // create /team/33/(user/11//right:chat)
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
*
* // remove the right secondary node
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
*
* // assuming the current url is `/team/33/user/11` and the route points to `user/11`
*
* // navigate to /team/33/user/11/details
* router.createUrlTree(['details'], {relativeTo: route});
*
* // navigate to /team/33/user/22
* router.createUrlTree(['../22'], {relativeTo: route});
*
* // navigate to /team/44/user/22
* router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
* ```
* @param {?} commands
* @param {?=} navigationExtras
* @return {?}
*/
Router.prototype.createUrlTree = function (commands, navigationExtras) {
if (navigationExtras === void 0) { navigationExtras = {}; }
var relativeTo = navigationExtras.relativeTo, queryParams = navigationExtras.queryParams, fragment = navigationExtras.fragment, preserveQueryParams = navigationExtras.preserveQueryParams, queryParamsHandling = navigationExtras.queryParamsHandling, preserveFragment = navigationExtras.preserveFragment;
if (_angular_core.isDevMode() && preserveQueryParams && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
var /** @type {?} */ a = relativeTo || this.routerState.root;
var /** @type {?} */ f = preserveFragment ? this.currentUrlTree.fragment : fragment;
var /** @type {?} */ q = null;
if (queryParamsHandling) {
switch (queryParamsHandling) {
case 'merge':
q = Object.assign({}, this.currentUrlTree.queryParams, queryParams);
break;
case 'preserve':
q = this.currentUrlTree.queryParams;
break;
default:
q = queryParams || null;
}
}
else {
q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null;
}
return createUrlTree(a, this.currentUrlTree, commands, /** @type {?} */ ((q)), /** @type {?} */ ((f)));
};
/**
* Navigate based on the provided url. This navigation is always absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigateByUrl("/team/33/user/11");
*
* // Navigate without updating the URL
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ```
*
* In opposite to `navigate`, `navigateByUrl` takes a whole URL
* and does not apply any delta to the current one.
* @param {?} url
* @param {?=} extras
* @return {?}
*/
Router.prototype.navigateByUrl = function (url, extras) {
if (extras === void 0) { extras = { skipLocationChange: false }; }
var /** @type {?} */ urlTree = url instanceof UrlTree ? url : this.parseUrl(url);
var /** @type {?} */ mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
return this.scheduleNavigation(mergedTree, 'imperative', extras);
};
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
* @param {?} commands
* @param {?=} extras
* @return {?}
*/
Router.prototype.navigate = function (commands, extras) {
if (extras === void 0) { extras = { skipLocationChange: false }; }
validateCommands(commands);
if (typeof extras.queryParams === 'object' && extras.queryParams !== null) {
extras.queryParams = this.removeEmptyProps(extras.queryParams);
}
return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
};
/**
* Serializes a {\@link UrlTree} into a string
* @param {?} url
* @return {?}
*/
Router.prototype.serializeUrl = function (url) { return this.urlSerializer.serialize(url); };
/**
* Parses a string into a {\@link UrlTree}
* @param {?} url
* @return {?}
*/
Router.prototype.parseUrl = function (url) { return this.urlSerializer.parse(url); };
/**
* Returns whether the url is activated
* @param {?} url
* @param {?} exact
* @return {?}
*/
Router.prototype.isActive = function (url, exact) {
if (url instanceof UrlTree) {
return containsTree(this.currentUrlTree, url, exact);
}
var /** @type {?} */ urlTree = this.urlSerializer.parse(url);
return containsTree(this.currentUrlTree, urlTree, exact);
};
/**
* @param {?} params
* @return {?}
*/
Router.prototype.removeEmptyProps = function (params) {
return Object.keys(params).reduce(function (result, key) {
var /** @type {?} */ value = params[key];
if (value !== null && value !== undefined) {
result[key] = value;
}
return result;
}, {});
};
/**
* @return {?}
*/
Router.prototype.processNavigations = function () {
var _this = this;
rxjs_operator_concatMap.concatMap
.call(this.navigations, function (nav) {
if (nav) {
_this.executeScheduledNavigation(nav);
// a failed navigation should not stop the router from processing
// further navigations => the catch
return nav.promise.catch(function () { });
}
else {
return (rxjs_observable_of.of(null));
}
})
.subscribe(function () { });
};
/**
* @param {?} rawUrl
* @param {?} source
* @param {?} extras
* @return {?}
*/
Router.prototype.scheduleNavigation = function (rawUrl, source, extras) {
var /** @type {?} */ lastNavigation = this.navigations.value;
// If the user triggers a navigation imperatively (e.g., by using navigateByUrl),
// and that navigation results in 'replaceState' that leads to the same URL,
// we should skip those.
if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
// Because of a bug in IE and Edge, the location class fires two events (popstate and
// hashchange) every single time. The second one should be ignored. Otherwise, the URL will
// flicker.
if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
lastNavigation.rawUrl.toString() === rawUrl.toString()) {
return Promise.resolve(true); // return value is not used
}
var /** @type {?} */ resolve = null;
var /** @type {?} */ reject = null;
var /** @type {?} */ promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
var /** @type {?} */ id = ++this.navigationId;
this.navigations.next({ id: id, source: source, rawUrl: rawUrl, extras: extras, resolve: resolve, reject: reject, promise: promise });
// Make sure that the error is propagated even though `processNavigations` catch
// handler does not rethrow
return promise.catch(function (e) { return Promise.reject(e); });
};
/**
* @param {?} __0
* @return {?}
*/
Router.prototype.executeScheduledNavigation = function (_a) {
var _this = this;
var id = _a.id, rawUrl = _a.rawUrl, extras = _a.extras, resolve = _a.resolve, reject = _a.reject;
var /** @type {?} */ url = this.urlHandlingStrategy.extract(rawUrl);
var /** @type {?} */ urlTransition = !this.navigated || url.toString() !== this.currentUrlTree.toString();
if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) {
this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url)));
Promise.resolve()
.then(function (_) { return _this.runNavigate(url, rawUrl, !!extras.skipLocationChange, !!extras.replaceUrl, id, null); })
.then(resolve, reject);
// we cannot process the current URL, but we could process the previous one =>
// we need to do some cleanup
}
else if (urlTransition && this.rawUrlTree &&
this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)) {
this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url)));
Promise.resolve()
.then(function (_) { return _this.runNavigate(url, rawUrl, false, false, id, createEmptyState(url, _this.rootComponentType).snapshot); })
.then(resolve, reject);
}
else {
this.rawUrlTree = rawUrl;
resolve(null);
}
};
/**
* @param {?} url
* @param {?} rawUrl
* @param {?} shouldPreventPushState
* @param {?} shouldReplaceUrl
* @param {?} id
* @param {?} precreatedState
* @return {?}
*/
Router.prototype.runNavigate = function (url, rawUrl, shouldPreventPushState, shouldReplaceUrl, id, precreatedState) {
var _this = this;
if (id !== this.navigationId) {
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url), "Navigation ID " + id + " is not equal to the current navigation id " + this.navigationId));
return Promise.resolve(false);
}
return new Promise(function (resolvePromise, rejectPromise) {
// create an observable of the url and route state snapshot
// this operation do not result in any side effects
var /** @type {?} */ urlAndSnapshot$;
if (!precreatedState) {
var /** @type {?} */ moduleInjector = _this.ngModule.injector;
var /** @type {?} */ redirectsApplied$ = applyRedirects(moduleInjector, _this.configLoader, _this.urlSerializer, url, _this.config);
urlAndSnapshot$ = rxjs_operator_mergeMap.mergeMap.call(redirectsApplied$, function (appliedUrl) {
return rxjs_operator_map.map.call(recognize(_this.rootComponentType, _this.config, appliedUrl, _this.serializeUrl(appliedUrl)), function (snapshot) {
_this.routerEvents.next(new RoutesRecognized(id, _this.serializeUrl(url), _this.serializeUrl(appliedUrl), snapshot));
return { appliedUrl: appliedUrl, snapshot: snapshot };
});
});
}
else {
urlAndSnapshot$ = rxjs_observable_of.of({ appliedUrl: url, snapshot: precreatedState });
}
var /** @type {?} */ beforePreactivationDone$ = rxjs_operator_mergeMap.mergeMap.call(urlAndSnapshot$, function (p) {
return rxjs_operator_map.map.call(_this.hooks.beforePreactivation(p.snapshot), function () { return p; });
});
// run preactivation: guards and data resolvers
var /** @type {?} */ preActivation;
var /** @type {?} */ preactivationTraverse$ = rxjs_operator_map.map.call(beforePreactivationDone$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot;
var /** @type {?} */ moduleInjector = _this.ngModule.injector;
preActivation =
new PreActivation(snapshot, _this.currentRouterState.snapshot, moduleInjector);
preActivation.traverse(_this.rootContexts);
return { appliedUrl: appliedUrl, snapshot: snapshot };
});
var /** @type {?} */ preactivationCheckGuards$ = rxjs_operator_mergeMap.mergeMap.call(preactivationTraverse$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot;
if (_this.navigationId !== id)
return rxjs_observable_of.of(false);
return rxjs_operator_map.map.call(preActivation.checkGuards(), function (shouldActivate) {
return { appliedUrl: appliedUrl, snapshot: snapshot, shouldActivate: shouldActivate };
});
});
var /** @type {?} */ preactivationResolveData$ = rxjs_operator_mergeMap.mergeMap.call(preactivationCheckGuards$, function (p) {
if (_this.navigationId !== id)
return rxjs_observable_of.of(false);
if (p.shouldActivate) {
return rxjs_operator_map.map.call(preActivation.resolveData(), function () { return p; });
}
else {
return rxjs_observable_of.of(p);
}
});
var /** @type {?} */ preactivationDone$ = rxjs_operator_mergeMap.mergeMap.call(preactivationResolveData$, function (p) {
return rxjs_operator_map.map.call(_this.hooks.afterPreactivation(p.snapshot), function () { return p; });
});
// create router state
// this operation has side effects => route state is being affected
var /** @type {?} */ routerState$ = rxjs_operator_map.map.call(preactivationDone$, function (_a) {
var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot, shouldActivate = _a.shouldActivate;
if (shouldActivate) {
var /** @type {?} */ state = createRouterState(_this.routeReuseStrategy, snapshot, _this.currentRouterState);
return { appliedUrl: appliedUrl, state: state, shouldActivate: shouldActivate };
}
else {
return { appliedUrl: appliedUrl, state: null, shouldActivate: shouldActivate };
}
});
// applied the new router state
// this operation has side effects
var /** @type {?} */ navigationIsSuccessful;
var /** @type {?} */ storedState = _this.currentRouterState;
var /** @type {?} */ storedUrl = _this.currentUrlTree;
routerState$
.forEach(function (_a) {
var appliedUrl = _a.appliedUrl, state = _a.state, shouldActivate = _a.shouldActivate;
if (!shouldActivate || id !== _this.navigationId) {
navigationIsSuccessful = false;
return;
}
_this.currentUrlTree = appliedUrl;
_this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl);
_this.currentRouterState = state;
if (!shouldPreventPushState) {
var /** @type {?} */ path = _this.urlSerializer.serialize(_this.rawUrlTree);
if (_this.location.isCurrentPathEqualTo(path) || shouldReplaceUrl) {
_this.location.replaceState(path);
}
else {
_this.location.go(path);
}
}
new ActivateRoutes(_this.routeReuseStrategy, state, storedState)
.activate(_this.rootContexts);
navigationIsSuccessful = true;
})
.then(function () {
if (navigationIsSuccessful) {
_this.navigated = true;
_this.routerEvents.next(new NavigationEnd(id, _this.serializeUrl(url), _this.serializeUrl(_this.currentUrlTree)));
resolvePromise(true);
}
else {
_this.resetUrlToCurrentUrlTree();
_this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), ''));
resolvePromise(false);
}
}, function (e) {
if (isNavigationCancelingError(e)) {
_this.resetUrlToCurrentUrlTree();
_this.navigated = true;
_this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), e.message));
resolvePromise(false);
}
else {
_this.routerEvents.next(new NavigationError(id, _this.serializeUrl(url), e));
try {
resolvePromise(_this.errorHandler(e));
}
catch (ee) {
rejectPromise(ee);
}
}
_this.currentRouterState = storedState;
_this.currentUrlTree = storedUrl;
_this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl);
_this.location.replaceState(_this.serializeUrl(_this.rawUrlTree));
});
});
};
/**
* @return {?}
*/
Router.prototype.resetUrlToCurrentUrlTree = function () {
var /** @type {?} */ path = this.urlSerializer.serialize(this.rawUrlTree);
this.location.replaceState(path);
};
return Router;
}());
var CanActivate = (function () {
/**
* @param {?} path
*/
function CanActivate(path) {
this.path = path;
}
Object.defineProperty(CanActivate.prototype, "route", {
/**
* @return {?}
*/
get: function () { return this.path[this.path.length - 1]; },
enumerable: true,
configurable: true
});
return CanActivate;
}());
var CanDeactivate = (function () {
/**
* @param {?} component
* @param {?} route
*/
function CanDeactivate(component, route) {
this.component = component;
this.route = route;
}
return CanDeactivate;
}());
var PreActivation = (function () {
/**
* @param {?} future
* @param {?} curr
* @param {?} moduleInjector
*/
function PreActivation(future, curr, moduleInjector) {
this.future = future;
this.curr = curr;
this.moduleInjector = moduleInjector;
this.canActivateChecks = [];
this.canDeactivateChecks = [];
}
/**
* @param {?} parentContexts
* @return {?}
*/
PreActivation.prototype.traverse = function (parentContexts) {
var /** @type {?} */ futureRoot = this.future._root;
var /** @type {?} */ currRoot = this.curr ? this.curr._root : null;
this.traverseChildRoutes(futureRoot, currRoot, parentContexts, [futureRoot.value]);
};
/**
* @return {?}
*/
PreActivation.prototype.checkGuards = function () {
var _this = this;
if (this.canDeactivateChecks.length === 0 && this.canActivateChecks.length === 0) {
return rxjs_observable_of.of(true);
}
var /** @type {?} */ canDeactivate$ = this.runCanDeactivateChecks();
return rxjs_operator_mergeMap.mergeMap.call(canDeactivate$, function (canDeactivate) { return canDeactivate ? _this.runCanActivateChecks() : rxjs_observable_of.of(false); });
};
/**
* @return {?}
*/
PreActivation.prototype.resolveData = function () {
var _this = this;
if (this.canActivateChecks.length === 0)
return rxjs_observable_of.of(null);
var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canActivateChecks);
var /** @type {?} */ runningChecks$ = rxjs_operator_concatMap.concatMap.call(checks$, function (check) { return _this.runResolve(check.route); });
return rxjs_operator_reduce.reduce.call(runningChecks$, function (_, __) { return _; });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @param {?} futurePath
* @return {?}
*/
PreActivation.prototype.traverseChildRoutes = function (futureNode, currNode, contexts, futurePath) {
var _this = this;
var /** @type {?} */ prevChildren = nodeChildrenAsMap(currNode);
// Process the children of the future route
futureNode.children.forEach(function (c) {
_this.traverseRoutes(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]));
delete prevChildren[c.value.outlet];
});
// Process any children left from the current route (not active for the future route)
forEach(prevChildren, function (v, k) { return _this.deactivateRouteAndItsChildren(v, /** @type {?} */ ((contexts)).getContext(k)); });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContexts
* @param {?} futurePath
* @return {?}
*/
PreActivation.prototype.traverseRoutes = function (futureNode, currNode, parentContexts, futurePath) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
var /** @type {?} */ context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
// reusing the node
if (curr && future._routeConfig === curr._routeConfig) {
if (this.shouldRunGuardsAndResolvers(curr, future, /** @type {?} */ ((future._routeConfig)).runGuardsAndResolvers)) {
this.canActivateChecks.push(new CanActivate(futurePath));
var /** @type {?} */ outlet = ((((context)).outlet));
this.canDeactivateChecks.push(new CanDeactivate(outlet.component, curr));
}
else {
// we need to set the data
future.data = curr.data;
future._resolvedData = curr._resolvedData;
}
// If we have a component, we need to go through an outlet.
if (future.component) {
this.traverseChildRoutes(futureNode, currNode, context ? context.children : null, futurePath);
// if we have a componentless route, we recurse but keep the same outlet map.
}
else {
this.traverseChildRoutes(futureNode, currNode, parentContexts, futurePath);
}
}
else {
if (curr) {
this.deactivateRouteAndItsChildren(currNode, context);
}
this.canActivateChecks.push(new CanActivate(futurePath));
// If we have a component, we need to go through an outlet.
if (future.component) {
this.traverseChildRoutes(futureNode, null, context ? context.children : null, futurePath);
// if we have a componentless route, we recurse but keep the same outlet map.
}
else {
this.traverseChildRoutes(futureNode, null, parentContexts, futurePath);
}
}
};
/**
* @param {?} curr
* @param {?} future
* @param {?} mode
* @return {?}
*/
PreActivation.prototype.shouldRunGuardsAndResolvers = function (curr, future, mode) {
switch (mode) {
case 'always':
return true;
case 'paramsOrQueryParamsChange':
return !equalParamsAndUrlSegments(curr, future) ||
!shallowEqual(curr.queryParams, future.queryParams);
case 'paramsChange':
default:
return !equalParamsAndUrlSegments(curr, future);
}
};
/**
* @param {?} route
* @param {?} context
* @return {?}
*/
PreActivation.prototype.deactivateRouteAndItsChildren = function (route, context) {
var _this = this;
var /** @type {?} */ children = nodeChildrenAsMap(route);
var /** @type {?} */ r = route.value;
forEach(children, function (node, childName) {
if (!r.component) {
_this.deactivateRouteAndItsChildren(node, context);
}
else if (context) {
_this.deactivateRouteAndItsChildren(node, context.children.getContext(childName));
}
else {
_this.deactivateRouteAndItsChildren(node, null);
}
});
if (!r.component) {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
}
else if (context && context.outlet && context.outlet.isActivated) {
this.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
}
else {
this.canDeactivateChecks.push(new CanDeactivate(null, r));
}
};
/**
* @return {?}
*/
PreActivation.prototype.runCanDeactivateChecks = function () {
var _this = this;
var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canDeactivateChecks);
var /** @type {?} */ runningChecks$ = rxjs_operator_mergeMap.mergeMap.call(checks$, function (check) { return _this.runCanDeactivate(check.component, check.route); });
return rxjs_operator_every.every.call(runningChecks$, function (result) { return result === true; });
};
/**
* @return {?}
*/
PreActivation.prototype.runCanActivateChecks = function () {
var _this = this;
var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canActivateChecks);
var /** @type {?} */ runningChecks$ = rxjs_operator_mergeMap.mergeMap.call(checks$, function (check) { return andObservables(rxjs_observable_from.from([_this.runCanActivateChild(check.path), _this.runCanActivate(check.route)])); });
return rxjs_operator_every.every.call(runningChecks$, function (result) { return result === true; });
};
/**
* @param {?} future
* @return {?}
*/
PreActivation.prototype.runCanActivate = function (future) {
var _this = this;
var /** @type {?} */ canActivate = future._routeConfig ? future._routeConfig.canActivate : null;
if (!canActivate || canActivate.length === 0)
return rxjs_observable_of.of(true);
var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(canActivate), function (c) {
var /** @type {?} */ guard = _this.getToken(c, future);
var /** @type {?} */ observable;
if (guard.canActivate) {
observable = wrapIntoObservable(guard.canActivate(future, _this.future));
}
else {
observable = wrapIntoObservable(guard(future, _this.future));
}
return rxjs_operator_first.first.call(observable);
});
return andObservables(obs);
};
/**
* @param {?} path
* @return {?}
*/
PreActivation.prototype.runCanActivateChild = function (path) {
var _this = this;
var /** @type {?} */ future = path[path.length - 1];
var /** @type {?} */ canActivateChildGuards = path.slice(0, path.length - 1)
.reverse()
.map(function (p) { return _this.extractCanActivateChild(p); })
.filter(function (_) { return _ !== null; });
return andObservables(rxjs_operator_map.map.call(rxjs_observable_from.from(canActivateChildGuards), function (d) {
var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(d.guards), function (c) {
var /** @type {?} */ guard = _this.getToken(c, d.node);
var /** @type {?} */ observable;
if (guard.canActivateChild) {
observable = wrapIntoObservable(guard.canActivateChild(future, _this.future));
}
else {
observable = wrapIntoObservable(guard(future, _this.future));
}
return rxjs_operator_first.first.call(observable);
});
return andObservables(obs);
}));
};
/**
* @param {?} p
* @return {?}
*/
PreActivation.prototype.extractCanActivateChild = function (p) {
var /** @type {?} */ canActivateChild = p._routeConfig ? p._routeConfig.canActivateChild : null;
if (!canActivateChild || canActivateChild.length === 0)
return null;
return { node: p, guards: canActivateChild };
};
/**
* @param {?} component
* @param {?} curr
* @return {?}
*/
PreActivation.prototype.runCanDeactivate = function (component, curr) {
var _this = this;
var /** @type {?} */ canDeactivate = curr && curr._routeConfig ? curr._routeConfig.canDeactivate : null;
if (!canDeactivate || canDeactivate.length === 0)
return rxjs_observable_of.of(true);
var /** @type {?} */ canDeactivate$ = rxjs_operator_mergeMap.mergeMap.call(rxjs_observable_from.from(canDeactivate), function (c) {
var /** @type {?} */ guard = _this.getToken(c, curr);
var /** @type {?} */ observable;
if (guard.canDeactivate) {
observable =
wrapIntoObservable(guard.canDeactivate(component, curr, _this.curr, _this.future));
}
else {
observable = wrapIntoObservable(guard(component, curr, _this.curr, _this.future));
}
return rxjs_operator_first.first.call(observable);
});
return rxjs_operator_every.every.call(canDeactivate$, function (result) { return result === true; });
};
/**
* @param {?} future
* @return {?}
*/
PreActivation.prototype.runResolve = function (future) {
var /** @type {?} */ resolve = future._resolve;
return rxjs_operator_map.map.call(this.resolveNode(resolve, future), function (resolvedData) {
future._resolvedData = resolvedData;
future.data = Object.assign({}, future.data, inheritedParamsDataResolve(future).resolve);
return null;
});
};
/**
* @param {?} resolve
* @param {?} future
* @return {?}
*/
PreActivation.prototype.resolveNode = function (resolve, future) {
var _this = this;
return waitForMap(resolve, function (k, v) {
var /** @type {?} */ resolver = _this.getToken(v, future);
return resolver.resolve ? wrapIntoObservable(resolver.resolve(future, _this.future)) :
wrapIntoObservable(resolver(future, _this.future));
});
};
/**
* @param {?} token
* @param {?} snapshot
* @return {?}
*/
PreActivation.prototype.getToken = function (token, snapshot) {
var /** @type {?} */ config = closestLoadedConfig(snapshot);
var /** @type {?} */ injector = config ? config.module.injector : this.moduleInjector;
return injector.get(token);
};
return PreActivation;
}());
var ActivateRoutes = (function () {
/**
* @param {?} routeReuseStrategy
* @param {?} futureState
* @param {?} currState
*/
function ActivateRoutes(routeReuseStrategy, futureState, currState) {
this.routeReuseStrategy = routeReuseStrategy;
this.futureState = futureState;
this.currState = currState;
}
/**
* @param {?} parentContexts
* @return {?}
*/
ActivateRoutes.prototype.activate = function (parentContexts) {
var /** @type {?} */ futureRoot = this.futureState._root;
var /** @type {?} */ currRoot = this.currState ? this.currState._root : null;
this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
advanceActivatedRoute(this.futureState.root);
this.activateChildRoutes(futureRoot, currRoot, parentContexts);
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @return {?}
*/
ActivateRoutes.prototype.deactivateChildRoutes = function (futureNode, currNode, contexts) {
var _this = this;
var /** @type {?} */ children = nodeChildrenAsMap(currNode);
// Recurse on the routes active in the future state to de-activate deeper children
futureNode.children.forEach(function (futureChild) {
var /** @type {?} */ childOutletName = futureChild.value.outlet;
_this.deactivateRoutes(futureChild, children[childOutletName], contexts);
delete children[childOutletName];
});
// De-activate the routes that will not be re-used
forEach(children, function (v, childName) {
_this.deactivateRouteAndItsChildren(v, contexts);
});
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContext
* @return {?}
*/
ActivateRoutes.prototype.deactivateRoutes = function (futureNode, currNode, parentContext) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
if (future === curr) {
// Reusing the node, check to see if the children need to be de-activated
if (future.component) {
// If we have a normal route, we need to go through an outlet.
var /** @type {?} */ context = parentContext.getContext(future.outlet);
if (context) {
this.deactivateChildRoutes(futureNode, currNode, context.children);
}
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.deactivateChildRoutes(futureNode, currNode, parentContext);
}
}
else {
if (curr) {
// Deactivate the current route which will not be re-used
this.deactivateRouteAndItsChildren(currNode, parentContext);
}
}
};
/**
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
ActivateRoutes.prototype.deactivateRouteAndItsChildren = function (route, parentContexts) {
if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
this.detachAndStoreRouteSubtree(route, parentContexts);
}
else {
this.deactivateRouteAndOutlet(route, parentContexts);
}
};
/**
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
ActivateRoutes.prototype.detachAndStoreRouteSubtree = function (route, parentContexts) {
var /** @type {?} */ context = parentContexts.getContext(route.value.outlet);
if (context && context.outlet) {
var /** @type {?} */ componentRef = context.outlet.detach();
var /** @type {?} */ contexts = context.children.onOutletDeactivated();
this.routeReuseStrategy.store(route.value.snapshot, { componentRef: componentRef, route: route, contexts: contexts });
}
};
/**
* @param {?} route
* @param {?} parentContexts
* @return {?}
*/
ActivateRoutes.prototype.deactivateRouteAndOutlet = function (route, parentContexts) {
var _this = this;
var /** @type {?} */ context = parentContexts.getContext(route.value.outlet);
if (context) {
var /** @type {?} */ children = nodeChildrenAsMap(route);
var /** @type {?} */ contexts_1 = route.value.component ? context.children : parentContexts;
forEach(children, function (v, k) { _this.deactivateRouteAndItsChildren(v, contexts_1); });
if (context.outlet) {
// Destroy the component
context.outlet.deactivate();
// Destroy the contexts for all the outlets that were in the component
context.children.onOutletDeactivated();
}
}
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} contexts
* @return {?}
*/
ActivateRoutes.prototype.activateChildRoutes = function (futureNode, currNode, contexts) {
var _this = this;
var /** @type {?} */ children = nodeChildrenAsMap(currNode);
futureNode.children.forEach(function (c) { _this.activateRoutes(c, children[c.value.outlet], contexts); });
};
/**
* @param {?} futureNode
* @param {?} currNode
* @param {?} parentContexts
* @return {?}
*/
ActivateRoutes.prototype.activateRoutes = function (futureNode, currNode, parentContexts) {
var /** @type {?} */ future = futureNode.value;
var /** @type {?} */ curr = currNode ? currNode.value : null;
advanceActivatedRoute(future);
// reusing the node
if (future === curr) {
if (future.component) {
// If we have a normal route, we need to go through an outlet.
var /** @type {?} */ context = parentContexts.getOrCreateContext(future.outlet);
this.activateChildRoutes(futureNode, currNode, context.children);
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.activateChildRoutes(futureNode, currNode, parentContexts);
}
}
else {
if (future.component) {
// if we have a normal route, we need to place the component into the outlet and recurse.
var /** @type {?} */ context = parentContexts.getOrCreateContext(future.outlet);
if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
var /** @type {?} */ stored = ((this.routeReuseStrategy.retrieve(future.snapshot)));
this.routeReuseStrategy.store(future.snapshot, null);
context.children.onOutletReAttached(stored.contexts);
context.attachRef = stored.componentRef;
context.route = stored.route.value;
if (context.outlet) {
// Attach right away when the outlet has already been instantiated
// Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
context.outlet.attach(stored.componentRef, stored.route.value);
}
advanceActivatedRouteNodeAndItsChildren(stored.route);
}
else {
var /** @type {?} */ config = parentLoadedConfig(future.snapshot);
var /** @type {?} */ cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
context.route = future;
context.resolver = cmpFactoryResolver;
if (context.outlet) {
// Activate the outlet when it has already been instantiated
// Otherwise it will get activated from its `ngOnInit` when instantiated
context.outlet.activateWith(future, cmpFactoryResolver);
}
this.activateChildRoutes(futureNode, null, context.children);
}
}
else {
// if we have a componentless route, we recurse but keep the same outlet map.
this.activateChildRoutes(futureNode, null, parentContexts);
}
}
};
return ActivateRoutes;
}());
/**
* @param {?} node
* @return {?}
*/
function advanceActivatedRouteNodeAndItsChildren(node) {
advanceActivatedRoute(node.value);
node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
}
/**
* @param {?} snapshot
* @return {?}
*/
function parentLoadedConfig(snapshot) {
for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) {
var /** @type {?} */ route = s._routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
if (route && route.component)
return null;
}
return null;
}
/**
* @param {?} snapshot
* @return {?}
*/
function closestLoadedConfig(snapshot) {
if (!snapshot)
return null;
for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) {
var /** @type {?} */ route = s._routeConfig;
if (route && route._loadedConfig)
return route._loadedConfig;
}
return null;
}
/**
* @template T
* @param {?} node
* @return {?}
*/
function nodeChildrenAsMap(node) {
var /** @type {?} */ map$$1 = {};
if (node) {
node.children.forEach(function (child) { return map$$1[child.value.outlet] = child; });
}
return map$$1;
}
/**
* @param {?} commands
* @return {?}
*/
function validateCommands(commands) {
for (var /** @type {?} */ i = 0; i < commands.length; i++) {
var /** @type {?} */ cmd = commands[i];
if (cmd == null) {
throw new Error("The requested path contains " + cmd + " segment at index " + i);
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Lets you link to specific parts of your app.
*
* \@howToUse
*
* Consider the following route configuration:
* `[{ path: 'user/:name', component: UserCmp }]`
*
* When linking to this `user/:name` route, you can write:
* `<a routerLink='/user/bob'>link to user component</a>`
*
* \@description
*
* The RouterLink directives let you link to specific parts of your app.
*
* When the link is static, you can use the directive as follows:
* `<a routerLink="/user/bob">link to user component</a>`
*
* If you use dynamic values to generate the link, you can pass an array of path
* segments, followed by the params for each segment.
*
* For instance `['/team', teamId, 'user', userName, {details: true}]`
* means that we want to generate a link to `/team/11/user/bob;details=true`.
*
* Multiple static segments can be merged into one
* (e.g., `['/team/11/user', userName, {details: true}]`).
*
* The first segment name can be prepended with `/`, `./`, or `../`:
* * If the first segment begins with `/`, the router will look up the route from the root of the
* app.
* * If the first segment begins with `./`, or doesn't begin with a slash, the router will
* instead look in the children of the current activated route.
* * And if the first segment begins with `../`, the router will go up one level.
*
* You can set query params and fragment as follows:
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
* link to user component
* </a>
* ```
* RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
*
* (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
* directive to preserve the current query params and fragment:
*
* ```
* <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
* link to user component
* </a>
* ```
*
* You can tell the directive to how to handle queryParams, available options are:
* - 'merge' merge the queryParams into the current queryParams
* - 'preserve' prserve the current queryParams
* - default / '' use the queryParams only
* same options for {\@link NavigationExtras#queryParamsHandling}
*
* ```
* <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
* link to user component
* </a>
* ```
*
* The router link directive always treats the provided input as a delta to the current url.
*
* For instance, if the current url is `/user/(box//aux:team)`.
*
* Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
* `/user/(jim//aux:team)`.
*
* \@ngModule RouterModule
*
* See {\@link Router#createUrlTree} for more information.
*
* \@stable
*/
var RouterLink = (function () {
/**
* @param {?} router
* @param {?} route
* @param {?} tabIndex
* @param {?} renderer
* @param {?} el
*/
function RouterLink(router, route, tabIndex, renderer, el) {
this.router = router;
this.route = route;
this.commands = [];
if (tabIndex == null) {
renderer.setElementAttribute(el.nativeElement, 'tabindex', '0');
}
}
Object.defineProperty(RouterLink.prototype, "routerLink", {
/**
* @param {?} commands
* @return {?}
*/
set: function (commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterLink.prototype, "preserveQueryParams", {
/**
* @deprecated 4.0.0 use `queryParamsHandling` instead.
* @param {?} value
* @return {?}
*/
set: function (value) {
if (_angular_core.isDevMode() && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.');
}
this.preserve = value;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
RouterLink.prototype.onClick = function () {
var /** @type {?} */ extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
};
Object.defineProperty(RouterLink.prototype, "urlTree", {
/**
* @return {?}
*/
get: function () {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
},
enumerable: true,
configurable: true
});
return RouterLink;
}());
RouterLink.decorators = [
{ type: _angular_core.Directive, args: [{ selector: ':not(a)[routerLink]' },] },
];
/**
* @nocollapse
*/
RouterLink.ctorParameters = function () { return [
{ type: Router, },
{ type: ActivatedRoute, },
{ type: undefined, decorators: [{ type: _angular_core.Attribute, args: ['tabindex',] },] },
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
]; };
RouterLink.propDecorators = {
'queryParams': [{ type: _angular_core.Input },],
'fragment': [{ type: _angular_core.Input },],
'queryParamsHandling': [{ type: _angular_core.Input },],
'preserveFragment': [{ type: _angular_core.Input },],
'skipLocationChange': [{ type: _angular_core.Input },],
'replaceUrl': [{ type: _angular_core.Input },],
'routerLink': [{ type: _angular_core.Input },],
'preserveQueryParams': [{ type: _angular_core.Input },],
'onClick': [{ type: _angular_core.HostListener, args: ['click',] },],
};
/**
* \@whatItDoes Lets you link to specific parts of your app.
*
* See {\@link RouterLink} for more information.
*
* \@ngModule RouterModule
*
* \@stable
*/
var RouterLinkWithHref = (function () {
/**
* @param {?} router
* @param {?} route
* @param {?} locationStrategy
*/
function RouterLinkWithHref(router, route, locationStrategy) {
var _this = this;
this.router = router;
this.route = route;
this.locationStrategy = locationStrategy;
this.commands = [];
this.subscription = router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.updateTargetUrlAndHref();
}
});
}
Object.defineProperty(RouterLinkWithHref.prototype, "routerLink", {
/**
* @param {?} commands
* @return {?}
*/
set: function (commands) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
}
else {
this.commands = [];
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterLinkWithHref.prototype, "preserveQueryParams", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
if (_angular_core.isDevMode() && (console) && (console.warn)) {
console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
}
this.preserve = value;
},
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
RouterLinkWithHref.prototype.ngOnChanges = function (changes) { this.updateTargetUrlAndHref(); };
/**
* @return {?}
*/
RouterLinkWithHref.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @param {?} button
* @param {?} ctrlKey
* @param {?} metaKey
* @param {?} shiftKey
* @return {?}
*/
RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) {
if (button !== 0 || ctrlKey || metaKey || shiftKey) {
return true;
}
if (typeof this.target === 'string' && this.target != '_self') {
return true;
}
var /** @type {?} */ extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return false;
};
/**
* @return {?}
*/
RouterLinkWithHref.prototype.updateTargetUrlAndHref = function () {
this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree));
};
Object.defineProperty(RouterLinkWithHref.prototype, "urlTree", {
/**
* @return {?}
*/
get: function () {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route,
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
},
enumerable: true,
configurable: true
});
return RouterLinkWithHref;
}());
RouterLinkWithHref.decorators = [
{ type: _angular_core.Directive, args: [{ selector: 'a[routerLink]' },] },
];
/**
* @nocollapse
*/
RouterLinkWithHref.ctorParameters = function () { return [
{ type: Router, },
{ type: ActivatedRoute, },
{ type: _angular_common.LocationStrategy, },
]; };
RouterLinkWithHref.propDecorators = {
'target': [{ type: _angular_core.HostBinding, args: ['attr.target',] }, { type: _angular_core.Input },],
'queryParams': [{ type: _angular_core.Input },],
'fragment': [{ type: _angular_core.Input },],
'queryParamsHandling': [{ type: _angular_core.Input },],
'preserveFragment': [{ type: _angular_core.Input },],
'skipLocationChange': [{ type: _angular_core.Input },],
'replaceUrl': [{ type: _angular_core.Input },],
'href': [{ type: _angular_core.HostBinding },],
'routerLink': [{ type: _angular_core.Input },],
'preserveQueryParams': [{ type: _angular_core.Input },],
'onClick': [{ type: _angular_core.HostListener, args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey'],] },],
};
/**
* @param {?} s
* @return {?}
*/
function attrBoolValue(s) {
return s === '' || !!s;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Lets you add a CSS class to an element when the link's route becomes active.
*
* \@howToUse
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* \@description
*
* The RouterLinkActive directive lets you add a CSS class to an element when the link's route
* becomes active.
*
* Consider the following example:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
* ```
*
* When the url is either '/user' or '/user/bob', the active-link class will
* be added to the `a` tag. If the url changes, the class will be removed.
*
* You can set more than one class, as follows:
*
* ```
* <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
* <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
* ```
*
* You can configure RouterLinkActive by passing `exact: true`. This will add the classes
* only when the url matches the link exactly.
*
* ```
* <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
* true}">Bob</a>
* ```
*
* You can assign the RouterLinkActive instance to a template variable and directly check
* the `isActive` status.
* ```
* <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
* Bob {{ rla.isActive ? '(already open)' : ''}}
* </a>
* ```
*
* Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
*
* ```
* <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
* <a routerLink="/user/jim">Jim</a>
* <a routerLink="/user/bob">Bob</a>
* </div>
* ```
*
* This will set the active-link class on the div tag if the url is either '/user/jim' or
* '/user/bob'.
*
* \@ngModule RouterModule
*
* \@stable
*/
var RouterLinkActive = (function () {
/**
* @param {?} router
* @param {?} element
* @param {?} renderer
* @param {?} cdr
*/
function RouterLinkActive(router, element, renderer, cdr) {
var _this = this;
this.router = router;
this.element = element;
this.renderer = renderer;
this.cdr = cdr;
this.classes = [];
this.active = false;
this.routerLinkActiveOptions = { exact: false };
this.subscription = router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.update();
}
});
}
Object.defineProperty(RouterLinkActive.prototype, "isActive", {
/**
* @return {?}
*/
get: function () { return this.active; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
RouterLinkActive.prototype.ngAfterContentInit = function () {
var _this = this;
this.links.changes.subscribe(function (_) { return _this.update(); });
this.linksWithHrefs.changes.subscribe(function (_) { return _this.update(); });
this.update();
};
Object.defineProperty(RouterLinkActive.prototype, "routerLinkActive", {
/**
* @param {?} data
* @return {?}
*/
set: function (data) {
var /** @type {?} */ classes = Array.isArray(data) ? data : data.split(' ');
this.classes = classes.filter(function (c) { return !!c; });
},
enumerable: true,
configurable: true
});
/**
* @param {?} changes
* @return {?}
*/
RouterLinkActive.prototype.ngOnChanges = function (changes) { this.update(); };
/**
* @return {?}
*/
RouterLinkActive.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @return {?}
*/
RouterLinkActive.prototype.update = function () {
var _this = this;
if (!this.links || !this.linksWithHrefs || !this.router.navigated)
return;
var /** @type {?} */ hasActiveLinks = this.hasActiveLinks();
// react only when status has changed to prevent unnecessary dom updates
if (this.active !== hasActiveLinks) {
this.classes.forEach(function (c) { return _this.renderer.setElementClass(_this.element.nativeElement, c, hasActiveLinks); });
Promise.resolve(hasActiveLinks).then(function (active) { return _this.active = active; });
}
};
/**
* @param {?} router
* @return {?}
*/
RouterLinkActive.prototype.isLinkActive = function (router) {
var _this = this;
return function (link) { return router.isActive(link.urlTree, _this.routerLinkActiveOptions.exact); };
};
/**
* @return {?}
*/
RouterLinkActive.prototype.hasActiveLinks = function () {
return this.links.some(this.isLinkActive(this.router)) ||
this.linksWithHrefs.some(this.isLinkActive(this.router));
};
return RouterLinkActive;
}());
RouterLinkActive.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[routerLinkActive]',
exportAs: 'routerLinkActive',
},] },
];
/**
* @nocollapse
*/
RouterLinkActive.ctorParameters = function () { return [
{ type: Router, },
{ type: _angular_core.ElementRef, },
{ type: _angular_core.Renderer, },
{ type: _angular_core.ChangeDetectorRef, },
]; };
RouterLinkActive.propDecorators = {
'links': [{ type: _angular_core.ContentChildren, args: [RouterLink, { descendants: true },] },],
'linksWithHrefs': [{ type: _angular_core.ContentChildren, args: [RouterLinkWithHref, { descendants: true },] },],
'routerLinkActiveOptions': [{ type: _angular_core.Input },],
'routerLinkActive': [{ type: _angular_core.Input },],
};
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Store contextual information about a {\@link RouterOutlet}
*
* \@stable
*/
var OutletContext = (function () {
function OutletContext() {
this.outlet = null;
this.route = null;
this.resolver = null;
this.children = new ChildrenOutletContexts();
this.attachRef = null;
}
return OutletContext;
}());
/**
* Store contextual information about the children (= nested) {\@link RouterOutlet}
*
* \@stable
*/
var ChildrenOutletContexts = (function () {
function ChildrenOutletContexts() {
this.contexts = new Map();
}
/**
* Called when a `RouterOutlet` directive is instantiated
* @param {?} childName
* @param {?} outlet
* @return {?}
*/
ChildrenOutletContexts.prototype.onChildOutletCreated = function (childName, outlet) {
var /** @type {?} */ context = this.getOrCreateContext(childName);
context.outlet = outlet;
this.contexts.set(childName, context);
};
/**
* Called when a `RouterOutlet` directive is destroyed.
* We need to keep the context as the outlet could be destroyed inside a NgIf and might be
* re-created later.
* @param {?} childName
* @return {?}
*/
ChildrenOutletContexts.prototype.onChildOutletDestroyed = function (childName) {
var /** @type {?} */ context = this.getContext(childName);
if (context) {
context.outlet = null;
}
};
/**
* Called when the corresponding route is deactivated during navigation.
* Because the component get destroyed, all children outlet are destroyed.
* @return {?}
*/
ChildrenOutletContexts.prototype.onOutletDeactivated = function () {
var /** @type {?} */ contexts = this.contexts;
this.contexts = new Map();
return contexts;
};
/**
* @param {?} contexts
* @return {?}
*/
ChildrenOutletContexts.prototype.onOutletReAttached = function (contexts) { this.contexts = contexts; };
/**
* @param {?} childName
* @return {?}
*/
ChildrenOutletContexts.prototype.getOrCreateContext = function (childName) {
var /** @type {?} */ context = this.getContext(childName);
if (!context) {
context = new OutletContext();
this.contexts.set(childName, context);
}
return context;
};
/**
* @param {?} childName
* @return {?}
*/
ChildrenOutletContexts.prototype.getContext = function (childName) { return this.contexts.get(childName) || null; };
return ChildrenOutletContexts;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Acts as a placeholder that Angular dynamically fills based on the current router
* state.
*
* \@howToUse
*
* ```
* <router-outlet></router-outlet>
* <router-outlet name='left'></router-outlet>
* <router-outlet name='right'></router-outlet>
* ```
*
* A router outlet will emit an activate event any time a new component is being instantiated,
* and a deactivate event when it is being destroyed.
*
* ```
* <router-outlet
* (activate)='onActivate($event)'
* (deactivate)='onDeactivate($event)'></router-outlet>
* ```
* \@ngModule RouterModule
*
* \@stable
*/
var RouterOutlet = (function () {
/**
* @param {?} parentContexts
* @param {?} location
* @param {?} resolver
* @param {?} name
* @param {?} changeDetector
*/
function RouterOutlet(parentContexts, location, resolver, name, changeDetector) {
this.parentContexts = parentContexts;
this.location = location;
this.resolver = resolver;
this.changeDetector = changeDetector;
this.activated = null;
this._activatedRoute = null;
this.activateEvents = new _angular_core.EventEmitter();
this.deactivateEvents = new _angular_core.EventEmitter();
this.name = name || PRIMARY_OUTLET;
parentContexts.onChildOutletCreated(this.name, this);
}
/**
* @return {?}
*/
RouterOutlet.prototype.ngOnDestroy = function () { this.parentContexts.onChildOutletDestroyed(this.name); };
/**
* @return {?}
*/
RouterOutlet.prototype.ngOnInit = function () {
if (!this.activated) {
// If the outlet was not instantiated at the time the route got activated we need to populate
// the outlet when it is initialized (ie inside a NgIf)
var /** @type {?} */ context = this.parentContexts.getContext(this.name);
if (context && context.route) {
if (context.attachRef) {
// `attachRef` is populated when there is an existing component to mount
this.attach(context.attachRef, context.route);
}
else {
// otherwise the component defined in the configuration is created
this.activateWith(context.route, context.resolver || null);
}
}
}
};
Object.defineProperty(RouterOutlet.prototype, "locationInjector", {
/**
* @deprecated since v4 *
* @return {?}
*/
get: function () { return this.location.injector; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "locationFactoryResolver", {
/**
* @deprecated since v4 *
* @return {?}
*/
get: function () { return this.resolver; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "isActivated", {
/**
* @return {?}
*/
get: function () { return !!this.activated; },
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "component", {
/**
* @return {?}
*/
get: function () {
if (!this.activated)
throw new Error('Outlet is not activated');
return this.activated.instance;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "activatedRoute", {
/**
* @return {?}
*/
get: function () {
if (!this.activated)
throw new Error('Outlet is not activated');
return (this._activatedRoute);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RouterOutlet.prototype, "activatedRouteData", {
/**
* @return {?}
*/
get: function () {
if (this._activatedRoute) {
return this._activatedRoute.snapshot.data;
}
return {};
},
enumerable: true,
configurable: true
});
/**
* Called when the `RouteReuseStrategy` instructs to detach the subtree
* @return {?}
*/
RouterOutlet.prototype.detach = function () {
if (!this.activated)
throw new Error('Outlet is not activated');
this.location.detach();
var /** @type {?} */ cmp = this.activated;
this.activated = null;
this._activatedRoute = null;
return cmp;
};
/**
* Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
* @param {?} ref
* @param {?} activatedRoute
* @return {?}
*/
RouterOutlet.prototype.attach = function (ref, activatedRoute) {
this.activated = ref;
this._activatedRoute = activatedRoute;
this.location.insert(ref.hostView);
};
/**
* @return {?}
*/
RouterOutlet.prototype.deactivate = function () {
if (this.activated) {
var /** @type {?} */ c = this.component;
this.activated.destroy();
this.activated = null;
this._activatedRoute = null;
this.deactivateEvents.emit(c);
}
};
/**
* @param {?} activatedRoute
* @param {?} resolver
* @return {?}
*/
RouterOutlet.prototype.activateWith = function (activatedRoute, resolver) {
if (this.isActivated) {
throw new Error('Cannot activate an already activated outlet');
}
this._activatedRoute = activatedRoute;
var /** @type {?} */ snapshot = activatedRoute._futureSnapshot;
var /** @type {?} */ component = (((snapshot._routeConfig)).component);
resolver = resolver || this.resolver;
var /** @type {?} */ factory = resolver.resolveComponentFactory(component);
var /** @type {?} */ childContexts = this.parentContexts.getOrCreateContext(this.name).children;
var /** @type {?} */ injector = new OutletInjector(activatedRoute, childContexts, this.location.injector);
this.activated = this.location.createComponent(factory, this.location.length, injector);
// Calling `markForCheck` to make sure we will run the change detection when the
// `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
this.changeDetector.markForCheck();
this.activateEvents.emit(this.activated.instance);
};
return RouterOutlet;
}());
RouterOutlet.decorators = [
{ type: _angular_core.Directive, args: [{ selector: 'router-outlet', exportAs: 'outlet' },] },
];
/**
* @nocollapse
*/
RouterOutlet.ctorParameters = function () { return [
{ type: ChildrenOutletContexts, },
{ type: _angular_core.ViewContainerRef, },
{ type: _angular_core.ComponentFactoryResolver, },
{ type: undefined, decorators: [{ type: _angular_core.Attribute, args: ['name',] },] },
{ type: _angular_core.ChangeDetectorRef, },
]; };
RouterOutlet.propDecorators = {
'activateEvents': [{ type: _angular_core.Output, args: ['activate',] },],
'deactivateEvents': [{ type: _angular_core.Output, args: ['deactivate',] },],
};
var OutletInjector = (function () {
/**
* @param {?} route
* @param {?} childContexts
* @param {?} parent
*/
function OutletInjector(route, childContexts, parent) {
this.route = route;
this.childContexts = childContexts;
this.parent = parent;
}
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
OutletInjector.prototype.get = function (token, notFoundValue) {
if (token === ActivatedRoute) {
return this.route;
}
if (token === ChildrenOutletContexts) {
return this.childContexts;
}
return this.parent.get(token, notFoundValue);
};
return OutletInjector;
}());
/**
*@license
*Copyright Google Inc. All Rights Reserved.
*
*Use of this source code is governed by an MIT-style license that can be
*found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Provides a preloading strategy.
*
* \@experimental
* @abstract
*/
var PreloadingStrategy = (function () {
function PreloadingStrategy() {
}
/**
* @abstract
* @param {?} route
* @param {?} fn
* @return {?}
*/
PreloadingStrategy.prototype.preload = function (route, fn) { };
return PreloadingStrategy;
}());
/**
* \@whatItDoes Provides a preloading strategy that preloads all modules as quickly as possible.
*
* \@howToUse
*
* ```
* RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
* ```
*
* \@experimental
*/
var PreloadAllModules = (function () {
function PreloadAllModules() {
}
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
PreloadAllModules.prototype.preload = function (route, fn) {
return rxjs_operator_catch._catch.call(fn(), function () { return rxjs_observable_of.of(null); });
};
return PreloadAllModules;
}());
/**
* \@whatItDoes Provides a preloading strategy that does not preload any modules.
*
* \@description
*
* This strategy is enabled by default.
*
* \@experimental
*/
var NoPreloading = (function () {
function NoPreloading() {
}
/**
* @param {?} route
* @param {?} fn
* @return {?}
*/
NoPreloading.prototype.preload = function (route, fn) { return rxjs_observable_of.of(null); };
return NoPreloading;
}());
/**
* The preloader optimistically loads all router configurations to
* make navigations into lazily-loaded sections of the application faster.
*
* The preloader runs in the background. When the router bootstraps, the preloader
* starts listening to all navigation events. After every such event, the preloader
* will check if any configurations can be loaded lazily.
*
* If a route is protected by `canLoad` guards, the preloaded will not load it.
*
* \@stable
*/
var RouterPreloader = (function () {
/**
* @param {?} router
* @param {?} moduleLoader
* @param {?} compiler
* @param {?} injector
* @param {?} preloadingStrategy
*/
function RouterPreloader(router, moduleLoader, compiler, injector, preloadingStrategy) {
this.router = router;
this.injector = injector;
this.preloadingStrategy = preloadingStrategy;
var onStartLoad = function (r) { return router.triggerEvent(new RouteConfigLoadStart(r)); };
var onEndLoad = function (r) { return router.triggerEvent(new RouteConfigLoadEnd(r)); };
this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad);
}
/**
* @return {?}
*/
RouterPreloader.prototype.setUpPreloading = function () {
var _this = this;
var /** @type {?} */ navigations$ = rxjs_operator_filter.filter.call(this.router.events, function (e) { return e instanceof NavigationEnd; });
this.subscription = rxjs_operator_concatMap.concatMap.call(navigations$, function () { return _this.preload(); }).subscribe(function () { });
};
/**
* @return {?}
*/
RouterPreloader.prototype.preload = function () {
var /** @type {?} */ ngModule = this.injector.get(_angular_core.NgModuleRef);
return this.processRoutes(ngModule, this.router.config);
};
/**
* @return {?}
*/
RouterPreloader.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
/**
* @param {?} ngModule
* @param {?} routes
* @return {?}
*/
RouterPreloader.prototype.processRoutes = function (ngModule, routes) {
var /** @type {?} */ res = [];
for (var _i = 0, routes_5 = routes; _i < routes_5.length; _i++) {
var route = routes_5[_i];
// we already have the config loaded, just recurse
if (route.loadChildren && !route.canLoad && route._loadedConfig) {
var /** @type {?} */ childConfig = route._loadedConfig;
res.push(this.processRoutes(childConfig.module, childConfig.routes));
// no config loaded, fetch the config
}
else if (route.loadChildren && !route.canLoad) {
res.push(this.preloadConfig(ngModule, route));
// recurse into children
}
else if (route.children) {
res.push(this.processRoutes(ngModule, route.children));
}
}
return rxjs_operator_mergeAll.mergeAll.call(rxjs_observable_from.from(res));
};
/**
* @param {?} ngModule
* @param {?} route
* @return {?}
*/
RouterPreloader.prototype.preloadConfig = function (ngModule, route) {
var _this = this;
return this.preloadingStrategy.preload(route, function () {
var /** @type {?} */ loaded$ = _this.loader.load(ngModule.injector, route);
return rxjs_operator_mergeMap.mergeMap.call(loaded$, function (config) {
route._loadedConfig = config;
return _this.processRoutes(config.module, config.routes);
});
});
};
return RouterPreloader;
}());
RouterPreloader.decorators = [
{ type: _angular_core.Injectable },
];
/**
* @nocollapse
*/
RouterPreloader.ctorParameters = function () { return [
{ type: Router, },
{ type: _angular_core.NgModuleFactoryLoader, },
{ type: _angular_core.Compiler, },
{ type: _angular_core.Injector, },
{ type: PreloadingStrategy, },
]; };
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes Contains a list of directives
* \@stable
*/
var ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* \@whatItDoes Is used in DI to configure the router.
* \@stable
*/
var ROUTER_CONFIGURATION = new _angular_core.InjectionToken('ROUTER_CONFIGURATION');
/**
* \@docsNotRequired
*/
var ROUTER_FORROOT_GUARD = new _angular_core.InjectionToken('ROUTER_FORROOT_GUARD');
var ROUTER_PROVIDERS = [
_angular_common.Location,
{ provide: UrlSerializer, useClass: DefaultUrlSerializer },
{
provide: Router,
useFactory: setupRouter,
deps: [
_angular_core.ApplicationRef, UrlSerializer, ChildrenOutletContexts, _angular_common.Location, _angular_core.Injector,
_angular_core.NgModuleFactoryLoader, _angular_core.Compiler, ROUTES, ROUTER_CONFIGURATION,
[UrlHandlingStrategy, new _angular_core.Optional()], [RouteReuseStrategy, new _angular_core.Optional()]
]
},
ChildrenOutletContexts,
{ provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
{ provide: _angular_core.NgModuleFactoryLoader, useClass: _angular_core.SystemJsNgModuleLoader },
RouterPreloader,
NoPreloading,
PreloadAllModules,
{ provide: ROUTER_CONFIGURATION, useValue: { enableTracing: false } },
];
/**
* @return {?}
*/
function routerNgProbeToken() {
return new _angular_core.NgProbeToken('Router', Router);
}
/**
* \@whatItDoes Adds router directives and providers.
*
* \@howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* \@NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* \@stable
*/
var RouterModule = (function () {
/**
* @param {?} guard
* @param {?} router
*/
function RouterModule(guard, router) {
}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
* @param {?} routes
* @param {?=} config
* @return {?}
*/
RouterModule.forRoot = function (routes, config) {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new _angular_core.Optional(), new _angular_core.SkipSelf()]]
},
{ provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
{
provide: _angular_common.LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
_angular_common.PlatformLocation, [new _angular_core.Inject(_angular_common.APP_BASE_HREF), new _angular_core.Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{ provide: _angular_core.NgProbeToken, multi: true, useFactory: routerNgProbeToken },
provideRouterInitializer(),
],
};
};
/**
* Creates a module with all the router directives and a provider registering routes.
* @param {?} routes
* @return {?}
*/
RouterModule.forChild = function (routes) {
return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
};
return RouterModule;
}());
RouterModule.decorators = [
{ type: _angular_core.NgModule, args: [{ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES },] },
];
/**
* @nocollapse
*/
RouterModule.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Inject, args: [ROUTER_FORROOT_GUARD,] },] },
{ type: Router, decorators: [{ type: _angular_core.Optional },] },
]; };
/**
* @param {?} platformLocationStrategy
* @param {?} baseHref
* @param {?=} options
* @return {?}
*/
function provideLocationStrategy(platformLocationStrategy, baseHref, options) {
if (options === void 0) { options = {}; }
return options.useHash ? new _angular_common.HashLocationStrategy(platformLocationStrategy, baseHref) :
new _angular_common.PathLocationStrategy(platformLocationStrategy, baseHref);
}
/**
* @param {?} router
* @return {?}
*/
function provideForRootGuard(router) {
if (router) {
throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");
}
return 'guarded';
}
/**
* \@whatItDoes Registers routes.
*
* \@howToUse
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@stable
* @param {?} routes
* @return {?}
*/
function provideRoutes(routes) {
return [
{ provide: _angular_core.ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes },
{ provide: ROUTES, multi: true, useValue: routes },
];
}
/**
* @param {?} ref
* @param {?} urlSerializer
* @param {?} contexts
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
* @param {?=} opts
* @param {?=} urlHandlingStrategy
* @param {?=} routeReuseStrategy
* @return {?}
*/
function setupRouter(ref, urlSerializer, contexts, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) {
if (opts === void 0) { opts = {}; }
var /** @type {?} */ router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
var /** @type {?} */ dom_1 = _angular_platformBrowser.ɵgetDOM();
router.events.subscribe(function (e) {
dom_1.logGroup("Router Event: " + ((e.constructor)).name);
dom_1.log(e.toString());
dom_1.log(e);
dom_1.logGroupEnd();
});
}
return router;
}
/**
* @param {?} router
* @return {?}
*/
function rootRoute(router) {
return router.routerState.root;
}
/**
* To initialize the router properly we need to do in two steps:
*
* We need to start the navigation in a APP_INITIALIZER to block the bootstrap if
* a resolver or a guards executes asynchronously. Second, we need to actually run
* activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation
* hook provided by the router to do that.
*
* The router navigation starts, reaches the point when preactivation is done, and then
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
*/
var RouterInitializer = (function () {
/**
* @param {?} injector
*/
function RouterInitializer(injector) {
this.injector = injector;
this.initNavigation = false;
this.resultOfPreactivationDone = new rxjs_Subject.Subject();
}
/**
* @return {?}
*/
RouterInitializer.prototype.appInitializer = function () {
var _this = this;
var /** @type {?} */ p = this.injector.get(_angular_common.LOCATION_INITIALIZED, Promise.resolve(null));
return p.then(function () {
var /** @type {?} */ resolve = ((null));
var /** @type {?} */ res = new Promise(function (r) { return resolve = r; });
var /** @type {?} */ router = _this.injector.get(Router);
var /** @type {?} */ opts = _this.injector.get(ROUTER_CONFIGURATION);
if (_this.isLegacyDisabled(opts) || _this.isLegacyEnabled(opts)) {
resolve(true);
}
else if (opts.initialNavigation === 'disabled') {
router.setUpLocationChangeListener();
resolve(true);
}
else if (opts.initialNavigation === 'enabled') {
router.hooks.afterPreactivation = function () {
// only the initial navigation should be delayed
if (!_this.initNavigation) {
_this.initNavigation = true;
resolve(true);
return _this.resultOfPreactivationDone;
// subsequent navigations should not be delayed
}
else {
return (rxjs_observable_of.of(null));
}
};
router.initialNavigation();
}
else {
throw new Error("Invalid initialNavigation options: '" + opts.initialNavigation + "'");
}
return res;
});
};
/**
* @param {?} bootstrappedComponentRef
* @return {?}
*/
RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) {
var /** @type {?} */ opts = this.injector.get(ROUTER_CONFIGURATION);
var /** @type {?} */ preloader = this.injector.get(RouterPreloader);
var /** @type {?} */ router = this.injector.get(Router);
var /** @type {?} */ ref = this.injector.get(_angular_core.ApplicationRef);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
if (this.isLegacyEnabled(opts)) {
router.initialNavigation();
}
else if (this.isLegacyDisabled(opts)) {
router.setUpLocationChangeListener();
}
preloader.setUpPreloading();
router.resetRootComponentType(ref.componentTypes[0]);
this.resultOfPreactivationDone.next(/** @type {?} */ ((null)));
this.resultOfPreactivationDone.complete();
};
/**
* @param {?} opts
* @return {?}
*/
RouterInitializer.prototype.isLegacyEnabled = function (opts) {
return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true ||
opts.initialNavigation === undefined;
};
/**
* @param {?} opts
* @return {?}
*/
RouterInitializer.prototype.isLegacyDisabled = function (opts) {
return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false;
};
return RouterInitializer;
}());
RouterInitializer.decorators = [
{ type: _angular_core.Injectable },
];
/**
* @nocollapse
*/
RouterInitializer.ctorParameters = function () { return [
{ type: _angular_core.Injector, },
]; };
/**
* @param {?} r
* @return {?}
*/
function getAppInitializer(r) {
return r.appInitializer.bind(r);
}
/**
* @param {?} r
* @return {?}
*/
function getBootstrapListener(r) {
return r.bootstrapListener.bind(r);
}
/**
* A token for the router initializer that will be called after the app is bootstrapped.
*
* \@experimental
*/
var ROUTER_INITIALIZER = new _angular_core.InjectionToken('Router Initializer');
/**
* @return {?}
*/
function provideRouterInitializer() {
return [
RouterInitializer,
{
provide: _angular_core.APP_INITIALIZER,
multi: true,
useFactory: getAppInitializer,
deps: [RouterInitializer]
},
{ provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
{ provide: _angular_core.APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER },
];
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
var VERSION = new _angular_core.Version('4.2.6');
exports.RouterLink = RouterLink;
exports.RouterLinkWithHref = RouterLinkWithHref;
exports.RouterLinkActive = RouterLinkActive;
exports.RouterOutlet = RouterOutlet;
exports.NavigationCancel = NavigationCancel;
exports.NavigationEnd = NavigationEnd;
exports.NavigationError = NavigationError;
exports.NavigationStart = NavigationStart;
exports.RouteConfigLoadEnd = RouteConfigLoadEnd;
exports.RouteConfigLoadStart = RouteConfigLoadStart;
exports.RoutesRecognized = RoutesRecognized;
exports.RouteReuseStrategy = RouteReuseStrategy;
exports.Router = Router;
exports.ROUTES = ROUTES;
exports.ROUTER_CONFIGURATION = ROUTER_CONFIGURATION;
exports.ROUTER_INITIALIZER = ROUTER_INITIALIZER;
exports.RouterModule = RouterModule;
exports.provideRoutes = provideRoutes;
exports.ChildrenOutletContexts = ChildrenOutletContexts;
exports.OutletContext = OutletContext;
exports.NoPreloading = NoPreloading;
exports.PreloadAllModules = PreloadAllModules;
exports.PreloadingStrategy = PreloadingStrategy;
exports.RouterPreloader = RouterPreloader;
exports.ActivatedRoute = ActivatedRoute;
exports.ActivatedRouteSnapshot = ActivatedRouteSnapshot;
exports.RouterState = RouterState;
exports.RouterStateSnapshot = RouterStateSnapshot;
exports.PRIMARY_OUTLET = PRIMARY_OUTLET;
exports.convertToParamMap = convertToParamMap;
exports.UrlHandlingStrategy = UrlHandlingStrategy;
exports.DefaultUrlSerializer = DefaultUrlSerializer;
exports.UrlSegment = UrlSegment;
exports.UrlSegmentGroup = UrlSegmentGroup;
exports.UrlSerializer = UrlSerializer;
exports.UrlTree = UrlTree;
exports.VERSION = VERSION;
exports.ɵROUTER_PROVIDERS = ROUTER_PROVIDERS;
exports.ɵflatten = flatten;
exports.ɵa = ROUTER_FORROOT_GUARD;
exports.ɵg = RouterInitializer;
exports.ɵh = getAppInitializer;
exports.ɵi = getBootstrapListener;
exports.ɵd = provideForRootGuard;
exports.ɵc = provideLocationStrategy;
exports.ɵj = provideRouterInitializer;
exports.ɵf = rootRoute;
exports.ɵb = routerNgProbeToken;
exports.ɵe = setupRouter;
exports.ɵk = Tree;
exports.ɵl = TreeNode;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=router.umd.js.map
|
(function(forp, $){
/**
* BarChart Class
*/
forp.BarChart = function(conf) {
forp.Graph.call(this, conf);
this.tmp = null;
this.restore = function() {
if(this.tmp) {
this.ctx.clearRect(0, 0, this.element.width, this.element.height);
this.ctx.drawImage(this.tmp, 0, 0);
}
};
this.highlight = function(idx) {
if(!this.tmp) {
this.tmp = document.createElement('canvas');
this.tmp.width = this.element.width;
this.tmp.height = this.element.height;
this.tmp.style.width = '100%';
this.tmp.style.height = '100px';
var context = this.tmp.getContext('2d');
context.drawImage(this.element, 0, 0);
}
this.ctx.beginPath();
this.ctx.strokeStyle = '#4D90FE';
this.ctx.lineWidth = 60;
this.ctx.moveTo(idx, this.conf.yaxis.length);
this.ctx.lineTo(
idx,
this.conf.yaxis.length -
(
(this.conf.val.call(this, idx) * 100) /
this.conf.yaxis.max
)
);
this.ctx.closePath();
this.ctx.stroke();
};
this.draw = function() {
if(!this.drawn) {
this.drawn = true;
var len = this.datas.length;
this.element.width = document.body.clientWidth*2;
this.element.height = this.conf.yaxis.length;
this.element.style.width = '100%';
this.element.style.height = this.conf.yaxis.length + 'px';
this.element.style.marginBottom = '-3px';
this.element.style.backgroundColor = '#333';
var x = 0;
for(var i = 0; i < len; i++) {
this.ctx.beginPath();
this.ctx.strokeStyle = this.conf.color.call(this, i);
this.ctx.lineWidth = 50;
this.ctx.moveTo(
x, 25
);
this.ctx.lineTo(
x += (
(this.conf.val.call(this, i) * this.element.width) /
this.conf.xaxis.max
) +2,
25
);
this.ctx.closePath();
this.ctx.stroke();
}
if(this.conf.mousemove) {
var self = this;
this.bind(
'mousemove',
function(e) {
self.conf.mousemove.call(self,e);
}
)
}
}
return this;
};
};
})(forp, jMicro);
|
const Parse = require('./parser');
describe('test_parse', () => {
describe('test_parse_key_values', () => {
it('should return the key values specified in the config from the body', () => {
const config = {
keys: ['to', 'from'],
};
const request = {
body: {
to: 'inbound@inbound.example.com',
from: 'Test User <test@example.com>',
subject: 'Test Subject',
},
};
const parse = new Parse(config, request);
const keyValues = parse.keyValues();
const expectedValues = {
to: 'inbound@inbound.example.com',
from: 'Test User <test@example.com>',
};
expect(keyValues).to.be.an('object');
expect(keyValues).to.deep.equal(expectedValues);
});
it('should return the key values specified in the config from the payload', () => {
const config = {
keys: ['to', 'from'],
};
const request = {
payload: {
to: 'inbound@inbound.example.com',
from: 'Test User <test@example.com>',
subject: 'Test Subject',
},
};
const parse = new Parse(config, request);
const keyValues = parse.keyValues();
const expectedValues = {
to: 'inbound@inbound.example.com',
from: 'Test User <test@example.com>',
};
expect(keyValues).to.be.an('object');
expect(keyValues).to.deep.equal(expectedValues);
});
});
describe('test_parse_get_raw_email', () => {
it('should return null if no raw email property in payload', (done) => {
const parse = new Parse({}, {});
function callback(email) {
expect(email).to.be.null();
done();
}
parse.getRawEmail(callback);
});
it('should parse raw email from payload and return a mail object', (done) => {
const request = {
body: {
email: 'MIME-Version: 1.0\r\nReceived: by 0.0.0.0 with HTTP; Wed, 10 Aug 2016 14:44:21 -0700 (PDT)\r\nFrom: Example User <test@example.com>\r\nDate: Wed, 10 Aug 2016 14:44:21 -0700\r\nSubject: Inbound Parse Test Raw Data\r\nTo: inbound@inbound.inbound.com\r\nContent-Type: multipart/alternative; boundary=001a113ee97c89842f0539be8e7a\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nHello Twilio SendGrid!\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n<html><body><strong>Hello Twilio SendGrid!</body></html>\r\n\r\n--001a113ee97c89842f0539be8e7a--\r\n',
},
};
const parse = new Parse({}, request);
function callback(email) {
expect(email).to.be.an('object');
done();
}
parse.getRawEmail(callback);
});
});
});
|
var Connection = require(['tedious']).Connection;
var config = {
userName: 'masproject2017',
password: 'MAS.2017',
server: 'masproject.database.windows.net',
// If you are on Microsoft Azure, you need this:
options: { encrypt: true, database: 'AdventureWorks' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
});
|
const PlayerError = require('./errors.js').UnknownPlayerIdException;
const Player = require('./player.js');
const Map = require('./map.js');
const Resources = require('./resources.js');
const Virus = require('./virus.js');
class Game {
constructor(playerId, id, tick, timeLeft, players, resources, map, viruses) {
this.id = id;
this.tick = tick;
this.timeLeft = timeLeft;
this.players = players;
this.resources = resources;
this.map = map;
this.viruses = viruses;
this.me = players.find(p => p.id === playerId);
if(this.me === undefined) {
throw new PlayerError();
}
this.enemies = players.filter(p => p.id !== playerId);
}
static parse(payload, playerId) {
return new Game(
playerId,
payload.id,
payload.tick,
payload.timeLeft,
payload.players.map(p => Player.parse(p)),
Resources.parse(payload.resources),
Map.parse(payload.map),
payload.viruses.map(v => Virus.parse(v))
);
}
static get RANKED_GAME_ID() {
return -1;
}
static get UPDATE_PER_SECOND() {
return 3;
}
get actions() {
return this.me.actions;
}
}
module.exports = Game;
|
var assert = require("assert")
var RequestSet = require("../lib/request_set")
var node = {
request: function () {}
}
var unhealthy = {
request: function (options, callback) { callback({ message: 'no nodes'}) }
}
function succeeding_request(options, cb) {
return cb(null, {}, "foo")
}
function failing_request(options, cb) {
return cb({
message: "crap",
reason: "ihateyou"
})
}
function hangup_request(options, cb) {
return cb({
message: "hang up",
reason: "socket hang up"
})
}
function aborted_request(options, cb) {
return cb({
message: "aborted",
reason: "aborted"
})
}
var pool = {
options: { maxRetries: 5 },
get_node: function () {
return node
},
onRetry: function () {},
length: 3
}
describe("RequestSet", function () {
it("defaults attempt count to at least 2", function () {
var r = new RequestSet({length: 1, options: { maxRetries: 5 }}, {}, null)
assert.equal(r.attempts, 2)
})
it("defaults attempt count to at most maxRetries + 1", function () {
var r = new RequestSet({length: 9, options: { maxRetries: 4 }}, {}, null)
assert.equal(r.attempts, 5)
})
it("defaults attempt count to pool.length", function () {
var r = new RequestSet({length: 4, options: { maxRetries: 5 }}, {}, null)
assert.equal(r.attempts, 4)
})
describe("request()", function () {
it("calls the callback on success", function (done) {
node.request = succeeding_request
RequestSet.request(pool, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("calls the callback on error", function (done) {
node.request = failing_request
RequestSet.request(pool, {}, function (err, res, body) {
assert.equal(err.message, "crap")
done()
})
})
it("calls the callback with a 'no nodes' error when there's no nodes to service the request", function (done) {
var p = {
options: { maxRetries: 5 },
get_node: function () { return unhealthy },
length: 0,
onRetry: function () {}
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.message, "no nodes")
done()
})
})
it("retries hangups once", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 2,
nodes: [{ request: hangup_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("retries hangups once then fails", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: hangup_request }, { request: hangup_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "socket hang up")
done()
})
})
it("retries aborts once", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 2,
nodes: [{ request: aborted_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
it("retries aborts once then fails", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: aborted_request }, { request: aborted_request }, { request: succeeding_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "aborted")
done()
})
})
it("retries up to this.attempts times", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 3,
nodes: [{ request: failing_request }, { request: failing_request }, { request: aborted_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err.reason, "aborted")
done()
})
})
it("retries up to the first success", function (done) {
var p = {
i: 0,
options: { maxRetries: 5 },
get_node: function () { return this.nodes[this.i++]},
onRetry: function () {},
length: 4,
nodes: [{ request: failing_request }, { request: failing_request }, { request: succeeding_request }, { request: failing_request }]
}
RequestSet.request(p, {}, function (err, res, body) {
assert.equal(err, null)
assert.equal(body, "foo")
done()
})
})
})
})
|
/**
* Created by sakura on 16/3/28.
*/
// $(function () {
// $('#myTab a:last').tab("show");
// })
document.getElementById("btn-normal").disabled = '';
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.7-5-b-84
description: >
Object.defineProperties - 'descObj' is the global object which
implements its own [[Get]] method to get 'configurable' property
(8.10.5 step 4.a)
includes:
- runTestCase.js
- fnGlobalObject.js
---*/
function testcase() {
var obj = {};
try {
fnGlobalObject().configurable = true;
Object.defineProperties(obj, {
prop: fnGlobalObject()
});
var result1 = obj.hasOwnProperty("prop");
delete obj.prop;
var result2 = obj.hasOwnProperty("prop");
return result1 === true && result2 === false;
} finally {
delete fnGlobalObject().configurable;
}
}
runTestCase(testcase);
|
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
function min() {
return ["female", 24];
}
let foo = Helper.namespace(function() {
const [gender, age] = min();
return {
gender: gender,
age: age
};
});
console.log(foo.age);
console.log(Helper.toString(foo.gender));
};
|
module.exports = {
SearchClient: require("./ddg/search-client")
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _validator = require('validator');
var _findOrCreatePlugin = require('./find-or-create-plugin');
var _findOrCreatePlugin2 = _interopRequireDefault(_findOrCreatePlugin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Schema = _mongoose2.default.Schema;
var userSchema = new Schema({
id: {
type: String,
required: true,
match: /\d+/
},
displayName: { type: String, required: true, match: /^([A-Za-z]+((\s[A-Za-z]+)+)?)$/ },
emails: [{ value: {
type: String,
required: true,
unique: true,
validate: [{ validator: function validator(value) {
return (0, _validator.isEmail)(value);
}, message: 'Invalid email.' }]
} }],
photos: [{ value: { type: String, validate: { validator: _validator.isURL } } }]
});
userSchema.plugin(_findOrCreatePlugin2.default);
var User = _mongoose2.default.model('User', userSchema);
exports.default = User;
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports BMNGOneImageLayer
* @version $Id: BMNGOneImageLayer.js 2942 2015-03-30 21:16:36Z tgaskins $
*/
define([
'../layer/RenderableLayer',
'../geom/Sector',
'../shapes/SurfaceImage',
'../util/WWUtil'
],
function (RenderableLayer,
Sector,
SurfaceImage,
WWUtil) {
"use strict";
/**
* Constructs a Blue Marble image layer that spans the entire globe.
* @alias BMNGOneImageLayer
* @constructor
* @augments RenderableLayer
* @classdesc Displays a Blue Marble image layer that spans the entire globe with a single image.
*/
var BMNGOneImageLayer = function () {
RenderableLayer.call(this, "Blue Marble Image");
var surfaceImage = new SurfaceImage(Sector.FULL_SPHERE,
WorldWind.configuration.baseUrl + "images/BMNG_world.topo.bathy.200405.3.2048x1024.jpg");
this.addRenderable(surfaceImage);
this.pickEnabled = false;
this.minActiveAltitude = 3e6;
};
BMNGOneImageLayer.prototype = Object.create(RenderableLayer.prototype);
return BMNGOneImageLayer;
});
|
var SimpleSuperclass = Hotcake.define(SimpleSuperclass,
{
ctor: function ()
{
this.value = 100;
},
incrementReturn: function ()
{
this.value += 100;
return this.value;
}
});
var SimpleSubclass = Hotcake.define(SimpleSubclass,
{
returnValue: function ()
{
return -11;
}
}, SimpleSuperclass);
var SimpleSubclass2 = Hotcake.define(SimpleSubclass,
{
returnNothing: function ()
{
return -1999;
}
}, SimpleSubclass2);
|
enyo.kind({
name: "bootstrap.Breadcrumb",
tag: "ul",
classes: "breadcrumb",
defaultKind: "bootstrap.MenuItem",
});
|
'use strict';
module.exports = {
"plugins": [],
"recurseDepth": 10,
"source": {
"includePattern": ".+\\.js(doc|x)?$",
"excludePattern": "(^|\\/|\\\\)_"
},
"sourceType": "module",
"tags": {
"allowUnknownTags": true,
"dictionaries": ["jsdoc","closure"]
},
"templates": {
"cleverLinks": false,
"monospaceLinks": false,
"default": {
"outputSourceFiles": false,
"includeDate": false,
"useLongnameInNav": false
}
},
"opts": {
"template": "templates/default", // same as -t templates/default
//"template": "node_modules/tui-jsdoc-template",
//"template": "node_modules/docdash",
//"template": "node_modules/minami",
//"template": "node_modules/postman-jsdoc-theme",
//"template": "node_modules/jaguarjs-jsdoc",
"encoding": "utf8", // same as -e utf8
"destination": "./docs/", // same as -d ./out/
"recurse": true, // same as -r
"debug": true, // same as --debug
"readme": "./README.md"
//"package": "./package.json", // same as --package
//"tutorials": "./tutorials/" // same as -u path/to/tutorials
}
};
|
import * as actions from './actions';
import mutations from './mutations';
import getters from './getters';
const state = {
transactions: [],
businesses: []
};
export default {
state,
actions,
mutations,
getters
};
|
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, .1, 1000 );
var renderer = new THREE.WebGLRenderer();
var container = document.getElementById('container');
container.appendChild(renderer.domElement);
renderer.setSize(window.innerWidth, window.innerHeight);
var loader = new THREE.STLLoader();
loader.load('../data/MonkeyBrain.stl', function(geometry) {
console.log(geometry)
var material = new THREE.MeshNormalMaterial({visible: true, transparent: true, opacity: 0.5});
// var material = new THREE.MeshBasicMaterial({visible: true, wireframe:true});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer.render(scene, camera);
});
|
function registerListeners() {
window.addEventListener("keydown", function(event) {
switch (event.keyCode) {
case 87: // w
keyStatus[0] = true;
break;
case 65: // a
keyStatus[1] = true;
break;
case 83: // s
keyStatus[2] = true;
break;
case 68: // d
keyStatus[3] = true;
break;
}
}, false);
window.addEventListener("keyup", function(event) {
switch (event.keyCode) {
case 87: // w
keyStatus[0] = false;
break;
case 65: // a
keyStatus[1] = false;
break;
case 83: // s
keyStatus[2] = false;
break;
case 68: // d
keyStatus[3] = false;
break;
}
}, false);
}
|
export class Validation {
constructor() {
this.errors = [];
}
get validationArray() {
return [];
}
get valid() {
let self = this;
return this.validationArray.reduce((isValid, isPartValid) => {
if(!isPartValid) return isValid;
if (typeof isPartValid.valid === 'boolean' && !isPartValid.valid) {
self.errors.push(isPartValid);
}
return isValid && isPartValid.valid;
}, true);
}
addErrors(newErrors) {
let self = this;
newErrors.forEach((errorObj) => {
self.errors.push(errorObj)
})
}
};
|
var helper = require('../support/spec_helper');
var ORM = require('../../');
describe("Model keys option", function () {
var db = null;
before(function () {
db = helper.connect();
});
after(function () {
return db.closeSync();
});
describe("if model id is a property", function () {
var Person = null;
before(function () {
Person = db.define("person", {
uid: String,
name: String,
surname: String
}, {
id: "uid"
});
return helper.dropSync(Person);
});
it("should not auto increment IDs", function () {
var JohnDoe = Person.createSync({
uid: "john-doe",
name: "John",
surname: "Doe"
});
assert.equal(JohnDoe.uid, "john-doe");
assert.notProperty(JohnDoe, "id");
});
});
describe("if model defines several keys", function () {
var DoorAccessHistory = null;
before(function () {
DoorAccessHistory = db.define("door_access_history", {
year: {
type: 'integer'
},
month: {
type: 'integer'
},
day: {
type: 'integer'
},
user: String,
action: ["in", "out"]
}, {
id: ["year", "month", "day"]
});
return helper.dropSync(DoorAccessHistory, function () {
DoorAccessHistory.createSync([{
year: 2013,
month: 7,
day: 11,
user: "dresende",
action: "in"
},
{
year: 2013,
month: 7,
day: 12,
user: "dresende",
action: "out"
}
]);
});
});
it("should make possible to get instances based on all keys", function () {
var HistoryItem = DoorAccessHistory.getSync(2013, 7, 11);
assert.equal(HistoryItem.year, 2013);
assert.equal(HistoryItem.month, 7);
assert.equal(HistoryItem.day, 11);
assert.equal(HistoryItem.user, "dresende");
assert.equal(HistoryItem.action, "in");
});
it("should make possible to remove instances based on all keys", function () {
var HistoryItem = DoorAccessHistory.getSync(2013, 7, 12);
HistoryItem.removeSync();
var exists = DoorAccessHistory.existsSync(2013, 7, 12);
assert.isFalse(exists);
});
});
});
|
function loadProjects(loadTarget) {
console.log(loadTarget);
$('.filter li').removeClass();
$('#filter-' + loadTarget).addClass('active');
var isLoaded = true;
switch (loadTarget) {
case 'all':
renderProjects(featured);
$('.load-more').removeClass('display-none');
$('.more-work').removeClass('isLoaded');
isLoaded = false;
break;
case 'all-more':
addProjects();
$('#filter-all').addClass('active');
break;
case 'design':
renderProjects(design);
break;
case 'dev':
renderProjects(dev);
break;
case 'hackathon':
renderProjects(hackathon);
break;
}
if (isLoaded) {
$('.load-more').addClass('display-none');
$('.more-work').addClass('isLoaded');
}
}
function renderProjects(projects) {
$('.js-project--container').html('');
$('.js-project--container').html(projects);
}
function addProjects() {
$('.js-project--container').append(all);
}
|
require('dotenv').config();
const api_key = process.env.MAILGUN_API_KEY;
const domain = process.env.MAILGUN_DOMAIN;
const mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
const list = mailgun.lists('subscriberlist@example.com');
const data = {
from: 'Dylan <me@me.com>',
to: 'dylantoyne@gmail.com',
subject: 'Testing',
text: 'Testing, Testing, Testing'
};
list.info((err, data) => {
// 'data' is mailing list info
console.log(data);
});
let user = {
subscribed: true,
address: 'dylantoyne@gmail.com',
name: 'Dylan',
moreInfo: {age: 24}
};
list.members().create(bob, ((err, data) => {
// 'data is the members details'
console.log(data);
});
list.members().list((err, members) => {
console.log(members);
});
list.members('dylan@gmail.com').update({name: 'John' }, (err, body) => {
console.log(body);
});
mailgun.lists('dylan@gmail.com').members().add({ members: members, subscribed: true }, (err, body) => {
console.log(body);
});
const sendMail = (id, email) => {
mailgun.messages().send(data(id, email), (error, body) => {
if(error) {
console.log(error)
}
console.log(`Sending the email to ${email}. Email content: ${body}`);
})
};
module.exports = sendMail;
|
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
module.exports = {
generate: require("./lib/generate"),
createFixer: require("./lib/fixer"),
}
|
define([
'../core',
'../var/rnotwhite',
'./accepts'
], function (jQuery, rnotwhite) {
function Data () {
// Support: Android<4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty(this.cache = {}, 0, {
get: function () {
return {}
}
})
this.expando = jQuery.expando + Data.uid++
}
Data.uid = 1
Data.accepts = jQuery.acceptData
Data.prototype = {
key: function (owner) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if (!Data.accepts(owner)) {
return 0
}
var descriptor = {}
// Check if the owner object already has a cache key
var unlock = owner[this.expando]
// If not, create one
if (!unlock) {
unlock = Data.uid++
// Secure it in a non-enumerable, non-writable property
try {
descriptor[this.expando] = { value: unlock }
Object.defineProperties(owner, descriptor)
// Support: Android<4
// Fallback to a less secure definition
} catch (e) {
descriptor[this.expando] = unlock
jQuery.extend(owner, descriptor)
}
}
// Ensure the cache object
if (!this.cache[unlock]) {
this.cache[unlock] = {}
}
return unlock
},
set: function (owner, data, value) {
var prop
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
var unlock = this.key(owner)
var cache = this.cache[unlock]
// Handle: [ owner, key, value ] args
if (typeof data === 'string') {
cache[data] = value
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if (jQuery.isEmptyObject(cache)) {
jQuery.extend(this.cache[unlock], data)
// Otherwise, copy the properties one-by-one to the cache object
} else {
for (prop in data) {
cache[prop] = data[prop]
}
}
}
return cache
},
get: function (owner, key) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[this.key(owner)]
return key === undefined
? cache : cache[key]
},
access: function (owner, key, value) {
var stored
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if (key === undefined ||
((key && typeof key === 'string') && value === undefined)) {
stored = this.get(owner, key)
return stored !== undefined
? stored : this.get(owner, jQuery.camelCase(key))
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set(owner, key, value)
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key
},
remove: function (owner, key) {
var i; var name; var camel
var unlock = this.key(owner)
var cache = this.cache[unlock]
if (key === undefined) {
this.cache[unlock] = {}
} else {
// Support array or space separated string of keys
if (jQuery.isArray(key)) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat(key.map(jQuery.camelCase))
} else {
camel = jQuery.camelCase(key)
// Try the string as a key before any manipulation
if (key in cache) {
name = [key, camel]
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel
name = name in cache
? [name] : (name.match(rnotwhite) || [])
}
}
i = name.length
while (i--) {
delete cache[name[i]]
}
}
},
hasData: function (owner) {
return !jQuery.isEmptyObject(
this.cache[owner[this.expando]] || {}
)
},
discard: function (owner) {
if (owner[this.expando]) {
delete this.cache[owner[this.expando]]
}
}
}
return Data
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.