code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19.99 9.79c.51-.4.51-1.18 0-1.58l-6.76-5.26c-.72-.56-1.73-.56-2.46 0L9.41 4.02l7.88 7.88 2.7-2.11zm0 3.49l-.01-.01a.991.991 0 00-1.22 0l-.05.04 1.4 1.4c.37-.41.34-1.07-.12-1.43zm1.45 5.6L4.12 1.56a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41l3.52 3.52-2.22 1.72c-.51.4-.51 1.18 0 1.58l6.76 5.26c.72.56 1.73.56 2.46 0l.87-.68 1.42 1.42-2.92 2.27c-.36.28-.87.28-1.23 0l-6.15-4.78a.991.991 0 00-1.22 0c-.51.4-.51 1.17 0 1.57l6.76 5.26c.72.56 1.73.56 2.46 0l3.72-2.89 3.07 3.07c.39.39 1.02.39 1.41 0 .41-.39.41-1.02.02-1.41z" /> , 'LayersClearRounded');
kybarg/material-ui
packages/material-ui-icons/src/LayersClearRounded.js
JavaScript
mit
673
import { assign, forEach, isArray } from 'min-dash'; var abs= Math.abs, round = Math.round; var TOLERANCE = 10; export default function BendpointSnapping(eventBus) { function snapTo(values, value) { if (isArray(values)) { var i = values.length; while (i--) if (abs(values[i] - value) <= TOLERANCE) { return values[i]; } } else { values = +values; var rem = value % values; if (rem < TOLERANCE) { return value - rem; } if (rem > values - TOLERANCE) { return value - rem + values; } } return value; } function mid(element) { if (element.width) { return { x: round(element.width / 2 + element.x), y: round(element.height / 2 + element.y) }; } } // connection segment snapping ////////////////////// function getConnectionSegmentSnaps(context) { var snapPoints = context.snapPoints, connection = context.connection, waypoints = connection.waypoints, segmentStart = context.segmentStart, segmentStartIndex = context.segmentStartIndex, segmentEnd = context.segmentEnd, segmentEndIndex = context.segmentEndIndex, axis = context.axis; if (snapPoints) { return snapPoints; } var referenceWaypoints = [ waypoints[segmentStartIndex - 1], segmentStart, segmentEnd, waypoints[segmentEndIndex + 1] ]; if (segmentStartIndex < 2) { referenceWaypoints.unshift(mid(connection.source)); } if (segmentEndIndex > waypoints.length - 3) { referenceWaypoints.unshift(mid(connection.target)); } context.snapPoints = snapPoints = { horizontal: [] , vertical: [] }; forEach(referenceWaypoints, function(p) { // we snap on existing bendpoints only, // not placeholders that are inserted during add if (p) { p = p.original || p; if (axis === 'y') { snapPoints.horizontal.push(p.y); } if (axis === 'x') { snapPoints.vertical.push(p.x); } } }); return snapPoints; } eventBus.on('connectionSegment.move.move', 1500, function(event) { var context = event.context, snapPoints = getConnectionSegmentSnaps(context), x = event.x, y = event.y, sx, sy; if (!snapPoints) { return; } // snap sx = snapTo(snapPoints.vertical, x); sy = snapTo(snapPoints.horizontal, y); // correction x/y var cx = (x - sx), cy = (y - sy); // update delta assign(event, { dx: event.dx - cx, dy: event.dy - cy, x: sx, y: sy }); }); // bendpoint snapping ////////////////////// function getBendpointSnaps(context) { var snapPoints = context.snapPoints, waypoints = context.connection.waypoints, bendpointIndex = context.bendpointIndex; if (snapPoints) { return snapPoints; } var referenceWaypoints = [ waypoints[bendpointIndex - 1], waypoints[bendpointIndex + 1] ]; context.snapPoints = snapPoints = { horizontal: [] , vertical: [] }; forEach(referenceWaypoints, function(p) { // we snap on existing bendpoints only, // not placeholders that are inserted during add if (p) { p = p.original || p; snapPoints.horizontal.push(p.y); snapPoints.vertical.push(p.x); } }); return snapPoints; } eventBus.on('bendpoint.move.move', 1500, function(event) { var context = event.context, snapPoints = getBendpointSnaps(context), target = context.target, targetMid = target && mid(target), x = event.x, y = event.y, sx, sy; if (!snapPoints) { return; } // snap sx = snapTo(targetMid ? snapPoints.vertical.concat([ targetMid.x ]) : snapPoints.vertical, x); sy = snapTo(targetMid ? snapPoints.horizontal.concat([ targetMid.y ]) : snapPoints.horizontal, y); // correction x/y var cx = (x - sx), cy = (y - sy); // update delta assign(event, { dx: event.dx - cx, dy: event.dy - cy, x: event.x - cx, y: event.y - cy }); }); } BendpointSnapping.$inject = [ 'eventBus' ];
pedesen/diagram-js
lib/features/bendpoints/BendpointSnapping.js
JavaScript
mit
4,283
var changeSpan; var i = 0; var hobbies = [ 'Music', 'HTML5', 'Learning', 'Exploring', 'Art', 'Teaching', 'Virtual Reality', 'The Cosmos', 'Unity3D', 'Tilemaps', 'Reading', 'Butterscotch', 'Drawing', 'Taking Photos', 'Smiles', 'The Poetics of Space', 'Making Sounds', 'Board games', 'Travelling', 'Sweetened condensed milk' ]; function changeWord() { changeSpan.textContent = hobbies[i]; i++; if (i >= hobbies.length) i = 0; } function init() { console.log('initialising scrolling text'); changeSpan = document.getElementById("scrollingText"); nIntervId = setInterval(changeWord, 950); changeWord(); } if (document.addEventListener) { init(); } else { init(); }
oddgoo/oddgoo.com
static/js/hobbies.js
JavaScript
mit
725
import { GraphQLInputObjectType, GraphQLID, GraphQLList, GraphQLBoolean, } from 'graphql'; import RecipientTypeEnum from './RecipientTypeEnum'; import MessageTypeEnum from './MessageTypeEnum'; import NoteInputType from './NoteInputType'; import TranslationInputType from './TranslationInputType'; import CommunicationInputType from './CommunicationInputType'; const MessageInputType = new GraphQLInputObjectType({ name: 'MessageInput', fields: { parentId: { type: GraphQLID, }, note: { type: NoteInputType, }, communication: { type: CommunicationInputType, }, subject: { type: TranslationInputType, }, enforceEmail: { type: GraphQLBoolean, }, isDraft: { type: GraphQLBoolean, }, recipients: { type: new GraphQLList(GraphQLID), }, recipientType: { type: RecipientTypeEnum }, messageType: { type: MessageTypeEnum }, }, }); export default MessageInputType;
nambawan/g-old
src/data/types/MessageInputType.js
JavaScript
mit
979
let _ = require('underscore'), React = require('react'); class Icon extends React.Component { render() { let className = "icon " + this.props.icon; let other = _.omit(this.props.icon, "icon"); return ( <span className={className} role="img" {...other}></span> ); } } Icon.propTypes = { icon: React.PropTypes.string.isRequired }; module.exports = Icon;
legendary-code/chaos-studio-web
app/src/js/components/Icon.js
JavaScript
mit
433
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class ChevronDown extends React.Component { render() { if(this.props.bare) { return <g> <path d="M256,298.3L256,298.3L256,298.3l174.2-167.2c4.3-4.2,11.4-4.1,15.8,0.2l30.6,29.9c4.4,4.3,4.5,11.3,0.2,15.5L264.1,380.9 c-2.2,2.2-5.2,3.2-8.1,3c-3,0.1-5.9-0.9-8.1-3L35.2,176.7c-4.3-4.2-4.2-11.2,0.2-15.5L66,131.3c4.4-4.3,11.5-4.4,15.8-0.2L256,298.3 z"></path> </g>; } return <IconBase> <path d="M256,298.3L256,298.3L256,298.3l174.2-167.2c4.3-4.2,11.4-4.1,15.8,0.2l30.6,29.9c4.4,4.3,4.5,11.3,0.2,15.5L264.1,380.9 c-2.2,2.2-5.2,3.2-8.1,3c-3,0.1-5.9-0.9-8.1-3L35.2,176.7c-4.3-4.2-4.2-11.2,0.2-15.5L66,131.3c4.4-4.3,11.5-4.4,15.8-0.2L256,298.3 z"></path> </IconBase>; } };ChevronDown.defaultProps = {bare: false}
fbfeix/react-icons
src/icons/ChevronDown.js
JavaScript
mit
819
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const webpack = require('webpack'); const paths = require('./tools/paths'); const env = { 'process.env.NODE_ENV': JSON.stringify('development') }; module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ require.resolve('./tools/polyfills'), 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index' ], output: { filename: 'static/js/bundle.js', path: paths.appDist, pathinfo: true, publicPath: '/' }, module: { rules: [ // Default loader: load all assets that are not handled // by other loaders with the url loader. // Note: This list needs to be updated with every change of extensions // the other loaders match. // E.g., when adding a loader for a new supported file extension, // we need to add the supported extension to this loader too. // Add one new line in `exclude` for each loader. // // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `dist` folder. // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { exclude: [ /\.html$/, /\.js$/, /\.scss$/, /\.json$/, /\.svg$/, /node_modules/ ], use: [{ loader: 'url-loader', options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }] }, { test: /\.js$/, enforce: 'pre', include: paths.appSrc, use: [{ loader: 'xo-loader', options: { // This loader must ALWAYS return warnings during development. If // errors are emitted, no changes will be pushed to the browser for // testing until the errors have been resolved. emitWarning: true } }] }, { test: /\.js$/, include: paths.appSrc, use: [{ loader: 'babel-loader', options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true } }] }, { test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2 } }, 'postcss-loader', 'sass-loader' ] }, { test: /\.svg$/, use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }] } ] }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: paths.appHtml }), new webpack.DefinePlugin(env), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // If you require a missing module and then `npm install` it, you still have // to restart the development server for Webpack to discover it. This plugin // makes the discovery automatic so you don't have to restart. // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } };
hn3etta/VS2015-React-Redux-Webpack-Front-end-example
webpack.config.js
JavaScript
mit
3,928
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var THREE = require('./three-math.js'); var PredictionMode = { NONE: 'none', INTERPOLATE: 'interpolate', PREDICT: 'predict' } // How much to interpolate between the current orientation estimate and the // previous estimate position. This is helpful for devices with low // deviceorientation firing frequency (eg. on iOS8 and below, it is 20 Hz). The // larger this value (in [0, 1]), the smoother but more delayed the head // tracking is. var INTERPOLATION_SMOOTHING_FACTOR = 0.01; // Angular threshold, if the angular speed (in deg/s) is less than this, do no // prediction. Without it, the screen flickers quite a bit. var PREDICTION_THRESHOLD_DEG_PER_S = 0.01; //var PREDICTION_THRESHOLD_DEG_PER_S = 0; // How far into the future to predict. window.WEBVR_PREDICTION_TIME_MS = 80; // Whether to predict or what. window.WEBVR_PREDICTION_MODE = PredictionMode.PREDICT; function PosePredictor() { this.lastQ = new THREE.Quaternion(); this.lastTimestamp = null; this.outQ = new THREE.Quaternion(); this.deltaQ = new THREE.Quaternion(); } PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) { // If there's no previous quaternion, output the current one and save for // later. if (!this.lastTimestamp) { this.lastQ.copy(currentQ); this.lastTimestamp = timestamp; return currentQ; } // DEBUG ONLY: Try with a fixed 60 Hz update speed. //var elapsedMs = 1000/60; var elapsedMs = timestamp - this.lastTimestamp; switch (WEBVR_PREDICTION_MODE) { case PredictionMode.INTERPOLATE: this.outQ.copy(currentQ); this.outQ.slerp(this.lastQ, INTERPOLATION_SMOOTHING_FACTOR); // Save the current quaternion for later. this.lastQ.copy(currentQ); break; case PredictionMode.PREDICT: var axisAngle; if (rotationRate) { axisAngle = this.getAxisAngularSpeedFromRotationRate_(rotationRate); } else { axisAngle = this.getAxisAngularSpeedFromGyroDelta_(currentQ, elapsedMs); } // If there is no predicted axis/angle, don't do prediction. if (!axisAngle) { this.outQ.copy(currentQ); this.lastQ.copy(currentQ); break; } var angularSpeedDegS = axisAngle.speed; var axis = axisAngle.axis; var predictAngleDeg = (WEBVR_PREDICTION_TIME_MS / 1000) * angularSpeedDegS; // If we're rotating slowly, don't do prediction. if (angularSpeedDegS < PREDICTION_THRESHOLD_DEG_PER_S) { this.outQ.copy(currentQ); this.lastQ.copy(currentQ); break; } // Calculate the prediction delta to apply to the original angle. this.deltaQ.setFromAxisAngle(axis, THREE.Math.degToRad(predictAngleDeg)); // DEBUG ONLY: As a sanity check, use the same axis and angle as before, // which should cause no prediction to happen. //this.deltaQ.setFromAxisAngle(axis, angle); this.outQ.copy(this.lastQ); this.outQ.multiply(this.deltaQ); // Use the predicted quaternion as the new last one. //this.lastQ.copy(this.outQ); this.lastQ.copy(currentQ); break; case PredictionMode.NONE: default: this.outQ.copy(currentQ); } this.lastTimestamp = timestamp; return this.outQ; }; PosePredictor.prototype.setScreenOrientation = function(screenOrientation) { this.screenOrientation = screenOrientation; }; PosePredictor.prototype.getAxis_ = function(quat) { // x = qx / sqrt(1-qw*qw) // y = qy / sqrt(1-qw*qw) // z = qz / sqrt(1-qw*qw) var d = Math.sqrt(1 - quat.w * quat.w); return new THREE.Vector3(quat.x / d, quat.y / d, quat.z / d); }; PosePredictor.prototype.getAngle_ = function(quat) { // angle = 2 * acos(qw) // If w is greater than 1 (THREE.js, how can this be?), arccos is not defined. if (quat.w > 1) { return 0; } var angle = 2 * Math.acos(quat.w); // Normalize the angle to be in [-π, π]. if (angle > Math.PI) { angle -= 2 * Math.PI; } return angle; }; PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) { if (!rotationRate) { return null; } var screenRotationRate; if (/iPad|iPhone|iPod/.test(navigator.platform)) { // iOS: angular speed in deg/s. var screenRotationRate = this.getScreenAdjustedRotationRateIOS_(rotationRate); } else { // Android: angular speed in rad/s, so need to convert. rotationRate.alpha = THREE.Math.radToDeg(rotationRate.alpha); rotationRate.beta = THREE.Math.radToDeg(rotationRate.beta); rotationRate.gamma = THREE.Math.radToDeg(rotationRate.gamma); var screenRotationRate = this.getScreenAdjustedRotationRate_(rotationRate); } var vec = new THREE.Vector3( screenRotationRate.beta, screenRotationRate.alpha, screenRotationRate.gamma); /* var vec; if (/iPad|iPhone|iPod/.test(navigator.platform)) { vec = new THREE.Vector3(rotationRate.gamma, rotationRate.alpha, rotationRate.beta); } else { vec = new THREE.Vector3(rotationRate.beta, rotationRate.alpha, rotationRate.gamma); } // Take into account the screen orientation too! vec.applyQuaternion(this.screenTransform); */ // Angular speed in deg/s. var angularSpeedDegS = vec.length(); var axis = vec.normalize(); return { speed: angularSpeedDegS, axis: axis } }; PosePredictor.prototype.getScreenAdjustedRotationRate_ = function(rotationRate) { var screenRotationRate = { alpha: -rotationRate.alpha, beta: rotationRate.beta, gamma: rotationRate.gamma }; switch (this.screenOrientation) { case 90: screenRotationRate.beta = - rotationRate.gamma; screenRotationRate.gamma = rotationRate.beta; break; case 180: screenRotationRate.beta = - rotationRate.beta; screenRotationRate.gamma = - rotationRate.gamma; break; case 270: case -90: screenRotationRate.beta = rotationRate.gamma; screenRotationRate.gamma = - rotationRate.beta; break; default: // SCREEN_ROTATION_0 screenRotationRate.beta = rotationRate.beta; screenRotationRate.gamma = rotationRate.gamma; break; } return screenRotationRate; }; PosePredictor.prototype.getScreenAdjustedRotationRateIOS_ = function(rotationRate) { var screenRotationRate = { alpha: rotationRate.alpha, beta: rotationRate.beta, gamma: rotationRate.gamma }; // Values empirically derived. switch (this.screenOrientation) { case 90: screenRotationRate.beta = -rotationRate.beta; screenRotationRate.gamma = rotationRate.gamma; break; case 180: // You can't even do this on iOS. break; case 270: case -90: screenRotationRate.alpha = -rotationRate.alpha; screenRotationRate.beta = rotationRate.beta; screenRotationRate.gamma = rotationRate.gamma; break; default: // SCREEN_ROTATION_0 screenRotationRate.alpha = rotationRate.beta; screenRotationRate.beta = rotationRate.alpha; screenRotationRate.gamma = rotationRate.gamma; break; } return screenRotationRate; }; PosePredictor.prototype.getAxisAngularSpeedFromGyroDelta_ = function(currentQ, elapsedMs) { // Sometimes we use the same sensor timestamp, in which case prediction // won't work. if (elapsedMs == 0) { return null; } // Q_delta = Q_last^-1 * Q_curr this.deltaQ.copy(this.lastQ); this.deltaQ.inverse(); this.deltaQ.multiply(currentQ); // Convert from delta quaternion to axis-angle. var axis = this.getAxis_(this.deltaQ); var angleRad = this.getAngle_(this.deltaQ); // It took `elapsed` ms to travel the angle amount over the axis. Now, // we make a new quaternion based how far in the future we want to // calculate. var angularSpeedRadMs = angleRad / elapsedMs; var angularSpeedDegS = THREE.Math.radToDeg(angularSpeedRadMs) * 1000; // If no rotation rate is provided, do no prediction. return { speed: angularSpeedDegS, axis: axis }; }; module.exports = PosePredictor;
lacker/universe
vr_webpack/webvr-polyfill/src/pose-predictor.js
JavaScript
mit
8,628
/** * JS for the player character. * * * * */ import * as Consts from './consts'; var leftLeg; var rightLeg; var leftArm; var rightArm; const BODY_HEIGHT = 5; const LEG_HEIGHT = 5; const HEAD_HEIGHT = Consts.BLOCK_WIDTH * (3/5); const SKIN_COLORS = [0xFADCAB, 0x9E7245, 0x4F3F2F]; const BASE_MAT = new THREE.MeshLambertMaterial({color: 0xFF0000}); export var Player = function() { THREE.Object3D.call(this); this.position.y += BODY_HEIGHT / 2 + LEG_HEIGHT / 2 + HEAD_HEIGHT / 2 + HEAD_HEIGHT; this.moveLeft = false; this.moveRight = false; this.moveUp = false; this.moveDown = false; this.orientation = "backward"; var scope = this; var legGeo = new THREE.BoxGeometry(Consts.BLOCK_WIDTH / 2, LEG_HEIGHT, Consts.BLOCK_WIDTH / 2); var armGeo = new THREE.BoxGeometry(Consts.BLOCK_WIDTH / 2, BODY_HEIGHT, Consts.BLOCK_WIDTH / 2); // Base mat(s) var redMaterial = new THREE.MeshLambertMaterial({color: 0xFF2E00}); var blueMaterial = new THREE.MeshLambertMaterial({color: 0x23A8FC}); var yellowMaterial = new THREE.MeshLambertMaterial({color: 0xFFD000}); // Skin color mat, only used for head var skinColor = SKIN_COLORS[Math.floor(Math.random() * SKIN_COLORS.length)] var skinMat = new THREE.MeshLambertMaterial({color: skinColor}); // Body material var bodyFrontMat = new THREE.MeshPhongMaterial({color: 0xFFFFFF}); var bodyFrontTexture = new THREE.TextureLoader().load("img/tetratowerbodyfront.png", function(texture) { bodyFrontMat.map = texture; bodyFrontMat.needsUpdate = true; }) var bodyMat = new THREE.MultiMaterial([ redMaterial, redMaterial, redMaterial, redMaterial, bodyFrontMat, bodyFrontMat ]); var armSideMat = new THREE.MeshLambertMaterial({color: 0xFFFFFF}) var armTopMat = new THREE.MeshLambertMaterial({color: 0xFFFFFF}); var armMat = new THREE.MultiMaterial([ armSideMat, armSideMat, armTopMat, armTopMat, armSideMat, armSideMat ]); // Leg material var legSideMat = new THREE.MeshLambertMaterial({color: 0xFFFFFF}) var legMat = new THREE.MultiMaterial([ legSideMat, legSideMat, blueMaterial, blueMaterial, legSideMat, legSideMat ]); var legTexture = new THREE.TextureLoader().load("/img/tetratowerleg.png", function (texture) { legSideMat.map = texture; legSideMat.needsUpdate = true; }); var textureURL; switch (skinColor) { case SKIN_COLORS[0]: textureURL = "/img/tetratowerarm_white.png"; break; case SKIN_COLORS[1]: textureURL = "/img/tetratowerarm_brown.png"; break; case SKIN_COLORS[2]: textureURL = "/img/tetratowerarm_black.png"; break; default: textureURL = "/img/tetratowerarm.png"; break; } var armTexture = new THREE.TextureLoader().load(textureURL, function(texture) { armSideMat.map = texture; armSideMat.needsUpdate = true; }); var armTopTexture = new THREE.TextureLoader().load("img/tetratowerarmtop.png", function(texture) { armTopMat.map = texture; armTopMat.needsUpdate = true; }) // Create a body var bodyGeo = new THREE.BoxGeometry(Consts.BLOCK_WIDTH, BODY_HEIGHT, Consts.BLOCK_WIDTH / 2); var body = new THREE.Mesh(bodyGeo, bodyMat); this.add(body); // Create some leggy legs leftLeg = new THREE.Mesh(legGeo, legMat); this.add(leftLeg) leftLeg.translateX(-Consts.BLOCK_WIDTH / 4); leftLeg.translateY(-(LEG_HEIGHT + BODY_HEIGHT) / 2); rightLeg = new THREE.Mesh(legGeo, legMat); this.add(rightLeg); rightLeg.translateX(Consts.BLOCK_WIDTH / 4); rightLeg.translateY(-(LEG_HEIGHT + BODY_HEIGHT) / 2); // Create the arms leftArm = new THREE.Mesh(armGeo, armMat); this.add(leftArm); leftArm.translateX(-(Consts.BLOCK_WIDTH / 4 + Consts.BLOCK_WIDTH / 2)); rightArm = new THREE.Mesh(armGeo, armMat); this.add(rightArm); rightArm.translateX((Consts.BLOCK_WIDTH / 4 + Consts.BLOCK_WIDTH / 2)); // Now add a head var headGeo = new THREE.BoxGeometry(Consts.BLOCK_WIDTH * (3/5), Consts.BLOCK_WIDTH * (3/5), Consts.BLOCK_WIDTH * (3/5)); var head = new THREE.Mesh(headGeo, skinMat); this.add(head); head.translateY((BODY_HEIGHT + HEAD_HEIGHT) / 2); // And a fashionable hat var hatBodyGeo = new THREE.BoxGeometry(HEAD_HEIGHT * 1.05, HEAD_HEIGHT * (4/5), HEAD_HEIGHT * 1.05); var hatBody = new THREE.Mesh(hatBodyGeo, yellowMaterial); head.add(hatBody); hatBody.translateY(HEAD_HEIGHT * (4/5)); var hatBrimGeo = new THREE.BoxGeometry(HEAD_HEIGHT * 1.05, HEAD_HEIGHT / 5, HEAD_HEIGHT * 0.525); var hatBrim = new THREE.Mesh(hatBrimGeo, yellowMaterial); head.add(hatBrim); hatBrim.translateZ((HEAD_HEIGHT * 1.05) / 2 + (HEAD_HEIGHT * 0.525 / 2)); hatBrim.translateY(HEAD_HEIGHT / 2); // Add some listeners var onKeyDown = function(event) { switch(event.keyCode) { case 38: // up case 87: // w scope.moveForward = true; break; case 40: // down case 83: // s scope.moveBackward = true; break; case 37: // left case 65: // a scope.moveLeft = true; break; case 39: // right case 68: // d scope.moveRight = true; break; } } var onKeyUp = function(event) { switch(event.keyCode) { case 38: // up case 87: // w scope.moveForward = false; break; case 40: // down case 83: // s scope.moveBackward = false; break; case 37: // left case 65: // a scope.moveLeft = false; break; case 39: // right case 68: // d scope.moveRight = false; break; } } document.addEventListener('keydown', onKeyDown, false); document.addEventListener('keyup', onKeyUp, false); } Player.prototype = new THREE.Object3D(); Player.prototype.constructor = Player; THREE.Object3D.prototype.worldToLocal = function ( vector ) { if ( !this.__inverseMatrixWorld ) this.__inverseMatrixWorld = new THREE.Matrix4(); return vector.applyMatrix4( this.__inverseMatrixWorld.getInverse( this.matrixWorld )); }; THREE.Object3D.prototype.lookAtWorld = function( vector ) { vector = vector.clone(); this.parent.worldToLocal( vector ); this.lookAt( vector ); };
Bjorkbat/tetratower
js/src/player.js
JavaScript
mit
6,258
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'superhero/tests/helpers/start-app'; import characterData from '../fixtures/character'; var application, server; module('Acceptance: Character', { beforeEach: function() { application = startApp(); var character = characterData(); server = new Pretender(function() { this.get('/v1/public/characters/1009609', function(request) { var responseData = JSON.stringify(character); return [ 200, {"Content-Type": "application/json"}, responseData ]; }); }); }, afterEach: function() { Ember.run(application, 'destroy'); server.shutdown(); } }); test('visiting /characters/1009609 shows character detail', function(assert) { assert.expect(3); visit('/characters/1009609'); andThen(function() { assert.equal(currentURL(), '/characters/1009609'); assert.equal(find('.heading').text(), 'Spider-Girl (May Parker)', 'Should show character heading'); assert.equal( find('.description').text(), "May \"Mayday\" Parker is the daughter of Spider-Man and Mary Jane Watson-Parker. Born with all her father's powers-and the same silly sense of humor-she's grown up to become one of Earth's most trusted heroes and a fitting tribute to her proud papa.", 'Should show character descripton' ); }); }); test('visiting /characters/1009609 shows key events for the character', function(assert) { assert.expect(2); visit('/characters/1009609'); andThen(function() { assert.equal(find('.events .event').length, 1, 'Should show one event'); assert.equal( find('.events .event:first').text(), 'Fear Itself', 'Should show event name' ); }); });
dtt101/superhero
tests/acceptance/character-test.js
JavaScript
mit
1,790
#!/usr/bin/env node (function () { var DirectoryLayout = require('../lib/index.js'), program = require('commander'), options; program .version('1.0.2') .usage('[options] <path, ...>') .option('-g, --generate <path> <output-directory-layout-file-path>', 'Generate directory layout') .option('-v, --verify <input-directory-layout-file-path> <path>', 'Verify directory layout') .parse(process.argv); if(program.generate) { options = { output: program.args[0] || 'layout.md', ignore: [] }; console.log('Generating layout for ' + program.generate + '... \n') DirectoryLayout .generate(program.generate, options) .then(function() { console.log('Layout generated at: ' + options.output); }); } else if(program.verify) { options = { root: program.args[0] }; console.log('Verifying layout for ' + options.root + ' ...\n'); DirectoryLayout .verify(program.verify, options) .then(function() { console.log('Successfully verified layout available in ' + program.verify + '.'); }); } }());
ApoorvSaxena/directory-layout
bin/index.js
JavaScript
mit
1,267
var class_snowflake_1_1_game_1_1_game_database = [ [ "GameDatabase", "class_snowflake_1_1_game_1_1_game_database.html#a2f09c1f7fe18beaf8be1447e541f4d68", null ], [ "AddGame", "class_snowflake_1_1_game_1_1_game_database.html#a859513bbac24328df5d3fe2e47dbc183", null ], [ "GetAllGames", "class_snowflake_1_1_game_1_1_game_database.html#a7c43f2ccabe44f0491ae25e9b88bb07a", null ], [ "GetGameByUUID", "class_snowflake_1_1_game_1_1_game_database.html#ada7d853b053f0bbfbc6dea8eb89e85c4", null ], [ "GetGamesByName", "class_snowflake_1_1_game_1_1_game_database.html#ac1bbd90e79957e360dd5542f6052616e", null ], [ "GetGamesByPlatform", "class_snowflake_1_1_game_1_1_game_database.html#a2e93a35ea18a9caac9a6165cb33b5494", null ] ];
SnowflakePowered/snowflakepowered.github.io
doc/html/class_snowflake_1_1_game_1_1_game_database.js
JavaScript
mit
745
// JavaScript Document $(document).ready(function() { $('form input[type="file"]').change(function() { var filename = $(this).val(); $(this).prev('i').text(filename); }); $('.input-file').click(function() { $(this).find('input').click(); }); /* * Previene doble click en boton submit de envio de datos de formulario y evitar doble envio */ $('form').on('submit', function() { var submit = $(this).find('input[type="submit"]'); submit.attr('disabled','yes').css('cursor', 'not-allowed'); }); $('form').on('reset', function() { $('form .input-file i').text('Selecciona un archivo'); }); /* * Toggle en menu principal lateral */ $('ul#navi li').click(function() { $(this).next('ul').slideToggle('fast'); //$(this).toggleClass('active'); }); /* * Coloca un simbolo para identificar los item con subitems en el menu navegacion izquierda */ $('ul.subnavi').each(function() { var ori_text = $(this).prev('li').find('a').text(); $(this).prev('li').find('a').html(ori_text+'<span class="fa ellipsis">&#xf107;</span>'); }); /* * Despliega cuadro de informacion de usuario */ $('li.user_photo, li.user_letter').click(function(e) { $(this).next('div.user_area').fadeToggle(50); e.stopPropagation(); }); $('body').click(function() { $('li.user_photo, li.user_letter').next('div.user_area').hide(); }); $('div.user_area').click(function(e) { e.stopPropagation(); }); /* * Mostrar/Ocultar mapa */ $('#toggle_map').click(function() { $('ul.map_icon_options').fadeToggle('fast'); $('img#mapa').fadeToggle('fast'); $(this).toggleClass('active'); }); /* * Confirmación de cerrar sesión */ /*$('#cerrar_sesion').click(function() { return confirm(String.fromCharCode(191)+'Esta seguro que desea salir de la sesi'+String.fromCharCode(243)+'n?'); });*/ /* * Confirmación de eliminar datos */ $('a.eliminar').click(function() { return confirm(String.fromCharCode(191)+'Esta seguro que desea eliminar este registro?'); }); /* * Confirmación de quitar asignacion a responsable de un area */ $('a.quitar_asignacion').click(function() { return confirm('Se quitara la asignacion al usuario. '+String.fromCharCode(191)+'Desea continuar?'); }); /* * Ajusta tamaño a imagenes de mapas que son mas altas que anchas */ $('.map_wrapper img#mapa').each(function() { var h = $(this).height(); var w = $(this).width(); if(h > w) { $(this).css('width', '50%').addClass('halign'); } }) /* * Envia a impresion */ $('#print').click(function() { window.print(); }); /* * Inhabilita el click derecho */ $(function(){ $(document).bind("contextmenu",function(e){ return false; }); }); /* * Toma atruto ALT de campo de formulario y lo usa como descripcion debajo del campo */ $('form.undertitled').find('input:text, input:password, input:file, select, textarea').each(function() { $(this).after('<span>'+$(this).attr('title')+'</span>'); }); /* * Hack para centrar horizontalmente mensajes de notificación */ $('p.notify').each(function() { var w = $(this).width(); $(this).css('left', -(w/2)+'px'); }).delay(5000).fadeOut('medium'); //-- /* * Focus en elementos de tabla */ $("table tbody tr").click(function() { $(this).addClass('current').siblings("tr").removeClass('current'); }); /* * Hace scroll al tope de la página * * $('.boton_accion').toTop(); */ $.fn.toTop = function() { $(this).click(function() { $('html, body').animate({scrollTop:0}, 'medium'); }) } //-- /* * Ventana modal * @param text box * Qparam text overlay * * $('.boton_que_acciona_ventana').lightbox('.objeto_a_mostrar', 'w|d : opcional') * w : Muestra una ventana al centro de la pantalla en fondo blanco * d : Muestra una ventana al top de la pantalla sobre fondo negro, si no define * el segundo parametro se mostrara por default este modo. */ $.fn.lightbox = function(box, overlay='d') { $(this).click(function() { var ol = (overlay=='w') ? 'div.overlay_white' : 'div.overlay'; $(ol).fadeIn(250).click(function() { $(box).slideUp(220); $(this).delay(221).fadeOut(250); }).attr('title','Click para cerrar'); $(box).delay(251).slideDown(220); }); if(overlay=='d') { $(box).each(function() { $(this).html($(this).html()+'<p style="border-top:1px #CCC solid; color:#888; margin-bottom:0; padding-top:10px">Para cerrar esta ventana haga click sobre el &aacute;rea sombreada.</p>'); }); } }; //-- })
rguezque/enlaces
web/res/js/jquery-functions.js
JavaScript
mit
4,483
var _ = require('underscore'); var colors = require('colors'); var sprintf = require('sprintf-js').sprintf; /** * used to decode AIS messages. * Currently decodes types 1,2,3,4,5,9,18,19,21,24,27 * Currently does not decode 6,7,8,10,11,12,13,14,15,16,17,20,22,23,25,26 * Currently does not support the USCG Extended AIVDM messages * * Normal usage: * var decoder = new aivdmDecode.aivdmDecode(options) * then * decoder.decode(aivdm); * var msgData = decoder.getData(); * * aisData will return with an object that contains the message fields. * The object returned will also include the sentence(s) that were decoded. This is to make it easy to * use the decoder to filter based on in-message criteria but then forward the undecoded packets. * * The decoded data object uses field naming conventions in the same way that GPSD does. * * @param {object} options: * returnJson: If true then json is returned instead of a javascript object (default false) * aivdmPassthrough If true then the aivdm messages that were decoded are included with the returned object * default false */ /** * String.lpad: Used to pad mmsi's to 9 digits and imo's to 7 digits * Converts number to string, then lpads it with padString to length * @param {string} padString The character to use when padding * @param desiredLength The desired length after padding */ Number.prototype.lpad = function (padString, desiredLength) { var str = '' + this; while (str.length < desiredLength) str = padString + str; return str; }; var aivdmDecode = function (options) { if (options) { // returnJson: If true, returns json instead of an object this.returnJson = options.returnJson || false; // aivdmPassthrough: If true then the original aivdm sentences are embedded in the returned object this.aivdmPassthrough = options.aivdmPassthrough || true; // includeMID: If true then the mid (nationality) of the vessels is included in the returned object this.includeMID = options.includeMID || true; // accept_related. Passed as true to decoder when you wish static packets with accepted MMSI passed to output //this.accept_related = options.accept_related || true; // isDebug. If true, prints debug messages this.isDebug = options.isDebug || false; } else { this.returnJson = false; this.aivdmPassthrough = true; this.includeMID = true; this.isDebug = false; } this.AIVDM = ''; this.splitParts = []; // Contains aivdm's of multi part messages this.splitPart1Sequence = null; this.splitPart1Type = null; this.splitLines = []; // contains untrimmed lines of multi part messages this.numFragments = null; this.fragmentNum = null; this.seqMsgId = ''; this.binString = ''; this.partNo = null; this.channel = null; this.msgType = null; this.supportedTypes = [1,2,3,4,5,9,18,19,21,24,27]; this.char_table = [ /* 4th line would normally be: '[', '\\', ']', '^', '_', ' ', '!', '"', '#', '$', '%', '&', '\\', '(', ')', '*', '+', ',', '-','.', '/', but has been customized to eliminate most punctuation characters Last line would normally be: ':', ';', '<', '=', '>', '?' but has been customized to eliminate most punctuation characters */ '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '-', '-', '-', '_', ' ', '-', '-', '-', '-', '-', '-', '-', '(', ')', '-', '-', '-', '-', '.', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '-', '<', '-', '>', '-' ]; this.posGroups = { 1: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}}, 2: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}}, 3: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}}, 4: {'lat': {'start': 107, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 79, 'length': 28, 'divisor': 600000.0}}, 9: {'lat': {'start': 89, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 61, 'length': 28, 'divisor': 600000.0}}, 18: {'lat': {'start': 85, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 57, 'length': 28, 'divisor': 600000.0}}, 19: {'lat': {'start': 85, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 57, 'length': 28, 'divisor': 600000.0}}, 21: {'lat': {'start': 192, 'length': 27, 'divisor': 600000.0}, 'lon': {'start': 164, 'length': 28, 'divisor': 600000.0}}, 27: {'lat': {'start': 62, 'length': 17, 'divisor': 600.0}, 'lon': {'start': 44, 'length': 18, 'divisor': 600.0}} }; this.speedGroups = { 1: {'start': 50, 'length': 10, 'divisor': 10}, 2: {'start': 50, 'length': 10, 'divisor': 10}, 3: {'start': 50, 'length': 10, 'divisor': 10}, 9: {'start': 50, 'length': 10, 'divisor': 1}, 18: {'start': 46, 'length': 10, 'divisor': 10}, 19: {'start': 46, 'length': 10, 'divisor': 10}, 27: {'start': 79, 'length': 6, 'divisor': 1} }; this.navStatusText = [ 'Under way using engine', 'At anchor', 'Not under command', 'Restricted manoeuverability', 'Constrained by her draught', 'Moored', 'Aground', 'Engaged in Fishing', 'Under way sailing', 'Reserved for future amendment of Navigational Status for HSC', 'Reserved for future amendment of Navigational Status for WIG', 'Reserved for future use', 'Reserved for future use', 'Reserved for future use', 'AIS-SART is active', 'Not defined' ]; this.maneuverText = [ 'Not available', 'No special maneuver', 'Special maneuver (such as regional passing arrangement' ]; this.epfdText = [ 'Undefined', 'GPS', 'GLONASS', 'Combined GPS/GLONASS', 'Loran-C', 'Chayka', 'Integrated navigation system', 'Surveyed', 'Galileo' ]; this.shiptypeText = [ "Not available", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Reserved for future use", "Wing in ground (WIG) - all ships of this type", "Wing in ground (WIG) - Hazardous category A", "Wing in ground (WIG) - Hazardous category B", "Wing in ground (WIG) - Hazardous category C", "Wing in ground (WIG) - Hazardous category D", "Wing in ground (WIG) - Reserved for future use", "Wing in ground (WIG) - Reserved for future use", "Wing in ground (WIG) - Reserved for future use", "Wing in ground (WIG) - Reserved for future use", "Wing in ground (WIG) - Reserved for future use", "Fishing", "Towing", "Towing: length exceeds 200m or breadth exceeds 25m", "Dredging or underwater ops", "Diving ops", "Military ops", "Sailing", "Pleasure Craft", "Reserved", "Reserved", "High speed craft (HSC) - all ships of this type", "High speed craft (HSC) - Hazardous category A", "High speed craft (HSC) - Hazardous category B", "High speed craft (HSC) - Hazardous category C", "High speed craft (HSC) - Hazardous category D", "High speed craft (HSC) - Reserved for future use", "High speed craft (HSC) - Reserved for future use", "High speed craft (HSC) - Reserved for future use", "High speed craft (HSC) - Reserved for future use", "High speed craft (HSC) - No additional information", "Pilot Vessel1", "Search and Rescue vessel", "Tug", "Port Tender", "Anti-pollution equipment", "Law Enforcement", "Spare - Local Vessel", "Spare - Local Vessel", "Medical Transport", "Ship according to RR Resolution No. 18", "Passenger - all ships of this type", "Passenger - Hazardous category A", "Passenger - Hazardous category B", "Passenger - Hazardous category C", "Passenger - Hazardous category D", "Passenger - Reserved for future use", "Passenger - Reserved for future use", "Passenger - Reserved for future use", "Passenger - Reserved for future use", "Passenger - No additional information", "Cargo - all ships of this type", "Cargo - Hazardous category A", "Cargo - Hazardous category B", "Cargo - Hazardous category C", "Cargo - Hazardous category D", "Cargo - Reserved for future use", "Cargo - Reserved for future use", "Cargo - Reserved for future use", "Cargo - Reserved for future use", "Cargo - No additional information", "Tanker - all ships of this type", "Tanker - Hazardous category A", "Tanker - Hazardous category B1", "Tanker - Hazardous category C1", "Tanker - Hazardous category D1", "Tanker - Reserved for future use", "Tanker - Reserved for future use", "Tanker - Reserved for future use", "Tanker - Reserved for future use", "Tanker - No additional information", "Other Type - all ships of this type", "Other Type - Hazardous category A", "Other Type - Hazardous category B", "Other Type - Hazardous category C", "Other Type - Hazardous category D", "Other Type - Reserved for future use", "Other Type - Reserved for future use", "Other Type - Reserved for future use", "Other Type - Reserved for future use", "Other Type - no additional information" ]; this.midTable = { 202: "Andorra (Principality of)", 203: "Austria", 204: "Azores - Portugal", 205: "Belgium", 206: "Belarus (Republic of)", 207: "Bulgaria (Republic of)", 208: "Vatican City State", 209: "Cyprus (Republic of)", 210: "Cyprus (Republic of)", 211: "Germany (Federal Republic of)", 212: "Cyprus (Republic of)", 213: "Georgia", 214: "Moldova (Republic of)", 215: "Malta", 216: "Armenia (Republic of)", 218: "Germany (Federal Republic of)", 219: "Denmark", 220: "Denmark", 224: "Spain", 225: "Spain", 226: "France", 227: "France", 228: "France", 229: "Malta", 230: "Finland", 231: "Faroe Islands - Denmark", 232: "United Kingdom of Great Britain and Northern Ireland", 233: "United Kingdom of Great Britain and Northern Ireland", 234: "United Kingdom of Great Britain and Northern Ireland", 235: "United Kingdom of Great Britain and Northern Ireland", 236: "Gibraltar - United Kingdom of Great Britain and Northern Ireland", 237: "Greece", 238: "Croatia (Republic of)", 239: "Greece", 240: "Greece", 241: "Greece", 242: "Morocco (Kingdom of)", 243: "Hungary", 244: "Netherlands (Kingdom of the)", 245: "Netherlands (Kingdom of the)", 246: "Netherlands (Kingdom of the)", 247: "Italy", 248: "Malta", 249: "Malta", 250: "Ireland", 251: "Iceland", 252: "Liechtenstein (Principality of)", 253: "Luxembourg", 254: "Monaco (Principality of)", 255: "Madeira - Portugal", 256: "Malta", 257: "Norway", 258: "Norway", 259: "Norway", 261: "Poland (Republic of)", 262: "Montenegro", 263: "Portugal", 264: "Romania", 265: "Sweden", 266: "Sweden", 267: "Slovak Republic", 268: "San Marino (Republic of)", 269: "Switzerland (Confederation of)", 270: "Czech Republic", 271: "Turkey", 272: "Ukraine", 273: "Russian Federation", 274: "The Former Yugoslav Republic of Macedonia", 275: "Latvia (Republic of)", 276: "Estonia (Republic of)", 277: "Lithuania (Republic of)", 278: "Slovenia (Republic of)", 279: "Serbia (Republic of)", 301: "Anguilla - United Kingdom of Great Britain and Northern Ireland", 303: "Alaska (State of) - United States of America", 304: "Antigua and Barbuda", 305: "Antigua and Barbuda", 306: "Dutch West Indies", //306: "Curaçao - Netherlands (Kingdom of the)", //306: "Sint Maarten (Dutch part) - Netherlands (Kingdom of the)", //306: "Bonaire, Sint Eustatius and Saba - Netherlands (Kingdom of the)", 307: "Aruba - Netherlands (Kingdom of the)", 308: "Bahamas (Commonwealth of the)", 309: "Bahamas (Commonwealth of the)", 310: "Bermuda - United Kingdom of Great Britain and Northern Ireland", 311: "Bahamas (Commonwealth of the)", 312: "Belize", 314: "Barbados", 316: "Canada", 319: "Cayman Islands - United Kingdom of Great Britain and Northern Ireland", 321: "Costa Rica", 323: "Cuba", 325: "Dominica (Commonwealth of)", 327: "Dominican Republic", 329: "Guadeloupe (French Department of) - France", 330: "Grenada", 331: "Greenland - Denmark", 332: "Guatemala (Republic of)", 334: "Honduras (Republic of)", 336: "Haiti (Republic of)", 338: "United States of America", 339: "Jamaica", 341: "Saint Kitts and Nevis (Federation of)", 343: "Saint Lucia", 345: "Mexico", 347: "Martinique (French Department of) - France", 348: "Montserrat - United Kingdom of Great Britain and Northern Ireland", 350: "Nicaragua", 351: "Panama (Republic of)", 352: "Panama (Republic of)", 353: "Panama (Republic of)", 354: "Panama (Republic of)", 355: "unassigned", 356: "unassigned", 357: "unassigned", 358: "Puerto Rico - United States of America", 359: "El Salvador (Republic of)", 361: "Saint Pierre and Miquelon (Territorial Collectivity of) - France", 362: "Trinidad and Tobago", 364: "Turks and Caicos Islands - United Kingdom of Great Britain and Northern Ireland", 366: "United States of America", 367: "United States of America", 368: "United States of America", 369: "United States of America", 370: "Panama (Republic of)", 371: "Panama (Republic of)", 372: "Panama (Republic of)", 373: "Panama (Republic of)", 375: "Saint Vincent and the Grenadines", 376: "Saint Vincent and the Grenadines", 377: "Saint Vincent and the Grenadines", 378: "British Virgin Islands - United Kingdom of Great Britain and Northern Ireland", 379: "United States Virgin Islands - United States of America", 401: "Afghanistan", 403: "Saudi Arabia (Kingdom of)", 405: "Bangladesh (People's Republic of)", 408: "Bahrain (Kingdom of)", 410: "Bhutan (Kingdom of)", 412: "China (People's Republic of)", 413: "China (People's Republic of)", 414: "China (People's Republic of)", 416: "Taiwan (Province of China) - China (People's Republic of)", 417: "Sri Lanka (Democratic Socialist Republic of)", 419: "India (Republic of)", 422: "Iran (Islamic Republic of)", 423: "Azerbaijan (Republic of)", 425: "Iraq (Republic of)", 428: "Israel (State of)", 431: "Japan", 432: "Japan", 434: "Turkmenistan", 436: "Kazakhstan (Republic of)", 437: "Uzbekistan (Republic of)", 438: "Jordan (Hashemite Kingdom of)", 440: "Korea (Republic of)", 441: "Korea (Republic of)", 443: "State of Palestine (In accordance with Resolution 99 Rev. Guadalajara, 2010)", 445: "Democratic People's Republic of Korea", 447: "Kuwait (State of)", 450: "Lebanon", 451: "Kyrgyz Republic", 453: "Macao (Special Administrative Region of China) - China (People's Republic of)", 455: "Maldives (Republic of)", 457: "Mongolia", 459: "Nepal (Federal Democratic Republic of)", 461: "Oman (Sultanate of)", 463: "Pakistan (Islamic Republic of)", 466: "Qatar (State of)", 468: "Syrian Arab Republic", 470: "United Arab Emirates", 472: "Tajikistan (Republic of)", 473: "Yemen (Republic of)", 475: "Yemen (Republic of)", 477: "Hong Kong (Special Administrative Region of China) - China (People's Republic of)", 478: "Bosnia and Herzegovina", 501: "Adelie Land - France", 503: "Australia", 506: "Myanmar (Union of)", 508: "Brunei Darussalam", 510: "Micronesia (Federated States of)", 511: "Palau (Republic of)", 512: "New Zealand", 514: "Cambodia (Kingdom of)", 515: "Cambodia (Kingdom of)", 516: "Christmas Island (Indian Ocean) - Australia", 518: "Cook Islands - New Zealand", 520: "Fiji (Republic of)", 523: "Cocos (Keeling) Islands - Australia", 525: "Indonesia (Republic of)", 529: "Kiribati (Republic of)", 531: "Lao People's Democratic Republic", 533: "Malaysia", 536: "Northern Mariana Islands (Commonwealth of the) - United States of America", 538: "Marshall Islands (Republic of the)", 540: "New Caledonia - France", 542: "Niue - New Zealand", 544: "Nauru (Republic of)", 546: "French Polynesia - France", 548: "Philippines (Republic of the)", 553: "Papua New Guinea", 555: "Pitcairn Island - United Kingdom of Great Britain and Northern Ireland", 557: "Solomon Islands", 559: "American Samoa - United States of America", 561: "Samoa (Independent State of)", 563: "Singapore (Republic of)", 564: "Singapore (Republic of)", 565: "Singapore (Republic of)", 566: "Singapore (Republic of)", 567: "Thailand", 570: "Tonga (Kingdom of)", 572: "Tuvalu", 574: "Viet Nam (Socialist Republic of)", 576: "Vanuatu (Republic of)", 577: "Vanuatu (Republic of)", 578: "Wallis and Futuna Islands - France", 601: "South Africa (Republic of)", 603: "Angola (Republic of)", 605: "Algeria (People's Democratic Republic of)", 607: "Saint Paul and Amsterdam Islands - France", 608: "Ascension Island - United Kingdom of Great Britain and Northern Ireland", 609: "Burundi (Republic of)", 610: "Benin (Republic of)", 611: "Botswana (Republic of)", 612: "Central African Republic", 613: "Cameroon (Republic of)", 615: "Congo (Republic of the)", 616: "Comoros (Union of the)", 617: "Cabo Verde (Republic of)", 618: "Crozet Archipelago - France", 619: "Côte d'Ivoire (Republic of)", 620: "Comoros (Union of the)", 621: "Djibouti (Republic of)", 622: "Egypt (Arab Republic of)", 624: "Ethiopia (Federal Democratic Republic of)", 625: "Eritrea", 626: "Gabonese Republic", 627: "Ghana", 629: "Gambia (Republic of the)", 630: "Guinea-Bissau (Republic of)", 631: "Equatorial Guinea (Republic of)", 632: "Guinea (Republic of)", 633: "Burkina Faso", 634: "Kenya (Republic of)", 635: "Kerguelen Islands - France", 636: "Liberia (Republic of)", 637: "Liberia (Republic of)", 638: "South Sudan (Republic of)", 642: "Libya", 644: "Lesotho (Kingdom of)", 645: "Mauritius (Republic of)", 647: "Madagascar (Republic of)", 649: "Mali (Republic of)", 650: "Mozambique (Republic of)", 654: "Mauritania (Islamic Republic of)", 655: "Malawi", 656: "Niger (Republic of the)", 657: "Nigeria (Federal Republic of)", 659: "Namibia (Republic of)", 660: "Reunion (French Department of) - France", 661: "Rwanda (Republic of)", 662: "Sudan (Republic of the)", 663: "Senegal (Republic of)", 664: "Seychelles (Republic of)", 665: "Saint Helena - United Kingdom of Great Britain and Northern Ireland", 666: "Somalia (Federal Republic of)", 667: "Sierra Leone", 668: "Sao Tome and Principe (Democratic Republic of)", 669: "Swaziland (Kingdom of)", 670: "Chad (Republic of)", 671: "Togolese Republic", 672: "Tunisia", 674: "Tanzania (United Republic of)", 675: "Uganda (Republic of)", 676: "Democratic Republic of the Congo", 677: "Tanzania (United Republic of)", 678: "Zambia (Republic of)", 679: "Zimbabwe (Republic of)", 701: "Argentine Republic", 710: "Brazil (Federative Republic of)", 720: "Bolivia (Plurinational State of)", 725: "Chile", 730: "Colombia (Republic of)", 735: "Ecuador", 740: "Falkland Islands (Malvinas) - United Kingdom of Great Britain and Northern Ireland", 745: "Guiana (French Department of) - France", 750: "Guyana", 755: "Paraguay (Republic of)", 760: "Peru", 765: "Suriname (Republic of)", 770: "Uruguay (Eastern Republic of)", 775: "Venezuela (Bolivarian Republic of)" }; this.functionMap = { "accuracy": "getAccuracy", "aid_type": "getAidType", "alt": "getAlt", "assigned": "getAssigned", "callsign": "getCallsign", "course": "getCourse", "day": "getDay", "destination": "getDestination", "dimensions": "getDimensions", "draught": "getDraught", "dte": "getDte", "epfd": "getEpfd", "fragmentNum": "getFragmentNum", "heading": "getHeading", "hour": "getHour", "imo": "getIMO", "latLon": "getLatLon", "maneuver": "getManeuver", "mid": "getMid", "mmsi": "getMMSI", "minute": "getMinute", "month": "getMonth", "name": "getName", "nameExtension": "getNameExtension", "numFragments": "getNumFragments", "off_position": "getOffPosition", "part": "getPartno", "radio": "getRadio", "raim": "getRaim", "second": "getSecond", "seqMsgId": "getSeqMsgId", "shiptype": "getShiptype", "speed": "getSpeed", "status": "getStatus", "turn": "getTurn", "type": "getType", "vendorInfo": "getVendorInfo", "virtual_aid": "getVirtualAid", "year": "getYear" }; /** * Type 6 and 8 (Binary addressed message and Binary broadcast message) contain lat/lon in some of their subtypes. * These messages are evidently only used in the St Lawrence seaway, the USG PAWSS system and the Port Authority of * london and aren't implemented in this code * * Type 17 is the Differential correction message type and is not implemented in this code * Type 22 is a channel management message and is not implemented in this code * Type 23 is a Group assignment message and is not implemented in this code */ }; /** Loads required attributes from AIVDM message for retrieval by other methods [0]=!AIVDM, [1]=Number of fragments, [2]=Fragment num, [3]=Seq msg ID, [4]=channel, [5]=payload, Fetch the AIVDM part of the line, from !AIVDM to the end of the line Split the line into fragments, delimited by commas fetch numFragments, fragmentNum and SeqMsgId (SeqMsgId may be empty) convert to a binary 6 bit string : param (string) line. The received message within which we hope an AIVDM statement exists :returns True if message is a single packet msg (1,2,3,9,18,27 etc) or part 1 of a multi_part message False if !AIVDM not in the line or exception during decode process */ aivdmDecode.prototype = { /** * getData(aivdm) * Decodes message, then returns an object containing extracted data * If the message is received in two parts (i.e. type 5 and 19) then * the return for the first of the messages is null. When the second part has been received then it * is combined with the first and decoded. * Whether a single or two part message, the return will contain the original message(s) in an array called 'aivdm' */ getData: function (line) { var lineData = { numFragments: this.numFragments, fragmentNum: this.fragmentNum, type: this.getType(), mmsi: this.getMMSI(), mid: this.getMid(), seqMsgId: this.getSeqMsgId(), aivdm: this.splitLines }; return this.msgTypeSwitcher(line, lineData); }, /** * msgTypeSwitcher * Used only by getData * Fills fields relevant to the message type * @param line The !AIVD string * @param lineData The partially filled lineData object * @returns {*} lineData object or false (if lineData is not filled */ msgTypeSwitcher: function (line, lineData) { switch (this.getType()) { // Implemented message types case 1: case 2: case 3: lineData = this.fill_1_2_3(line, lineData); break; case 4: lineData = this.fill_4(line, lineData); break; case 5: lineData = this.fill_5(line, lineData); break; case 9: lineData = this.fill_9(line, lineData); break; case 18: lineData = this.fill_18(line, lineData); break; case 19: lineData = this.fill_19(line, lineData); break; case 21: lineData = this.fill_21(line, lineData); break; case 24: lineData.partno = this.getPartno(); if (lineData.partno === 'A') { lineData = this.fill_24_0(line, lineData); } else if (lineData.partno === 'B') { lineData = this.fill_24_1(line, lineData); } break; case 27: lineData = this.fill_27(line, lineData); break; // unimplemented message types case 6: case 7: case 8: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 20: case 22: case 23: case 25: case 26: if (module.parent && module.parent.exports.isDebug) { //if (swu.hasProp(module, 'parent.exports.isDebug')) { console.log('Message type (switch) %d', parseInt(this.binString.substr(0, 6), 2)); console.log(line); console.log('-------------------------------------------------------'); } lineData = false; break; default: if (module.parent && module.parent.exports.isDebug) { //if (swu.hasProp(module, 'prent.exports.isDebug')) { console.log('Message type ????? %d ?????', parseInt(this.binString.substr(0, 6), 2)); } lineData = false; } if (lineData) { if (this.returnJson) { return JSON.stringify(lineData); } else { return lineData; } } else { return false; } }, fill_1_2_3: function (line, lineData) { var latLon = this.getLatLon(); var status = this.getStatus(); var maneuver = this.getManeuver(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.status = status.status_num; lineData.status_text = status.status_text; lineData.turn = this.getTurn(); lineData.speed = this.getSpeed(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.course = this.getCourse(); lineData.heading = this.getHeading(); lineData.second = this.getSecond(); lineData.maneuver = maneuver.maneuver; lineData.maneuver_text = maneuver.maneuver_text; lineData.raim = this.getRaim(); lineData.radio = this.getRadio(); return lineData; }, fill_4: function (line, lineData) { var latLon = this.getLatLon(); var epfd = this.getEpfd(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.year = this.getYear(); lineData.month = this.getMonth(); lineData.day = this.getDay(); lineData.hour = this.getHour(); lineData.minute = this.getMinute(); lineData.second = this.getSecond(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.epfd = epfd.epfd; lineData.epfd_text = epfd.epfd_text; lineData.raim = this.getRaim(); lineData.radio = this.getRadio(); return lineData; }, fill_5: function (line, lineData) { var dimensions = this.getDimensions(); var epfd = this.getEpfd(); var shiptype = this.getShiptype(); var eta = sprintf( '%s-%sT%s:%sZ', this.getMonth().lpad('0', 2), this.getDay().lpad('0', 2), this.getHour().lpad('0', 2), this.getMinute().lpad('0', 2) ); //if (this.aivdmPassthrough) { lineData.aivdm = this.splitLines; } //if (this.aivdmPassthrough) { lineData.aivdm = this.splitParts; } lineData.imo = this.getIMO(); lineData.callsign = this.getCallsign(); lineData.shipname = this.getName(); lineData.shiptype = shiptype.shiptype; lineData.shiptype_text = shiptype.shiptype_text; lineData.to_bow = dimensions.to_bow; lineData.to_stern = dimensions.to_stern; lineData.to_port = dimensions.to_port; lineData.to_starboard = dimensions.to_starboard; lineData.epfd = epfd.epfd; lineData.eta = eta; lineData.epfd_text = epfd.epfd.text; lineData.month = this.getMonth(); lineData.day = this.getDay(); lineData.hour = this.getHour(); lineData.minute = this.getMinute(); lineData.draught = this.getDraught(); lineData.destination = this.getDestination(); lineData.dte = this.getDte(); return lineData; }, fill_9: function (line, lineData) { var latLon = this.getLatLon(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.alt = this.getAlt(); lineData.speed = this.getSpeed(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.course = this.getCourse(); lineData.second = this.getSecond(); lineData.assigned = this.getAssigned(); lineData.raim = this.getRaim(); lineData.radio = this.getRadio(); return lineData; }, fill_18: function (line, lineData) { var latLon = this.getLatLon(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.speed = this.getSpeed(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.course = this.getCourse(); lineData.heading = this.getHeading(); lineData.second = this.getSecond(); lineData.raim = this.getRaim(); lineData.radio = this.getRadio(); return lineData; }, fill_19: function (line, lineData) { var latLon = this.getLatLon(); var dimensions = this.getDimensions(); var epfd = this.getEpfd(); var shiptype = this.getShiptype(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.speed = this.getSpeed(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.course = this.getCourse(); lineData.heading = this.getHeading(); lineData.second = this.getSecond(); lineData.shipname = this.getName(); lineData.shiptype = shiptype.shiptype; lineData.shiptype_text = shiptype.shiptype_text; lineData.to_bow = dimensions.to_bow; lineData.to_stern = dimensions.to_stern; lineData.to_port = dimensions.to_port; lineData.to_starboard = dimensions.to_starboard; lineData.epfd = epfd.epfd; lineData.epfd_text = epfd.epfd_text; lineData.raim = this.getRaim(); return lineData; }, fill_21: function (line, lineData) { var latLon = this.getLatLon(); var dimensions = this.getDimensions(); var epfd = this.getEpfd(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.aid_type = this.getAidType(); lineData.name = this.getName(); lineData.accuracy = this.getAccuracy(); lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.to_bow = dimensions.to_bow; lineData.to_stern = dimensions.to_stern; lineData.to_port = dimensions.to_port; lineData.to_starboard = dimensions.to_starboard; lineData.epfd = epfd.epfd; lineData.epfd_text = epfd.epfd_text; lineData.second = this.getSecond(); lineData.off_position = this.getOffPosition(); lineData.raim = this.getRaim(); lineData.virtual_aid = this.getVirtualAid(); lineData.assigned = this.getAssigned(); lineData.name += this.getNameExtension(); return lineData; }, fill_24_0: function (line, lineData) { if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.part = this.getPartno(); lineData.shipname = this.getName(); return lineData; }, fill_24_1: function (line, lineData) { var dimensions; var vendorInfo = this.getVendorInfo(); var shiptype = this.getShiptype(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.part = this.getPartno(); lineData.shiptype = shiptype.shiptype; lineData.shiptype_text = shiptype.shiptype_text; lineData.callsign = this.getCallsign(); if (lineData.mmsi.toString().substr(0, 2) === '98') { // Then this is an auxiliary craft (see AIVDM Docs) lineData.mothership_mmsi = this.getBits(132, 30); dimensions = {to_bow: null, to_stern: null, to_port: null, to_starboard: null}; } else { lineData.mothership_mmsi = null; dimensions = this.getDimensions(); } lineData.vendorid = vendorInfo.vendorString; lineData.model = vendorInfo.model; lineData.serial = vendorInfo.serial; lineData.to_bow = dimensions.to_bow; lineData.to_stern = dimensions.to_stern; lineData.to_port = dimensions.to_port; lineData.to_starboard = dimensions.to_starboard; return lineData; }, fill_27: function (line, lineData) { var latLon = this.getLatLon(); var status = this.getStatus(); if (this.aivdmPassthrough) { lineData.aivdm = [line]; } lineData.accuracy = this.getAccuracy(); lineData.raim = this.getRaim(); lineData.status = status.status_num; lineData.status_text = status.status_text; lineData.lon = latLon.lon; lineData.lat = latLon.lat; lineData.speed = this.getSpeed(); lineData.course = this.getCourse(); return lineData; }, // ------------------------------- /** * getAccuracy() * @returns {boolean} false if 0, else true - to synchronise with how gpsd handles it */ getAccuracy: function () { switch (this.msgType) { case 1: case 2: case 3: case 9: return this.getBits(60, 1) !== 0; case 18: case 19: return this.getBits(56, 1) !== 0; case 21: return this.getBits(163, 1) !== 0; case 27: return this.getBits(38, 1) !== 0; default: return false; } }, getAidType: function () { return this.getBits(38,5); }, getAlt: function () { return this.getBits(38, 12); }, getAssigned: function () { switch (this.msgType) { case 9: return this.getBits(146, 1); case 21: return this.getBits(270, 1); default: return false; } }, getCallsign: function () { var callsignField; switch (this.msgType) { case 5: callsignField = this.binString.substr(70, 42); break; case 24: if (this.partNo == 1) { callsignField = this.binString.substr(90, 42); } else { callsignField = null; } break; default: callsignField = null } if (callsignField) { var callsignArray = callsignField.match(/.{1,6}/g); var callsign = ''; var self = this; _.each(callsignArray, function (binChar, index) { callsign += self.char_table[parseInt(binChar, 2)]; }); return callsign.replace(/@/g, '').trim(); } else { return false; } }, getCourse: function () { switch (this.msgType) { case 1: case 2: case 3: case 9: return this.getBits(116, 12) / 10; break; case 18: case 19: return this.getBits(112, 12) / 10; break; case 27: return this.getBits(85, 9); break; default: return false; } }, getDay: function () { switch (this.msgType) { case 4: return this.getBits(56, 5); case 5: return this.getBits(278, 5); default: return false; } }, getDestination: function () { var destField = null; switch (this.msgType) { case 5: destField = this.binString.substr(302, 120); break; default: destField = null } if (destField) { var destArray = destField.match(/.{1,6}/g); var destination = ''; var self = this; _.each(destArray, function (binChar, index) { destination += self.char_table[parseInt(binChar, 2)]; }); return destination.replace(/@/g, '').trim(); } else { return false; } }, getDimensions: function () { var dimensions = {to_bow: null, to_stern: null, to_port: null, to_starboard: null}; switch (this.msgType) { case 5: dimensions.to_bow = this.getBits(240, 9); dimensions.to_stern = this.getBits(249, 9); dimensions.to_port = this.getBits(258, 6); dimensions.to_starboard = this.getBits(264, 6); break; case 19: dimensions.to_bow = this.getBits(271, 9); dimensions.to_stern = this.getBits(280, 9); dimensions.to_port = this.getBits(289, 6); dimensions.to_starboard = this.getBits(295, 6); break; case 21: dimensions.to_bow = this.getBits(219, 9); dimensions.to_stern = this.getBits(228, 9); dimensions.to_port = this.getBits(237, 6); dimensions.to_starboard = this.getBits(243, 6); break; case 24: dimensions.to_bow = this.getBits(132, 9); dimensions.to_stern = this.getBits(141, 9); dimensions.to_port = this.getBits(150, 6); dimensions.to_starboard = this.getBits(156, 6); break; } return dimensions; }, getDraught: function () { switch (this.msgType) { case 5: return this.getBits(294, 8) / 10; default: return 0; } }, getDte: function () { switch (this.msgType) { case 5: return this.getBits(423, 1); default: return 0; } }, getETA: function () { }, getEpfd: function () { var epfd; switch (this.msgType) { case 4: epfd = this.getBits(134, 4); break; case 5: epfd = this.getBits(270, 4); break; case 19: epfd = this.getBits(310, 4); break; case 21: epfd = this.getBits(249, 4); break; default: epfd = 0; } if (epfd < 0 || epfd > 8) { epfd = 0; } return {epfd: epfd, epfd_text: this.epfdText[epfd]} }, getFragmentNum: function getFragmentNum () { return this.fragmentNum; }, getHeading: function () { switch (this.msgType) { case 1: case 2: case 3: return this.getBits(128, 9); case 18: case 19: return this.getBits(124, 9); default: return false; } }, getHour: function () { switch (this.msgType) { case 4: return this.getBits(61, 5); case 5: return this.getBits(283, 5); default: return false; } }, getIMO: function () { switch (this.msgType) { case 5: return this.getBits(40, 30); default: return false; } }, getLatLon: function () { // Does this message contain position info? var msgType = this.getType(); if (msgType in this.posGroups) { var latGroup = this.posGroups[msgType]['lat']; var lonGroup = this.posGroups[msgType]['lon']; // fetch the relevant bits var latString = this.binString.substr(latGroup['start'], latGroup['length']); var lonString = this.binString.substr(lonGroup['start'], lonGroup['length']); // convert them var lat = this.toTwosComplement(parseInt(latString, 2), latString.length) / latGroup['divisor']; var lon = this.toTwosComplement(parseInt(lonString, 2), lonString.length) / lonGroup['divisor']; return {"lat": parseFloat(lat.toFixed(4)), "lon": parseFloat(lon.toFixed(4))}; } else { // Not a message type that contains a position return {'lat': null, 'lon': null}; } }, getManeuver: function () { var man, maneuver_text; switch (this.msgType) { case 1: case 2: case 3: man = this.getBits(143, 2); break; default: man = 0; } if (man < 1 || man > 2) { man = 0; } maneuver_text = this.maneuverText[man]; return {maneuver: man, maneuver_text: maneuver_text}; }, /** * getMid() Fetched 3 digit MID number that is embedded in MMSI * The mid usually occupies chars 0,1 and 2 of the MMSI string * For some special cases it may be at another location (see below). * Uses this.midTable to look up nationality. * Returns "" unless the option 'includeMID' is set true in the aivdmDecode constructor options * @returns {string} mid - a string containing 3 numeric digits. */ getMid: function () { // See info in http://catb.org/gpsd/AIVDM.html if (this.includeMID) { var mid; var mmsi = this.getMMSI(); var nationality; if (mmsi !== null && mmsi.length === 9) { // Coastal station if (mmsi.substr(0, 2) == "00") { mid = mmsi.substr(2, 3); } // Group of ships (i.e. coast guard is 0369 else if (mmsi.substr(0, 1) === "0") { mid = mmsi.substr(1, 3); } // SAR Aircraft else if (mmsi.substr(0, 3) === "111") { mid = mmsi.substr(3, 3); } // Aus craft associated with a parent ship else if (mmsi.substr(0, 2) === "98" || mmsi.substr(0, 2) === "99") { mid = mmsi.substr(2, 3); } // AIS SART else if (mmsi.substr(0, 3) === "970") { mid = mmsi.substr(3, 3); } // MOB device (972) or EPIRB (974). Neither of these have a MID else if (mmsi.substr(0, 3) === "972" || mmsi.substr(0, 3) === "974") { mid = ""; } // Normal ship transponder else { mid = mmsi.substr(0, 3); } if (mid !== "") { nationality = this.midTable[mid]; if (nationality !== undefined) { if (typeof(nationality) !== 'string') { nationality = ""; } } else { nationality = ""; } } else { nationality = ""; } } else { nationality = ""; } } else { nationality = ""; } return nationality; }, getMMSI: function (/* onlyValidMid */) { //TODO: onlyValidMid to be implemented later return this.getBits(8, 30); }, getMinute: function () { switch (this.msgType) { case 4: return this.getBits(66, 6); case 5: return this.getBits(288, 6); default: return false; } }, getMonth: function () { switch (this.msgType) { case 4: return this.getBits(53, 4); case 5: return this.getBits(274, 4); default: return false; } }, getName: function () { var msgType = this.getType(); var nameField = null; switch (msgType) { case 5: nameField = this.binString.substr(112, 120); break; case 19: nameField = this.binString.substr(143, 120); break; case 21: nameField = this.binString.substr(43, 120); break; case 24: nameField = this.binString.substr(40, 120); break; default: nameField = null } if (nameField) { var nameArray = nameField.match(/.{1,6}/g); var name = ''; var self = this; _.each(nameArray, function (binChar, index) { name += self.char_table[parseInt(binChar, 2)]; }); return name.replace(/@/g, '').trim(); } else { return false; } }, getNameExtension: function () { switch (this.msgType) { case 21: if (this.binString.length >= 272) { var nameBits = this.binString.substring(272, this.binString.length -1); var nameArray = nameBits.match(/.{1,6}/g); var name = ''; var self = this; _.each(nameArray, function (binChar, index) { name += self.char_table[parseInt(binChar, 2)]; }); return name.replace(/@/g, '').trim(); } else { return ''; } break; default: return false; } }, getNumFragments: function getNumFragments () { return this.numFragments; }, getOffPosition: function () { return this.getBits(259, 1); }, getPartno: function () { switch (this.msgType) { case 24: var partRaw = parseInt(this.getBits(38, 2), 2); var partNo = partRaw === 0 ? 'A' : 'B'; return partNo; default: return ''; } }, getRadio: function () { switch (this.msgType) { case 1: case 2: case 3: return this.getBits(149, 19); case 9: case 18: return this.getBits(148, 19); default: return false; } }, getRaim: function () { switch (this.msgType) { case 1: case 2: case 3: return this.getBits(148, 1) !== 0; case 9: case 18: return this.getBits(147, 1) !== 0; case 19: return this.getBits(305, 1) !== 0; case 21: return this.getBits(268, 1) !== 0; case 27: return this.getBits(39, 1) !== 0; default: return false; } }, getSecond: function () { switch (this.msgType) { case 1: case 2: case 3: return this.getBits(137, 6); case 9: return this.getBits(128, 6); case 18: case 19: return this.getBits(133, 6); case 21: return this.getBits(253, 6); default: return false; } }, getSeqMsgId: function () { return this.seqMsgId; }, getShiptype: function () { var sType; switch (this.msgType) { case 5: sType = this.getBits(232, 8); break; case 19: sType = this.getBits(263, 8); break; case 24: sType = this.getBits(40, 8); break; default: sType = 0; } if (sType < 0 || sType > 99) { sType = 0; } return {shiptype: sType, shiptype_text: this.shiptypeText[sType]}; }, getSpeed: function () { if (this.numFragments == 1) { var msgType = this.getType(); if (msgType in this.speedGroups) { var group = this.speedGroups[msgType]; var speedString = this.binString.substr(group['start'], group['length']); return parseInt(speedString, 2) / group['divisor']; } else { return false; } } else { return false; } }, getStatus: function () { var statusText = "", statusNum = -1; switch (this.msgType) { case 1: case 2: case 3: statusNum = this.getBits(38, 4); break; case 27: statusNum = this.getBits(40, 4); break; } if (statusNum >= 0 && statusNum <= 15) { statusText = this.navStatusText[statusNum]; } // status_num coerced to string to match gpsdecode / gpsd return {status_num: '' + statusNum, status_text: statusText} }, /** * getTurn() Called only for types 1,2 and 3 * @returns {null} */ getTurn: function () { var turn = this.getBits(42, 8); switch (true) { case turn === 0: break; case turn > 0 && turn <= 126: return '' + (4.733 * Math.sqrt(turn)); case turn === 127: return 'fastright'; case turn < 0 && turn >= -126: return '' + (4.733 * Math.sqrt(turn)); case turn === -127: return 'fastleft'; case turn == 128 || turn == -128: return "nan"; default: return "nan"; } }, getType: function () { return this.getBits(0,6); }, getVendorInfo: function () { var vendorBits, vendorArray, vendorString, model, serial; switch (this.msgType) { case 24: vendorBits = this.binString.substr(48, 38); vendorArray = vendorBits.match(/.{1,6}/g); vendorString = ''; var self = this; _.each(vendorArray, function (binChar, index) { vendorString += self.char_table[parseInt(binChar, 2)]; }); vendorString = vendorString.replace(/@/g, '').trim(); model = parseInt(this.binString.substr(66, 4), 2); serial = parseInt(this.binString.substr(70, 20), 2); return {vendorString: vendorString, model: model, serial: serial}; } }, /** * getVendorID not currently implemented * @returns {*} */ getVendorID: function () { var msgType = this.getType(); var vendorID = null; switch (msgType) { case 24: vendorID = this.binString.substr(48, 18); break; default: vendorID = null } if (vendorID) { var vendorIDArray = vendorID.match(/.{1,6}/g); var vid = ''; var self = this; _.each(vendorIDArray, function (binChar, index) { vid += self.char_table[parseInt(binChar, 2)]; }); return vid.replace(/@/g, '').trim(); } else { return false; } }, getVirtualAid: function () { return this.getBits(269, 1); }, getYear: function () { switch (this.msgType) { case 4: return this.getBits(38, 14); default: return false; } }, // --------------------------------------- /** * manageFragments * makes aivdm sentences ready for data fetching by using buildBinString to convert them to a binary string * Returns true when a message is ready for data to be fetched. * For single part messages this is after processing of the aivdm payload * For multi part messages the payloads are accumulated until all have been received, then the binString * conversion is done. * For multi part messages returns false for the first and any intermediate messages * @param line A string containing an AIVDM or AIVDO sentence. May have a tag block on the front of the msg * @param payload The payload portion of the AIVD? string * @returns {boolean} true when this.binString has been set, false when this.binString is not set */ manageFragments: function (line, payload) { // this.splitParts is an array of payloads that are joined to become the binString of multi msgs // this.splitLines is an array of the received lines including AIVDM's if (this.numFragments === 1) { this.splitLines = [line]; this.binString = this.buildBinString(payload); this.msgType = this.getType(); return true; } else if (this.numFragments > 1 && this.fragmentNum === 1) { this.splitParts = [payload]; this.splitLines = [line]; this.splitPart1Sequence = this.seqMsgId; this.binString = this.buildBinString(payload); this.splitPart1Type = this.getType(); this.msgType = this.getType(); return false; } else if (this.numFragments > 1 && this.fragmentNum > 1) { if (this.seqMsgId === this.splitPart1Sequence) { this.splitParts.push(payload); this.splitLines.push(line); } } if (this.fragmentNum === this.numFragments) { var parts = this.splitParts.join(''); this.binString = this.buildBinString(parts); this.msgType = this.splitPart1Type; return true; } else { return false; } }, /** * decode * @param line A line containing an !AIVD sentence * @returns {boolean} true if this.binString has been set (ready for data to be fetched * false if: * binString not set, * line is not an !AIVD * !AIVD is not a supported type (see this.supportedTypes) */ decode: function (bLine) { var line = bLine.toString('utf8'); var aivdmPos = line.indexOf('!AIVD'); if (aivdmPos !== -1) { this.AIVDM = line.substr(aivdmPos); var aivdmFragments = this.AIVDM.split(','); this.numFragments = parseInt(aivdmFragments[1]); this.fragmentNum = parseInt(aivdmFragments[2]); try { this.seqMsgId = parseInt(aivdmFragments[3]); if (typeof(this.seqMsgId) !== 'number') { this.seqMsgId = ''; } } catch (err) { this.seqMsgId = ''; } this.channel = aivdmFragments[4]; var payload = aivdmFragments[5]; if (this.manageFragments(line, payload)) { if (_.contains(this.supportedTypes, this.msgType)) { this.msgType = this.getType(); if (this.msgType == 24) { this.partNo = this.getBits(38, 2) } return this.getData(bLine); //return true; // this.binString is ready } else { return false; } } else { // this.binString is not ready return false; } } else { // no !AIVD on front of line return false; } }, buildBinString: function (payload) { var binStr = ''; var payloadArr = payload.split(""); _.each(payloadArr, function (value) { var dec = value.charCodeAt(0); var bit8 = dec - 48; if (bit8 > 40) { bit8 -= 8; } var strBin = bit8.toString(2); strBin = sprintf('%06s', strBin); binStr += strBin; }); if (module.parent && module.parent.exports.isDebug) { //if (swu.hasProp(module, 'parent.exports.isDebug')) { console.log('binString for type ', parseInt(binStr.substr(0, 6), 2), payload, binStr); } return binStr; }, getBits: function (start, len) { return parseInt(this.binString.substr(start, len), 2); }, asciidec_2_8bit: function (dec) { var newDec = dec - 48; if (newDec > 40) { newDec -= 8; } return newDec; }, dec_2_6bit: function (bit8) { var strBin = bit8.toString(2); strBin = sprintf('%06s', strBin); return strBin; }, toTwosComplement: function (val, bits) { if ((val & (1 << (bits - 1))) != 0) { val -= 1 << bits; } return val; } }; module.exports = { aivdmDecode: aivdmDecode }; if (require.main === module) { var SW_utilsModule = require('SW_utils'); SW_utils = new SW_utilsModule.SW_Utils('aivdmDecode', false); /** * testSet * An array of objects. Each object contains: * aivdm: The raw aivdm sentence to be decoded * gpsd: aivdm as decoded by gpsdecode * test: The fields within the decoded aivdm to test * @type {*[]} */ var testSet = [ // type 5 first msg {aivdm: '!AIVDM,2,1,4,A,539cRCP00000@7WSON08:3?V222222222222221@4@=3340Ht50000000000,0*13', gpsd: '' }, // type 5 second msg {aivdm: '!AIVDM,2,2,4,A,00000000000,2*20', gpsd: {"class":"AIS","device":"stdin","type":5,"repeat":0,"mmsi":211477070,"scaled":true,"imo":0,"ais_version":0,"callsign":"DA9877 ","shipname":"BB 39","shiptype":80,"shiptype_text":"Tanker - all ships of this type","to_bow":34,"to_stern":13,"to_port":3,"to_starboard":3,"epfd":1,"epfd_text":"GPS","eta":"00-00T24:60Z","draught":2.0,"destination":"","dte":0}, test: ['type', 'mmsi', 'imo', 'callsign', 'shipname', 'shiptype', 'shiptype_text', 'to_bow', 'to_stern', 'to_port', 'to_starboard', 'epfd', 'eta', 'draught', 'destination', 'dte'] }, // type 1 {aivdm: '!AIVDM,1,1,,A,144iRPgP001N;PjOb:@F1?vj0PSB,0*47', gpsd: {"class":"AIS","device":"stdin","type":1,"repeat":0,"mmsi":273441410,"scaled":true,"status":"15","status_text":"Not defined","turn":"nan","speed":0.0,"accuracy":false,"lon":20.5739,"lat":55.3277,"course":154.0,"heading":511,"second":25,"maneuver":0,"raim":false,"radio":133330}, test: ['type', 'mmsi', 'status', 'status_text','turn', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second', 'maneuver', 'raim', 'radio'] }, // type 3 {aivdm: '!AIVDM,1,1,,A,33aTCJ0Oh;8>Q>7kW>eKwaf6010P,0*63', gpsd: {"class":"AIS","device":"stdin","type":3,"repeat":0,"mmsi":244913000,"scaled":true,"status":"0","status_text":"Under way using engine","turn":"fastright","speed":1.1,"accuracy":false,"lon":115.0198,"lat":-21.6479,"course":307.0,"heading":311,"second":3,"maneuver":0,"raim":false,"radio":4128}, test: ['type', 'mmsi', 'status', 'status_text', 'turn', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second', 'maneuver', 'raim', 'radio'] }, // type 9 {aivdm: "!AIVDM,1,1,,A,97oordNF>hPppq5af003QHi0S7sE,0*52", gpsd: { "class": "AIS", "device": "stdin", "type": 9, "repeat": 0, "mmsi": 528349873, "scaled": true, "alt": 3672, "speed": 944, "accuracy": true, "lon": 12.4276, "lat": -38.9393, "course": 90.1, "second": 35, "regional": 16, "dte": 0, "raim": false, "radio": 818901 }, test: ['type', 'mmsi', 'speed', 'lon', 'lat'] }, // type 24 {aivdm: '!AIVDM,1,1,,B,H7OeD@QLE=A<D63:22222222220,2*25', gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":503010370,"scaled":true,"part":"A","shipname":"WESTSEA 2"}, test: ['type', 'mmsi', 'part', 'shipname'] }, //type 24 part A {aivdm: '!AIVDM,1,1,,A,H697GjPhT4t@4qUF3;G;?F22220,2*7E', gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":412211146,"scaled":true,"part":"A","shipname":"LIAODANYU 25235"}, test: ['type', 'mmsi', 'part', 'shipname'] }, // type 24 part B {aivdm: '!AIVDM,1,1,,B,H3mw=<TT@B?>1F0<7kplk01H1120,0*5D', gpsd: {"class":"AIS","device":"stdin","type":24,"repeat":0,"mmsi":257936690,"scaled":true,"part":"B","shiptype":36,"shiptype_text":"Sailing","vendorid":"PRONAV","model":3,"serial":529792,"callsign":"LG3843","to_bow":11,"to_stern":1,"to_port":1,"to_starboard":2}, test: ['type', 'mmsi', 'part', 'shiptype', 'shiptype_text', 'vendorid', 'model', 'serial', 'callsign', 'to_bow', 'to_stern', 'to_port', 'to_starboard'] } ]; var aisDecoder = new aivdmDecode({returnJson: false, aivdmPassthrough: true}); _.each(testSet, function (val, index) { var decoded = aisDecoder.decode(val.aivdm); if (decoded) { var testSubject = aisDecoder.getData(val.aivdm); console.log(colors.cyan('Test subject ' + index)); if (testSubject && testSubject.type) { //if (swu.hasProp(testSubject, 'type')) { console.log(colors.cyan('Type: ' + testSubject.type)); } if (val.gpsd.part) { console.log(sprintf(colors.cyan('Part %s'), val.gpsd.part)); } if (val.test) { _.each(val.test, function (item) { console.log('Testing: ' + item); // test for undefined item in testSubject if (testSubject[item] === undefined) { console.log(colors.red('Item missing ' + item)); return; } // test that both items are the same type else if (typeof(val.gpsd[item]) !== typeof(testSubject[item])) { console.log(colors.red('Type mismatch: gpsd: ' + typeof(val.gpsd[item]) + ' me: ' + typeof(testSubject[item]))); return; } // if gpsd is int then testSubject should also be int else if (SW_utils.isInt(val.gpsd[item])) { if (!SW_utils.isInt(testSubject[item])) { console.log(colors.red('Type mismatch (gpsd int testsubject float')); return; } // if gpsd is float then testSubject should also be float } else if (SW_utils.isFloat(val.gpsd[item])) { if (!SW_utils.isFloat(testSubject[item])) { console.log(colors.red('Type mismatch (gpsd float testsubject int')); return } } // finally, test items for equality if (typeof(val.gpsd[item]) === 'string') { gItem = val.gpsd[item].trim(); tItem = testSubject[item].trim(); } else { gItem = val.gpsd[item]; tItem = testSubject[item]; } if (gItem === tItem) { console.log( sprintf(colors.yellow('Test ok gpsd: %s'), gItem) + sprintf(colors.cyan(' me: %s'), tItem) ); } else { console.log(colors.red('Test failed')); console.log(colors.red('gpsd: ' + val.gpsd[item] + ' me: ' + testSubject[item])) } }) } } if (this.isDebug) { console.log(colors.magenta('----------------------------------------------------------')); } }); }
Royhb/aivdmDecode
bin/aivdmDecode.js
JavaScript
mit
69,382
/** * Created by raynald on 8/22/14. */ App.Collections.Contacts = Backbone.Collection.extend({ model : App.Models.Contact, localStorage: new Backbone.LocalStorage('my-contacts') });
raynaldmo/my-contacts
v1/public/js/collection/Contacts.js
JavaScript
mit
189
const assert = require('assert')
airtoxin/elekiter
test/index.js
JavaScript
mit
33
'use strict'; var _ = require('lodash'), jsonFormat = require('json-format'), grunt = require('grunt'); var util = require('../util/util'); module.exports = { json: function(data, options, generatedContent, callback){ if(_.isString(options.dest)){ grunt.file.write(options.dest + '/json/' + generatedContent.task + '.json', jsonFormat(generatedContent)); grunt.file.write(options.dest + '/json/content/' + data.uuid + '.json', jsonFormat(data)); } callback(generatedContent); } }; //
lwhiteley/grunt-pagespeed-report
tasks/config/reporters/json.js
JavaScript
mit
523
/** * Dont edit this file! * This module generates itself from lang.js files! * Instead edit the language files in /lang/ **/ /*global define*/ define(function () { "use strict"; var i18n = {}; i18n.de = { "Visit %s overview" : "Zur %s Übersicht", "An error occured, please reload." : "Es gab einen unerwarteten Fehler. Bitte laden Sie die Seite neu.", "Order successfully saved" : "Reihenfolge erfolgreich gespeichert", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "Ihr Browser unterstützt die folgenden Technologien nicht: %s <br>Bitte installieren Sie eine neuere Version Ihres Browsers!", "Close" : "Schließen", "When asynchronously trying to load a ressource, I came across an error: %s" : "Beim Laden einer Ressource gab es leider folgenden Fehler: %s", "You are using an outdated web browser. Please consider an update!" : "Sie benutzen eine veraltete Browser Version. Bitte installieren Sie einen aktuelleren Browser.", "No results found." : "Keine Ergebnisse gefunden.", "No results found for \"%s\"." : "Keine Ergebnisse für \"%s\" gefunden.", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "Du hast es fast geschafft!", "Show overview" : "Übersicht anzeigen", "Show %d contents for \"%s\"" : "", "Abort": "Abbrechen" }; i18n.en = { "An error occured, please reload." : "", "Close" : "", "Visit %s overview" : "", "Order successfully saved" : "", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "", "When asynchronously trying to load a ressource, I came across an error: %s" : "", "You are using an outdated web browser. Please consider an update!" : "", "No results found." : "", "No results found for \"%s\"." : "", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "", "Show overview" : "", "Show %d contents for \"%s\"" : "", "Abort": "" }; return i18n; });
creitiv/athene2
src/assets/source/scripts/modules/serlo_i18n.js
JavaScript
mit
2,085
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Person = mongoose.model('Person'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), _ = require('lodash'); /** * Create a Person */ exports.create = function(req, res) { var person = new Person(req.body); person.user = req.user; person.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * Show the current Person */ exports.read = function(req, res) { // convert mongoose document to JSON var person = req.person ? req.person.toJSON() : {}; // Add a custom field to the Article, for determining if the current User is the "owner". // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model. // person.isCurrentUserOwner = req.user && person.user && person.user._id.toString() === req.user._id.toString(); res.jsonp(person); }; /** * Update a Person */ exports.update = function(req, res) { var person = req.person; person = _.extend(person, req.body); person.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * Delete a Person */ exports.delete = function(req, res) { var person = req.person; person.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * List of People */ exports.list = function(req, res) { var search = {}; if (req.query.full_name) { search.full_name = new RegExp(req.query.full_name, 'i'); } if (req.query.url) { search.url = new RegExp(req.query.url, 'i'); } if (req.query.email) { search.email = new RegExp(req.query.email, 'i'); } if (req.query.job) { search.job = new RegExp(req.query.job, 'i'); } if (req.query.location_safe) { search.location_safe = new RegExp(req.query.location_safe, 'i'); } if (req.query.phone) { search.phone = new RegExp(req.query.phone, 'i'); } if (req.query.notes) { search.notes = new RegExp(req.query.notes, 'i'); } if (req.query.keywords) { search.keywords = new RegExp(req.query.keywords, 'i'); } Person.find(search).sort('-created').exec(function (err, people) { if (err) { return res.status(400).send({ message: err.message }); } else { res.json(people); } }); }; /** * List of Dupliacte People */ exports.duplicates = function (req, res) { var aggregate = [ { $group: { _id: { url: '$url' }, count: { $sum: 1 } } }, { $match: { count: { $gte: 2 } } } ]; Person.aggregate(aggregate, function (err, groups) { if (err) { return res.status(400).send({ message: err.message }); } else { var dup_urls = []; for (var i = 0; i < groups.length; i++) { var group = groups[i]; var _id = group._id; dup_urls.push(_id.url); } Person.find({ url: { $in: dup_urls } }).sort('url').exec(function (err, people) { if (err) { return res.status(400).send({ message: err.message }); } else { res.json(people); } }); } }); }; /** * Person middleware */ exports.personByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Person is invalid' }); } Person.findById(id).populate('user', 'displayName').exec(function (err, person) { if (err) { return next(err); } else if (!person) { return res.status(404).send({ message: 'No Person with that identifier has been found' }); } req.person = person; next(); }); };
tmrotz/LinkedIn-People-MEAN.JS
modules/people/server/controllers/people.server.controller.js
JavaScript
mit
4,096
"use strict";require("retape")(require("./index"))
SunboX/fxos-washing-machine_interface
b2g_sdk/34.0a1-2014-08-12-04-02-01/B2G.app/Contents/MacOS/modules/commonjs/diffpatcher/test/tap.js
JavaScript
mit
50
/** * Copyright © 2009-2012 A. Matías Quezada */ use('sassmine').on(function(sas) { var Block = Class.extend({ constructor: function(message, code) { this.base(); this.message = message; this.code = code; this.before = []; this.after = []; }, execute: function() { this.code.call(null, sas); }, addBeforeEach: function(action) { this.before.push(action); }, addAfterEach: function(action) { this.after.push(action); }, beforeEach: function() { for (var i = 0; i < this.before.length; i++) this.before[i].call(null, sas); }, afterEach: function() { for (var i = 0; i < this.after.length; i++) this.after[i].call(null, sas); } }); sas.Spec = sas.Suite = Block.extend(); });
amatiasq/Sassmine
lib/Block.js
JavaScript
mit
753
'use strict' const { describe, it, beforeEach, afterEach } = require('mocha') const Helper = require('hubot-test-helper') const { expect } = require('chai') const mock = require('mock-require') const http = require('http') const sleep = m => new Promise(resolve => setTimeout(() => resolve(), m)) const request = uri => { return new Promise((resolve, reject) => { http .get(uri, res => { const result = { statusCode: res.statusCode } if (res.statusCode !== 200) { resolve(result) } else { res.setEncoding('utf8') let rawData = '' res.on('data', chunk => { rawData += chunk }) res.on('end', () => { result.body = rawData resolve(result) }) } }) .on('error', err => reject(err)) }) } const infoRutStub = { getPersonByRut (rut) { return new Promise((resolve, reject) => { if (rut === '11111111-1') { return resolve({ name: 'Anonymous', rut }) } else if (rut === '77777777-7') { return resolve({ name: 'Sushi', rut }) } else if (rut === '22222222-2') { return resolve(null) } reject(new Error('Not found')) }) }, getEnterpriseByRut (rut) { return new Promise((resolve, reject) => { if (rut === '11111111-1') { return resolve({ name: 'Anonymous', rut }) } else if (rut === '77777777-7') { return resolve({ name: 'Sushi', rut }) } else if (rut === '22222222-2') { return resolve(null) } reject(new Error('Not found')) }) }, getPersonByName (name) { return new Promise((resolve, reject) => { if (name === 'juan perez perez') { return resolve([ { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' } ]) } else if (name === 'soto') { return resolve([ { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' }, { rut: '11.111.111-1', name: 'Anonymous' } ]) } else if (name === 'info-rut') { return resolve([]) } reject(new Error('Not found')) }) }, getEnterpriseByName (name) { return new Promise((resolve, reject) => { if (name === 'perez') { return resolve([{ rut: '11.111.111-1', name: 'Anonymous' }]) } else if (name === 'info-rut') { return resolve([]) } reject(new Error('Not found')) }) } } mock('info-rut', infoRutStub) const helper = new Helper('./../src/index.js') describe('info rut', function () { beforeEach(() => { this.room = helper.createRoom() }) afterEach(() => this.room.destroy()) describe('person rut valid', () => { const rut = '11111111-1' beforeEach(async () => { this.room.user.say('user', `hubot info-rut rut ${rut}`) await sleep(1000) }) it('should return a full name', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut rut ${rut}`], ['hubot', `Anonymous (${rut})`] ]) }) }) describe('enterprise rut valid', () => { const rut = '77777777-7' beforeEach(async () => { this.room.user.say('user', `hubot info-rut rut ${rut}`) await sleep(1000) }) it('should return a full name', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut rut ${rut}`], ['hubot', `Sushi (${rut})`] ]) }) }) describe('rut invalid', () => { const rut = '22222222-2' beforeEach(async () => { this.room.user.say('user', `hubot info-rut rut ${rut}`) await sleep(1000) }) it('should return a error', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut rut ${rut}`], ['hubot', '@user rut sin resultados'] ]) }) }) describe('rut error', () => { const rut = '1' beforeEach(async () => { this.room.user.say('user', `hubot info-rut rut ${rut}`) await sleep(1000) }) it('should return a error', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut rut ${rut}`], ['hubot', '@user ocurrio un error al consultar el rut'] ]) }) }) describe('name valid', () => { const name = 'juan perez perez' beforeEach(async () => { this.room.user.say('user', `hubot info-rut persona ${name}`) await sleep(1000) }) it('should return a array of results with link', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut persona ${name}`], [ 'hubot', 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Más resultados en ' + 'http://localhost:8080/info-rut?name=juan%20perez%20perez&' + 'type=persona' ] ]) }) }) describe('name valid', () => { const name = 'soto' beforeEach(async () => { this.room.user.say('user', `hubot info-rut persona ${name}`) await sleep(500) }) it('should return a array of results', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut persona ${name}`], [ 'hubot', 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)\n' + 'Anonymous (11.111.111-1)' ] ]) }) }) describe('name without results', () => { const name = 'info-rut' beforeEach(async () => { this.room.user.say('user', `hubot info-rut empresa ${name}`) await sleep(500) }) it('should return a empty results', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut empresa ${name}`], ['hubot', `@user no hay resultados para ${name}`] ]) }) }) describe('name invalid', () => { const name = 'asdf' beforeEach(async () => { this.room.user.say('user', `hubot info-rut persona ${name}`) await sleep(500) }) it('should return a empty results', () => { expect(this.room.messages).to.eql([ ['user', `hubot info-rut persona ${name}`], ['hubot', '@user ocurrio un error al consultar el nombre'] ]) }) }) describe('GET /info-rut?name=perez&type=persona', () => { beforeEach(async () => { this.response = await request( 'http://localhost:8080/info-rut?name=juan%20perez%20perez&type=persona' ) }) it('responds with status 200 and results', () => { expect(this.response.statusCode).to.equal(200) expect(this.response.body).to.equal( 'Anonymous (11.111.111-1)<br/>' + 'Anonymous (11.111.111-1)<br/>' + 'Anonymous (11.111.111-1)<br/>' + 'Anonymous (11.111.111-1)<br/>' + 'Anonymous (11.111.111-1)<br/>' + 'Anonymous (11.111.111-1)' ) }) }) describe('GET /info-rut?name=perez&type=empresa', () => { beforeEach(async () => { this.response = await request( 'http://localhost:8080/info-rut?name=perez&type=empresa' ) }) it('responds with status 200 and results', () => { expect(this.response.statusCode).to.equal(200) expect(this.response.body).to.equal('Anonymous (11.111.111-1)') }) }) describe('GET /info-rut?name=info-rut&type=persona', () => { beforeEach(async () => { this.response = await request( 'http://localhost:8080/info-rut?name=info-rut&type=persona' ) }) it('responds with status 200 and not results', () => { expect(this.response.statusCode).to.equal(200) expect(this.response.body).to.equal('no hay resultados para info-rut') }) }) describe('GET /info-rut', () => { beforeEach(async () => { this.response = await request('http://localhost:8080/info-rut') }) it('responds with status 200 and not results', () => { expect(this.response.statusCode).to.equal(200) expect(this.response.body).to.equal('faltan los parametros type y name') }) }) describe('GET /info-rut?name=asdf&type=persona', () => { beforeEach(async () => { this.response = await request( 'http://localhost:8080/info-rut?name=asdf&type=persona' ) }) it('responds with status 200 and not results', () => { expect(this.response.statusCode).to.equal(200) expect(this.response.body).to.equal( 'Ocurrio un error al consultar el nombre' ) }) }) })
lgaticaq/hubot-info-rut
test/test.js
JavaScript
mit
9,067
// package metadata file for Meteor.js Package.describe({ name: 'startup-cafe', "author": "Dragos Mateescu <dmateescu@tremend.ro>", "licenses": [ { "type": "MIT", "url": "http://opensource.org/licenses/MIT" } ], "scripts": { }, "engines": { "node": ">= 0.10.0" }, "devDependencies": { "grunt": "~0.4.5", "grunt-autoprefixer": "~0.8.1", "grunt-contrib-concat": "~0.4.0", "grunt-contrib-jshint": "~0.10.0", "grunt-contrib-less": "~0.11.3", "grunt-contrib-uglify": "~0.5.0", "grunt-contrib-watch": "~0.6.1", "grunt-contrib-clean": "~ v0.6.0", "grunt-modernizr": "~0.5.2", "grunt-stripmq": "0.0.6", "grunt-wp-assets": "~0.2.6", "load-grunt-tasks": "~0.6.0", "time-grunt": "~0.3.2", "grunt-bless": "^0.1.1" } }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2', 'dist/css/bootstrap.css', 'dist/js/bootstrap.js', ], 'client'); });
dragosmateescu/startup-cafe
package.js
JavaScript
mit
1,260
exports.engine = function(version){ version = version || null; switch (version){ case null: case '0.8.2': return require('./0.8.2').engine; default: return null; } };
keeto/deck
Source/engines/v8cgi/engine.js
JavaScript
mit
182
'use strict'; var Killable = artifacts.require('../contracts/lifecycle/Killable.sol'); require('./helpers/transactionMined.js'); contract('Killable', function(accounts) { it('should send balance to owner after death', async function() { let killable = await Killable.new({from: accounts[0], value: web3.toWei('10','ether')}); let owner = await killable.owner(); let initBalance = web3.eth.getBalance(owner); await killable.kill({from: owner}); let newBalance = web3.eth.getBalance(owner); assert.isTrue(newBalance > initBalance); }); });
maraoz/zeppelin-solidity
test/Killable.js
JavaScript
mit
571
'use strict'; describe('Directive: resize', function () { // load the directive's module beforeEach(module('orderDisplayApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); //TODO: Add unit tests /*it('should change height', inject(function ($compile, $window) { element = angular.element('<resize></resize>'); element = $compile(element)(scope); expect(scope.screenHeight).toBe($window.outerHeight); }));*/ });
PureHacks/PickMeUp
test/spec/directives/resize.js
JavaScript
mit
487
'use strict'; angular.module('core').controller('HomeController', ['$scope', 'Authentication', '$http', '$modal','$rootScope', function($scope, Authentication, $http, $modal, $rootScope) { // This provides Authentication context. $scope.authentication = Authentication; $scope.card = {}; $scope.columnWidth = function() { return Math.floor((100 / $scope.columns.length) * 100) / 100; }; $scope.updateCard = function(column, card) { var modalInstance = $modal.open({ templateUrl: '/modules/core/views/card-details.client.view.html', controller: modalController, size: 'lg', resolve: { items: function() { return angular.copy({ title: card.title, Details: card.details, release: card.release, cardColor: card.ragStatus, column: column, architect: card.architect, analyst: card.Analyst, designer: card.designer, buildCell: card.buildCell }); } } }); modalInstance.result.then(function(result) { console.log(result.title); angular.forEach($scope.columns, function(col) { if(col.name === column.name) { angular.forEach(col.cards, function(cd) { if (cd.title === card.title) { if (col.name === 'Backlog') { cd.details = result.Details; } else { cd.details = result.Details; if (result.cardColor) { cd.ragStatus = '#' + result.cardColor; } else { cd.ragStatus = '#5CB85C'; } cd.release = result.release; cd.architect = result.architect; cd.designer = result.designer; cd.Analyst = result.analyst; cd.buildCell = result.buildCell } } }); } }); console.log('modal closed'); }, function() { console.log('modal dismissed'); }); //setTimeout(function() { // $scope.$apply(function(){ // console.log('broadcasting event'); // $rootScope.$broadcast('OpenCardDetails', column, card); // }); //}, 500); }; var modalController = function($scope, $modalInstance, items) { $scope.colorOptions = ['5CB85C','FFEB13','FF0000']; console.log(items.column.name); $scope.card = items; $scope.ok = function () { //events(); $modalInstance.close($scope.card); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; $scope.$on('OpenCardDetails', function(e, column,card) { console.log('in broadcast event'); console.log(column.name); $scope.card = card; }); $scope.columns = [ {'name': 'Backlog',cards: [{'id': '1', 'title': 'item1', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}, {'id': '2','title': 'item2', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}, {'id': '3','title': 'item3', 'drag':true, 'release':"",'ragStatus':'#ffeb13', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}, {'id': '4','title': 'item4', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}, {'id': '5','title': 'item5', 'drag':true, 'release':"",'ragStatus':'#ff0000', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}, {'id': '6','title': 'item6', 'drag':true, 'release':"",'ragStatus':'#5cb85c', 'details':"",'architect':"", 'Analyst':"",'designer':"",'buildCell':""}], 'hideCol':false}, {'name': 'Discovery',cards: [], 'hideCol':false}, {'name': 'Design',cards: [], 'hideCol':false}, {'name': 'Build',cards: [], 'hideCol':false}, {'name': 'Pilot',cards: [], 'hideCol':false} ]; $scope.hiddenCol = function(column) { angular.forEach($scope.columns, function(col) { if(col.name === column.name) { if(column.hideCol === true) { column.hideCol = false; } else { column.hideCol = true; } } }); }; $scope.addCard = function(column) { angular.forEach($scope.columns, function(col){ if(col.name === column.name) { column.cards.push({'title': 'item8','drag':true}); } }); }; $scope.list1 = [ {'title': 'item1', 'drag':true}, {'title': 'item2', 'drag':true}, {'title': 'item3', 'drag':true}, {'title': 'item4', 'drag':true}, {'title': 'item5', 'drag':true}, {'title': 'item6', 'drag':true} ]; $scope.list2 = []; $scope.sortableOptions = { //containment: '#sortable-container1' }; $scope.sortableOptions1 = { //containment: '#sortable-container2' }; $scope.removeCard = function(column, card) { angular.forEach($scope.columns, function(col) { if (col.name === column.name) { col.cards.splice(col.cards.indexOf(card), 1); } }); }; $scope.dragControlListeners = { itemMoved: function (event) { var releaseVar = ''; var columnName = event.dest.sortableScope.$parent.column.name; if (columnName === 'Backlog') { releaseVar = ''; } else { //releaseVar = prompt('Enter Release Info !'); } angular.forEach($scope.columns, function(col) { if (col.name === columnName) { angular.forEach(col.cards, function(card) { if (card.title === event.source.itemScope.modelValue.title) { if (releaseVar === ' ' || releaseVar.length === 0) { releaseVar = 'Rel'; } card.release = releaseVar; } }); } }); } }; } ]);
bonzyKul/continuous
public/modules/core/controllers/home.client.controller.js
JavaScript
mit
7,537
/*eslint-disable */ var webpack = require( "webpack" ); var sml = require( "source-map-loader" ); /*eslint-enable */ var path = require( "path" ); module.exports = { module: { preLoaders: [ { test: /\.js$/, loader: "source-map-loader" } ], loaders: [ { test: /sinon.*\.js/, loader: "imports?define=>false" }, { test: /\.spec\.js$/, exclude: /node_modules/, loader: "babel-loader" } ], postLoaders: [ { test: /\.js$/, exclude: /(spec|node_modules)\//, loader: "istanbul-instrumenter" } ] }, resolve: { alias: { "when.parallel": "when/parallel", "when.pipeline": "when/pipeline", react: "react/dist/react-with-addons.js", lux: path.join( __dirname, "./lib/lux.js" ) } } };
rniemeyer/lux.js
webpack.config.test.js
JavaScript
mit
733
const { environment } = require('@rails/webpacker') const webpack = require('webpack') // excluding node_modules from being transpiled by babel-loader. environment.loaders.delete("nodeModules"); environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: "jquery", Popper: ['popper.js', 'default'] })) // const aliasConfig = { // 'jquery': 'jquery-ui-dist/external/jquery/jquery.js', // 'jquery-ui': 'jquery-ui-dist/jquery-ui.js' // }; // environment.config.set('resolve.alias', aliasConfig); // resolve-url-loader must be used before sass-loader // https://github.com/rails/webpacker/blob/master/docs/css.md#resolve-url-loader environment.loaders.get("sass").use.splice(-1, 0, { loader: "resolve-url-loader" }); module.exports = environment
edk/tribalknow
config/webpack/environment.js
JavaScript
mit
810
const ResponseMessage = require('../../messages').Response; const through2 = require('through2'); const xtend = require('xtend'); var defaults = { ignore_invalid: false }; function encoder(Message, options) { options = xtend(defaults, options || {}); return through2.obj(function(message, enc, callback) { if (Message.verify(message)) { if (options.ignore_invalid) { return this.queue(message); } throw new Error('unhandled request'); } return callback(null, Message.encodeDelimited(message).finish()); }); } module.exports = function () { return encoder(ResponseMessage); };
auth0/node-baas
lib/pipeline/response_writer.js
JavaScript
mit
673
// Modified from https://github.com/dburrows/draft-js-basic-html-editor/blob/master/src/utils/draftRawToHtml.js 'use strict'; import { List } from 'immutable'; import * as InlineStylesProcessor from './inline-styles-processor'; import ApiDataInstance from './api-data-instance'; import AtomicBlockProcessor from './atomic-block-processor'; import ENTITY from './entities'; import merge from 'lodash/merge'; const _ = { merge, } const annotationIndicatorPrefix = '__ANNOTATION__='; let defaultBlockTagMap = { 'atomic': `<div>%content%</div>`, 'blockquote': `<blockquote>%content%</blockquote>`, 'code-block': `<code>%content%</code>`, 'default': `<p>%content%</p>`, 'header-one': `<h1>%content%</h1>`, 'header-two': `<h2>%content%</h2>`, 'header-three': `<h3>%content%</h3>`, 'header-four': `<h4>%content%</h4>`, 'header-five': `<h5>%content%</h5>`, 'header-six': `<h6>%content%</h6>`, 'ordered-list-item': `<li>%content%</li>`, 'paragraph': `<p>%content%</p>`, 'unordered-list-item': `<li>%content%</li>`, 'unstyled': `<p>%content%</p>`, }; let inlineTagMap = { BOLD: ['<strong>', '</strong>'], CODE: ['<code>', '</code>'], default: ['<span>', '</span>'], ITALIC: ['<em>', '</em>'], UNDERLINE: ['<u>', '</u>'], }; let defaultEntityTagMap = { [ENTITY.ANNOTATION.type]: ['<abbr title="<%= data.pureAnnotationText %>"><%= data.text %>', '</abbr>'], [ENTITY.AUDIO.type]: ['<div class="audio-container"><div class="audio-title"><%= data.title %></div><div class="audio-desc"><%= data.description %></div><audio src="<%= data.url %>" />', '</div>'], [ENTITY.BLOCKQUOTE.type]: ['<blockquote><div><%= data.quote %></div><div><%= data.quoteBy %></div>', '<blockquote>'], [ENTITY.EMBEDDEDCODE.type]: ['<div><%= data.embeddedCode%>', '</div>'], [ENTITY.INFOBOX.type]: ['<div class="info-box-container"><div class="info-box-title"><%= data.title %></div><div class="info-box-body"><%= data.body %></div>', '</div>'], [ENTITY.LINK.type]: ['<a target="_blank" href="<%= data.url %>">', '</a>'], [ENTITY.IMAGE.type]: ['<img alt="<%= data.description %>" src="<%= data.url %>">', '</img>'], [ENTITY.IMAGELINK.type]: ['<img alt="<%= data.description %>" src="<%= data.url %>">', '</img>'], [ENTITY.SLIDESHOW.type]: ['<!-- slideshow component start --> <ol class="slideshow-container"> <% if(!data) { data = []; } data.forEach(function(image) { %><li class="slideshow-slide"><img src="<%- image.url %>" /></li><% }); %>', '</ol><!-- slideshow component end -->'], [ENTITY.IMAGEDIFF.type]: ['<!-- imageDiff component start --> <ol class="image-diff-container"> <% if(!data) { data = []; } data.forEach(function(image, index) { if (index > 1) { return; } %><li class="image-diff-item"><img src="<%- image.url %>" /></li><% }); %>', '</ol><!-- imageDiff component end-->'], [ENTITY.YOUTUBE.type]: ['<iframe width="560" height="315" src="https://www.youtube.com/embed/<%= data.youtubeId %>" frameborder="0" allowfullscreen>', '</iframe>'], }; let nestedTagMap = { 'ordered-list-item': ['<ol>', '</ol>'], 'unordered-list-item': ['<ul>', '</ul>'], }; function _convertInlineStyle (block, entityMap, blockTagMap, entityTagMap) { return blockTagMap[block.type] ? blockTagMap[block.type].replace( '%content%', InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block) ) : blockTagMap.default.replace( '%content%', InlineStylesProcessor.convertToHtml(inlineTagMap, block) ); } function _convertBlocksToHtml (blocks, entityMap, blockTagMap, entityTagMap) { let html = ''; let nestLevel = []; // store the list type of the previous item: null/ol/ul blocks.forEach((block) => { // create tag for <ol> or <ul>: deal with ordered/unordered list item // if the block is a list-item && the previous block is not a list-item if (nestedTagMap[block.type] && nestLevel[0] !== block.type) { html += nestedTagMap[block.type][0]; // start with <ol> or <ul> nestLevel.unshift(block.type); } // end tag with </ol> or </ul>: deal with ordered/unordered list item if (nestLevel.length > 0 && nestLevel[0] !== block.type) { html += nestedTagMap[nestLevel.shift()][1]; // close with </ol> or </ul> } html += _convertInlineStyle(block, entityMap, blockTagMap, entityTagMap); }); // end tag with </ol> or </ul>: or if it is the last block if (blocks.length > 0 && nestedTagMap[blocks[blocks.length - 1].type]) { html += nestedTagMap[nestLevel.shift()][1]; // close with </ol> or </ul> } return html; } function convertBlocksToApiData (blocks, entityMap, entityTagMap) { let apiDataArr = List(); let content = []; let nestLevel = []; blocks.forEach((block) => { // block is not a list-item if (!nestedTagMap[block.type]) { // if previous block is a list-item if (content.length > 0 && nestLevel.length > 0) { apiDataArr = apiDataArr.push(new ApiDataInstance({ type: nestLevel[0], content: content })); content = []; nestLevel.shift(); } if (block.type.startsWith('atomic') || block.type.startsWith('media')) { apiDataArr = apiDataArr.push(AtomicBlockProcessor.convertBlock(entityMap, block)); } else { let converted = InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block); let type = block.type; // special case for block containing annotation entity // set this block type as annotation if (converted.indexOf(annotationIndicatorPrefix) > -1) { type = ENTITY.ANNOTATION.type.toLowerCase(); } apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: type, content: [converted] })); } } else { let converted = InlineStylesProcessor.convertToHtml(inlineTagMap, entityTagMap, entityMap, block); // previous block is not an item-list block if (nestLevel.length === 0) { nestLevel.unshift(block.type); content.push(converted); } else if (nestLevel[0] === block.type) { // previous block is a item-list and current block is the same item-list content.push(converted); } else if (nestLevel[0] !== block.type) { // previous block is a different item-list. apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: nestLevel[0], content: content })); content = [converted]; nestLevel[0] = block.type; } } }); // last block is a item-list if (blocks.length > 0 && nestLevel.length > 0) { let block = blocks[blocks.length - 1]; apiDataArr = apiDataArr.push(new ApiDataInstance({ id: block.key, type: block.type, content: content })); } return apiDataArr; } function convertRawToHtml (raw, blockTagMap, entityTagMap) { blockTagMap = _.merge({}, defaultBlockTagMap, blockTagMap); entityTagMap = entityTagMap || defaultEntityTagMap; let html = ''; raw = raw || {}; const blocks = Array.isArray(raw.blocks) ? raw.blocks : []; const entityMap = typeof raw.entityMap === 'object' ? raw.entityMap : {}; html = _convertBlocksToHtml(blocks, entityMap, blockTagMap, entityTagMap); return html; } function convertRawToApiData (raw) { let apiData; raw = raw || {}; const blocks = Array.isArray(raw.blocks) ? raw.blocks : []; const entityMap = typeof raw.entityMap === 'object' ? raw.entityMap : {}; let entityTagMap = _.merge({}, defaultEntityTagMap, { // special handling for annotation entity // annotation entity data will be included in the speical comment. [ENTITY.ANNOTATION.type]: [`<!--${annotationIndicatorPrefix}<%= JSON.stringify(data) %>--><!--`, '-->'], }); apiData = convertBlocksToApiData(blocks, entityMap, entityTagMap); return apiData; } export default { convertToHtml: convertRawToHtml, convertToApiData: convertRawToApiData, };
nickhsine/keystone
fields/types/html/editor/draft-converter.js
JavaScript
mit
7,620
var log = require('./logger')('reporter', 'yellow'); var colors = require('colors'); /* eslint no-console: 0 */ module.exports = function(diff) { var keys = Object.keys(diff); var count = 0; var timer = log.timer('reporting'); if (keys.length === 0) { log('✔ no diff detected', 'green'); } else { log('✗ build doesn\'t match!', 'red'); console.log('\nREPORT\n' + colors.white.bgBlack(' [selector] ') + '\n [attribute] ' + '[actual] '.red + '[expected]'.green); keys.forEach(function(key) { var rules = Object.keys(diff[key]); console.log(colors.white.bgBlack('\n ' + key + ' ')); rules.forEach(function(rule) { count++; var expected = pretty(diff[key][rule].expected); var actual = pretty(diff[key][rule].actual); console.log(' ' + rule + ': ' + actual.red + ' ' + expected.green); }); }); } console.log(''); var c = count === 0 ? 'green' : 'red'; log('Broken rules: ' + count, c); log('Affected selectors: ' + keys.length, c); timer(); }; function pretty(val) { if (typeof val !== 'string') { val = JSON.stringify(val, null, 4); } return val; }
zeachco/css-specs
lib/reporter.js
JavaScript
mit
1,160
'use strict'; const moment = require('moment-timezone'); const mongoose = web.require('mongoose'); const Schema = mongoose.Schema, ObjectId = Schema.ObjectId; const OTHERS = {key: 'OTH', value: 'Others'}; module.exports = function({ modelName, displayName, cols, colMap = {}, enableDangerousClientFiltering = false, style, addPermission, editPermission, populate, // do you validations, extra save logic here // throw an error or handle it yourself by returning true beforeSave = (record, req, res)=>{}, beforeRender, afterSave, parentTemplate, shouldShowDeleteAction = true, shouldShowSaveButton = true, additionalSubmitButtons = [], handlers = {}, } = {}) { return { get: async function(req, res) { let queryModel = enableDangerousClientFiltering && req.query.model; let modelStr = modelName || queryModel; let recId = req.query._id; let isUpdateMode = recId; let isInsertMode = !isUpdateMode; let querySaveView = req.query.saveView; let queryDisplayName = displayName || req.query.displayName; let colIds = []; for (let col of cols || []) { if (web.objectUtils.isString(col)) { colIds.push(col); } else { colIds.push(col.id); colMap[col.id] = Object.assign({}, col, colMap[col.id]); } } let model = web.cms.dbedit.utils.searchModel(modelStr); // deep clone let modelAttr = model.getModelDictionary(); let modelSchema = modelAttr.schema; let filterCols = (colIds.length > 0 ? colIds : null) || (enableDangerousClientFiltering && req.query.filterCols && req.query.filterCols.split(',')) || Object.keys(modelSchema); for (let colId of filterCols) { if (!colMap[colId]) { colMap[colId] = {}; } } const readOnly = (enableDangerousClientFiltering && req.query.readOnly && req.query.readOnly.split(',')); let myShouldShowDeleteAction = shouldShowDeleteAction; if (enableDangerousClientFiltering && req.query.shouldShowDeleteAction) { myShouldShowDeleteAction = req.query.shouldShowDeleteAction === "Y"; } let myModelName = modelAttr.name; let modelDisplayName = queryDisplayName || modelAttr.displayName || modelAttr.name; parentTemplate = parentTemplate || web.cms.conf.adminTemplate; let redirectAfter = req.query._backUrl || ('/admin/dbedit/list' + (queryModel ? ('?model=' + encodeURIComponent(queryModel)) : '')); //can be optimized by avoiding query if there's no id let rec = {}; if (isUpdateMode) { let recProm = model.findOne({_id:recId}); if (populate) { recProm.populate(populate); } rec = await recProm.exec(); if (!rec) { req.flash('error', 'Record not found.'); res.redirect(redirectAfter); return; } } if (req.session.recCache && req.session.recCache[req.url]) { rec = req.session.recCache[req.url]; req.session.recCache[req.url] = null; } let pageTitle = null; if (isUpdateMode) { pageTitle = 'Update ' + modelDisplayName; } else { pageTitle = 'Create ' + modelDisplayName; } for (let colName in colMap) { let colMapObj = colMap[colName]; if (colMapObj.default && rec[colName] === undefined) { rec[colName] = colMapObj.default; } if (colMapObj.colSpan) { colMapObj.colSpanStr = '-' + colMapObj.colSpan.toString(); } if (colMapObj.inline) { colMapObj.inlineStr = " form-check-inline mr-2"; } if (colMapObj.hideLabel === true) { colMapObj._hideLabel = colMapObj.hideLabel; } else { colMapObj._hideLabel = false; } if (colMapObj.addOthers) { colMapObj._addOthers = Object.assign({ value: getVal(rec, colMapObj.addOthers.id), placeholder: 'If Others, please specify' }, colMapObj.addOthers); } if (colMapObj._addOthers) { colMapObj.inputValues.set(OTHERS.key, OTHERS.value) } handleModelSchemaForColObj(modelSchema, colName, colMap, rec) if (handlers[colName]) { colMapObj.htmlValue = await handlers[colName](rec, isUpdateMode, req); } handleColObjMultiple(colMapObj, colName, rec); if (colMapObj.inputValues && web.objectUtils.isFunction(colMapObj.inputValues)) { // need to do this to avoid the cache and overwriting the existing colMapObj.inputValuesFunc = colMapObj.inputValues; } if (colMapObj.inputValuesFunc) { colMapObj.inputValues = await colMapObj.inputValuesFunc(rec, req, isInsertMode); } colMapObj.readOnlyComputed = (readOnly && readOnly.indexOf(colName) !== -1) || (colMapObj.readOnly === 'U' && isUpdateMode) || (colMapObj.readOnly === 'I' && isInsertMode) || (web.objectUtils.isFunction(colMapObj.readOnly) && await colMapObj.readOnly(rec, req, isInsertMode)) || colMapObj.readOnly === true; colMapObj.visibleComputed = true; if (colMapObj.visible !== undefined) { colMapObj.visibleComputed = await colMapObj.visible(rec, req, isInsertMode); } if (colMapObj.header) { colMapObj.headerComputed = (web.objectUtils.isFunction(colMapObj.header) && await colMapObj.header(rec, req, isInsertMode)) || colMapObj.header; } let propsStrArr = []; colMapObj.props = colMapObj.props || {}; let inputType = colMapObj.inputType || colMapObj.props.type || 'text'; if (inputType === 'money') { inputType = 'number'; colMapObj.props.step = '0.01'; } switch (inputType) { case 'datetime': case 'date': case 'radio': case 'checkbox': case 'select': break; default: colMapObj.props.type = inputType; } for (let propName in colMapObj.props) { let propsValStr = colMapObj.props[propName] || ''; propsStrArr.push(`${propName}="${web.stringUtils.escapeHTML(propsValStr)}"`) } // TODO: unify all props later colMapObj._propsHtml = propsStrArr.join(' '); } let myShowSaveButton = true; if (isUpdateMode && shouldShowSaveButton !== undefined) { myShowSaveButton = (web.objectUtils.isFunction(shouldShowSaveButton) && await shouldShowSaveButton(rec, req, isInsertMode)) || shouldShowSaveButton === true; } for (let submitBtnObj of additionalSubmitButtons) { submitBtnObj.visibleComputed = true; if (submitBtnObj.visible) { submitBtnObj.visibleComputed = await submitBtnObj.visible(rec, req, isInsertMode); } } let fileBackUrl = encodeURIComponent(req.url); let options = { rec: rec, style: style, isUpdateMode: isUpdateMode, modelAttr: modelAttr, queryModelName: queryModel, pageTitle: pageTitle, redirectAfter: redirectAfter, fileBackUrl: fileBackUrl, colMap: colMap, parentTemplate: parentTemplate, filterCols: filterCols, shouldShowDeleteAction: myShouldShowDeleteAction, shouldShowSaveButton: myShowSaveButton, additionalSubmitButtons: additionalSubmitButtons, }; if (beforeRender) { await beforeRender(req, res, options); } let saveView = (enableDangerousClientFiltering && querySaveView) || web.cms.dbedit.conf.saveView; res.render(saveView, options); }, post: async function(req, res) { // TODO: proper error handling let queryModelName = enableDangerousClientFiltering && req.body.modelName; let myModelName = modelName || queryModelName || ''; let recId = req.body._id; if (recId == "") { recId = null; } let isInsertMode = !recId; if (isInsertMode) { if (addPermission && !req.user.hasPermission(addPermission)) { throw new Error("You don't have a permission to add this record."); } } else { if (editPermission && !req.user.hasPermission(editPermission)) { throw new Error("You don't have a permission to edit this record."); } } let model = web.models(myModelName); let rec = await save(recId, req, res, model, beforeSave, colMap, isInsertMode, queryModelName); if (!rec) { return; } if (afterSave && await afterSave(rec, req, res, isInsertMode)) { return; } let handled = false; for (let submitBtnObj of additionalSubmitButtons) { if (req.body.hasOwnProperty(submitBtnObj.actionName)) { handled = await submitBtnObj.handler(rec, req, res); } } if (!handled) { req.flash('info', 'Record saved.'); res.redirect(getRedirectAfter(rec, req, queryModelName)); } } } } async function save(recId, req, res, model, beforeSave, colMap, isInsertMode, queryModelName) { let rec = await model.findOne({_id:recId}); let modelAttr = model.getModelDictionary(); let modelSchema = modelAttr.schema; // TODO: use the col list to set one by one let attrToSet = Object.assign({}, req.body); const shouldSetProperTimezone = web.conf.timezone; for (let colName in modelAttr.schema) { if (attrToSet[colName] || attrToSet[colName] === "") { if (web.objectUtils.isArray(modelSchema[colName])) { attrToSet[colName] = web.ext.arrayUtils.removeDuplicateAndEmpty(attrToSet[colName]); } let dbCol = modelAttr.schema[colName]; if (shouldSetProperTimezone && dbCol.type == Date) { if (attrToSet[colName]) { let date = attrToSet[colName]; let dateFormat = 'MM/DD/YYYY'; if (colMap[colName] && colMap[colName].inputType === "datetime") { dateFormat = 'MM/DD/YYYY hh:mm A'; } if (!web.ext.dateTimeUtils.momentFromString(date, dateFormat).isValid()) { req.flash('error', `${colMap[colName].label} is an invalid date.`); res.redirect(req.url); return; } attrToSet[colName] = moment.tz(attrToSet[colName], dateFormat, web.conf.timezone).toDate(); } else if (attrToSet[colName] === "") { attrToSet[colName] = null; } } else if (dbCol.type == ObjectId) { if (attrToSet[colName] === "") { // for errors of casting empty string to object id attrToSet[colName] = null; } } } } if (!rec) { rec = new model(); attrToSet.createDt = new Date(); attrToSet.createBy = req.user._id; } delete attrToSet._id; attrToSet[web.cms.dbedit.conf.updateDtCol] = new Date(); attrToSet[web.cms.dbedit.conf.updateByCol] = req.user._id; rec.set(attrToSet); try { if (await beforeSave(rec, req, res, isInsertMode)) { return null; } } catch (ex) { console.error("beforeSave threw an error", ex); let errStr = ex.message || "Error on saving record."; req.flash('error', errStr); req.session.recCache[req.url] = req.body; res.redirect(req.url); return null; } if (web.ext && web.ext.dbUtils) { await web.ext.dbUtils.save(rec, req); } else { await rec.save(); } return rec; } function handleModelSchemaForColObj(modelSchema, colName, colMap, rec) { let colMapObj = colMap[colName]; if (modelSchema[colName]) { let attr = modelSchema[colName]; if (!colMap[colName]) { colMap[colName] = {}; } if (attr.default && rec[colName] === undefined) { // assign default values if non existing rec[colName] = attr.default; } colMapObj.required = colMapObj.required || attr.required; colMapObj.label = colMapObj.label == null ? attr.dbeditDisplay || web.cms.dbedit.utils.camelToTitle(colName) : colMapObj.label; } } function getRedirectAfter(rec, req, queryModelName) { let redirectAfter = 'save?_id=' + encodeURIComponent(rec._id.toString()); if (queryModelName) { redirectAfter += '&model=' + encodeURIComponent(queryModelName); } if (req.body._backUrl) { redirectAfter += '&_backUrl=' + encodeURIComponent(req.body._backUrl); } return redirectAfter; } function handleColObjMultiple(colMapObj, colName, rec) { colMapObj.multiple = colMapObj.multiple; if (colMapObj.multiple) { colMapObj.inputName = colName + '[]'; colMapObj._copies = colMapObj.copies; if (!colMapObj._copies) { if (colMapObj.inputType === 'checkbox') { colMapObj._copies = 1; } else { colMapObj._copies = 3; } } if (rec[colName] && rec[colName].length > colMapObj._copies && colMapObj.inputType !== 'checkbox') { colMapObj._copies = rec[colName].length; } } else { colMapObj.inputName = colName; colMapObj._copies = colMapObj._copies || 1; } } function getVal(recObj, key) { if (key.indexOf('.') == -1) { return recObj[key]; } else { return web.objectUtils.resolvePath(recObj, key); } }
mannyvergel/braziw-plugin-dbedit
utils/dbeditSaveController.js
JavaScript
mit
13,441
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape = require('js-string-escape'); var eol = require('os').EOL; function Partial2Js( opts ) { opts = opts || {}; var self = this; this.debug = !!opts.debug; this.patterns = []; this.files = []; this.contents = {}; this.uniqueFn = function( file ) { return file; }; var log = (function log() { if ( this.debug ) { console.log.apply( console, arguments ); } }).bind( this ); var find = (function() { this.files = glob.sync( this.patterns.slice( 0 )) || []; }).bind( this ); function cleanPatterns( patterns ) { return patterns.map(function( entry ) { return entry.replace(/\/\*+/g, ''); }); } function compare( patterns, a, b ) { return matchInPattern( patterns, a ) - matchInPattern( patterns, b ); } var sort = (function() { var clean = cleanPatterns( this.patterns ); this.files.sort(function( a, b ) { return compare( clean, a, b ); }); }).bind( this ); // // this function is not every functional ;) // Should use findIndex() [ES6] as soon as possible // function matchInPattern( patterns, entry ) { var res = patterns.length + 100; patterns.every(function( pattern, index ) { if ( entry.indexOf( pattern ) > -1 ) { res = index; return false; } return true; }); return res; } var unique = (function() { if ( typeof this.uniqueFn === 'function' && this.files && this.files.length ) { var obj = {}; this.files.forEach(function( file ) { var key = self.uniqueFn( file ); if ( !obj[key] ) { obj[key] = file; } }); this.files = obj; } }).bind( this ); var asString = (function( moduleName ) { var buffer = ''; buffer += '(function(window,document){' + eol; buffer += '"use strict";' + eol; buffer += 'angular.module("'+moduleName+'",[]).run(["$templateCache",function($templateCache){' + eol; for ( var k in this.contents ) { buffer += ' $templateCache.put("'+k+'","'+this.contents[k]+'");' + eol; } buffer += '}]);' + eol; buffer += '})(window,document);'; return buffer; }).bind( this ); var read = (function() { var id, path, stat; this.contents = {}; for( var k in this.files ) { id = k; path = this.files[k]; stat = fs.statSync( path ); if ( stat.isFile()) { log('read file:', path, '=>', id ); this.contents[id] = fs.readFileSync( path ); } } return this.contents; }).bind( this ); var asStream = function( string ) { var s = new stream.Readable(); s._read = function noop() {}; s.push( string ); s.push(null); return s; }; var minify = (function() { var opts = { collapseWhitespace: true, preserveLineBreaks: false, removeComments: true, removeRedundantAttributes: true, removeEmptyAttributes: false, keepClosingSlash: true, maxLineLength: 0, customAttrCollapse: /.+/, html5: true }; for ( var k in this.contents ) { this.contents[k] = escape(htmlmin( String(this.contents[k]), opts )); } }).bind( this ); this.add = function( pattern ) { this.patterns.push( pattern ); return this; }; this.not = function( pattern ) { this.patterns.push( '!'+pattern ); return this; }; this.folder = function( folder ) { if ( folder && String( folder ) === folder ) { folder = path.resolve( folder ) + '/**/*'; this.patterns.push( folder ); } return this; }; this.unique = function( fn ) { this.uniqueFn = fn; return this; }; this.stringify = function( moduleName ) { find(); sort(); unique(); read(); minify(); return asString( moduleName ); }; this.stream = function( moduleName ) { return asStream( this.stringify( moduleName ) ); }; } module.exports = function( opts ) { return new Partial2Js( opts ); };
ds82/partial2js
index.js
JavaScript
mit
4,307
var testLogin = function(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; alert("username="+username+" , password="+password); } window.onload = function (){ }
Xcoder1011/OC_StudyDemo
OC与JS互调/WebView-JS/WebView-JS/加载本地的js,html,css/js/test.js
JavaScript
mit
248
/** * marked - a markdown parser * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ ;(function() { /** * Block-Level Grammar */ var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/ }; block.bullet = /(?:[*+-]|\d+\.)/; block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; block.item = replace(block.item, 'gm') (/bull/g, block.bullet) (); block.list = replace(block.list) (/bull/g, block.bullet) ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') ('def', '\\n+(?=' + block.def.source + ')') (); block.blockquote = replace(block.blockquote) ('def', block.def) (); block._tag = '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; block.html = replace(block.html) ('comment', /<!--[\s\S]*?-->/) ('closed', /<(tag)[\s\S]+?<\/\1>/) ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/) (/tag/g, block._tag) (); block.paragraph = replace(block.paragraph) ('hr', block.hr) ('heading', block.heading) ('lheading', block.lheading) ('blockquote', block.blockquote) ('tag', '<' + block._tag) ('def', block.def) (); /** * Normal Block Grammar */ block.normal = merge({}, block); /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, paragraph: /^/, heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ }); block.gfm.paragraph = replace(block.paragraph) ('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|' + block.list.source.replace('\\1', '\\3') + '|') (); /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ }); /** * Block Lexer */ function Lexer(options) { this.tokens = []; this.tokens.links = {}; this.options = options || marked.defaults; this.rules = block.normal; if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables; } else { this.rules = block.gfm; } } } /** * Expose Block Rules */ Lexer.rules = block; /** * Static Lex Method */ Lexer.lex = function(src, options) { var lexer = new Lexer(options); return lexer.lex(src); }; /** * Preprocessing */ Lexer.prototype.lex = function(src) { src = src .replace(/\r\n|\r/g, '\n') .replace(/\t/g, ' ') .replace(/\u00a0/g, ' ') .replace(/\u2424/g, '\n'); return this.token(src, true); }; /** * Lexing */ Lexer.prototype.token = function(src, top, bq) { var src = src.replace(/^ +$/gm, '') , next , loose , cap , bull , b , item , space , i , l; while (src) { // newline if (cap = this.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this.tokens.push({ type: 'space' }); } } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ''); this.tokens.push({ type: 'code', text: !this.options.pedantic ? cap.replace(/\n+$/, '') : cap }); continue; } // fences (gfm) if (cap = this.rules.fences.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'code', lang: cap[2], text: cap[3] || '' }); continue; } // heading if (cap = this.rules.heading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[1].length, text: cap[2] }); continue; } // table no leading pipe (gfm) if (top && (cap = this.rules.nptable.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */); } this.tokens.push(item); continue; } // lheading if (cap = this.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[2] === '=' ? 1 : 2, text: cap[1] }); continue; } // hr if (cap = this.rules.hr.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'hr' }); continue; } // blockquote if (cap = this.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'blockquote_start' }); cap = cap[0].replace(/^ *> ?/gm, ''); // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this.token(cap, top, true); this.tokens.push({ type: 'blockquote_end' }); continue; } // list if (cap = this.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; this.tokens.push({ type: 'list_start', ordered: bull.length > 1 }); // Get each top-level item. cap = cap[0].match(this.rules.item); next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+\.) +/, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (this.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join('\n') + src; i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) loose = next; } this.tokens.push({ type: loose ? 'loose_item_start' : 'list_item_start' }); // Recurse. this.token(item, false, bq); this.tokens.push({ type: 'list_item_end' }); } this.tokens.push({ type: 'list_end' }); continue; } // html if (cap = this.rules.html.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: this.options.sanitize ? 'paragraph' : 'html', pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), text: cap[0] }); continue; } // def if ((!bq && top) && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length); this.tokens.links[cap[1].toLowerCase()] = { href: cap[2], title: cap[3] }; continue; } // table (gfm) if (top && (cap = this.rules.table.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i] .replace(/^ *\| *| *\| *$/g, '') .split(/ *\| */); } this.tokens.push(item); continue; } // top-level paragraph if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this.tokens.push({ type: 'paragraph', text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] }); continue; } // text if (cap = this.rules.text.exec(src)) { // Top-level should never reach here. src = src.substring(cap[0].length); this.tokens.push({ type: 'text', text: cap[0] }); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return this.tokens; }; /** * Inline-Level Grammar */ var inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)([\s\S]*?[^`])\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/ }; inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/; inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/; inline.link = replace(inline.link) ('inside', inline._inside) ('href', inline._href) (); inline.reflink = replace(inline.reflink) ('inside', inline._inside) (); /** * Normal Inline Grammar */ inline.normal = merge({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ }); /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)('])', '~|])')(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text) (']|', '~]|') ('|', '|https?://|') () }); /** * GFM + Line Breaks Inline Grammar */ inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)('{2,}', '*')(), text: replace(inline.gfm.text)('{2,}', '*')() }); /** * Inline Lexer & Compiler */ function InlineLexer(links, options) { this.options = options || marked.defaults; this.links = links; this.rules = inline.normal; this.renderer = this.options.renderer || new Renderer; this.renderer.options = this.options; if (!this.links) { throw new Error('Tokens array requires a `links` property.'); } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks; } else { this.rules = inline.gfm; } } else if (this.options.pedantic) { this.rules = inline.pedantic; } } /** * Expose Inline Rules */ InlineLexer.rules = inline; /** * Static Lexing/Compiling Method */ InlineLexer.output = function(src, links, options) { var inline = new InlineLexer(links, options); return inline.output(src); }; /** * Lexing/Compiling */ InlineLexer.prototype.output = function(src) { var out = '' , link , text , href , cap; while (src) { // escape if (cap = this.rules.escape.exec(src)) { src = src.substring(cap[0].length); out += cap[1]; continue; } // autolink if (cap = this.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === '@') { text = cap[1].charAt(6) === ':' ? this.mangle(cap[1].substring(7)) : this.mangle(cap[1]); href = this.mangle('mailto:') + text; } else { text = escape(cap[1]); href = text; } out += this.renderer.link(href, null, text); continue; } // url (gfm) if (!this.inLink && (cap = this.rules.url.exec(src))) { src = src.substring(cap[0].length); text = escape(cap[1]); href = text; out += this.renderer.link(href, null, text); continue; } // tag if (cap = this.rules.tag.exec(src)) { if (!this.inLink && /^<a /i.test(cap[0])) { this.inLink = true; } else if (this.inLink && /^<\/a>/i.test(cap[0])) { this.inLink = false; } src = src.substring(cap[0].length); out += this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0] continue; } // link if (cap = this.rules.link.exec(src)) { src = src.substring(cap[0].length); this.inLink = true; out += this.outputLink(cap, { href: cap[2], title: cap[3] }); this.inLink = false; continue; } // reflink, nolink if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = this.links[link.toLowerCase()]; if (!link || !link.href) { out += cap[0].charAt(0); src = cap[0].substring(1) + src; continue; } this.inLink = true; out += this.outputLink(cap, link); this.inLink = false; continue; } // strong if (cap = this.rules.strong.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.strong(this.output(cap[2] || cap[1])); continue; } // em if (cap = this.rules.em.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.em(this.output(cap[2] || cap[1])); continue; } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.codespan(escape(cap[2].trim(), true)); continue; } // br if (cap = this.rules.br.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.br(); continue; } // del (gfm) if (cap = this.rules.del.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.del(this.output(cap[1])); continue; } // text if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.text(escape(this.smartypants(cap[0]))); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return out; }; /** * Compile Link */ InlineLexer.prototype.outputLink = function(cap, link) { var href = escape(link.href) , title = link.title ? escape(link.title) : null; return cap[0].charAt(0) !== '!' ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1])); }; /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function(text) { if (!this.options.smartypants) return text; return text // em-dashes .replace(/---/g, '\u2014') // en-dashes .replace(/--/g, '\u2013') // opening singles .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // closing singles & apostrophes .replace(/'/g, '\u2019') // opening doubles .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // closing doubles .replace(/"/g, '\u201d') // ellipses .replace(/\.{3}/g, '\u2026'); }; /** * Mangle Links */ InlineLexer.prototype.mangle = function(text) { if (!this.options.mangle) return text; var out = '' , l = text.length , i = 0 , ch; for (; i < l; i++) { ch = text.charCodeAt(i); if (Math.random() > 0.5) { ch = 'x' + ch.toString(16); } out += '&#' + ch + ';'; } return out; }; /** * Renderer */ function Renderer(options) { this.options = options || {}; } Renderer.prototype.code = function(code, lang, escaped) { if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out; } } if (!lang) { return '<pre><code>' + (escaped ? code : escape(code, true)) + '\n</code></pre>'; } return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + '\n</code></pre>\n'; }; Renderer.prototype.blockquote = function(quote) { return '<blockquote>\n' + quote + '</blockquote>\n'; }; Renderer.prototype.html = function(html) { return html; }; Renderer.prototype.heading = function(text, level, raw) { return '<h' + level + ' id="' + this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, '-') + '">' + text + '</h' + level + '>\n'; }; Renderer.prototype.hr = function() { return this.options.xhtml ? '<hr/>\n' : '<hr>\n'; }; Renderer.prototype.list = function(body, ordered) { var type = ordered ? 'ol' : 'ul'; return '<' + type + '>\n' + body + '</' + type + '>\n'; }; Renderer.prototype.listitem = function(text) { return '<li>' + text + '</li>\n'; }; Renderer.prototype.paragraph = function(text) { return '<p>' + text + '</p>\n'; }; Renderer.prototype.table = function(header, body) { return '<table>\n' + '<thead>\n' + header + '</thead>\n' + '<tbody>\n' + body + '</tbody>\n' + '</table>\n'; }; Renderer.prototype.tablerow = function(content) { return '<tr>\n' + content + '</tr>\n'; }; Renderer.prototype.tablecell = function(content, flags) { var type = flags.header ? 'th' : 'td'; var tag = flags.align ? '<' + type + ' style="text-align:' + flags.align + '">' : '<' + type + '>'; return tag + content + '</' + type + '>\n'; }; // span level renderer Renderer.prototype.strong = function(text) { return '<strong>' + text + '</strong>'; }; Renderer.prototype.em = function(text) { return '<em>' + text + '</em>'; }; Renderer.prototype.codespan = function(text) { return '<code>' + text + '</code>'; }; Renderer.prototype.br = function() { return this.options.xhtml ? '<br/>' : '<br>'; }; Renderer.prototype.del = function(text) { return '<del>' + text + '</del>'; }; Renderer.prototype.link = function(href, title, text) { if (this.options.sanitize) { try { var prot = decodeURIComponent(unescape(href)) .replace(/[^\w:]/g, '') .toLowerCase(); } catch (e) { return ''; } if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { return ''; } } if (this.options.baseUrl && !originIndependentUrl.test(href)) { href = resolveUrl(this.options.baseUrl, href); } var out = '<a href="' + href + '"'; if (title) { out += ' title="' + title + '"'; } out += '>' + text + '</a>'; return out; }; Renderer.prototype.image = function(href, title, text) { if (this.options.baseUrl && !originIndependentUrl.test(href)) { href = resolveUrl(this.options.baseUrl, href); } var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; Renderer.prototype.text = function(text) { return text; }; /** * Parsing & Compiling */ function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; this.options.renderer = this.options.renderer || new Renderer; this.renderer = this.options.renderer; this.renderer.options = this.options; } /** * Static Parse Method */ Parser.parse = function(src, options, renderer) { var parser = new Parser(options, renderer); return parser.parse(src); }; /** * Parse Loop */ Parser.prototype.parse = function(src) { this.inline = new InlineLexer(src.links, this.options, this.renderer); this.tokens = src.reverse(); var out = ''; while (this.next()) { out += this.tok(); } return out; }; /** * Next Token */ Parser.prototype.next = function() { return this.token = this.tokens.pop(); }; /** * Preview Next Token */ Parser.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0; }; /** * Parse Text Tokens */ Parser.prototype.parseText = function() { var body = this.token.text; while (this.peek().type === 'text') { body += '\n' + this.next().text; } return this.inline.output(body); }; /** * Parse Current Token */ Parser.prototype.tok = function() { switch (this.token.type) { case 'space': { return ''; } case 'hr': { return this.renderer.hr(); } case 'heading': { return this.renderer.heading( this.inline.output(this.token.text), this.token.depth, this.token.text); } case 'code': { return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); } case 'table': { var header = '' , body = '' , i , row , cell , flags , j; // header cell = ''; for (i = 0; i < this.token.header.length; i++) { flags = { header: true, align: this.token.align[i] }; cell += this.renderer.tablecell( this.inline.output(this.token.header[i]), { header: true, align: this.token.align[i] } ); } header += this.renderer.tablerow(cell); for (i = 0; i < this.token.cells.length; i++) { row = this.token.cells[i]; cell = ''; for (j = 0; j < row.length; j++) { cell += this.renderer.tablecell( this.inline.output(row[j]), { header: false, align: this.token.align[j] } ); } body += this.renderer.tablerow(cell); } return this.renderer.table(header, body); } case 'blockquote_start': { var body = ''; while (this.next().type !== 'blockquote_end') { body += this.tok(); } return this.renderer.blockquote(body); } case 'list_start': { var body = '' , ordered = this.token.ordered; while (this.next().type !== 'list_end') { body += this.tok(); } return this.renderer.list(body, ordered); } case 'list_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this.token.type === 'text' ? this.parseText() : this.tok(); } return this.renderer.listitem(body); } case 'loose_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this.tok(); } return this.renderer.listitem(body); } case 'html': { var html = !this.token.pre && !this.options.pedantic ? this.inline.output(this.token.text) : this.token.text; return this.renderer.html(html); } case 'paragraph': { return this.renderer.paragraph(this.inline.output(this.token.text)); } case 'text': { return this.renderer.paragraph(this.parseText()); } } }; /** * Helpers */ function escape(html, encode) { return html .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } function unescape(html) { // explicitly match decimal, hex, and named HTML entities return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } function replace(regex, opt) { regex = regex.source; opt = opt || ''; return function self(name, val) { if (!name) return new RegExp(regex, opt); val = val.source || val; val = val.replace(/(^|[^\[])\^/g, '$1'); regex = regex.replace(name, val); return self; }; } function resolveUrl(base, href) { if (!baseUrls[' ' + base]) { // we can ignore everything in base after the last slash of its path component, // but we might need to add _that_ // https://tools.ietf.org/html/rfc3986#section-3 if (/^[^:]+:\/*[^/]*$/.test(base)) { baseUrls[' ' + base] = base + '/'; } else { baseUrls[' ' + base] = base.replace(/[^/]*$/, ''); } } base = baseUrls[' ' + base]; if (href.slice(0, 2) === '//') { return base.replace(/:[^]*/, ':') + href; } else if (href.charAt(0) === '/') { return base.replace(/(:\/*[^/]*)[^]*/, '$1') + href; } else { return base + href; } } baseUrls = {}; originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; function noop() {} noop.exec = noop; function merge(obj) { var i = 1 , target , key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } /** * Marked */ function marked(src, opt, callback) { if (callback || typeof opt === 'function') { if (!callback) { callback = opt; opt = null; } opt = merge({}, marked.defaults, opt || {}); var highlight = opt.highlight , tokens , pending , i = 0; try { tokens = Lexer.lex(src, opt) } catch (e) { return callback(e); } pending = tokens.length; var done = function(err) { if (err) { opt.highlight = highlight; return callback(err); } var out; try { out = Parser.parse(tokens, opt); } catch (e) { err = e; } opt.highlight = highlight; return err ? callback(err) : callback(null, out); }; if (!highlight || highlight.length < 3) { return done(); } delete opt.highlight; if (!pending) return done(); for (; i < tokens.length; i++) { (function(token) { if (token.type !== 'code') { return --pending || done(); } return highlight(token.text, token.lang, function(err, code) { if (err) return done(err); if (code == null || code === token.text) { return --pending || done(); } token.text = code; token.escaped = true; --pending || done(); }); })(tokens[i]); } return; } try { if (opt) opt = merge({}, marked.defaults, opt); return Parser.parse(Lexer.lex(src, opt), opt); } catch (e) { e.message += '\nPlease report this to https://github.com/chjj/marked.'; if ((opt || marked.defaults).silent) { return '<p>An error occured:</p><pre>' + escape(e.message + '', true) + '</pre>'; } throw e; } } /** * Options */ marked.options = marked.setOptions = function(opt) { merge(marked.defaults, opt); return marked; }; marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, sanitizer: null, mangle: true, smartLists: false, silent: false, highlight: null, langPrefix: 'lang-', smartypants: false, headerPrefix: '', renderer: new Renderer, xhtml: false, baseUrl: null }; /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.parse = marked; if (typeof module !== 'undefined' && typeof exports === 'object') { module.exports = marked; } else if (typeof define === 'function' && define.amd) { define(function() { return marked; }); } else { this.marked = marked; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
jhelbig/postman-linux-app
app/resources/app/node_modules/8fold-marked/lib/marked.js
JavaScript
mit
29,680
import React from "react"; import { Message } from "semantic-ui-react"; import Bracket from "./Bracket"; import "./index.scss"; import parseStats from './parseStats'; export default class Brackets extends React.PureComponent { constructor(props) { super(props); this.state = { data: this.updateStats(props), }; } componentWillReceiveProps(nextProps) { if (nextProps.stats !== this.props.stats) { this.setState({ data: this.updateStats(nextProps), }); } } updateStats = (props) => { return parseStats(props.stats); }; render () { if (!this.props.stats) { return ( <Message>Waiting for Tournament Stats...</Message> ); } return ( <div> {this.state.data.map((bracket, $index) => ( <div className="tournament-bracket" key={ bracket.match.matchID }> <Bracket finished={ this.props.stats.finished } item={bracket} key={$index} totalGames={ this.props.stats.options.numberOfGames } /> </div> ))} </div> ); } }
socialgorithm/ultimate-ttt-web
src/components/Lobby/Tournament/types/Brackets/index.js
JavaScript
mit
1,151
define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) { var MotivationBtnView = Backbone.View.extend({ className: 'motivation-btn-view menu-btn', events: { 'click': 'toggle', 'mouseover': 'over', 'mouseout': 'out', }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out'); //initial param this.motivationView = new MotivationView(); //add to page this.render(); }, render: function() { var $button = $('<span class="mif-compass">'); $(this.el).html($button); $(this.el).attr('title', 'motivation...'); $('body > .container').append($(this.el)); return this; }, unrender: function() { this.drawElementsView.unrender(); $(this.el).remove(); }, toggle: function() { this.drawElementsView.toggle(); }, over: function() { $(this.el).addClass('expand'); }, out: function() { $(this.el).removeClass('expand'); } }); var MotivationView = Backbone.View.extend({ className: 'motivation-view', events: { 'click .draw': 'draw', 'click .clean': 'clean', 'change .input-type > select': 'clean' }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'drawMotivation', 'drawGPS', 'drawAssignedSection', 'drawAugmentedSection'); //motivation param this.param = {}; this.param.o_lng = 114.05604600906372; this.param.o_lat = 22.551225247189432; this.param.d_lng = 114.09120440483093; this.param.d_lat = 22.545463347318833; this.param.path = "33879,33880,33881,33882,33883,33884,33885,41084,421,422,423,2383,2377,2376,2334,2335,2565,2566,2567,2568,2569,2570,2571,2572,2573,39716,39717,39718,39719,39720,39721,39722,39723,448,39677,39678"; //GPS param this.param.gps = "114.05538082122803,22.551086528436926#114.05844390392303,22.551324331927283#114.06151771545409,22.551264881093118#114.06260132789612,22.54908499948478#114.06269788742065,22.5456862971879#114.06271934509277,22.54315951091646#114.06271934509277,22.538938188315093#114.06284809112547,22.53441944644356"; //assigned section param this.param.assign = "33878,33881,33883,2874,2877,2347,937,941"; //augmented section param //33878,33879,33880,33881,33882,33883,2874,2875,2876,2877,2878,2347,935,936,937,938,939,940,941, this.param.augment = "33879,33880,33882,2875,2876,2878,935,936,938,939,940"; //add to page this.render(); }, render: function() { //this.drawMotivation(); this.drawAssignedSection(); this.drawAugmentedSection(); this.drawGPS(); return this; }, unrender: function() { $(this.el).remove(); }, toggle: function() { $(this.el).css('display') == 'none' ? $(this.el).show() : $(this.el).hide(); }, drawMotivation: function() { $.get('api/trajectories/motivation', this.param, function(data){ Backbone.trigger('MapView:drawMotivation', data); }); }, drawGPS: function() { var self = this; setTimeout(function() { var points = self.param.gps.split('#'); _.each(points, function(point_text, index) { var data = {}; data.geojson = self._getPoint(point_text); data.options = {}; Backbone.trigger('MapView:drawSampleGPSPoint', data); }); }, 2000); }, drawAssignedSection: function() { $.get('api/elements/sections', {id: this.param.assign}, function(data){ Backbone.trigger('MapView:drawSampleAssignedSection', data); }); }, drawAugmentedSection: function() { $.get('api/elements/sections', {id: this.param.augment}, function(data){ Backbone.trigger('MapView:drawSampleAugmentedSection', data); }); }, _getPoint: function(text) { var point = text.split(','); var geojson = { "type": "FeatureCollection", "features":[{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [parseFloat(point[0]), parseFloat(point[1])] } }] }; return geojson; }, }); return MotivationBtnView; });
AjaxJackjia/TGA
WebContent/module/view/tools/MotivationBtnView.js
JavaScript
mit
4,112
/* * App Actions * * Actions change things in your application * Since this boilerplate uses a uni-directional data flow, specifically redux, * we have these actions which are the only way your application interacts with * your application state. This guarantees that your state is up to date and nobody * messes it up weirdly somewhere. * * To add a new Action: * 1) Import your constant * 2) Add a function like this: * export function yourAction(var) { * return { type: YOUR_ACTION_CONSTANT, var: var } * } */ import { LOAD_SONGS, LOAD_SONGS_SUCCESS, LOAD_SONGS_ERROR, } from './constants'; // /** // * Load the repositories, this action starts the request saga // * // * @return {object} An action object with a type of LOAD_REPOS // */ export function loadSongs() { return { type: LOAD_SONGS, }; } // /** // * Dispatched when the repositories are loaded by the request saga // * // * @param {array} repos The repository data // * @param {string} username The current username // * // * @return {object} An action object with a type of LOAD_REPOS_SUCCESS passing the repos // */ export function songsLoaded(repos, username) { return { type: LOAD_SONGS_SUCCESS, repos, username, }; } // /** // * Dispatched when loading the repositories fails // * // * @param {object} error The error // * // * @return {object} An action object with a type of LOAD_REPOS_ERROR passing the error // */ export function songsLoadingError(error) { return { type: LOAD_SONGS_ERROR, error, }; }
madHEYsia/Muzk
app/containers/App/actions.js
JavaScript
mit
1,581
const simple_sort = (key, a, b) => { if (a[key] < b[key]) return -1 if (a[key] > b[key]) return 1 return 0 } const name_sort = (a, b) => simple_sort('name', a, b) const skill_sort = (a, b) => simple_sort('skill', a, b) const speed_sort = (a, b) => simple_sort('speed', a, b) export { simple_sort, name_sort, skill_sort, speed_sort }
stevegood/tython
util/sorting.js
JavaScript
mit
348
export { default } from './EditData';
caspg/datamaps.co
src/pages/Editor/pages/MapEditor/pages/EditData/index.js
JavaScript
mit
38
// ========================================================================== // DG.ScatterPlotModel // // Author: William Finzer // // Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ========================================================================== sc_require('components/graph/plots/plot_model'); sc_require('components/graph/plots/numeric_plot_model_mixin'); /** @class DG.ScatterPlotModel @extends DG.PlotModel */ DG.ScatterPlotModel = DG.PlotModel.extend(DG.NumericPlotModelMixin, /** @scope DG.ScatterPlotModel.prototype */ { /** * * @param iPlace {DG.GraphTypes.EPlace} * @return { class } */ getDesiredAxisClassFor: function( iPlace) { if( iPlace === DG.GraphTypes.EPlace.eX || iPlace === DG.GraphTypes.EPlace.eY) return DG.CellLinearAxisModel; else if(iPlace === DG.GraphTypes.EPlace.eY2) { return (this.getPath('dataConfiguration.y2AttributeID') === DG.Analysis.kNullAttribute) ? DG.AxisModel : DG.CellLinearAxisModel; } }, /** @property { DG.MovablePointModel } */ movablePoint: null, /** @property { Boolean } */ isMovablePointVisible: function () { return !SC.none(this.movablePoint) && this.movablePoint.get('isVisible'); }.property(), isMovablePointVisibleDidChange: function() { this.notifyPropertyChange('isMovablePointVisible'); }.observes('*movablePoint.isVisible'), /** @property { DG.MovableLineModel } */ movableLine: null, /** @property { Boolean, read only } */ isMovableLineVisible: function () { return !SC.none(this.movableLine) && this.movableLine.get('isVisible'); }.property(), isMovableLineVisibleDidChange: function() { this.notifyPropertyChange('isMovableLineVisible'); }.observes('*movableLine.isVisible'), /** @property { DG.MultipleLSRLsModel } */ multipleLSRLs: null, /** @property { Boolean, read only } */ isLSRLVisible: function () { return !SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isVisible'); }.property(), isLSRLVisibleDidChange: function() { this.notifyPropertyChange('isLSRLVisible'); }.observes('*multipleLSRLs.isVisible'), /** @property { Boolean } */ isInterceptLocked: function ( iKey, iValue) { if( !SC.none( iValue)) { this.setPath('movableLine.isInterceptLocked', iValue); this.setPath('multipleLSRLs.isInterceptLocked', iValue); } return !SC.none(this.movableLine) && this.movableLine.get('isInterceptLocked') || !SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isInterceptLocked'); }.property(), isInterceptLockedDidChange: function() { this.notifyPropertyChange('isInterceptLocked'); }.observes('*movableLine.isInterceptLocked', '*multipleLSRLs.isInterceptLocked'), /** @property { Boolean } */ areSquaresVisible: false, /** * Used for notification * @property{} */ squares: null, init: function() { sc_super(); this.addObserver('movableLine.slope',this.lineDidChange); this.addObserver('movableLine.intercept',this.lineDidChange); }, destroy: function() { this.removeObserver('movableLine.slope',this.lineDidChange); this.removeObserver('movableLine.intercept',this.lineDidChange); sc_super(); }, dataConfigurationDidChange: function() { sc_super(); var tDataConfiguration = this.get('dataConfiguration'); if( tDataConfiguration) { tDataConfiguration.set('sortCasesByLegendCategories', false); // This is a cheat. The above line _should_ bring this about, but I couldn't make it work properly tDataConfiguration.invalidateCaches(); } }.observes('dataConfiguration'), /** Returns true if the plot is affected by the specified change such that a redraw is required, false otherwise. @param {Object} iChange -- The change request to/from the DataContext @returns {Boolean} True if the plot must redraw, false if it is unaffected */ isAffectedByChange: function (iChange) { if (!iChange || !iChange.operation) return false; return sc_super() || (this.isAdornmentVisible('connectingLine') && (iChange.operation === 'moveAttribute' || iChange.operation === 'moveCases')); }, /** * Used for notification */ lineDidChange: function () { SC.run(function() { this.notifyPropertyChange('squares'); }.bind(this)); }, /** * Utility function to create a movable line when needed */ createMovablePoint: function () { if (SC.none(this.movablePoint)) { this.beginPropertyChanges(); this.set('movablePoint', DG.MovablePointModel.create( { plotModel: this })); this.movablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis')); this.endPropertyChanges(); } }, /** * Utility function to create a movable line when needed */ createMovableLine: function () { if (SC.none(this.movableLine)) { this.beginPropertyChanges(); this.set('movableLine', DG.MovableLineModel.create( { plotModel: this, showSumSquares: this.get('areSquaresVisible') })); this.movableLine.recomputeSlopeAndIntercept(this.get('xAxis'), this.get('yAxis')); this.endPropertyChanges(); } }, squaresVisibilityChanged: function() { var tMovableLine = this.get('movableLine'), tMultipleLSRLs = this.get('multipleLSRLs'), tSquaresVisible = this.get('areSquaresVisible'); if( tMovableLine) tMovableLine.set('showSumSquares', tSquaresVisible); if( tMultipleLSRLs) tMultipleLSRLs.set('showSumSquares', tSquaresVisible); }.observes('areSquaresVisible'), enableMeasuresForSelectionDidChange: function(){ sc_super(); this.setPath('multipleLSRLs.enableMeasuresForSelection', this.get('enableMeasuresForSelection')); }.observes('enableMeasuresForSelection'), /** If we need to make a movable line, do so. In any event toggle its visibility. */ toggleMovablePoint: function () { var this_ = this; function toggle() { function doToggle( iPlot) { if (SC.none(iPlot.movablePoint)) { iPlot.createMovablePoint(); // Default is to be visible } else { iPlot.movablePoint.recomputePositionIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis')); iPlot.movablePoint.set('isVisible', !iPlot.movablePoint.get('isVisible')); } } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } var willShow = !this.movablePoint || !this.movablePoint.get('isVisible'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleMovablePoint", undoString: (willShow ? 'DG.Undo.graph.showMovablePoint' : 'DG.Undo.graph.hideMovablePoint'), redoString: (willShow ? 'DG.Redo.graph.showMovablePoint' : 'DG.Redo.graph.hideMovablePoint'), log: "toggleMovablePoint: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle movable point', type: 'DG.GraphView' } }, execute: function () { toggle(); }, undo: function () { toggle(); } })); }, /** If we need to make a movable line, do so. In any event toggle its visibility. */ toggleMovableLine: function () { var this_ = this; function toggle() { function doToggle(iPlot) { if (SC.none(iPlot.movableLine)) { iPlot.createMovableLine(); // Default is to be visible } else { iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis')); iPlot.movableLine.set('isVisible', !iPlot.movableLine.get('isVisible')); } } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } var willShow = !this.movableLine || !this.movableLine.get('isVisible'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleMovableLine", undoString: (willShow ? 'DG.Undo.graph.showMovableLine' : 'DG.Undo.graph.hideMovableLine'), redoString: (willShow ? 'DG.Redo.graph.showMovableLine' : 'DG.Redo.graph.hideMovableLine'), log: "toggleMovableLine: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle movable line', type: 'DG.GraphView' } }, execute: function () { toggle(); }, undo: function () { toggle(); } })); }, /** * Utility function to create the multipleLSRLs object when needed */ createLSRLLines: function () { if (SC.none(this.multipleLSRLs)) { this.set('multipleLSRLs', DG.MultipleLSRLsModel.create( { plotModel: this, showSumSquares: this.get('areSquaresVisible'), isInterceptLocked: this.get('isInterceptLocked'), enableMeasuresForSelection: this.get('enableMeasuresForSelection') })); this.setPath('multipleLSRLs.isVisible', true); } }, /** If we need to make a movable line, do so. In any event toggle its visibility. */ toggleLSRLLine: function () { var this_ = this; function toggle() { function doToggle( iPlot) { if (SC.none(iPlot.get('multipleLSRLs'))) { iPlot.createLSRLLines(); } else { iPlot.setPath('multipleLSRLs.isVisible', !iPlot.getPath('multipleLSRLs.isVisible')); } } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } var willShow = !this.multipleLSRLs || !this.multipleLSRLs.get('isVisible'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleLSRLLine", undoString: (willShow ? 'DG.Undo.graph.showLSRL' : 'DG.Undo.graph.hideLSRL'), redoString: (willShow ? 'DG.Redo.graph.showLSRL' : 'DG.Redo.graph.hideLSRL'), log: "toggleLSRL: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle LSRL', type: 'DG.GraphView' } }, execute: function () { toggle(); }, undo: function () { toggle(); } })); }, /** If we need to make a movable line, do so. In any event toggle whether its intercept is locked. */ toggleInterceptLocked: function () { var this_ = this; function toggle() { function doToggle( iPlot) { if (!SC.none(iPlot.movableLine)) { iPlot.movableLine.toggleInterceptLocked(); iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis')); } if (!SC.none(iPlot.multipleLSRLs)) { iPlot.multipleLSRLs.toggleInterceptLocked(); } } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } function gatherUndoData() { function doGatherUndoData( iPlot) { tResult.push( { movableLine: iPlot.movableLine ? iPlot.movableLine.createStorage() : null, lsrlStorage: iPlot.multipleLSRLs ? iPlot.multipleLSRLs.createStorage() : null }); } var tResult = []; doGatherUndoData( this_); this_.get('siblingPlots').forEach( doGatherUndoData); return tResult; } function restoreFromUndoData( iUndoData) { function doRestoreFromUndoData( iPlot, iIndexMinusOne) { var tUndoData = iUndoData[ iIndexMinusOne + 1]; if( iPlot.movableLine) iPlot.movableLine.restoreStorage(tUndoData.movableLine); if( iPlot.multipleLSRLs) iPlot.multipleLSRLs.restoreStorage(tUndoData.lsrlStorage); } doRestoreFromUndoData( this_, -1); this_.get('siblingPlots').forEach( doRestoreFromUndoData); } var willLock = (this.movableLine && !this.movableLine.get('isInterceptLocked')) || (this.multipleLSRLs && !this.multipleLSRLs.get('isInterceptLocked')); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleLockIntercept", undoString: (willLock ? 'DG.Undo.graph.lockIntercept' : 'DG.Undo.graph.unlockIntercept'), redoString: (willLock ? 'DG.Redo.graph.lockIntercept' : 'DG.Redo.graph.unlockIntercept'), log: "lockIntercept: %@".fmt(willLock), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle lock intercept', type: 'DG.GraphView' } }, execute: function () { this._undoData = gatherUndoData(); toggle(); }, undo: function () { restoreFromUndoData( this._undoData); this._undoData = null; } })); }, /** If we need to make a plotted function, do so. In any event toggle its visibility. */ togglePlotFunction: function () { var this_ = this; function toggle() { function doToggle( iPlot) { iPlot.toggleAdornmentVisibility('plottedFunction', 'togglePlotFunction'); } this_.get('siblingPlots').forEach( doToggle); doToggle( this_); } function connectFunctions() { var tSiblingPlots = this_.get('siblingPlots'), tMasterPlottedFunction = this_.getAdornmentModel('plottedFunction'); tMasterPlottedFunction.set('siblingPlottedFunctions', tSiblingPlots.map( function( iPlot) { return iPlot.getAdornmentModel( 'plottedFunction'); })); } var willShow = !this.isAdornmentVisible('plottedFunction'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.togglePlotFunction", undoString: (willShow ? 'DG.Undo.graph.showPlotFunction' : 'DG.Undo.graph.hidePlotFunction'), redoString: (willShow ? 'DG.Redo.graph.showPlotFunction' : 'DG.Redo.graph.hidePlotFunction'), log: "togglePlotFunction: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle plot function', type: 'DG.GraphView' } }, execute: function () { toggle(); connectFunctions(); }, undo: function () { toggle(); this_.getAdornmentModel('plottedFunction').set('siblingPlottedFunctions', null); } })); }, /** If we need to make a connecting line, do so. In any event toggle its visibility. */ toggleConnectingLine: function () { var this_ = this; function toggle() { function doToggle( iPlot) { var tAdornModel = iPlot.toggleAdornmentVisibility('connectingLine', 'toggleConnectingLine'); if (tAdornModel && tAdornModel.get('isVisible')) tAdornModel.recomputeValue(); // initialize } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } var willShow = !this.isAdornmentVisible('connectingLine'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleConnectingLine", undoString: (willShow ? 'DG.Undo.graph.showConnectingLine' : 'DG.Undo.graph.hideConnectingLine'), redoString: (willShow ? 'DG.Redo.graph.showConnectingLine' : 'DG.Redo.graph.hideConnectingLine'), log: "toggleConnectingLine: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle connecting line', type: 'DG.GraphView' } }, execute: function () { toggle(); }, undo: function () { toggle(); } })); }, /** * Toggle where the squares drawn from points to lines and functions are being shown */ toggleShowSquares: function () { var this_ = this; function toggle() { function doToggle( iPlot) { iPlot.set('areSquaresVisible', !iPlot.get('areSquaresVisible')); } doToggle( this_); this_.get('siblingPlots').forEach( doToggle); } var willShow = !this.get('areSquaresVisible'); DG.UndoHistory.execute(DG.Command.create({ name: "graph.toggleShowSquares", undoString: (willShow ? 'DG.Undo.graph.showSquares' : 'DG.Undo.graph.hideSquares'), redoString: (willShow ? 'DG.Redo.graph.showSquares' : 'DG.Redo.graph.hideSquares'), log: "toggleShowSquares: %@".fmt(willShow ? "show" : "hide"), executeNotification: { action: 'notify', resource: 'component', values: { operation: 'toggle show squares', type: 'DG.GraphView' } }, execute: function () { toggle(); }, undo: function () { toggle(); } })); }, handleDataConfigurationChange: function (iKey) { sc_super(); this.rescaleAxesFromData(iKey !== 'hiddenCases', /* allow scale shrinkage */ true /* do animation */); var adornmentModel = this.getAdornmentModel('connectingLine'); if (adornmentModel) { adornmentModel.setComputingNeeded(); // invalidate if axis model/attribute change } }, /** Each axis should rescale based on the values to be plotted with it. @param{Boolean} Default is false @param{Boolean} Default is true @param{Boolean} Default is false */ rescaleAxesFromData: function (iAllowScaleShrinkage, iAnimatePoints, iLogIt, isUserAction) { if (iAnimatePoints === undefined) iAnimatePoints = true; this.doRescaleAxesFromData([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY, DG.GraphTypes.EPlace.eY2], iAllowScaleShrinkage, iAnimatePoints, isUserAction); if (iLogIt && !isUserAction) DG.logUser("rescaleScatterplot"); }, /** @param{ {x: {Number}, y: {Number} } } @param{Number} */ dilate: function (iFixedPoint, iFactor) { this.doDilation([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY], iFixedPoint, iFactor); }, /** * Return a list of objects { key, class, useAdornmentModelsArray, storage } * Subclasses should override calling sc_super first. * @return {[Object]} */ getAdornmentSpecs: function() { var tSpecs = sc_super(), this_ = this; ['movablePoint', 'movableLine', 'multipleLSRLs'].forEach( function( iKey) { var tAdorn = this_.get( iKey); if (tAdorn) tSpecs.push({ key: iKey, "class": tAdorn.constructor, useAdornmentModelsArray: false, storage: tAdorn.createStorage() }); }); DG.ObjectMap.forEach( this._adornmentModels, function( iKey, iAdorn) { tSpecs.push( { key: iKey, "class": iAdorn.constructor, useAdornmentModelsArray: true, storage: iAdorn.createStorage() }); }); return tSpecs; }, /** * Base class will do most of the work. We just have to finish up setting the axes. * @param {DG.PlotModel} iSourcePlot */ installAdornmentModelsFrom: function( iSourcePlot) { sc_super(); var tMovablePoint = this.get('movablePoint'); if (tMovablePoint) { tMovablePoint.set('xAxis', this.get('xAxis')); tMovablePoint.set('yAxis', this.get('yAxis')); tMovablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis')); } var tMultipleLSRLs = this.get('multipleLSRLs'); if (tMultipleLSRLs) { tMultipleLSRLs.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis')); } }, checkboxDescriptions: function () { var this_ = this; return sc_super().concat([ { title: 'DG.Inspector.graphConnectingLine', value: this_.isAdornmentVisible('connectingLine'), classNames: 'dg-graph-connectingLine-check'.w(), valueDidChange: function () { this_.toggleConnectingLine(); }.observes('value') }, { title: 'DG.Inspector.graphMovablePoint', value: this_.get('isMovablePointVisible'), classNames: 'dg-graph-movablePoint-check'.w(), valueDidChange: function () { this_.toggleMovablePoint(); }.observes('value') }, { title: 'DG.Inspector.graphMovableLine', value: this_.get('isMovableLineVisible'), classNames: 'dg-graph-movableLine-check'.w(), valueDidChange: function () { this_.toggleMovableLine(); }.observes('value') }, { title: 'DG.Inspector.graphLSRL', value: this_.get('isLSRLVisible'), classNames: 'dg-graph-lsrl-check'.w(), valueDidChange: function () { this_.toggleLSRLLine(); }.observes('value') }, { title: 'DG.Inspector.graphInterceptLocked', classNames: 'dg-graph-interceptLocked-check'.w(), _changeInProgress: true, valueDidChange: function () { if( !this._changeInProgress) this_.toggleInterceptLocked(); }.observes('value'), lineVisibilityChanged: function() { this._changeInProgress = true; var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible'); if( !tLineIsVisible) this_.set('isInterceptLocked', false); this.set('value', this_.get('isInterceptLocked')); this.set('isEnabled', tLineIsVisible); this._changeInProgress = false; }, init: function() { sc_super(); this.lineVisibilityChanged(); this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged'); this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged'); this._changeInProgress = false; }, destroy: function() { this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged'); this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged'); sc_super(); } }, { title: 'DG.Inspector.graphPlottedFunction', value: this_.isAdornmentVisible('plottedFunction'), classNames: 'dg-graph-plottedFunction-check'.w(), valueDidChange: function () { this_.togglePlotFunction(); }.observes('value') }, { title: 'DG.Inspector.graphPlottedValue', value: this_.isAdornmentVisible('plottedValue'), classNames: 'dg-graph-plottedValue-check'.w(), valueDidChange: function () { this_.togglePlotValue(); }.observes('value') }, { title: 'DG.Inspector.graphSquares', value: this_.get('areSquaresVisible'), classNames: 'dg-graph-squares-check'.w(), lineVisibilityChanged: function() { var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible'); this.set('isEnabled', tLineIsVisible); if( this_.get('areSquaresVisible') && !tLineIsVisible) this.set('value', false); }, init: function() { sc_super(); this.lineVisibilityChanged(); this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged'); this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged'); }, destroy: function() { this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged'); this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged'); }, valueDidChange: function () { this_.toggleShowSquares(); }.observes('value') } ]); }.property(), /** * When making a copy of a plot (e.g. for use in split) the returned object * holds those properties that should be assigned to the copy. * @return {{}} */ getPropsForCopy: function() { var tResult = sc_super(); return $.extend( tResult, { areSquaresVisible: this.get('areSquaresVisible') }); }, /** * @return { Object } with properties specific to a given subclass */ createStorage: function () { var tStorage = sc_super(), tMovablePoint = this.get('movablePoint'), tMovableLine = this.get('movableLine'), tLSRL = this.get('multipleLSRLs'); if (!SC.none(tMovablePoint)) tStorage.movablePointStorage = tMovablePoint.createStorage(); if (!SC.none(tMovableLine)) tStorage.movableLineStorage = tMovableLine.createStorage(); if (!SC.none(tLSRL) && tLSRL.get('isVisible')) tStorage.multipleLSRLsStorage = tLSRL.createStorage(); if (this.get('areSquaresVisible')) tStorage.areSquaresVisible = true; if (this.get('isLSRLVisible')) tStorage.isLSRLVisible = true; return tStorage; }, /** * @param { Object } with properties specific to a given subclass */ restoreStorage: function (iStorage) { /* Older documents stored adornments individually in the plot model * that used them, e.g. movable lines and function plots were stored * here with the scatter plot model. In newer documents, there is an * 'adornments' property in the base class (plot model) which stores * all or most of the adornments. To preserve file format compatibility * we move the locally stored storage objects into the base class * 'adornments' property where the base class will process them when * we call sc_super(). */ this.moveAdornmentStorage(iStorage, 'movableLine', iStorage.movableLineStorage); this.moveAdornmentStorage(iStorage, 'multipleLSRLs', iStorage.multipleLSRLsStorage); this.moveAdornmentStorage(iStorage, 'plottedFunction', iStorage.plottedFunctionStorage); sc_super(); if (iStorage.movablePointStorage) { if (SC.none(this.movablePoint)) this.createMovablePoint(); this.get('movablePoint').restoreStorage(iStorage.movablePointStorage); } if (iStorage.movableLineStorage) { if (SC.none(this.movableLine)) this.createMovableLine(); this.get('movableLine').restoreStorage(iStorage.movableLineStorage); } this.areSquaresVisible = iStorage.areSquaresVisible; if (iStorage.multipleLSRLsStorage) { if (SC.none(this.multipleLSRLs)) this.createLSRLLines(); this.get('multipleLSRLs').restoreStorage(iStorage.multipleLSRLsStorage); } // Legacy document support if (iStorage.plottedFunctionStorage) { if (SC.none(this.plottedFunction)) this.set('plottedFunction', DG.PlottedFunctionModel.create()); this.get('plottedFunction').restoreStorage(iStorage.plottedFunctionStorage); } }, onRescaleIsComplete: function () { if (!SC.none(this.movableLine)) this.movableLine.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis')); if (!SC.none(this.movablePoint)) this.movablePoint.recomputePositionIfNeeded(this.get('xAxis'), this.get('yAxis')); }, /** * Get an array of non-missing case counts in each axis cell. * Also cell index on primary and secondary axis, with primary axis as major axis. * @return {Array} [{count, primaryCell, secondaryCell},...] (all values are integers 0+). */ getCellCaseCounts: function ( iForSelectionOnly) { var tCases = iForSelectionOnly ? this.get('selection') : this.get('cases'), tXVarID = this.get('xVarID'), tYVarID = this.get('yVarID'), tCount = 0, tValueArray = []; if (!( tXVarID && tYVarID )) { return tValueArray; // too early to recompute, caller must try again later. } // compute count and percent cases in each cell, excluding missing values tCases.forEach(function (iCase, iIndex) { var tXVal = iCase.getForcedNumericValue(tXVarID), tYVal = iCase.getForcedNumericValue(tYVarID); if (isFinite(tXVal) && isFinite(tYVal)) ++tCount; }); // initialize the values for the single 'cell' of the scatterplot var tCell = { primaryCell: 0, secondaryCell: 0 }; if( iForSelectionOnly) tCell.selectedCount = tCount; else tCell.count = tCount; tValueArray.push(tCell); return tValueArray; } });
concord-consortium/codap
apps/dg/components/graph/plots/scatter_plot_model.js
JavaScript
mit
31,775
const Koa = require('koa') const screenshot = require('./screenshot') const app = new Koa() app.use(async ctx => { var url = ctx.query.url console.log('goto:', url) if (!/^https?:\/\/.+/.test(url)) { ctx.body = 'url 不合法' } else { if (!isNaN(ctx.query.wait)) { ctx.query.wait = ~~ctx.query.wait } let data = await screenshot(url, ctx.query.wait, ~~ctx.query.width) if (ctx.query.base64) { ctx.body = 'data:image/jpeg;base64,' + data } else { ctx.body = `<img src="data:image/jpeg;base64,${data}" />` } } }) app.listen(8000) console.log('server start success at 8000') // process.on('unCaughtException', function (err) { // console.log(err) // })
lwdgit/chrome-automator
examples/screenshot/index.js
JavaScript
mit
710
// Test get machiens var fs = require('fs'); try { fs.accessSync('testdb.json', fs.F_OK); fs.unlinkSync('testdb.json'); // Do something } catch (e) { // It isn't accessible console.log(e); } var server = require('../server.js').createServer(8000, 'testdb.json'); var addTestMachine = function(name) { var newMachine = {}; newMachine.name = name; newMachine.type = 'washer'; newMachine.queue = []; newMachine.operational = true; newMachine.problemMessage = ""; newMachine.activeJob = {}; server.db('machines').push(newMachine); } describe('ALL THE TESTS LOL', function() { it('should add a machine', function(done) { var options = { method: 'POST', url: '/machines', payload: { name: 'test1', type: 'washer' } } server.inject(options, function(response) { expect(response.statusCode).toBe(200); var p = JSON.parse(response.payload); expect(p.name).toBe(options.payload.name); expect(p.type).toBe(options.payload.type); done(); }) }); it('should get all machines', function(done) { var name = 'testMachine'; var name2 = 'anotherMachine'; addTestMachine(name); addTestMachine(name2); var options = { method: 'GET', url: '/machines', } server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); // check p has test and anotherMachine done(); }); }); it('should get one machine', function(done) { var name = 'sweetTestMachine'; addTestMachine(name); var options = { method: 'GET', url: '/machines/'+name }; server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe(name); done(); }); }); it('should add a job the queue then th queue should have the person', function(done) { addTestMachine('queueTest'); var addOptions = { method: 'POST', url: '/machines/queueTest/queue', payload: { user: 'test@mail.com', pin: 1234, minutes: 50 } }; server.inject(addOptions, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe('queueTest'); var getQueue = { method: 'GET', url: '/machines/queueTest/queue' }; server.inject(getQueue, function(newRes) { expect(newRes.statusCode).toBe(200); var q = JSON.parse(newRes.payload); console.log(q); expect(q.queue[0].user).toBe('test@mail.com'); expect(q.queue[0].pin).toBe(1234); done(); }) }) }); it('should delete a job from the queue', function(done) { addTestMachine('anotherQueue'); var addOptions = { method: 'POST', url: '/machines/anotherQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(res) { var deleteOptions = addOptions; deleteOptions.url = '/machines/anotherQueue/queue/delete'; deleteOptions.payload = { user: addOptions.payload.user, pin: addOptions.payload.pin } server.inject(deleteOptions, function(r) { expect(r.statusCode).toBe(200); console.log(JSON.parse(r.payload)); done(); }) }) }) it('should add a job to the active queue', function(done) { addTestMachine('activeQueue'); var addOptions = { method: 'POST', url: '/machines/activeQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(r) { var runJobOptions = { method: 'POST', url: '/machines/activeQueue/queue/start', payload: { command: 'next', pin: 1235, minutes: 0 } }; server.inject(runJobOptions, function(res) { expect(res.statusCode).toBe(200); done(); }) }) }); });
sdierauf/laundrytime
spec/getMachinesSpec.js
JavaScript
mit
4,145
require('./loader.jsx');
arjunmehta/react-frontend-template
src/index.js
JavaScript
mit
25
game.PlayerEntity = me.Entity.extend ({ //builds the player class init: function(x, y, settings){ this.setSuper(x, y); this.setPlayerTimer(); this.setAttributes(); this.type="PlayerEntity"; this.setFlags(); me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //locks camera on the character this.addAnimation(); this.renderable.setCurrentAnimation("idle"); //sets the idle animation }, setSuper: function(x, y){ this._super(me.Entity, 'init', [x, y, {//._super reaches to the object entity image: "player",//uses the image player width: 64, //preserves the height and width for player height: 64, spritewidth: "64", //uses height and width for player spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 64, 64)) . toPolygon(); //creates a little rectangle for what the player can walk into. } }]); }, setPlayerTimer: function(){ this.now = new Date().getTime(); //keeps track of what time it is this.lastHit = this.now; //same as this.now this.lastSpear = this.now; this.lastAttack = new Date().getTime(); }, setAttributes: function(){ this.health = game.data.playerHealth; this.body.setVelocity(game.data.playerMoveSpeed, 20); //sets velocity to 5 this.attack = game.data.playerAttack; }, setFlags: function(){ this.facing = "right"; //makes the character face right this.dead = false; this.attacking = false; }, addAnimation: function(){ this.renderable.addAnimation("idle", [78]); //idle animation this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80); //walking animation this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80); //setting the attack animation }, update: function(delta){ this.now = new Date().getTime(); //everytime we call update it updates the time this.dead = this.checkIfDead(); this.checkKeyPressesAndMove(); this.checkAbilityKeys(); this.setAnimation(); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); //delta is the change in time this._super(me.Entity, "update", [delta]); return true; }, checkIfDead: function(){ if (this.health <= 0){ return true; } }, checkKeyPressesAndMove: function(){ if(me.input.isKeyPressed("right")){ //checks to see if the right key is pressed this.moveRight(); } else if(me.input.isKeyPressed("left")){ //allows the player to move left this.moveLeft(); } else{ this.body.vel.x = 0; //stops the movement } if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){ //allows the player to jump without double jumping or falling and jumping this.jump(); } this.attacking = me.input.isKeyPressed("attack"); //attack key }, moveRight: function(){ this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth this.facing = "right"; //sets the character to face right this.flipX(false); }, moveLeft: function(){ this.body.vel.x -= this.body.accel.x * me.timer.tick; this.facing = "left"; this.flipX(true); }, jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; }, checkAbilityKeys: function(){ if(me.input.isKeyPressed("skill1")){ // this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ // this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, throwSpear: function(){ if(this.now-this.lastSpear >= game.data.spearTimer*100 && game.data.ability3 > 0){ this.lastSpear = this.now; var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, setAnimation: function(){ if(this.attacking){ if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("attack", "idle"); this.renderable.setAnimationFrame(); } } else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking if (!this.renderable.isCurrentAnimation("walk")) { //sets the current animation for walk this.renderable.setCurrentAnimation("walk"); }; } else if(!this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to idle this.renderable.setCurrentAnimation("idle"); //if the player is not walking it uses idle animation } }, loseHealth: function(damage){ this.health = this.health - damage; }, collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top this.collideWithEnemyBase(response); } else if(response.b.type==='EnemyCreep'){ this.collideWithEnemyCreep(response); } }, collideWithEnemyBase: function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; if(ydif<-40 && xdif<70 && xdif>-35){ this.body.falling=false; this.body.vel.y = -1; } if(xdif>-35 && this.facing==='right' && (xdif<0)){ this.body.vel.x = 0; //this.pos.x = this.pos.x -1; } else if(xdif<70 && this.facing==='left' && (xdif>0)){ this.body.vel.x=0; //this.pos.x = this.pos.x +1; } if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //if the animation is attack it will lose the base health and that it will check when the lasthit was this.lastHit = this.now; response.b.loseHealth(game.data.playerAttack); } }, collideWithEnemyCreep: function(response){ var xdif = this.pos.x - response.b.pos.x; var ydif = this.pos.y - response.b.pos.y; this.stopMovement(xdif); if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ if(xdif > 0){ //this.pos.x = this.pos.x + 1; if (this.facing === "left"){ this.body.vel.x = 0; } } else{ //this.pos.x = this.pos.x - 1; if(this.facing === "right"){ this.body.vel.x = 0; } } }, checkAttack: function(xdif, ydif){ if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer && (Math.abs(ydif) <=40) && ((xdif>0) && this.facing==="left") || (((xdif<0) && this.facing === "right"))){ this.lastHit = this.now; return true; } return false; }, hitCreep: function(response){ if(response.b.health <= game.data.playerAttack){ game.data.gold += 1; } response.b.loseHealth(game.data.playerAttack); } }); //intermeidiae challenge creating an ally creep game.MyCreep = me.Entity.extend({ init: function(x, y, settings){ this._super(me.Entity, 'init', [x, y, { image: "creep2", width: 100, height:85, spritewidth: "100", spriteheight: "85", getShape: function(){ return (new me.Rect(0, 0, 52, 100)).toPolygon(); } }]); this.health = game.data.allyCreepHealth; this.alwaysUpdate = true; // //this.attacking lets us know if the enemy is currently attacking this.attacking = false; // //keeps track of when our creep last attacked anyting this.lastAttacking = new Date().getTime(); this.lastHit = new Date().getTime(); this.now = new Date().getTime(); this.body.setVelocity(game.data.allyCreepMoveSpeed, 20); this.type = "MyCreep"; this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80); this.renderable.setCurrentAnimation("walk"); }, update: function(delta) { // this.now = new Date().getTime(); this.body.vel.x += this.body.accel.x * me.timer.tick; this.flipX(true); me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response) { if(response.b.type==='EnemyBaseEntity'){ this.attacking = true; //this.lastAttacking = this.now; this.body.vel.x = 0; this.pos.x = this.pos.x +1; //checks that it has been at least 1 second since this creep hit a base if((this.now-this.lastHit <= game.data.allyCreepAttackTimer)){ //updates the last hit timer this.lastHit = this.now; //makes the player base call its loseHealth function and passes it a damage of 1 response.b.loseHealth(1); } } } });
romulus1/FinalAwesomauts
js/entities/entities.js
JavaScript
mit
8,421
import Helper from '@ember/component/helper'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; export default class MediaHelper extends Helper { @service() media; constructor() { super(...arguments); this.media.on('mediaChanged', () => { this.recompute(); }); } compute([prop]) { return get(this, `media.${prop}`); } }
freshbooks/ember-responsive
addon/helpers/media.js
JavaScript
mit
395
Enum = { BarDrawDirect: { Horizontal: "Horizontal", Vertical: "Vertical" }, PowerType: { MP: 0, Angery: 1 }, EffectType: { StateChange: "StateChange", HpChange: "HpChange", Timing: "Timing", Control: "Control" }, EffectControlType: { Stun: "Stun", Silence: "Silence", Sleep: "Sleep" }, EffectCharacterType: { Passive: "Passive", Self: "Self", Column: "Column", Single: "Single", Row: "Row", All: "All" }, EffectRange: { Melee: "Melee", Range: "Range" }, StateChangeClass: { Plus: "Plus", Minus: "Minus" }, StateChangeType: { HitRate: "HitRate", DodgeRate: "DodgeRate" }, HpChangeClass: { Damage: "Damage", Heal: "Heal" }, HpChangeType: { Normal: "Normal", Critial: "Critial" }, BattleActionType: { Physical: "Physical", Magical: "Magical" }, EffectStyle: { Temp: "Temp", Static: "Static", UniqueTemp: "UniqueTemp" }, Align: { Left: "Left", Right: "Right", Center: "Center" } }
mt830813/code
Project/HTML5Test/Test1/Scripts/Customer/Setting/Enum.js
JavaScript
mit
1,263
'use strict'; console.log('TESTTTT'); var mean = require('meanio'); exports.render = function (req, res) { function isAdmin() { return req.user && req.user.roles.indexOf('admin') !== -1; } // Send some basic starting info to the view res.render('index', { user: req.user ? { name: req.user.name, _id: req.user._id, username: req.user.username, roles: req.user.roles } : {}, modules: 'ho', motti: 'motti is cool', isAdmin: 'motti', adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin') }); };
mottihoresh/nodarium-web
packages/custom/nodarium/server/controllers/index.js
JavaScript
mit
627
/* concatenated from client/src/app/js/globals.js */ (function () { if (!window.console) { window.console = {}; } var m = [ "log", "info", "warn", "error", "debug", "trace", "dir", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd", "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear" ]; for (var i = 0; i < m.length; i++) { if (!window.console[m[i]]) { window.console[m[i]] = function() {}; } } _.mixin({ compactObject: function(o) { _.each(o, function(v, k) { if(!v) { delete o[k]; } }); return o; } }); })(); /* concatenated from client/src/app/js/app.js */ const mainPages = { HOME: "/", WALKS: "/walks", SOCIAL: "/social", JOIN_US: "/join-us", CONTACT_US: "/contact-us", COMMITTEE: "/committee", ADMIN: "/admin", HOW_TO: "/how-to" }; angular.module("ekwgApp", [ "btford.markdown", "ngRoute", "ngSanitize", "ui.bootstrap", "angularModalService", "btford.markdown", "mongolabResourceHttp", "ngAnimate", "ngCookies", "ngFileUpload", "ngSanitize", "ui.bootstrap", "ui.select", "angular-logger", "ezfb", "ngCsv"]) .constant("MONGOLAB_CONFIG", { trimErrorMessage: false, baseUrl: "/databases/", database: "ekwg" }) .constant("AUDIT_CONFIG", { auditSave: true, }) .constant("PAGE_CONFIG", { mainPages: mainPages }) .config(["$compileProvider", function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|tel):/); }]) .constant("MAILCHIMP_APP_CONSTANTS", { allowSendCampaign: true, apiServer: "https://us3.admin.mailchimp.com" }) .config(["$locationProvider", function ($locationProvider) { $locationProvider.hashPrefix(""); }]) .config(["$routeProvider", "uiSelectConfig", "uibDatepickerConfig", "uibDatepickerPopupConfig", "logEnhancerProvider", function ($routeProvider, uiSelectConfig, uibDatepickerConfig, uibDatepickerPopupConfig, logEnhancerProvider) { uiSelectConfig.theme = "bootstrap"; uiSelectConfig.closeOnSelect = false; $routeProvider .when(mainPages.ADMIN + "/expenseId/:expenseId", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "expenses" }) .when(mainPages.ADMIN + "/:area?", { controller: "AdminController", templateUrl: "partials/admin/admin.html", title: "admin" }) .when(mainPages.COMMITTEE + "/committeeFileId/:committeeFileId", { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.COMMITTEE, { controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee" }) .when(mainPages.HOW_TO, { controller: "HowToController", templateUrl: "partials/howTo/how-to.html", title: "How-to" }) .when("/image-editor/:imageSource", { controller: "ImageEditController", templateUrl: "partials/imageEditor/image-editor.html", title: "image editor" }) .when(mainPages.JOIN_US, { controller: "HomeController", templateUrl: "partials/joinUs/join-us.html", title: "join us" }) .when("/letterhead/:firstPart?/:secondPart", { controller: "LetterheadController", templateUrl: "partials/letterhead/letterhead.html", title: "letterhead" }) .when(mainPages.CONTACT_US, { controller: "ContactUsController", templateUrl: "partials/contactUs/contact-us.html", title: "contact us" }) .when("/links", {redirectTo: mainPages.CONTACT_US}) .when(mainPages.SOCIAL + "/socialEventId/:socialEventId", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.SOCIAL + "/:area?", { controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social" }) .when(mainPages.WALKS + "/walkId/:walkId", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.WALKS + "/:area?", { controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks" }) .when(mainPages.HOME, { controller: "HomeController", templateUrl: "partials/home/home.html", title: "home" }) .when("/set-password/:passwordResetId", { controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }) .otherwise({ controller: "AuthenticationModalsController", templateUrl: "partials/home/home.html" }); uibDatepickerConfig.startingDay = 1; uibDatepickerConfig.showWeeks = false; uibDatepickerPopupConfig.datepickerPopup = "dd-MMM-yyyy"; uibDatepickerPopupConfig.formatDay = "dd"; logEnhancerProvider.datetimePattern = "hh:mm:ss"; logEnhancerProvider.prefixPattern = "%s - %s -"; }]) .run(["$log", "$rootScope", "$route", "URLService", "CommitteeConfig", "CommitteeReferenceData", function ($log, $rootScope, $route, URLService, CommitteeConfig, CommitteeReferenceData) { var logger = $log.getInstance("App.run"); $log.logLevels["App.run"] = $log.LEVEL.OFF; $rootScope.$on('$locationChangeStart', function (evt, absNewUrl, absOldUrl) { }); $rootScope.$on("$locationChangeSuccess", function (event, newUrl, absOldUrl) { if (!$rootScope.pageHistory) $rootScope.pageHistory = []; $rootScope.pageHistory.push(URLService.relativeUrl(newUrl)); logger.info("newUrl", newUrl, "$rootScope.pageHistory", $rootScope.pageHistory); }); $rootScope.$on("$routeChangeSuccess", function (currentRoute, previousRoute) { $rootScope.title = $route.current.title; }); CommitteeConfig.getConfig() .then(function (config) { angular.extend(CommitteeReferenceData, config.committee); $rootScope.$broadcast("CommitteeReferenceDataReady", CommitteeReferenceData); }); }]); /* concatenated from client/src/app/js/admin.js */ angular.module('ekwgApp') .controller('AdminController', ["$rootScope", "$scope", "LoggedInMemberService", function($rootScope, $scope, LoggedInMemberService) { function setViewPriveleges() { $scope.loggedIn = LoggedInMemberService.memberLoggedIn(); $scope.memberAdmin = LoggedInMemberService.allowMemberAdminEdits(); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); } setViewPriveleges(); $scope.$on('memberLoginComplete', function() { setViewPriveleges(); }); $scope.$on('memberLogoutComplete', function() { setViewPriveleges(); }); }] ); /* concatenated from client/src/app/js/authenticationModalsController.js */ angular.module('ekwgApp') .controller("AuthenticationModalsController", ["$log", "$scope", "URLService", "$location", "$routeParams", "AuthenticationModalsService", "LoggedInMemberService", function ($log, $scope, URLService, $location, $routeParams, AuthenticationModalsService, LoggedInMemberService) { var logger = $log.getInstance("AuthenticationModalsController"); $log.logLevels["AuthenticationModalsController"] = $log.LEVEL.OFF; var urlFirstSegment = URLService.relativeUrlFirstSegment(); logger.info("URLService.relativeUrl:", urlFirstSegment, "$routeParams:", $routeParams); switch (urlFirstSegment) { case "/login": return AuthenticationModalsService.showLoginDialog(); case "/logout": return LoggedInMemberService.logout(); case "/mailing-preferences": if (LoggedInMemberService.memberLoggedIn()) { return AuthenticationModalsService.showMailingPreferencesDialog(LoggedInMemberService.loggedInMember().memberId); } else { return URLService.setRoot(); } case "/forgot-password": return AuthenticationModalsService.showForgotPasswordModal(); case "/set-password": return LoggedInMemberService.getMemberByPasswordResetId($routeParams.passwordResetId) .then(function (member) { logger.info("for $routeParams.passwordResetId", $routeParams.passwordResetId, "member", member); if (_.isEmpty(member)) { return AuthenticationModalsService.showResetPasswordFailedDialog(); } else { return AuthenticationModalsService.showResetPasswordModal(member.userName) } }); default: logger.warn(URLService.relativeUrl(), "doesnt match any of the supported urls"); return URLService.setRoot(); } }] ); /* concatenated from client/src/app/js/authenticationModalsService.js */ angular.module('ekwgApp') .factory("AuthenticationModalsService", ["$log", "ModalService", "URLService", function ($log, ModalService, URLService) { var logger = $log.getInstance("AuthenticationModalsService"); $log.logLevels["AuthenticationModalsService"] = $log.LEVEL.OFF; function showForgotPasswordModal() { logger.info('called showForgotPasswordModal'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/forgotten-password-dialog.html", controller: "ForgotPasswordController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }).catch(function (error) { logger.warn("error happened:", error); }) } function showResetPasswordModal(userName, message) { logger.info('called showResetPasswordModal for userName', userName); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-dialog.html", controller: "ResetPasswordController", inputs: {userName: userName, message: message}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordModal close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showLoginDialog() { logger.info('called showLoginDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/login-dialog.html", controller: "LoginController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showLoginDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showResetPasswordFailedDialog() { logger.info('called showResetPasswordFailedDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/reset-password-failed-dialog.html", controller: "ResetPasswordFailedController", preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showResetPasswordFailedDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('showResetPasswordFailedDialog close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } function showMailingPreferencesDialog(memberId) { logger.info('called showMailingPreferencesDialog'); ModalService.closeModals(true); ModalService.showModal({ templateUrl: "partials/index/mailing-preferences-dialog.html", controller: "MailingPreferencesController", inputs: {memberId: memberId}, preClose: function (modal) { modal.element.modal('hide'); } }).then(function (modal) { logger.info('showMailingPreferencesDialog modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.info('close event with result', result); if (!result) URLService.navigateBackToLastMainPage(); }); }) } return { showResetPasswordModal: showResetPasswordModal, showResetPasswordFailedDialog: showResetPasswordFailedDialog, showForgotPasswordModal: showForgotPasswordModal, showLoginDialog: showLoginDialog, showMailingPreferencesDialog: showMailingPreferencesDialog } }]); /* concatenated from client/src/app/js/awsServices.js */ angular.module('ekwgApp') .factory('AWSConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/aws/config').then(HTTPResponseService.returnResponse); } function awsPolicy(fileType, objectKey) { return $http.get('/aws/s3Policy?mimeType=' + fileType + '&objectKey=' + objectKey).then(HTTPResponseService.returnResponse); } return { getConfig: getConfig, awsPolicy: awsPolicy } }]) .factory('EKWGFileUpload', ["$log", "AWSConfig", "NumberUtils", "Upload", function ($log, AWSConfig, NumberUtils, Upload) { $log.logLevels['EKWGFileUpload'] = $log.LEVEL.OFF; var logger = $log.getInstance('EKWGFileUpload'); var awsConfig; AWSConfig.getConfig().then(function (config) { awsConfig = config; }); function onFileSelect(file, notify, objectKey) { logger.debug(file, objectKey); function generateFileNameData() { return { originalFileName: file.name, awsFileName: NumberUtils.generateUid() + '.' + _.last(file.name.split('.')) }; } var fileNameData = generateFileNameData(), fileUpload = file; fileUpload.progress = parseInt(0); logger.debug('uploading fileNameData', fileNameData); return AWSConfig.awsPolicy(file.type, objectKey) .then(function (response) { var s3Params = response; var url = 'https://' + awsConfig.bucket + '.s3.amazonaws.com/'; return Upload.upload({ url: url, method: 'POST', data: { 'key': objectKey + '/' + fileNameData.awsFileName, 'acl': 'public-read', 'Content-Type': file.type, 'AWSAccessKeyId': s3Params.AWSAccessKeyId, 'success_action_status': '201', 'Policy': s3Params.s3Policy, 'Signature': s3Params.s3Signature }, file: file }).then(function (response) { fileUpload.progress = parseInt(100); if (response.status === 201) { var data = xml2json.parser(response.data), parsedData; parsedData = { location: data.postresponse.location, bucket: data.postresponse.bucket, key: data.postresponse.key, etag: data.postresponse.etag }; logger.debug('parsedData', parsedData); return fileNameData; } else { notify.error('Upload Failed for file ' + fileNameData); } }, notify.error, function (evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); }); }); } return {onFileSelect: onFileSelect}; }]); /* concatenated from client/src/app/js/batchGeoServices.js */ angular.module('ekwgApp') .factory('BatchGeoExportService', ["StringUtils", "DateUtils", "$filter", function(StringUtils, DateUtils, $filter) { function exportWalksFileName() { return 'batch-geo-walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walks) { return _(walks).sortBy('walkDate'); } function exportWalks(walks) { return _.chain(walks) .filter(filterWalk) .sortBy('walkDate') .last(250) .map(walkToCsvRecord) .value(); } function filterWalk(walk) { return _.has(walk, 'briefDescriptionAndStartPoint') && (_.has(walk, 'gridReference') || _.has(walk, 'postcode')); } function exportColumnHeadings() { return [ "Walk Date", "Start Time", "Postcode", "Contact Name/Email", "Distance", "Description", "Longer Description", "Grid Ref" ]; } function walkToCsvRecord(walk) { return { "walkDate": walkDate(walk), "startTime": walkStartTime(walk), "postcode": walkPostcode(walk), "displayName": contactDisplayName(walk), "distance": walkDistanceMiles(walk), "description": walkTitle(walk), "longerDescription": walkDescription(walk), "gridRef": walkGridReference(walk) }; } function walkTitle(walk) { var walkDescription = []; if (walk.includeWalkDescriptionPrefix) walkDescription.push(walk.walkDescriptionPrefix); if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function replaceSpecialCharacters(value) { return value ? StringUtils.stripLineBreaks(value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“')) : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return $filter('displayDate')(walk.walkDate); } return { exportWalksFileName: exportWalksFileName, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }]); /* concatenated from client/src/app/js/bulkUploadServices.js */ angular.module('ekwgApp') .factory('MemberBulkUploadService', ["$log", "$q", "$filter", "MemberService", "MemberUpdateAuditService", "MemberBulkLoadAuditService", "ErrorMessageService", "EmailSubscriptionService", "DateUtils", "DbUtils", "MemberNamingService", function ($log, $q, $filter, MemberService, MemberUpdateAuditService, MemberBulkLoadAuditService, ErrorMessageService, EmailSubscriptionService, DateUtils, DbUtils, MemberNamingService) { var logger = $log.getInstance('MemberBulkUploadService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['MemberBulkUploadService'] = $log.LEVEL.OFF; $log.logLevels['NoLogger'] = $log.LEVEL.OFF; var RESET_PASSWORD = 'changeme'; function processMembershipRecords(file, memberBulkLoadServerResponse, members, notify) { notify.setBusy(); var today = DateUtils.momentNowNoTime().valueOf(); var promises = []; var memberBulkLoadResponse = memberBulkLoadServerResponse.data; logger.debug('received', memberBulkLoadResponse); return DbUtils.auditedSaveOrUpdate(new MemberBulkLoadAuditService(memberBulkLoadResponse)) .then(function (auditResponse) { var uploadSessionId = auditResponse.$id(); return processBulkLoadResponses(promises, uploadSessionId); }); function updateGroupMembersPreBulkLoadProcessing(promises) { if (memberBulkLoadResponse.members && memberBulkLoadResponse.members.length > 1) { notify.progress('Processing ' + members.length + ' members ready for bulk load'); _.each(members, function (member) { if (member.receivedInLastBulkLoad) { member.receivedInLastBulkLoad = false; promises.push(DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member))); } }); return $q.all(promises).then(function () { notify.progress('Marked ' + promises.length + ' out of ' + members.length + ' in preparation for update'); return promises; }); } else { return $q.when(promises); } } function processBulkLoadResponses(promises, uploadSessionId) { return updateGroupMembersPreBulkLoadProcessing(promises).then(function (updatedPromises) { _.each(memberBulkLoadResponse.members, function (ramblersMember, recordIndex) { createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, updatedPromises); }); return $q.all(updatedPromises).then(function () { logger.debug('performed total of', updatedPromises.length, 'audit or member updates'); return updatedPromises; }); }); } function auditUpdateCallback(member) { return function (response) { logger.debug('auditUpdateCallback for member:', member, 'response', response); } } function auditErrorCallback(member, audit) { return function (response) { logger.warn('member save error for member:', member, 'response:', response); if (audit) { audit.auditErrorMessage = response; } } } function saveAndAuditMemberUpdate(promises, uploadSessionId, rowNumber, memberAction, changes, auditMessage, member) { var audit = new MemberUpdateAuditService({ uploadSessionId: uploadSessionId, updateTime: DateUtils.nowAsValue(), memberAction: memberAction, rowNumber: rowNumber, changes: changes, auditMessage: auditMessage }); var qualifier = 'for membership ' + member.membershipNumber; member.receivedInLastBulkLoad = true; member.lastBulkLoadDate = DateUtils.momentNow().valueOf(); return DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member, audit)) .then(function (savedMember) { if (savedMember) { audit.memberId = savedMember.$id(); notify.success({title: 'Bulk member load ' + qualifier + ' was successful', message: auditMessage}) } else { audit.member = member; audit.memberAction = 'error'; logger.warn('member was not saved, so saving it to audit:', audit); notify.warning({title: 'Bulk member load ' + qualifier + ' failed', message: auditMessage}) } logger.debug('saveAndAuditMemberUpdate:', audit); promises.push(audit.$save()); return promises; }); } function convertMembershipExpiryDate(ramblersMember) { var dataValue = ramblersMember.membershipExpiryDate ? DateUtils.asValueNoTime(ramblersMember.membershipExpiryDate, 'DD/MM/YYYY') : ramblersMember.membershipExpiryDate; logger.debug('ramblersMember', ramblersMember, 'membershipExpiryDate', ramblersMember.membershipExpiryDate, '->', DateUtils.displayDate(dataValue)); return dataValue; } function createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, promises) { var memberAction; ramblersMember.membershipExpiryDate = convertMembershipExpiryDate(ramblersMember); ramblersMember.groupMember = !ramblersMember.membershipExpiryDate || ramblersMember.membershipExpiryDate >= today; var member = _.find(members, function (member) { var existingUserName = MemberNamingService.createUserName(ramblersMember); var match = member.membershipNumber && member.membershipNumber.toString() === ramblersMember.membershipNumber; if (!match && member.userName) { match = member.userName === existingUserName; } noLogger.debug('match', !!(match), 'ramblersMember.membershipNumber', ramblersMember.membershipNumber, 'ramblersMember.userName', existingUserName, 'member.membershipNumber', member.membershipNumber, 'member.userName', member.userName); return match; }); if (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); } else { memberAction = 'created'; member = new MemberService(); member.userName = MemberNamingService.createUniqueUserName(ramblersMember, members); member.displayName = MemberNamingService.createUniqueDisplayName(ramblersMember, members); member.password = RESET_PASSWORD; member.expiredPassword = true; EmailSubscriptionService.defaultMailchimpSettings(member, true); logger.debug('new member created:', member); } var updateAudit = {auditMessages: [], fieldsChanged: 0, fieldsSkipped: 0}; _.each([ {fieldName: 'membershipExpiryDate', writeDataIf: 'changed', type: 'date'}, {fieldName: 'membershipNumber', writeDataIf: 'changed', type: 'string'}, {fieldName: 'mobileNumber', writeDataIf: 'empty', type: 'string'}, {fieldName: 'email', writeDataIf: 'empty', type: 'string'}, {fieldName: 'firstName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'lastName', writeDataIf: 'empty', type: 'string'}, {fieldName: 'postcode', writeDataIf: 'empty', type: 'string'}, {fieldName: 'groupMember', writeDataIf: 'not-revoked', type: 'boolean'}], function (field) { changeAndAuditMemberField(updateAudit, member, ramblersMember, field) }); DbUtils.removeEmptyFieldsIn(member); logger.debug('saveAndAuditMemberUpdate -> member:', member, 'updateAudit:', updateAudit); return saveAndAuditMemberUpdate(promises, uploadSessionId, recordIndex + 1, memberAction || (updateAudit.fieldsChanged > 0 ? 'updated' : 'skipped'), updateAudit.fieldsChanged, updateAudit.auditMessages.join(', '), member); } function changeAndAuditMemberField(updateAudit, member, ramblersMember, field) { function auditValueForType(field, source) { var dataValue = source[field.fieldName]; switch (field.type) { case 'date': return ($filter('displayDate')(dataValue) || '(none)'); case 'boolean': return dataValue || false; default: return dataValue || '(none)'; } } var fieldName = field.fieldName; var performMemberUpdate = false; var auditQualifier = ' not overwritten with '; var auditMessage; var oldValue = auditValueForType(field, member); var newValue = auditValueForType(field, ramblersMember); if (field.writeDataIf === 'changed') { performMemberUpdate = (oldValue !== newValue) && ramblersMember[fieldName]; } else if (field.writeDataIf === 'empty') { performMemberUpdate = !member[fieldName]; } else if (field.writeDataIf === 'not-revoked') { performMemberUpdate = newValue && (oldValue !== newValue) && !member.revoked; } else if (field.writeDataIf) { performMemberUpdate = newValue; } if (performMemberUpdate) { auditQualifier = ' updated to '; member[fieldName] = ramblersMember[fieldName]; updateAudit.fieldsChanged++; } if (oldValue !== newValue) { if (!performMemberUpdate) updateAudit.fieldsSkipped++; auditMessage = fieldName + ': ' + oldValue + auditQualifier + newValue; } if ((performMemberUpdate || (oldValue !== newValue)) && auditMessage) { updateAudit.auditMessages.push(auditMessage); } } } return { processMembershipRecords: processMembershipRecords, } }]); /* concatenated from client/src/app/js/clipboardService.js */ angular.module('ekwgApp') .factory('ClipboardService', ["$compile", "$rootScope", "$document", "$log", function ($compile, $rootScope, $document, $log) { return { copyToClipboard: function (element) { var logger = $log.getInstance("ClipboardService"); $log.logLevels['ClipboardService'] = $log.LEVEL.OFF; var copyElement = angular.element('<span id="clipboard-service-copy-id">' + element + '</span>'); var body = $document.find('body').eq(0); body.append($compile(copyElement)($rootScope)); var ClipboardServiceElement = angular.element(document.getElementById('clipboard-service-copy-id')); logger.debug(ClipboardServiceElement); var range = document.createRange(); range.selectNode(ClipboardServiceElement[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; logger.debug('Copying text command was ' + msg); window.getSelection().removeAllRanges(); copyElement.remove(); } } }]); /* concatenated from client/src/app/js/comitteeNotifications.js */ angular.module('ekwgApp') .controller('CommitteeNotificationsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "CommitteeQueryService", "committeeFile", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, CommitteeReferenceData, CommitteeQueryService, committeeFile, close) { var logger = $log.getInstance('CommitteeNotificationsController'); $log.logLevels['CommitteeNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.members = []; $scope.committeeFile = committeeFile; $scope.roles = {signoff: CommitteeReferenceData.contactUsRolesAsArray(), replyTo: []}; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } $scope.fromDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.fromDateCalendar.opened = true; } }; $scope.toDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.toDateCalendar.opened = true; } }; $scope.populateGroupEvents = function () { notify.setBusy(); populateGroupEvents().then(function () { notify.clearBusy(); return true; }) }; function populateGroupEvents() { return CommitteeQueryService.groupEvents($scope.userEdits.groupEvents) .then(function (events) { $scope.userEdits.groupEvents.events = events; logger.debug('groupEvents', events); return events; }); } $scope.changeGroupEventSelection = function (groupEvent) { groupEvent.selected = !groupEvent.selected; }; $scope.notification = { editable: { text: '', signoffText: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,', }, destinationType: 'committee', includeSignoffText: true, addresseeType: 'Hi *|FNAME|*,', addingNewFile: false, recipients: [], groupEvents: function () { return _.filter($scope.userEdits.groupEvents.events, function (groupEvent) { logger.debug('notification.groupEvents ->', groupEvent); return groupEvent.selected; }); }, signoffAs: { include: true, value: loggedOnRole().type || 'secretary' }, includeDownloadInformation: $scope.committeeFile, title: 'Committee Notification', text: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.text); }, signoffText: function () { return $filter('lineFeedsToBreaks')($scope.notification.editable.signoffText); } }; if ($scope.committeeFile) { $scope.notification.title = $scope.committeeFile.fileType; $scope.notification.editable.text = 'This is just a quick note to let you know in case you are interested, that I\'ve uploaded a new file to the EKWG website. The file information is as follows:'; } logger.debug('initialised on open: committeeFile', $scope.committeeFile, ', roles', $scope.roles); logger.debug('initialised on open: notification ->', $scope.notification); $scope.userEdits = { sendInProgress: false, cancelled: false, groupEvents: { events: [], fromDate: DateUtils.momentNowNoTime().valueOf(), toDate: DateUtils.momentNowNoTime().add(2, 'weeks').valueOf(), includeContact: true, includeDescription: true, includeLocation: true, includeWalks: true, includeSocialEvents: true, includeCommitteeEvents: true }, allGeneralSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED) .map(toSelectGeneralMember).value(); }, allWalksSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED) .map(toSelectWalksMember).value(); }, allSocialSubscribedList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectSocialMember).value(); }, allCommitteeList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.COMMITTEE_MEMBERS) .map(toSelectGeneralMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress || ($scope.notification.recipients.length === 0 && $scope.notification.destinationType === 'custom'); } }; function toSelectGeneralMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.general.subscribed) { memberGrouping = 'Subscribed to general emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.general.subscribed) { memberGrouping = 'Not subscribed to general emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectWalksMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.walks.subscribed) { memberGrouping = 'Subscribed to walks emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.walks.subscribed) { memberGrouping = 'Not subscribed to walks emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function toSelectSocialMember(member) { var memberGrouping; var order; if (member.groupMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.groupMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.groupMember) { memberGrouping = 'Not a group member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } $scope.editAllEKWGRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('general'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allGeneralSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllWalksRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('walks'); $scope.notification.list = 'walks'; $scope.notification.recipients = $scope.userEdits.allWalksSubscribedList(); $scope.campaignIdChanged(); }; $scope.editAllSocialRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('socialEvents'); $scope.notification.list = 'socialEvents'; $scope.notification.recipients = $scope.userEdits.allSocialSubscribedList(); $scope.campaignIdChanged(); }; $scope.editCommitteeRecipients = function () { $scope.notification.destinationType = 'custom'; $scope.notification.campaignId = campaignIdFor('committee'); $scope.notification.list = 'general'; $scope.notification.recipients = $scope.userEdits.allCommitteeList(); $scope.campaignIdChanged(); }; $scope.clearRecipientsForCampaignOfType = function (campaignType) { $scope.notification.customCampaignType = campaignType; $scope.notification.campaignId = campaignIdFor(campaignType); $scope.notification.list = 'general'; $scope.notification.recipients = []; $scope.campaignIdChanged(); }; $scope.fileUrl = function () { return $scope.committeeFile && $scope.committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + $scope.committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function () { return $scope.committeeFile ? DateUtils.asString($scope.committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + $scope.committeeFile.fileNameData.title : ''; }; function campaignIdFor(campaignType) { switch (campaignType) { case 'committee': return $scope.config.mailchimp.campaigns.committee.campaignId; case 'general': return $scope.config.mailchimp.campaigns.newsletter.campaignId; case 'socialEvents': return $scope.config.mailchimp.campaigns.socialEvents.campaignId; case 'walks': return $scope.config.mailchimp.campaigns.walkNotification.campaignId; default: return $scope.config.mailchimp.campaigns.committee.campaignId; } } function campaignInfoForCampaign(campaignId) { return _.chain($scope.config.mailchimp.campaigns) .map(function (data, campaignType) { var campaignData = _.extend({campaignType: campaignType}, data); logger.debug('campaignData for', campaignType, '->', campaignData); return campaignData; }).find({campaignId: campaignId}) .value(); } $scope.campaignIdChanged = function () { var infoForCampaign = campaignInfoForCampaign($scope.notification.campaignId); logger.debug('for campaignId', $scope.notification.campaignId, 'infoForCampaign', infoForCampaign); if (infoForCampaign) { $scope.notification.title = infoForCampaign.name; } }; $scope.confirmSendNotification = function (dontSend) { $scope.userEdits.sendInProgress = true; var campaignName = $scope.notification.title; notify.setBusy(); return $q.when(templateFor('partials/committee/committee-notification.html')) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(notifyEmailSendComplete) .catch(handleNotificationError); function templateFor(template) { return $templateRequest($sce.getTrustedResourceUrl(template)) } function handleNotificationError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.clearBusy(); notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function sendEmailCampaign(contentSections) { notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); return MailchimpConfig.getConfig() .then(function (config) { var replyToRole = $scope.notification.signoffAs.value || 'secretary'; logger.debug('replyToRole', replyToRole); var members; var list = $scope.notification.list; var otherOptions = { from_name: CommitteeReferenceData.contactUsField(replyToRole, 'fullName'), from_email: CommitteeReferenceData.contactUsField(replyToRole, 'email'), list_id: config.mailchimp.lists[list] }; logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); var segmentId = config.mailchimp.segments[list].committeeSegmentId; var campaignId = $scope.notification.campaignId; switch ($scope.notification.destinationType) { case 'custom': members = $scope.notification.recipients; break; case 'committee': members = $scope.userEdits.allCommitteeList(); break; default: members = []; break; } logger.debug('sendCommitteeNotification:notification->', $scope.notification); if (members.length === 0) { logger.debug('about to replicateAndSendWithOptions to', list, 'list with campaignName', campaignName, 'campaign Id', campaignId, 'dontSend', dontSend); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } else { var segmentName = MailchimpSegmentService.formatSegmentName('Committee Notification Recipients'); return MailchimpSegmentService.saveSegment(list, {segmentId: segmentId}, members, segmentName, $scope.members) .then(function (segmentResponse) { logger.debug('segmentResponse following save segment of segmentName:', segmentName, '->', segmentResponse); logger.debug('about to replicateAndSendWithOptions to committee with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentResponse.segment.id); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentResponse.segment.id, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); }); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function notifyEmailSendComplete() { if (!$scope.userEdits.cancelled) { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; $scope.cancelSendNotification(); } notify.clearBusy(); } }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.cancelSendNotification = function () { if ($scope.userEdits.sendInProgress) { $scope.userEdits.sendInProgress = false; $scope.userEdits.cancelled = true; notify.error({ title: 'Cancelling during send', message: "Because notification sending was already in progress when you cancelled, campaign may have already been sent - check in Mailchimp if in doubt." }); } else { logger.debug('calling cancelSendNotification'); close(); } }; var promises = [ MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectGeneralMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); }), MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); $scope.clearRecipientsForCampaignOfType('committee'); }), MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: 'Master' }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); })]; if (!$scope.committeeFile) promises.push(populateGroupEvents()); $q.all(promises).then(function () { logger.debug('performed total of', promises.length); notify.clearBusy(); }); }] ); /* concatenated from client/src/app/js/committee.js */ angular.module('ekwgApp') .controller('CommitteeController', ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "EKWGFileUpload", "CommitteeQueryService", "CommitteeReferenceData", "ModalService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, EKWGFileUpload, CommitteeQueryService, CommitteeReferenceData, ModalService) { var logger = $log.getInstance('CommitteeController'); $log.logLevels['CommitteeController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); $scope.emailingInProgress = false; $scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles'); $scope.destinationType = ''; $scope.members = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.committeeReferenceData = CommitteeReferenceData; $scope.selected = { addingNewFile: false, committeeFiles: [] }; $rootScope.$on('CommitteeReferenceDataReady', function () { assignFileTypes(); }); function assignFileTypes() { $scope.fileTypes = CommitteeReferenceData.fileTypes; logger.debug('CommitteeReferenceDataReady -> fileTypes ->', $scope.fileTypes); } $scope.userEdits = { saveInProgress: false }; $scope.showAlertMessage = function () { return ($scope.alert.class === 'alert-danger') || $scope.emailingInProgress; }; $scope.latestYear = function () { return CommitteeQueryService.latestYear($scope.committeeFiles) }; $scope.committeeFilesForYear = function (year) { return CommitteeQueryService.committeeFilesForYear(year, $scope.committeeFiles) }; $scope.isActive = function (committeeFile) { return committeeFile === $scope.selected.committeeFile; }; $scope.eventDateCalendar = { open: function ($event) { $scope.eventDateCalendar.opened = true; } }; $scope.allowSend = function () { return LoggedInMemberService.allowFileAdmin(); }; $scope.allowAddCommitteeFile = function () { return $scope.fileTypes && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEditCommitteeFile = function (committeeFile) { return $scope.allowAddCommitteeFile() && committeeFile && committeeFile.$id(); }; $scope.allowDeleteCommitteeFile = function (committeeFile) { return $scope.allowEditCommitteeFile(committeeFile); }; $scope.cancelFileChange = function () { $q.when($scope.hideCommitteeFileDialog()).then(refreshCommitteeFiles).then(notify.clearBusy); }; $scope.saveCommitteeFile = function () { $scope.userEdits.saveInProgress = true; $scope.selected.committeeFile.eventDate = DateUtils.asValueNoTime($scope.selected.committeeFile.eventDate); logger.debug('saveCommitteeFile ->', $scope.selected.committeeFile); return $scope.selected.committeeFile.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.saveInProgress = false; notify.error({ title: 'Your changes could not be saved', message: (errorResponse && errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } }; var defaultCommitteeFile = function () { return _.clone({ "createdDate": DateUtils.nowAsValue(), "fileType": $scope.fileTypes && $scope.fileTypes[0].description, "fileNameData": {} }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNewFile = false; $scope.userEdits.saveInProgress = false; } $scope.deleteCommitteeFile = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDeleteCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDeleteCommitteeFile = function () { $scope.userEdits.saveInProgress = true; function showCommitteeFileDeleted() { return notify.success('File was deleted successfully'); } $scope.selected.committeeFile.$remove(showCommitteeFileDeleted, showCommitteeFileDeleted, notify.error, notify.error) .then($scope.hideCommitteeFileDialog) .then(refreshCommitteeFiles) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectCommitteeFile = function (committeeFile, committeeFiles) { if (!$scope.selected.addingNewFile) { $scope.selected.committeeFile = committeeFile; $scope.selected.committeeFiles = committeeFiles; } }; $scope.editCommitteeFile = function () { removeDeleteOrAddOrInProgressFlags(); delete $scope.uploadedFile; $('#file-detail-dialog').modal('show'); }; $scope.openMailchimp = function () { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns", '_blank'); }; $scope.openSettings = function () { ModalService.showModal({ templateUrl: "partials/committee/notification-settings-dialog.html", controller: "CommitteeNotificationSettingsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.sendNotification = function (committeeFile) { ModalService.showModal({ templateUrl: "partials/committee/send-notification-dialog.html", controller: "CommitteeNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { committeeFile: committeeFile } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; $scope.cancelSendNotification = function () { $('#send-notification-dialog').modal('hide'); $scope.resubmit = false; }; $scope.addCommitteeFile = function ($event) { $event.stopPropagation(); $scope.selected.addingNewFile = true; var committeeFile = new CommitteeFileService(defaultCommitteeFile()); $scope.selected.committeeFiles.push(committeeFile); $scope.selected.committeeFile = committeeFile; logger.debug('addCommitteeFile:', committeeFile, 'of', $scope.selected.committeeFiles.length, 'files'); $scope.editCommitteeFile(); }; $scope.hideCommitteeFileDialog = function () { removeDeleteOrAddOrInProgressFlags(); $('#file-detail-dialog').modal('hide'); }; $scope.attachFile = function (file) { $scope.oldTitle = $scope.selected.committeeFile.fileNameData ? $scope.selected.committeeFile.fileNameData.title : file.name; logger.debug('then:attachFile:oldTitle', $scope.oldTitle); $('#hidden-input').click(); }; $scope.onFileSelect = function (file) { if (file) { $scope.userEdits.saveInProgress = true; logger.debug('onFileSelect:file:about to upload ->', file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'committeeFiles') .then(function (fileNameData) { logger.debug('onFileSelect:file:upload complete -> fileNameData', fileNameData); $scope.selected.committeeFile.fileNameData = fileNameData; $scope.selected.committeeFile.fileNameData.title = $scope.oldTitle || file.name; $scope.userEdits.saveInProgress = false; }); } }; $scope.attachmentTitle = function () { return ($scope.selected.committeeFile && _.isEmpty($scope.selected.committeeFile.fileNameData) ? 'Attach' : 'Replace') + ' File'; }; $scope.fileUrl = function (committeeFile) { return committeeFile && committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + committeeFile.fileNameData.awsFileName : ''; }; $scope.fileTitle = function (committeeFile) { return committeeFile ? DateUtils.asString(committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + committeeFile.fileNameData.title : ''; }; $scope.iconFile = function (committeeFile) { if (!committeeFile.fileNameData) return undefined; function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } if (fileExtensionIs(committeeFile.fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { return 'icon-' + fileExtension(committeeFile.fileNameData.awsFileName).substring(0, 3) + '.jpg'; } else { return 'icon-default.jpg'; } }; $scope.$on('memberLoginComplete', function () { refreshAll(); }); $scope.$on('memberLogoutComplete', function () { refreshAll(); }); function refreshMembers() { function assignMembersToScope(members) { $scope.members = members; return $scope.members; } if (LoggedInMemberService.allowFileAdmin()) { return MemberService.all() .then(assignMembersToScope); } } function refreshCommitteeFiles() { CommitteeQueryService.committeeFiles(notify).then(function (files) { logger.debug('committeeFiles', files); if (URLService.hasRouteParameter('committeeFileId')) { $scope.committeeFiles = _.filter(files, function (file) { return file.$id() === $routeParams.committeeFileId; }); } else { $scope.committeeFiles = files; } $scope.committeeFileYears = CommitteeQueryService.committeeFileYears($scope.committeeFiles); }); } function refreshAll() { refreshCommitteeFiles(); refreshMembers(); } assignFileTypes(); refreshAll(); }]); /* concatenated from client/src/app/js/committeeData.js */ angular.module('ekwgApp') .factory('CommitteeConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('committee', { committee: { contactUs: { chairman: {description: 'Chairman', fullName: 'Claire Mansfield', email: 'chairman@ekwg.co.uk'}, secretary: {description: 'Secretary', fullName: 'Kerry O\'Grady', email: 'secretary@ekwg.co.uk'}, treasurer: {description: 'Treasurer', fullName: 'Marianne Christensen', email: 'treasurer@ekwg.co.uk'}, membership: {description: 'Membership', fullName: 'Desiree Nel', email: 'membership@ekwg.co.uk'}, social: {description: 'Social Co-ordinator', fullName: 'Suzanne Graham Beer', email: 'social@ekwg.co.uk'}, walks: {description: 'Walks Co-ordinator', fullName: 'Stuart Maisner', email: 'walks@ekwg.co.uk'}, support: {description: 'Technical Support', fullName: 'Nick Barrett', email: 'nick.barrett@ekwg.co.uk'} }, fileTypes: [ {description: "AGM Agenda", public: true}, {description: "AGM Minutes", public: true}, {description: "Committee Meeting Agenda"}, {description: "Committee Meeting Minutes"}, {description: "Financial Statements", public: true} ] } }) } function saveConfig(config, saveCallback, errorSaveCallback) { return Config.saveConfig('committee', config, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('CommitteeFileService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('committeeFiles'); }]) .factory('CommitteeReferenceData', ["$rootScope", function ($rootScope) { var refData = { contactUsRoles: function () { var keys = _.keys(refData.contactUs); if (keys.length > 0) { return keys; } }, contactUsField: function (role, field) { return refData.contactUs && refData.contactUs[role][field] }, fileTypesField: function (type, field) { return refData.fileTypes && refData.fileTypes[type][field] }, toFileType: function (fileTypeDescription, fileTypes) { return _.find(fileTypes, {description: fileTypeDescription}); }, contactUsRolesAsArray: function () { return _.map(refData.contactUs, function (data, type) { return { type: type, fullName: data.fullName, memberId: data.memberId, description: data.description + ' (' + data.fullName + ')', email: data.email }; }); } }; $rootScope.$on('CommitteeReferenceDataReady', function () { refData.ready = true; }); return refData; }]) .factory('CommitteeQueryService', ["$q", "$log", "$filter", "$routeParams", "URLService", "CommitteeFileService", "CommitteeReferenceData", "DateUtils", "LoggedInMemberService", "WalksService", "SocialEventsService", function ($q, $log, $filter, $routeParams, URLService, CommitteeFileService, CommitteeReferenceData, DateUtils, LoggedInMemberService, WalksService, SocialEventsService) { var logger = $log.getInstance('CommitteeQueryService'); $log.logLevels['CommitteeQueryService'] = $log.LEVEL.OFF; function groupEvents(groupEvents) { logger.debug('groupEvents', groupEvents); var fromDate = DateUtils.convertDateField(groupEvents.fromDate); var toDate = DateUtils.convertDateField(groupEvents.toDate); logger.debug('groupEvents:fromDate', $filter('displayDate')(fromDate), 'toDate', $filter('displayDate')(toDate)); var events = []; var promises = []; if (groupEvents.includeWalks) promises.push( WalksService.query({walkDate: {$gte: fromDate, $lte: toDate}}) .then(function (walks) { return _.map(walks, function (walk) { return events.push({ id: walk.$id(), selected: true, eventType: 'Walk', area: 'walks', type: 'walk', eventDate: walk.walkDate, eventTime: walk.startTime, distance: walk.distance, postcode: walk.postcode, title: walk.briefDescriptionAndStartPoint || 'Awaiting walk details', description: walk.longerDescription, contactName: walk.displayName || 'Awaiting walk leader', contactPhone: walk.contactPhone, contactEmail: walk.contactEmail }); }) })); if (groupEvents.includeCommitteeEvents) promises.push( CommitteeFileService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (committeeFiles) { return _.map(committeeFiles, function (committeeFile) { return events.push({ id: committeeFile.$id(), selected: true, eventType: 'AGM & Committee', area: 'committee', type: 'committeeFile', eventDate: committeeFile.eventDate, postcode: committeeFile.postcode, description: committeeFile.fileType, title: committeeFile.fileNameData.title }); }) })); if (groupEvents.includeSocialEvents) promises.push( SocialEventsService.query({eventDate: {$gte: fromDate, $lte: toDate}}) .then(function (socialEvents) { return _.map(socialEvents, function (socialEvent) { return events.push({ id: socialEvent.$id(), selected: true, eventType: 'Social Event', area: 'social', type: 'socialEvent', eventDate: socialEvent.eventDate, eventTime: socialEvent.eventTimeStart, postcode: socialEvent.postcode, title: socialEvent.briefDescription, description: socialEvent.longerDescription, contactName: socialEvent.displayName, contactPhone: socialEvent.contactPhone, contactEmail: socialEvent.contactEmail }); }) })); return $q.all(promises).then(function () { logger.debug('performed total of', promises.length, 'events of length', events.length); return _.chain(events) .sortBy('eventDate') .value(); }); } function committeeFilesLatestFirst(committeeFiles) { return _.chain(committeeFiles) .sortBy('eventDate') .reverse() .value(); } function latestYear(committeeFiles) { return _.first( _.chain(committeeFilesLatestFirst(committeeFiles)) .pluck('eventDate') .map(function (eventDate) { return parseInt(DateUtils.asString(eventDate, undefined, 'YYYY')); }) .value()); } function committeeFilesForYear(year, committeeFiles) { var latestYearValue = latestYear(committeeFiles); return _.filter(committeeFilesLatestFirst(committeeFiles), function (committeeFile) { var fileYear = extractYear(committeeFile); return (fileYear === year) || (!fileYear && (latestYearValue === year)); }); } function extractYear(committeeFile) { return parseInt(DateUtils.asString(committeeFile.eventDate, undefined, 'YYYY')); } function committeeFileYears(committeeFiles) { var latestYearValue = latestYear(committeeFiles); function addLatestYearFlag(committeeFileYear) { return {year: committeeFileYear, latestYear: latestYearValue === committeeFileYear}; } var years = _.chain(committeeFiles) .map(extractYear) .unique() .sort() .map(addLatestYearFlag) .reverse() .value(); logger.debug('committeeFileYears', years); return years.length === 0 ? [{year: latestYear(committeeFiles), latestYear: true}] : years; } function committeeFiles(notify) { notify.progress('Refreshing Committee files...'); function queryCommitteeFiles() { if (URLService.hasRouteParameter('committeeFileId')) { return CommitteeFileService.getById($routeParams.committeeFileId) .then(function (committeeFile) { if (!committeeFile) notify.error('Committee file could not be found. Try opening again from the link in the notification email'); return [committeeFile]; }); } else { return CommitteeFileService.all().then(function (files) { return filterCommitteeFiles(files); }); } } return queryCommitteeFiles() .then(function (committeeFiles) { notify.progress('Found ' + committeeFiles.length + ' committee file(s)'); notify.setReady(); return _.chain(committeeFiles) .sortBy('fileDate') .reverse() .sortBy('createdDate') .value(); }, notify.error); } function filterCommitteeFiles(files) { logger.debug('filterCommitteeFiles files ->', files); var filteredFiles = _.filter(files, function (file) { return CommitteeReferenceData.fileTypes && CommitteeReferenceData.toFileType(file.fileType, CommitteeReferenceData.fileTypes).public || LoggedInMemberService.allowCommittee() || LoggedInMemberService.allowFileAdmin(); }); logger.debug('filterCommitteeFiles in ->', files && files.length, 'out ->', filteredFiles.length, 'CommitteeReferenceData.fileTypes', CommitteeReferenceData.fileTypes); return filteredFiles } return { groupEvents: groupEvents, committeeFiles: committeeFiles, latestYear: latestYear, committeeFileYears: committeeFileYears, committeeFilesForYear: committeeFilesForYear } }] ); /* concatenated from client/src/app/js/committeeNotificationSettingsController.js */ angular.module('ekwgApp') .controller('CommitteeNotificationSettingsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, close) { var logger = $log.getInstance('CommitteeNotificationSettingsController'); $log.logLevels['CommitteeNotificationSettingsController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.campaigns = []; var notify = Notifier($scope.notify); var campaignSearchTerm = 'Master'; notify.setBusy(); notify.progress({ title: 'Mailchimp Campaigns', message: 'Getting campaign information matching "' + campaignSearchTerm + '"' }); $scope.notReady = function () { return $scope.campaigns.length === 0; }; MailchimpConfig.getConfig() .then(function (config) { $scope.config = config; logger.debug('retrieved config', $scope.config); }); MailchimpCampaignService.list({ limit: 1000, concise: true, status: 'save', title: campaignSearchTerm }).then(function (response) { $scope.campaigns = response.data; logger.debug('response.data', response.data); notify.success({ title: 'Mailchimp Campaigns', message: 'Found ' + $scope.campaigns.length + ' draft campaigns matching "' + campaignSearchTerm + '"' }); notify.clearBusy(); }); $scope.editCampaign = function (campaignId) { if (!campaignId) { notify.error({ title: 'Edit Mailchimp Campaign', message: 'Please select a campaign from the drop-down before choosing edit' }); } else { notify.hide(); var webId = _.find($scope.campaigns, function (campaign) { return campaign.id === campaignId; }).web_id; logger.debug('editCampaign:campaignId', campaignId, 'web_id', webId); $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/edit?id=" + webId, '_blank'); } }; $scope.save = function () { logger.debug('saving config', $scope.config); MailchimpConfig.saveConfig($scope.config).then(close).catch(notify.error); }; $scope.cancel = function () { close(); }; }] ); /* concatenated from client/src/app/js/contentMetaServices.js */ angular.module('ekwgApp') .factory('ContentMetaDataService', ["ContentMetaData", "$q", function (ContentMetaData, $q) { var baseUrl = function (metaDataPathSegment) { return '/aws/s3/' + metaDataPathSegment; }; var createNewMetaData = function (withDefaults) { if (withDefaults) { return {image: '/(select file)', text: '(Enter title here)'}; } else { return {}; } }; var getMetaData = function (contentMetaDataType) { var task = $q.defer(); ContentMetaData.query({contentMetaDataType: contentMetaDataType}, {limit: 1}) .then(function (results) { if (results && results.length > 0) { task.resolve(results[0]); } else { task.resolve(new ContentMetaData({ contentMetaDataType: contentMetaDataType, baseUrl: baseUrl(contentMetaDataType), files: [createNewMetaData(true)] })); } }, function (response) { task.reject('Query of contentMetaDataType for ' + contentMetaDataType + ' failed: ' + response); }); return task.promise; }; var saveMetaData = function (metaData, saveCallback, errorSaveCallback) { return metaData.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback); }; return { baseUrl: baseUrl, getMetaData: getMetaData, createNewMetaData: createNewMetaData, saveMetaData: saveMetaData } }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ContentTextService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentText'); }]) .factory('ContentText', ["ContentTextService", function (ContentTextService) { function forName(name) { return ContentTextService.all().then(function (contentDocuments) { return _.findWhere(contentDocuments, {name: name}) || new ContentTextService({name: name}); }); } return {forName: forName} }]); /* concatenated from client/src/app/js/directives.js */ angular.module('ekwgApp') .directive('contactUs', ["$log", "$compile", "URLService", "CommitteeReferenceData", function ($log, $compile, URLService, CommitteeReferenceData) { var logger = $log.getInstance('contactUs'); $log.logLevels['contactUs'] = $log.LEVEL.OFF; function email(role) { return CommitteeReferenceData.contactUsField(role, 'email'); } function description(role) { return CommitteeReferenceData.contactUsField(role, 'description'); } function fullName(role) { return CommitteeReferenceData.contactUsField(role, 'fullName'); } function createHref(scope, role) { return '<a href="mailto:' + email(role) + '">' + (scope.text || email(role)) + '</a>'; } function createListItem(scope, role) { return '<li ' + 'style="' + 'font-weight: normal;' + 'padding: 4px 0px 4px 21px;' + 'list-style: none;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/bull-green.png);' + 'background-position: 0px 9px;' + 'background-repeat: no-repeat no-repeat">' + fullName(role) + ' - ' + description(role) + ' - ' + '<a href="mailto:' + email(role) + '"' + 'style="' + 'background-color: transparent;' + 'color: rgb(120, 35, 39);' + 'text-decoration: none; ' + 'font-weight: bold; ' + 'background-position: initial; ' + 'background-repeat: initial;">' + (scope.text || email(role)) + '</a>' + '</li>'; } function expandRoles(scope) { var roles = scope.role ? scope.role.split(',') : CommitteeReferenceData.contactUsRoles(); logger.debug('role ->', scope.role, ' roles ->', roles); return _(roles).map(function (role) { if (scope.format === 'list') { return createListItem(scope, role); } else { return createHref(scope, role); } }).join('\n'); } function wrapInUL(scope) { if (scope.format === 'list') { return '<ul style="' + 'margin: 10px 0 0;' + 'padding: 0 0 10px 10px;' + 'font-weight: bold;' + 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/dot-darkgrey-hor.png);' + 'background-position: 0% 100%;' + 'background-repeat: repeat no-repeat;' + 'margin-bottom: 20px;"> ' + (scope.heading || '') + expandRoles(scope) + '</ul>'; } else { return expandRoles(scope); } } return { restrict: 'EA', replace: true, link: function (scope, element) { scope.$watch('name', function () { if (CommitteeReferenceData.ready) { var html = wrapInUL(scope); logger.debug('html before compile ->', html); element.html($compile(html)(scope)); } }); }, scope: { format: '@', text: '@', role: '@', heading: '@' } }; }]); /* concatenated from client/src/app/js/emailerService.js */ angular.module('ekwgApp') .factory('EmailSubscriptionService', ["$rootScope", "$log", "$http", "$q", "MemberService", "DateUtils", "MailchimpErrorParserService", function ($rootScope, $log, $http, $q, MemberService, DateUtils, MailchimpErrorParserService) { var logger = $log.getInstance('EmailSubscriptionService'); $log.logLevels['EmailSubscriptionService'] = $log.LEVEL.OFF; var resetAllBatchSubscriptions = function (members, subscribedState) { var deferredTask = $q.defer(); var savePromises = []; deferredTask.notify('Resetting Mailchimp subscriptions for ' + members.length + ' members'); _.each(members, function (member) { defaultMailchimpSettings(member, subscribedState); savePromises.push(member.$saveOrUpdate()); }); $q.all(savePromises).then(function () { deferredTask.notify('Reset of Mailchimp subscriptions completed. Next member save will resend all lists to Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }) }); }; function defaultMailchimpSettings(member, subscribedState) { member.mailchimpLists = { "walks": {"subscribed": subscribedState}, "socialEvents": {"subscribed": subscribedState}, "general": {"subscribed": subscribedState} } } function booleanToString(value) { return String(value || false); } function addMailchimpIdentifiersToRequest(member, listType, request) { var mailchimpIdentifiers = {email: {}}; mailchimpIdentifiers.email.email = member.email; if (member.mailchimpLists[listType].leid) { mailchimpIdentifiers.email.leid = member.mailchimpLists[listType].leid; } if (request) { return angular.extend(request, mailchimpIdentifiers); } else { return mailchimpIdentifiers.email; } } var createBatchSubscriptionForList = function (listType, members) { var deferredTask = $q.defer(); var progress = 'Sending ' + listType + ' member data to Mailchimp'; deferredTask.notify(progress); var batchedMembers = []; var subscriptionEntries = _.chain(members) .filter(function (member) { return includeMemberInSubscription(listType, member); }) .map(function (member) { batchedMembers.push(member); var request = { "merge_vars": { "FNAME": member.firstName, "LNAME": member.lastName, "MEMBER_NUM": member.membershipNumber, "MEMBER_EXP": DateUtils.displayDate(member.membershipExpiryDate), "USERNAME": member.userName, "PW_RESET": member.passwordResetId || '' } }; return addMailchimpIdentifiersToRequest(member, listType, request); }).value(); if (subscriptionEntries.length > 0) { var url = '/mailchimp/lists/' + listType + '/batchSubscribe'; logger.debug('sending', subscriptionEntries.length, listType, 'subscriptions to mailchimp', subscriptionEntries); $http({method: 'POST', url: url, data: subscriptionEntries}) .then(function (response) { var responseData = response.data; logger.debug('received response', responseData); var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = { message: 'Sending of ' + listType + ' list subscription to Mailchimp was not successful', error: errorObject.error }; deferredTask.reject(errorResponse); } else { var totalResponseCount = responseData.updates.concat(responseData.adds).concat(responseData.errors).length; deferredTask.notify('Send of ' + subscriptionEntries.length + ' ' + listType + ' members completed - processing ' + totalResponseCount + ' Mailchimp response(s)'); var savePromises = []; processValidResponses(listType, responseData.updates.concat(responseData.adds), batchedMembers, savePromises, deferredTask); processErrorResponses(listType, responseData.errors, batchedMembers, savePromises, deferredTask); $q.all(savePromises).then(function () { MemberService.all().then(function (refreshedMembers) { deferredTask.notify('Send of ' + subscriptionEntries.length + ' members to ' + listType + ' list completed with ' + responseData.add_count + ' member(s) added, ' + responseData.update_count + ' updated and ' + responseData.error_count + ' error(s)'); deferredTask.resolve(refreshedMembers); }) }); } }).catch(function (response) { var data = response.data; var errorMessage = 'Sending of ' + listType + ' member data to Mailchimp was not successful due to response: ' + data.trim(); logger.error(errorMessage); deferredTask.reject(errorMessage); }) } else { deferredTask.notify('No ' + listType + ' updates to send Mailchimp'); MemberService.all().then(function (refreshedMembers) { deferredTask.resolve(refreshedMembers); }); } return deferredTask.promise; }; function includeMemberInEmailList(listType, member) { if (member.email && member.mailchimpLists[listType].subscribed) { if (listType === 'socialEvents') { return member.groupMember && member.socialMember; } else { return member.groupMember; } } else { return false; } } function includeMemberInSubscription(listType, member) { return includeMemberInEmailList(listType, member) && !member.mailchimpLists[listType].updated; } function includeMemberInUnsubscription(listType, member) { if (!member || !member.groupMember) { return true; } else if (member.mailchimpLists) { if (listType === 'socialEvents') { return (!member.socialMember && member.mailchimpLists[listType].subscribed); } else { return (!member.mailchimpLists[listType].subscribed); } } else { return false; } } function includeSubscriberInUnsubscription(listType, allMembers, subscriber) { return includeMemberInUnsubscription(listType, responseToMember(listType, allMembers, subscriber)); } function resetUpdateStatusForMember(member) { // updated == false means not up to date with mail e.g. next list update will send this data to mailchimo member.mailchimpLists.walks.updated = false; member.mailchimpLists.socialEvents.updated = false; member.mailchimpLists.general.updated = false; } function responseToMember(listType, allMembers, mailchimpResponse) { return _(allMembers).find(function (member) { var matchedOnListSubscriberId = mailchimpResponse.leid && member.mailchimpLists[listType].leid && (mailchimpResponse.leid.toString() === member.mailchimpLists[listType].leid.toString()); var matchedOnLastReturnedEmail = member.mailchimpLists[listType].email && (mailchimpResponse.email.toLowerCase() === member.mailchimpLists[listType].email.toLowerCase()); var matchedOnCurrentEmail = member.email && mailchimpResponse.email.toLowerCase() === member.email.toLowerCase(); return (matchedOnListSubscriberId || matchedOnLastReturnedEmail || matchedOnCurrentEmail); }); } function findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask) { var member = responseToMember(listType, batchedMembers, response); if (member) { member.mailchimpLists[listType].leid = response.leid; member.mailchimpLists[listType].updated = true; // updated == true means up to date e.g. nothing to send to mailchimo member.mailchimpLists[listType].lastUpdated = DateUtils.nowAsValue(); member.mailchimpLists[listType].email = member.email; } else { deferredTask.notify('From ' + batchedMembers.length + ' members, could not find any member related to response ' + JSON.stringify(response)); } return member; } function processValidResponses(listType, validResponses, batchedMembers, savePromises, deferredTask) { _.each(validResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask); if (member) { delete member.mailchimpLists[listType].code; delete member.mailchimpLists[listType].error; deferredTask.notify('processing valid response for member ' + member.email); savePromises.push(member.$saveOrUpdate()); } }); } function processErrorResponses(listType, errorResponses, batchedMembers, savePromises, deferredTask) { _.each(errorResponses, function (response) { var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response.email, deferredTask); if (member) { deferredTask.notify('processing error response for member ' + member.email); member.mailchimpLists[listType].code = response.code; member.mailchimpLists[listType].error = response.error; if (_.contains([210, 211, 212, 213, 214, 215, 220, 250], response.code)) member.mailchimpLists[listType].subscribed = false; savePromises.push(member.$saveOrUpdate()); } }); } return { responseToMember: responseToMember, defaultMailchimpSettings: defaultMailchimpSettings, createBatchSubscriptionForList: createBatchSubscriptionForList, resetAllBatchSubscriptions: resetAllBatchSubscriptions, resetUpdateStatusForMember: resetUpdateStatusForMember, addMailchimpIdentifiersToRequest: addMailchimpIdentifiersToRequest, includeMemberInSubscription: includeMemberInSubscription, includeMemberInEmailList: includeMemberInEmailList, includeSubscriberInUnsubscription: includeSubscriberInUnsubscription } }]); /* concatenated from client/src/app/js/expenses.js */ angular.module('ekwgApp') .controller('ExpensesController', ["$compile", "$log", "$timeout", "$sce", "$templateRequest", "$q", "$rootScope", "$location", "$routeParams", "$scope", "$filter", "DateUtils", "NumberUtils", "URLService", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "ExpenseClaimsService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "EKWGFileUpload", function ($compile, $log, $timeout, $sce, $templateRequest, $q, $rootScope, $location, $routeParams, $scope, $filter, DateUtils, NumberUtils, URLService, LoggedInMemberService, MemberService, ContentMetaDataService, ExpenseClaimsService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, EKWGFileUpload) { var logger = $log.getInstance('ExpensesController'); var noLogger = $log.getInstance('ExpensesControllerNoLogger'); $log.logLevels['ExpensesControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['ExpensesController'] = $log.LEVEL.OFF; const SELECTED_EXPENSE = 'Expense from last email link'; $scope.receiptBaseUrl = ContentMetaDataService.baseUrl('expenseClaims'); $scope.dataError = false; $scope.members = []; $scope.expenseClaims = []; $scope.unfilteredExpenseClaims = []; $scope.expensesOpen = URLService.hasRouteParameter('expenseId') || URLService.isArea('expenses'); $scope.alertMessages = []; $scope.filterTypes = [{ disabled: !$routeParams.expenseId, description: SELECTED_EXPENSE, filter: function (expenseClaim) { if ($routeParams.expenseId) { return expenseClaim && expenseClaim.$id() === $routeParams.expenseId; } else { return false; } } }, { description: 'Unpaid expenses', filter: function (expenseClaim) { return !$scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Paid expenses', filter: function (expenseClaim) { return $scope.expenseClaimStatus(expenseClaim).atEndpoint; } }, { description: 'Expenses awaiting action from me', filter: function (expenseClaim) { return LoggedInMemberService.allowFinanceAdmin() ? editable(expenseClaim) : editableAndOwned(expenseClaim); } }, { description: 'All expenses', filter: function () { return true; } }]; $scope.selected = { showOnlyMine: !allowAdminFunctions(), saveInProgress: false, expenseClaimIndex: 0, expenseItemIndex: 0, expenseFilter: $scope.filterTypes[$routeParams.expenseId ? 0 : 1] }; $scope.itemAlert = {}; var notify = Notifier($scope); var notifyItem = Notifier($scope.itemAlert); notify.setBusy(); var notificationsBaseUrl = 'partials/expenses/notifications'; LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.selected.expenseClaim = function () { try { return $scope.expenseClaims[$scope.selected.expenseClaimIndex]; } catch (e) { console.error(e); } }; $scope.isInactive = function (expenseClaim) { return expenseClaim !== $scope.selected.expenseClaim(); }; $scope.selected.expenseItem = function () { try { var expenseClaim = $scope.expenseClaims[$scope.selected.expenseClaimIndex]; return expenseClaim ? expenseClaim.expenseItems[$scope.selected.expenseItemIndex] : undefined; } catch (e) { console.error(e); } }; $scope.expenseTypes = [ {value: "travel-reccie", name: "Travel (walk reccie)", travel: true}, {value: "travel-committee", name: "Travel (attend committee meeting)", travel: true}, {value: "other", name: "Other"}]; var eventTypes = { created: {description: "Created", editable: true}, submitted: {description: "Submitted", actionable: true, notifyCreator: true, notifyApprover: true}, 'first-approval': {description: "First Approval", actionable: true, notifyApprover: true}, 'second-approval': { description: "Second Approval", actionable: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true }, returned: {description: "Returned", atEndpoint: false, editable: true, notifyCreator: true, notifyApprover: true}, paid: {description: "Paid", atEndpoint: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true} }; var defaultExpenseClaim = function () { return _.clone({ "cost": 0, "expenseItems": [], "expenseEvents": [] }) }; var defaultExpenseItem = function () { return _.clone({ expenseType: $scope.expenseTypes[0], "travel": { "costPerMile": 0.28, "miles": 0, "from": '', "to": '', "returnJourney": true } }); }; function editable(expenseClaim) { return memberCanEditClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } function editableAndOwned(expenseClaim) { return memberOwnsClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable; } $scope.editable = function () { return editable($scope.selected.expenseClaim()); }; $scope.allowClearError = function () { return URLService.hasRouteParameter('expenseId') && $scope.dataError; }; $scope.allowAddExpenseClaim = function () { return !$scope.dataError && !_.find($scope.unfilteredExpenseClaims, editableAndOwned); }; $scope.allowFinanceAdmin = function () { return LoggedInMemberService.allowFinanceAdmin(); }; $scope.allowEditExpenseItem = function () { return $scope.allowAddExpenseItem() && $scope.selected.expenseItem() && $scope.selected.expenseClaim().$id(); }; $scope.allowAddExpenseItem = function () { return $scope.editable(); }; $scope.allowDeleteExpenseItem = function () { return $scope.allowEditExpenseItem(); }; $scope.allowDeleteExpenseClaim = function () { return !$scope.allowDeleteExpenseItem() && $scope.allowAddExpenseItem(); }; $scope.allowSubmitExpenseClaim = function () { return $scope.allowEditExpenseItem() && !$scope.allowResubmitExpenseClaim(); }; function allowAdminFunctions() { return LoggedInMemberService.allowTreasuryAdmin() || LoggedInMemberService.allowFinanceAdmin(); } $scope.allowAdminFunctions = function () { return allowAdminFunctions(); }; $scope.allowReturnExpenseClaim = function () { return $scope.allowAdminFunctions() && $scope.selected.expenseClaim() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.submitted) && !expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned) && $scope.expenseClaimStatus($scope.selected.expenseClaim()).actionable; }; $scope.allowResubmitExpenseClaim = function () { return $scope.editable() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned); }; $scope.allowPaidExpenseClaim = function () { return LoggedInMemberService.allowTreasuryAdmin() && _.contains( [eventTypes.submitted.description, eventTypes['second-approval'].description, eventTypes['first-approval'].description], $scope.expenseClaimLatestEvent().eventType.description); }; function activeEvents(optionalEvents) { var events = optionalEvents || $scope.selected.expenseClaim().expenseEvents; var latestReturnedEvent = _.find(events.reverse(), function (event) { return _.isEqual(event.eventType, $scope.expenseClaimStatus.returned); }); return latestReturnedEvent ? events.slice(events.indexOf(latestReturnedEvent + 1)) : events; } function expenseClaimHasEventType(expenseClaim, eventType) { if (!expenseClaim) return false; return eventForEventType(expenseClaim, eventType); } function eventForEventType(expenseClaim, eventType) { if (expenseClaim) return _.find(expenseClaim.expenseEvents, function (event) { return _.isEqual(event.eventType, eventType); }); } $scope.allowApproveExpenseClaim = function () { return false; }; $scope.lastApprovedByMe = function () { var approvalEvents = $scope.approvalEvents(); return approvalEvents.length > 0 && _.last(approvalEvents).memberId === LoggedInMemberService.loggedInMember().memberId; }; $scope.approvalEvents = function () { if (!$scope.selected.expenseClaim()) return []; return _.filter($scope.selected.expenseClaim().expenseEvents, function (event) { return _.isEqual(event.eventType, eventTypes['first-approval']) || _.isEqual(event.eventType, eventTypes['second-approval']); }); }; $scope.expenseClaimStatus = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return $scope.expenseClaimLatestEvent(expenseClaim).eventType; }; $scope.expenseClaimLatestEvent = function (optionalExpenseClaim) { var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim(); return expenseClaim ? _.last(expenseClaim.expenseEvents) : {}; }; $scope.nextApprovalStage = function () { var approvals = $scope.approvalEvents(); if (approvals.length === 0) { return 'First Approval'; } else if (approvals.length === 1) { return 'Second Approval' } else { return 'Already has ' + approvals.length + ' approvals!'; } }; $scope.confirmApproveExpenseClaim = function () { var approvals = $scope.approvalEvents(); notifyItem.hide(); if (approvals.length === 0) { createEventAndSendNotifications(eventTypes['first-approval']); } else if (approvals.length === 1) { createEventAndSendNotifications(eventTypes['second-approval']); } else { notify.error('This expense claim already has ' + approvals.length + ' approvals!'); } }; $scope.showAllExpenseClaims = function () { $scope.dataError = false; $location.path('/admin/expenses') }; $scope.addExpenseClaim = function () { $scope.expenseClaims.unshift(new ExpenseClaimsService(defaultExpenseClaim())); $scope.selectExpenseClaim(0); createEvent(eventTypes.created); $scope.addExpenseItem(); }; $scope.selectExpenseItem = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseItem - selected.saveInProgress - not changing to index', index); } else { noLogger.info('selectExpenseItem:', index); $scope.selected.expenseItemIndex = index; } }; $scope.selectExpenseClaim = function (index) { if ($scope.selected.saveInProgress) { noLogger.info('selectExpenseClaim - selected.saveInProgress - not changing to index', index); } else { $scope.selected.expenseClaimIndex = index; var expenseClaim = $scope.selected.expenseClaim(); noLogger.info('selectExpenseClaim:', index, expenseClaim); } }; $scope.editExpenseItem = function () { $scope.removeConfirm(); delete $scope.uploadedFile; $('#expense-detail-dialog').modal('show'); }; $scope.hideExpenseClaim = function () { $scope.removeConfirm(); $('#expense-detail-dialog').modal('hide'); }; $scope.addReceipt = function () { $('#hidden-input').click(); }; $scope.removeReceipt = function () { delete $scope.selected.expenseItem().receipt; delete $scope.uploadedFile; }; $scope.receiptTitle = function (expenseItem) { return expenseItem && expenseItem.receipt ? (expenseItem.receipt.title || expenseItem.receipt.originalFileName) : ''; }; function baseUrl() { return _.first($location.absUrl().split('/#')); } $scope.receiptUrl = function (expenseItem) { return expenseItem && expenseItem.receipt ? baseUrl() + $scope.receiptBaseUrl + '/' + expenseItem.receipt.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'expenseClaims') .then(function (fileNameData) { var expenseItem = $scope.selected.expenseItem(); var oldTitle = (expenseItem.receipt && expenseItem.receipt.title) ? receipt.title : undefined; expenseItem.receipt = fileNameData; expenseItem.receipt.title = oldTitle; }); } }; function createEvent(eventType, reason) { var expenseClaim = $scope.selected.expenseClaim(); if (!expenseClaim.expenseEvents) expenseClaim.expenseEvents = []; var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "eventType": eventType }; if (reason) event.reason = reason; expenseClaim.expenseEvents.push(event); } $scope.addExpenseItem = function () { $scope.removeConfirm(); var newExpenseItem = defaultExpenseItem(); $scope.selected.expenseClaim().expenseItems.push(newExpenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(newExpenseItem); if (index > -1) { $scope.selectExpenseItem(index); $scope.editExpenseItem(); } else { showExpenseErrorAlert('Could not display new expense item') } }; $scope.expenseTypeChange = function () { logger.debug('$scope.selected.expenseItem().expenseType', $scope.selected.expenseItem().expenseType); if ($scope.selected.expenseItem().expenseType.travel) { if (!$scope.selected.expenseItem().travel) $scope.selected.expenseItem().travel = defaultExpenseItem().travel; } else { delete $scope.selected.expenseItem().travel; } $scope.setExpenseItemFields(); }; $scope.expenseDateCalendar = { open: function ($event) { $scope.expenseDateCalendar.opened = true; } }; function recalculateClaimCost() { $scope.selected.expenseClaim().cost = $filter('sumValues')($scope.selected.expenseClaim().expenseItems, 'cost'); } $scope.cancelExpenseChange = function () { $scope.refreshExpenses().then($scope.hideExpenseClaim).then(notify.clearBusy); }; function showExpenseErrorAlert(message) { var messageDefaulted = message || 'Please try this again.'; notify.error('Your expense claim could not be saved. ' + messageDefaulted); $scope.selected.saveInProgress = false; } function showExpenseEmailErrorAlert(message) { $scope.selected.saveInProgress = false; notify.error('Your expense claim email processing failed. ' + message); } function showExpenseProgressAlert(message, busy) { notify.progress(message, busy); } function showExpenseSuccessAlert(message, busy) { notify.success(message, busy); } $scope.saveExpenseClaim = function (optionalExpenseClaim) { $scope.selected.saveInProgress = true; function showExpenseSaved(data) { $scope.expenseClaims[$scope.selected.expenseClaimIndex] = data; $scope.selected.saveInProgress = false; return notify.success('Expense was saved successfully'); } showExpenseProgressAlert('Saving expense claim', true); $scope.setExpenseItemFields(); return (optionalExpenseClaim || $scope.selected.expenseClaim()).$saveOrUpdate(showExpenseSaved, showExpenseSaved, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(notify.clearBusy); }; $scope.approveExpenseClaim = function () { $scope.confirmAction = {approve: true}; if ($scope.lastApprovedByMe()) notifyItem.warning({ title: 'Duplicate approval warning', message: 'You were the previous approver, therefore ' + $scope.nextApprovalStage() + ' ought to be carried out by someone else. Are you sure you want to do this?' }); }; $scope.deleteExpenseClaim = function () { $scope.confirmAction = {delete: true}; }; $scope.deleteExpenseItem = function () { $scope.confirmAction = {delete: true}; }; $scope.confirmDeleteExpenseItem = function () { $scope.selected.saveInProgress = true; showExpenseProgressAlert('Deleting expense item', true); var expenseItem = $scope.selected.expenseItem(); logger.debug('removing', expenseItem); var index = $scope.selected.expenseClaim().expenseItems.indexOf(expenseItem); if (index > -1) { $scope.selected.expenseClaim().expenseItems.splice(index, 1); } else { showExpenseErrorAlert('Could not delete expense item') } $scope.selectExpenseItem(0); recalculateClaimCost(); $scope.saveExpenseClaim() .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.removeConfirm = function () { delete $scope.confirmAction; showExpenseSuccessAlert(); }; $scope.confirmDeleteExpenseClaim = function () { showExpenseProgressAlert('Deleting expense claim', true); function showExpenseDeleted() { return showExpenseSuccessAlert('Expense was deleted successfully'); } $scope.selected.expenseClaim().$remove(showExpenseDeleted, showExpenseDeleted, showExpenseErrorAlert, showExpenseErrorAlert) .then($scope.hideExpenseClaim) .then(showExpenseDeleted) .then($scope.refreshExpenses) .then($scope.removeConfirm) .then(notify.clearBusy); }; $scope.submitExpenseClaim = function (state) { $scope.resubmit = state; $('#submit-dialog').modal('show'); }; function hideSubmitDialog() { $('#submit-dialog').modal('hide'); $scope.resubmit = false; } $scope.cancelSubmitExpenseClaim = function () { hideSubmitDialog(); }; $scope.returnExpenseClaim = function () { $('#return-dialog').modal('show'); }; $scope.confirmReturnExpenseClaim = function (reason) { hideReturnDialog(); return createEventAndSendNotifications(eventTypes.returned, reason); }; function hideReturnDialog() { $('#return-dialog').modal('hide'); } $scope.cancelReturnExpenseClaim = function () { hideReturnDialog(); }; $scope.paidExpenseClaim = function () { $('#paid-dialog').modal('show'); }; $scope.confirmPaidExpenseClaim = function () { createEventAndSendNotifications(eventTypes.paid) .then(hidePaidDialog); }; function hidePaidDialog() { $('#paid-dialog').modal('hide'); } $scope.cancelPaidExpenseClaim = function () { hidePaidDialog(); }; $scope.confirmSubmitExpenseClaim = function () { if ($scope.resubmit) $scope.selected.expenseClaim().expenseEvents = [eventForEventType($scope.selected.expenseClaim(), eventTypes.created)]; createEventAndSendNotifications(eventTypes.submitted); }; $scope.resubmitExpenseClaim = function () { $scope.submitExpenseClaim(true); }; $scope.expenseClaimCreatedEvent = function (optionalExpenseClaim) { return eventForEventType(optionalExpenseClaim || $scope.selected.expenseClaim(), eventTypes.created); }; function createEventAndSendNotifications(eventType, reason) { notify.setBusy(); $scope.selected.saveInProgress = true; var expenseClaim = $scope.selected.expenseClaim(); var expenseClaimCreatedEvent = $scope.expenseClaimCreatedEvent(expenseClaim); return $q.when(createEvent(eventType, reason)) .then(sendNotificationsToAllRoles, showExpenseEmailErrorAlert) .then($scope.saveExpenseClaim, showExpenseEmailErrorAlert, showExpenseProgressAlert); function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(expenseClaimCreatedEvent.memberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', expenseClaimCreatedEvent.memberId, 'member', member); var memberFullName = $filter('fullNameWithAlias')(member); return $q.when(showExpenseProgressAlert('Preparing to email ' + memberFullName)) .then(hideSubmitDialog, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendCreatorNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendApproverNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendTreasurerNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert); function sendCreatorNotifications() { if (eventType.notifyCreator) return sendNotificationsTo({ templateUrl: templateForEvent('creator', eventType), memberIds: [expenseClaimCreatedEvent.memberId], segmentType: 'directMail', segmentNameSuffix: '', destination: 'creator' }); return false; } function sendApproverNotifications() { if (eventType.notifyApprover) return sendNotificationsTo({ templateUrl: templateForEvent('approver', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('financeAdmin', $scope.members), segmentType: 'expenseApprover', segmentNameSuffix: 'approval ', destination: 'approvers' }); return false; } function sendTreasurerNotifications() { if (eventType.notifyTreasurer) return sendNotificationsTo({ templateUrl: templateForEvent('treasurer', eventType), memberIds: MemberService.allMemberIdsWithPrivilege('treasuryAdmin', $scope.members), segmentType: 'expenseTreasurer', segmentNameSuffix: 'payment ', destination: 'treasurer' }); return false; } function templateForEvent(role, eventType) { return notificationsBaseUrl + '/' + role + '/' + eventType.description.toLowerCase().replace(' ', '-') + '-notification.html'; } function sendNotificationsTo(templateAndNotificationMembers) { logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = 'Expense ' + eventType.description + ' notification (to ' + templateAndNotificationMembers.destination + ')'; var campaignNameAndMember = campaignName + ' (' + memberFullName + ')'; var segmentName = 'Expense notification ' + templateAndNotificationMembers.segmentNameSuffix + '(' + memberFullName + ')'; if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications for this step will fail!!'); return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent) .then(populateContentSections) .then(sendNotification(templateAndNotificationMembers)) .catch(showExpenseEmailErrorAlert); function populateContentSections(expenseNotificationText) { return { sections: { expense_id_url: 'Please click <a href="' + baseUrl() + '/#/admin/expenseId/' + expenseClaim.$id() + '" target="_blank">this link</a> to see the details of the above expense claim, or to make changes to it.', expense_notification_text: expenseNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(sendEmailCampaign, showExpenseEmailErrorAlert, showExpenseProgressAlert) .then(notifyEmailSendComplete, showExpenseEmailErrorAlert, showExpenseSuccessAlert); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, $scope.members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { showExpenseProgressAlert('Sending ' + campaignNameAndMember); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.expenseNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to replicateAndSendWithOptions with campaignName', campaignNameAndMember, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignNameAndMember, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { showExpenseProgressAlert('Sending of ' + campaignNameAndMember + ' was successful', true); }); } function notifyEmailSendComplete() { showExpenseSuccessAlert('Sending of ' + campaignName + ' was successful. Check your inbox for progress.'); } } } } }); } } $scope.setExpenseItemFields = function () { var expenseItem = $scope.selected.expenseItem(); if (expenseItem) { expenseItem.expenseDate = DateUtils.asValueNoTime(expenseItem.expenseDate); if (expenseItem.travel) expenseItem.travel.miles = NumberUtils.asNumber(expenseItem.travel.miles); expenseItem.description = expenseItemDescription(expenseItem); expenseItem.cost = expenseItemCost(expenseItem); } recalculateClaimCost(); }; $scope.prefixedExpenseItemDescription = function (expenseItem) { if (!expenseItem) return ''; var prefix = expenseItem.expenseType && expenseItem.expenseType.travel ? expenseItem.expenseType.name + ' - ' : ''; return prefix + expenseItem.description; }; function expenseItemDescription(expenseItem) { var description; if (!expenseItem) return ''; if (expenseItem.travel && expenseItem.expenseType.travel) { description = [ expenseItem.travel.from, 'to', expenseItem.travel.to, expenseItem.travel.returnJourney ? 'return trip' : 'single trip', '(' + expenseItem.travel.miles, 'miles', expenseItem.travel.returnJourney ? 'x 2' : '', 'x', parseInt(expenseItem.travel.costPerMile * 100) + 'p per mile)' ].join(' '); } else { description = expenseItem.description; } return description; } function expenseItemCost(expenseItem) { var cost; if (!expenseItem) return 0; if (expenseItem.travel && expenseItem.expenseType.travel) { cost = (NumberUtils.asNumber(expenseItem.travel.miles) * (expenseItem.travel.returnJourney ? 2 : 1) * NumberUtils.asNumber(expenseItem.travel.costPerMile)); } else { cost = expenseItem.cost; } noLogger.info(cost, 'from expenseItem=', expenseItem); return NumberUtils.asNumber(cost, 2); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { notify.progress('Refreshing member data...'); return MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { logger.debug('refreshMembers: found', members.length, 'members'); return $scope.members = members; }); } } function memberCanEditClaim(expenseClaim) { if (!expenseClaim) return false; return memberOwnsClaim(expenseClaim) || LoggedInMemberService.allowFinanceAdmin(); } function memberOwnsClaim(expenseClaim) { if (!expenseClaim) return false; return (LoggedInMemberService.loggedInMember().memberId === $scope.expenseClaimCreatedEvent(expenseClaim).memberId); } $scope.refreshExpenses = function () { $scope.dataError = false; logger.debug('refreshExpenses started'); notify.setBusy(); notify.progress('Filtering for ' + $scope.selected.expenseFilter.description + '...'); logger.debug('refreshing expenseFilter', $scope.selected.expenseFilter); let noExpenseFound = function () { $scope.dataError = true; return notify.warning({ title: 'Expense claim could not be found', message: 'Try opening again from the link in the notification email, or click Show All Expense Claims' }) }; function query() { if ($scope.selected.expenseFilter.description === SELECTED_EXPENSE && $routeParams.expenseId) { return ExpenseClaimsService.getById($routeParams.expenseId) .then(function (expense) { if (!expense) { return noExpenseFound(); } else { return [expense]; } }) .catch(noExpenseFound); } else { return ExpenseClaimsService.all(); } } return query() .then(function (expenseClaims) { $scope.unfilteredExpenseClaims = []; $scope.expenseClaims = _.chain(expenseClaims).filter(function (expenseClaim) { return $scope.allowAdminFunctions() ? ($scope.selected.showOnlyMine ? memberOwnsClaim(expenseClaim) : true) : memberCanEditClaim(expenseClaim); }).filter(function (expenseClaim) { $scope.unfilteredExpenseClaims.push(expenseClaim); return $scope.selected.expenseFilter.filter(expenseClaim); }).sortBy(function (expenseClaim) { var expenseClaimLatestEvent = $scope.expenseClaimLatestEvent(expenseClaim); return expenseClaimLatestEvent ? expenseClaimLatestEvent.date : true; }).reverse().value(); let outcome = 'Found ' + $scope.expenseClaims.length + ' expense claim(s)'; notify.progress(outcome); logger.debug('refreshExpenses finished', outcome); notify.clearBusy(); return $scope.expenseClaims; }, notify.error) .catch(notify.error); }; $q.when(refreshMembers()) .then($scope.refreshExpenses) .then(notify.setReady) .catch(notify.error); }] ); /* concatenated from client/src/app/js/filters.js */ angular.module('ekwgApp') .factory('FilterUtils', function () { return { nameFilter: function (alias) { return alias ? 'fullNameWithAlias' : 'fullName'; } }; }) .filter('keepLineFeeds', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') .replace(/ /g, '&nbsp;'); } }) .filter('lineFeedsToBreaks', function () { return function (input) { if (!input) return input; return input .replace(/(\r\n|\r|\n)/g, '<br/>') } }) .filter('displayName', function () { return function (member) { return member === undefined ? null : (member.firstName + ' ' + (member.hideSurname ? '' : member.lastName)).trim(); } }) .filter('fullName', function () { return function (member, defaultValue) { return member === undefined ? defaultValue || '(deleted member)' : (member.firstName + ' ' + member.lastName).trim(); } }) .filter('fullNameWithAlias', ["$filter", function ($filter) { return function (member, defaultValue) { return member ? ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '') : defaultValue; } }]) .filter('fullNameWithAliasOrMe', ["$filter", "LoggedInMemberService", function ($filter, LoggedInMemberService) { return function (member, defaultValue, memberId) { return member ? (LoggedInMemberService.loggedInMember().memberId === member.$id() && member.$id() === memberId ? "Me" : ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '')) : defaultValue; } }]) .filter('firstName', ["$filter", function ($filter) { return function (member, defaultValue) { return s.words($filter('fullName')(member, defaultValue))[0]; } }]) .filter('memberIdsToFullNames', ["$filter", function ($filter) { return function (memberIds, members, defaultValue) { return _(memberIds).map(function (memberId) { return $filter('memberIdToFullName')(memberId, members, defaultValue); }).join(', '); } }]) .filter('memberIdToFullName', ["$filter", "MemberService", "FilterUtils", function ($filter, MemberService, FilterUtils) { return function (memberId, members, defaultValue, alias) { return $filter(FilterUtils.nameFilter(alias))(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('memberIdToFirstName', ["$filter", "MemberService", function ($filter, MemberService) { return function (memberId, members, defaultValue) { return $filter('firstName')(MemberService.toMember(memberId, members), defaultValue); } }]) .filter('asMoney', ["NumberUtils", function (NumberUtils) { return function (number) { return isNaN(number) ? '' : '£' + NumberUtils.asNumber(number).toFixed(2); } }]) .filter('humanize', function () { return function (string) { return s.humanize(string); } }) .filter('sumValues', ["NumberUtils", function (NumberUtils) { return function (items, propertyName) { return NumberUtils.sumValues(items, propertyName); } }]) .filter('walkSummary', ["$filter", function ($filter) { return function (walk) { return walk === undefined ? null : $filter('displayDate')(walk.walkDate) + " led by " + (walk.displayName || walk.contactName || "unknown") + " (" + (walk.briefDescriptionAndStartPoint || 'no description') + ')'; } }]) .filter('meetupEventSummary', ["$filter", function ($filter) { return function (meetupEvent) { return meetupEvent ? $filter('displayDate')(meetupEvent.startTime) + " (" + meetupEvent.title + ')' : null; } }]) .filter('asWalkEventType', ["WalksReferenceService", function (WalksReferenceService) { return function (eventTypeString, field) { var eventType = WalksReferenceService.toEventType(eventTypeString); return eventType && field ? eventType[field] : eventType; } }]) .filter('asEventNote', function () { return function (event) { return _.compact([event.description, event.reason]).join(', '); } }) .filter('asChangedItemsTooltip', ["$filter", function ($filter) { return function (event, members) { return _(event.data).map(function (value, key) { return s.humanize(key) + ': ' + $filter('toAuditDeltaValue')(value, key, members); }).join(', '); } }]) .filter('valueOrDefault', function () { return function (value, defaultValue) { return value || defaultValue || '(none)'; } }) .filter('toAuditDeltaValue', ["$filter", function ($filter) { return function (value, fieldName, members, defaultValue) { switch (fieldName) { case 'walkDate': return $filter('displayDate')(value); case 'walkLeaderMemberId': return $filter('memberIdToFullName')(value, members, defaultValue); default: return $filter('valueOrDefault')(value, defaultValue); } } }]) .filter('toAuditDeltaChangedItems', function () { return function (dataAuditDeltaInfoItems) { return _(dataAuditDeltaInfoItems).pluck('fieldName').map(s.humanize).join(', '); } }) .filter('asWalkValidationsList', function () { return function (walkValidations) { var lastItem = _.last(walkValidations); var firstItems = _.without(walkValidations, lastItem); var joiner = firstItems.length > 0 ? ' and ' : ''; return firstItems.join(', ') + joiner + lastItem; } }) .filter('idFromRecord', function () { return function (mongoRecord) { return mongoRecord.$id; } }) .filter('eventTimes', function () { return function (socialEvent) { var eventTimes = socialEvent.eventTimeStart; if (socialEvent.eventTimeEnd) eventTimes += ' - ' + socialEvent.eventTimeEnd; return eventTimes; } }) .filter('displayDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('displayDay', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDay(dateValue); } }]) .filter('displayDates', ["$filter", function ($filter) { return function (dateValues) { return _(dateValues).map(function (dateValue) { return $filter('displayDate')(dateValue); }).join(', '); } }]) .filter('displayDateAndTime', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('fromExcelDate', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDate(dateValue); } }]) .filter('lastLoggedInDateDisplayed', ["DateUtils", function (DateUtils) { return function (dateValue) { return DateUtils.displayDateAndTime(dateValue); } }]) .filter('lastConfirmedDateDisplayed', ["DateUtils", function (DateUtils) { return function (member) { return member && member.profileSettingsConfirmedAt ? 'by ' + (member.profileSettingsConfirmedBy || 'member') + ' at ' + DateUtils.displayDateAndTime(member.profileSettingsConfirmedAt) : 'not confirmed yet'; } }]) .filter('createdAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.createdBy, resource.createdDate, members) } }]) .filter('updatedAudit', ["StringUtils", function (StringUtils) { return function (resource, members) { return StringUtils.formatAudit(resource.updatedBy, resource.updatedDate, members) } }]); /* concatenated from client/src/app/js/forgotPasswordController.js */ angular.module("ekwgApp") .controller("ForgotPasswordController", ["$q", "$log", "$scope", "$rootScope", "$location", "$routeParams", "EmailSubscriptionService", "MemberService", "LoggedInMemberService", "URLService", "MailchimpConfig", "MailchimpSegmentService", "MailchimpCampaignService", "Notifier", "ValidationUtils", "close", function ($q, $log, $scope, $rootScope, $location, $routeParams, EmailSubscriptionService, MemberService, LoggedInMemberService, URLService, MailchimpConfig, MailchimpSegmentService, MailchimpCampaignService, Notifier, ValidationUtils, close) { var logger = $log.getInstance("ForgotPasswordController"); $log.logLevels["ForgotPasswordController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); $scope.showSubmit = true; $scope.FORGOTTEN_PASSWORD_SEGMENT = "Forgotten Password"; $scope.forgottenPasswordCredentials = {}; $scope.actions = { close: function () { close(); }, submittable: function () { var onePopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialOne"); var twoPopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialTwo"); logger.info("notSubmittable: onePopulated", onePopulated, "twoPopulated", twoPopulated); return twoPopulated && onePopulated; }, submit: function () { var userDetails = "User Name " + $scope.forgottenPasswordCredentials.credentialOne + " and Membership Number " + $scope.forgottenPasswordCredentials.credentialTwo; notify.setBusy(); $scope.showSubmit = false; notify.success("Checking our records for " + userDetails, true); if ($scope.forgottenPasswordCredentials.credentialOne.length === 0 || $scope.forgottenPasswordCredentials.credentialTwo.length === 0) { $scope.showSubmit = true; notify.error({ title: "Incorrect information entered", message: "Please enter both a User Name and a Membership Number" }); } else { var forgotPasswordData = {loginResponse: {memberLoggedIn: false}}; var message; LoggedInMemberService.getMemberForResetPassword($scope.forgottenPasswordCredentials.credentialOne, $scope.forgottenPasswordCredentials.credentialTwo) .then(function (member) { if (_.isEmpty(member)) { message = "No member was found with " + userDetails; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Incorrect information entered", message: message } }; } else if (!member.mailchimpLists.general.subscribed) { message = "Sorry, " + userDetails + " is not setup in our system to receive emails"; forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = message; $scope.showSubmit = true; return { forgotPasswordData: forgotPasswordData, notifyObject: { title: "Message cannot be sent", message: message } }; } else { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); logger.debug("saving member", member); $scope.forgottenPasswordMember = member; member.$saveOrUpdate(sendForgottenPasswordEmailToMember, sendForgottenPasswordEmailToMember, saveFailed, saveFailed); forgotPasswordData.member = member; forgotPasswordData.loginResponse.alertMessage = "New password requested from login screen"; return {forgotPasswordData: forgotPasswordData}; } }).then(function (response) { return LoggedInMemberService.auditMemberLogin($scope.forgottenPasswordCredentials.credentialOne, "", response.forgotPasswordData.member, response.forgotPasswordData.loginResponse) .then(function () { if (response.notifyObject) { notify.error(response.notifyObject) } }); }); } } }; function saveFailed(error) { notify.error({title: "The password reset failed", message: error}); } function getMailchimpConfig() { return MailchimpConfig.getConfig() .then(function (config) { $scope.mailchimpConfig = config.mailchimp; }); } function createOrSaveForgottenPasswordSegment() { return MailchimpSegmentService.saveSegment("general", {segmentId: $scope.mailchimpConfig.segments.general.forgottenPasswordSegmentId}, [{id: $scope.forgottenPasswordMember.$id()}], $scope.FORGOTTEN_PASSWORD_SEGMENT, [$scope.forgottenPasswordMember]); } function saveSegmentDataToMailchimpConfig(segmentResponse) { return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general.forgottenPasswordSegmentId = segmentResponse.segment.id; MailchimpConfig.saveConfig(config); }); } function sendForgottenPasswordCampaign() { var member = $scope.forgottenPasswordMember.firstName + " " + $scope.forgottenPasswordMember.lastName; return MailchimpConfig.getConfig() .then(function (config) { logger.debug("config.mailchimp.campaigns.forgottenPassword.campaignId", config.mailchimp.campaigns.forgottenPassword.campaignId); logger.debug("config.mailchimp.segments.general.forgottenPasswordSegmentId", config.mailchimp.segments.general.forgottenPasswordSegmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: config.mailchimp.campaigns.forgottenPassword.campaignId, campaignName: "EKWG website password reset instructions (" + member + ")", segmentId: config.mailchimp.segments.general.forgottenPasswordSegmentId }); }); } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList("general", [$scope.forgottenPasswordMember]); } function sendForgottenPasswordEmailToMember() { $q.when(notify.success("Sending forgotten password email")) .then(updateGeneralList) .then(getMailchimpConfig) .then(createOrSaveForgottenPasswordSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendForgottenPasswordCampaign) .then(finalMessage) .then(notify.clearBusy) .catch(handleSendError); } function handleSendError(errorResponse) { notify.error({ title: "Your email could not be sent", message: (errorResponse.message || errorResponse) + (errorResponse.error ? (". Error was: " + ErrorMessageService.stringify(errorResponse.error)) : "") }); } function finalMessage() { return notify.success({ title: "Message sent", message: "We've sent a message to the email address we have for you. Please check your inbox and follow the instructions in the message." }) } }] ); /* concatenated from client/src/app/js/googleMapsServices.js */ angular.module('ekwgApp') .factory('GoogleMapsConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function getConfig() { return $http.get('/googleMaps/config').then(function (response) { return HTTPResponseService.returnResponse(response); }); } return { getConfig: getConfig, } }]); /* concatenated from client/src/app/js/homeController.js */ angular.module('ekwgApp') .controller('HomeController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "ContentMetaDataService", "CommitteeReferenceData", "InstagramService", "SiteEditService", function ($log, $scope, $routeParams, LoggedInMemberService, ContentMetaDataService, CommitteeReferenceData, InstagramService, SiteEditService) { var logger = $log.getInstance('HomeController'); $log.logLevels['HomeController'] = $log.LEVEL.OFF; $scope.feeds = {instagram: {recentMedia: []}, facebook: {}}; ContentMetaDataService.getMetaData('imagesHome') .then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; }); InstagramService.recentMedia() .then(function (recentMediaResponse) { $scope.feeds.instagram.recentMedia = _.take(recentMediaResponse.instagram, 14); logger.debug("Refreshed social media", $scope.feeds.instagram.recentMedia, 'count =', $scope.feeds.instagram.recentMedia.length); }); $scope.mediaUrlFor = function (media) { logger.debug('mediaUrlFor:media', media); return (media && media.images) ? media.images.standard_resolution.url : ""; }; $scope.mediaCaptionFor = function (media) { logger.debug('mediaCaptionFor:media', media); return media ? media.caption.text : ""; }; $scope.allowEdits = function () { return SiteEditService.active() && LoggedInMemberService.allowContentEdits(); }; }]); /* concatenated from client/src/app/js/howTo.js */ angular.module('ekwgApp') .controller("HowToDialogController", ["$rootScope", "$log", "$q", "$scope", "$filter", "FileUtils", "DateUtils", "EKWGFileUpload", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "MailchimpLinkService", "MailchimpCampaignService", "Notifier", "MemberResourcesReferenceData", "memberResource", "close", function ($rootScope, $log, $q, $scope, $filter, FileUtils, DateUtils, EKWGFileUpload, DbUtils, LoggedInMemberService, ErrorMessageService, MailchimpLinkService, MailchimpCampaignService, Notifier, MemberResourcesReferenceData, memberResource, close) { var logger = $log.getInstance("HowToDialogController"); $log.logLevels["HowToDialogController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.mailchimpLinkService = MailchimpLinkService; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.memberResource = memberResource; logger.debug("memberResourcesReferenceData:", $scope.memberResourcesReferenceData, "memberResource:", memberResource); $scope.resourceDateCalendar = { open: function () { $scope.resourceDateCalendar.opened = true; } }; $scope.cancel = function () { close(); }; $scope.onSelect = function (file) { if (file) { logger.debug("onSelect:file:about to upload ->", file); $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, "memberResources") .then(function (fileNameData) { logger.debug("onSelect:file:upload complete -> fileNameData", fileNameData); $scope.memberResource.data.fileNameData = fileNameData; $scope.memberResource.data.fileNameData.title = $scope.oldTitle || file.name; }); } }; $scope.attach = function (file) { $("#hidden-input").click(); }; $scope.save = function () { notify.setBusy(); logger.debug("save ->", $scope.memberResource); return $scope.memberResource.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error) .then($scope.hideDialog) .then(notify.clearBusy) .catch(handleError); function handleError(errorResponse) { notify.error({ title: "Your changes could not be saved", message: (errorResponse && errorResponse.error ? (". Error was: " + JSON.stringify(errorResponse.error)) : "") }); notify.clearBusy(); } }; $scope.cancelChange = function () { $q.when($scope.hideDialog()).then(notify.clearBusy); }; $scope.campaignDate = function (campaign) { return DateUtils.asValueNoTime(campaign.send_time || campaign.create_time); }; $scope.campaignTitle = function (campaign) { return campaign.title + " (" + $filter("displayDate")($scope.campaignDate(campaign)) + ")"; }; $scope.campaignChange = function () { logger.debug("campaignChange:memberResource.data.campaign", $scope.memberResource.data.campaign); if ($scope.memberResource.data.campaign) { $scope.memberResource.title = $scope.memberResource.data.campaign.title; $scope.memberResource.resourceDate = $scope.campaignDate($scope.memberResource.data.campaign); } }; $scope.performCampaignSearch = function (selectFirst) { var campaignSearchTerm = $scope.memberResource.data.campaignSearchTerm; if (campaignSearchTerm) { notify.setBusy(); notify.progress({ title: "Email search", message: "searching for campaigns matching '" + campaignSearchTerm + "'" }); var options = { limit: $scope.memberResource.data.campaignSearchLimit, concise: true, status: "sent", campaignSearchTerm: campaignSearchTerm }; options[$scope.memberResource.data.campaignSearchField] = campaignSearchTerm; return MailchimpCampaignService.list(options).then(function (response) { $scope.campaigns = response.data; if (selectFirst) { $scope.memberResource.data.campaign = _.first($scope.campaigns); $scope.campaignChange(); } else { logger.debug("$scope.memberResource.data.campaign", $scope.memberResource.data.campaign, "first campaign=", _.first($scope.campaigns)) } logger.debug("response.data", response.data); notify.success({ title: "Email search", message: "Found " + $scope.campaigns.length + " campaigns matching '" + campaignSearchTerm + "'" }); notify.clearBusy(); return true; }); } else { return $q.when(true); } }; $scope.hideDialog = function () { $rootScope.$broadcast("memberResourcesChanged"); close(); }; $scope.editMode = $scope.memberResource.$id() ? "Edit" : "Add"; logger.debug("editMode:", $scope.editMode); if ($scope.memberResource.resourceType === "email" && $scope.memberResource.$id()) { $scope.performCampaignSearch(false).then(notify.clearBusy) } else { notify.clearBusy(); } }]) .controller("HowToController", ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "MailchimpLinkService", "FileUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "MailchimpSegmentService", "MailchimpCampaignService", "MemberResourcesReferenceData", "MailchimpConfig", "Notifier", "MemberResourcesService", "CommitteeReferenceData", "ModalService", "SiteEditService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams, $location, URLService, DateUtils, MailchimpLinkService, FileUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, MailchimpSegmentService, MailchimpCampaignService, MemberResourcesReferenceData, MailchimpConfig, Notifier, MemberResourcesService, CommitteeReferenceData, ModalService, SiteEditService) { var logger = $log.getInstance("HowToController"); $log.logLevels["HowToController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); $scope.fileUtils = FileUtils; $scope.memberResourcesReferenceData = MemberResourcesReferenceData; $scope.mailchimpLinkService = MailchimpLinkService; $scope.destinationType = ""; $scope.members = []; $scope.memberResources = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.selected = { addingNew: false, }; $scope.isActive = function (memberResource) { var active = SiteEditService.active() && LoggedInMemberService.memberLoggedIn() && memberResource === $scope.selected.memberResource; logger.debug("isActive =", active, "with memberResource", memberResource); return active; }; $scope.allowAdd = function () { return SiteEditService.active() && LoggedInMemberService.allowFileAdmin(); }; $scope.allowEdit = function (memberResource) { return $scope.allowAdd() && memberResource && memberResource.$id(); }; $scope.allowDelete = function (memberResource) { return $scope.allowEdit(memberResource); }; var defaultMemberResource = function () { return new MemberResourcesService({ data: {campaignSearchLimit: "1000", campaignSearchField: "title"}, resourceType: "email", accessLevel: "hidden", createdDate: DateUtils.nowAsValue(), createdBy: LoggedInMemberService.loggedInMember().memberId }) }; function removeDeleteOrAddOrInProgressFlags() { $scope.allowConfirmDelete = false; $scope.selected.addingNew = false; } $scope.delete = function () { $scope.allowConfirmDelete = true; }; $scope.cancelDelete = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.confirmDelete = function () { notify.setBusy(); function showDeleted() { return notify.success("member resource was deleted successfully"); } $scope.selected.memberResource.$remove(showDeleted, showDeleted, notify.error, notify.error) .then($scope.hideDialog) .then(refreshMemberResources) .then(removeDeleteOrAddOrInProgressFlags) .then(notify.clearBusy); }; $scope.selectMemberResource = function (memberResource) { logger.debug("selectMemberResource with memberResource", memberResource, "$scope.selected.addingNew", $scope.selected.addingNew); if (!$scope.selected.addingNew) { $scope.selected.memberResource = memberResource; } }; $scope.edit = function () { ModalService.showModal({ templateUrl: "partials/howTo/how-to-dialog.html", controller: "HowToDialogController", preClose: function (modal) { logger.debug("preClose event with modal", modal); modal.element.modal("hide"); }, inputs: { memberResource: $scope.selected.memberResource } }).then(function (modal) { logger.debug("modal event with modal", modal); modal.element.modal(); modal.close.then(function (result) { logger.debug("close event with result", result); }); }) }; $scope.add = function () { $scope.selected.addingNew = true; var memberResource = defaultMemberResource(); $scope.selected.memberResource = memberResource; logger.debug("add:", memberResource); $scope.edit(); }; $scope.hideDialog = function () { removeDeleteOrAddOrInProgressFlags(); }; $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberResourcesChanged", function () { refreshAll(); }); $scope.$on("memberLoginComplete", function () { refreshAll(); }); $scope.$on("memberLogoutComplete", function () { refreshAll(); }); $scope.$on("editSite", function (event, data) { logger.debug("editSite:", data); refreshAll(); }); function refreshMemberResources() { MemberResourcesService.all() .then(function (memberResources) { if (URLService.hasRouteParameter("memberResourceId")) { $scope.memberResources = _.filter(memberResources, function (memberResource) { return memberResource.$id() === $routeParams.memberResourceId; }); } else { $scope.memberResources = _.chain(memberResources) .filter(function (memberResource) { return $scope.memberResourcesReferenceData.accessLevelFor(memberResource.accessLevel).filter(); }).sortBy("resourceDate") .value() .reverse(); logger.debug(memberResources.length, "memberResources", $scope.memberResources.length, "filtered memberResources"); } }); } function refreshAll() { refreshMemberResources(); } refreshAll(); }]); /* concatenated from client/src/app/js/httpServices.js */ angular.module('ekwgApp') .factory('HTTPResponseService', ["$log", function ($log) { var logger = $log.getInstance('HTTPResponseService'); $log.logLevels['HTTPResponseService'] = $log.LEVEL.OFF; function returnResponse(response) { logger.debug('response.data=', response.data); var returnObject = (typeof response.data === 'object') || !response.data ? response.data : JSON.parse(response.data); logger.debug('returned ', typeof response.data, 'response status =', response.status, returnObject.length, 'response items:', returnObject); return returnObject; } return { returnResponse: returnResponse } }]); /* concatenated from client/src/app/js/imageEditor.js */ angular.module('ekwgApp') .controller('ImageEditController', ["$scope", "$location", "Upload", "$http", "$q", "$routeParams", "$window", "LoggedInMemberService", "ContentMetaDataService", "Notifier", "EKWGFileUpload", function($scope, $location, Upload, $http, $q, $routeParams, $window, LoggedInMemberService, ContentMetaDataService, Notifier, EKWGFileUpload) { var notify = Notifier($scope); $scope.imageSource = $routeParams.imageSource; applyAllowEdits(); $scope.onFileSelect = function(file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, $scope.imageSource).then(function(fileNameData) { $scope.currentImageMetaDataItem.image = $scope.imageMetaData.baseUrl + '/' + fileNameData.awsFileName; console.log(' $scope.currentImageMetaDataItem.image', $scope.currentImageMetaDataItem.image); }); } }; $scope.refreshImageMetaData = function(imageSource) { notify.setBusy(); $scope.imageSource = imageSource; ContentMetaDataService.getMetaData(imageSource).then(function(contentMetaData) { $scope.imageMetaData = contentMetaData; notify.clearBusy(); }, function(response) { notify.error(response); }); }; $scope.refreshImageMetaData($scope.imageSource); $scope.$on('memberLoginComplete', function() { applyAllowEdits(); }); $scope.$on('memberLogoutComplete', function() { applyAllowEdits(); }); $scope.exitBackToPreviousWindow = function() { $window.history.back(); }; $scope.reverseSortOrder = function() { $scope.imageMetaData.files = $scope.imageMetaData.files.reverse(); }; $scope.imageTitleLength = function() { if ($scope.imageSource === 'imagesHome') { return 50; } else { return 20 } }; $scope.replace = function(imageMetaDataItem) { $scope.files = []; $scope.currentImageMetaDataItem = imageMetaDataItem; $('#hidden-input').click(); }; $scope.moveUp = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex > 0) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex - 1, 0, imageMetaDataItem); } }; $scope.moveDown = function(imageMetaDataItem) { var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); if (currentIndex < $scope.imageMetaData.files.length) { $scope.delete(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex + 1, 0, imageMetaDataItem); } }; $scope.delete = function(imageMetaDataItem) { $scope.imageMetaData.files = _.without($scope.imageMetaData.files, imageMetaDataItem); }; $scope.insertHere = function(imageMetaDataItem) { var insertedImageMetaDataItem = new ContentMetaDataService.createNewMetaData(true); var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem); $scope.imageMetaData.files.splice(currentIndex, 0, insertedImageMetaDataItem); $scope.replace(insertedImageMetaDataItem); }; $scope.currentImageMetaDataItemBeingUploaded = function(imageMetaDataItem) { return ($scope.currentImageMetaDataItem && $scope.currentImageMetaDataItem.$$hashKey === imageMetaDataItem.$$hashKey); }; $scope.saveAll = function() { ContentMetaDataService.saveMetaData($scope.imageMetaData, saveOrUpdateSuccessful, notify.error) .then(function(contentMetaData) { $scope.exitBackToPreviousWindow(); }, function(response) { notify.error(response); }); }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowContentEdits(); } function saveOrUpdateSuccessful() { notify.success('data for ' + $scope.imageMetaData.files.length + ' images was saved successfully.'); } }]); /* concatenated from client/src/app/js/indexController.js */ angular.module('ekwgApp') .controller("IndexController", ["$q", "$cookieStore", "$log", "$scope", "$rootScope", "URLService", "LoggedInMemberService", "ProfileConfirmationService", "AuthenticationModalsService", "Notifier", "DateUtils", function ($q, $cookieStore, $log, $scope, $rootScope, URLService, LoggedInMemberService, ProfileConfirmationService, AuthenticationModalsService, Notifier, DateUtils) { var logger = $log.getInstance("IndexController"); $log.logLevels["IndexController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info('called IndexController'); $scope.ready = false; $scope.year = DateUtils.asString(DateUtils.momentNow().valueOf(), undefined, "YYYY"); $scope.actions = { forgotPassword: function () { URLService.navigateTo("forgot-password"); }, loginOrLogout: function () { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.logout(); } else { URLService.navigateTo("login"); } } }; $scope.memberLoggedIn = function () { return LoggedInMemberService.memberLoggedIn() }; $scope.memberLoginStatus = function () { if (LoggedInMemberService.memberLoggedIn()) { var loggedInMember = LoggedInMemberService.loggedInMember(); return "Logout " + loggedInMember.firstName + " " + loggedInMember.lastName; } else { return "Login to EWKG Site"; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowContentEdits(); }; $scope.isHome = function () { return URLService.relativeUrlFirstSegment() === "/"; }; $scope.isOnPage = function (data) { var matchedUrl = s.endsWith(URLService.relativeUrlFirstSegment(), data); logger.debug("isOnPage", matchedUrl, "data=", data); return matchedUrl; }; $scope.isProfileOrAdmin = function () { return $scope.isOnPage("profile") || $scope.isOnPage("admin"); }; }]); /* concatenated from client/src/app/js/instagramServices.js */ angular.module('ekwgApp') .factory('InstagramService', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) { function recentMedia() { return $http.get('/instagram/recentMedia').then(HTTPResponseService.returnResponse); } return { recentMedia: recentMedia, } }]); /* concatenated from client/src/app/js/letterheadController.js */ angular.module('ekwgApp') .controller('LetterheadController', ["$scope", "$location", function ($scope, $location) { var pathParts = $location.path().replace('/letterhead/', '').split('/'); $scope.firstPart = _.first(pathParts); $scope.lastPart = _.last(pathParts); }]); /* concatenated from client/src/app/js/links.js */ angular.module('ekwgApp') .factory('ContactUsAmendService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { }]) .controller('ContactUsController', ["$log", "$rootScope", "$routeParams", "$scope", "CommitteeReferenceData", "LoggedInMemberService", function ($log, $rootScope, $routeParams, $scope, CommitteeReferenceData, LoggedInMemberService) { var logger = $log.getInstance('ContactUsController'); $log.logLevels['ContactUsController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.allowEdits = function () { return LoggedInMemberService.allowMemberAdminEdits(); } }]); /* concatenated from client/src/app/js/loggedInMemberService.js */ angular.module('ekwgApp') .factory('LoggedInMemberService', ["$rootScope", "$q", "$routeParams", "$cookieStore", "URLService", "MemberService", "MemberAuditService", "DateUtils", "NumberUtils", "$log", function ($rootScope, $q, $routeParams, $cookieStore, URLService, MemberService, MemberAuditService, DateUtils, NumberUtils, $log) { var logger = $log.getInstance('LoggedInMemberService'); var noLogger = $log.getInstance('NoLogger'); $log.logLevels['NoLogger'] = $log.LEVEL.OFF; $log.logLevels['LoggedInMemberService'] = $log.LEVEL.OFF; function loggedInMember() { if (!getCookie('loggedInMember')) setCookie('loggedInMember', {}); return getCookie('loggedInMember'); } function loginResponse() { if (!getCookie('loginResponse')) setCookie('loginResponse', {memberLoggedIn: false}); return getCookie('loginResponse'); } function showResetPassword() { return getCookie('showResetPassword'); } function allowContentEdits() { return memberLoggedIn() ? loggedInMember().contentAdmin : false; } function allowMemberAdminEdits() { return loginResponse().memberLoggedIn ? loggedInMember().memberAdmin : false; } function allowFinanceAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().financeAdmin : false; } function allowCommittee() { return loginResponse().memberLoggedIn ? loggedInMember().committee : false; } function allowTreasuryAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().treasuryAdmin : false; } function allowFileAdmin() { return loginResponse().memberLoggedIn ? loggedInMember().fileAdmin : false; } function memberLoggedIn() { return !_.isEmpty(loggedInMember()) && loginResponse().memberLoggedIn; } function showLoginPromptWithRouteParameter(routeParameter) { if (URLService.hasRouteParameter(routeParameter) && !memberLoggedIn()) $('#login-dialog').modal(); } function allowWalkAdminEdits() { return memberLoggedIn() ? loggedInMember().walkAdmin : false; } function allowSocialAdminEdits() { return memberLoggedIn() ? loggedInMember().socialAdmin : false; } function allowSocialDetailView() { return memberLoggedIn() ? loggedInMember().socialMember : false; } function logout() { var member = loggedInMember(); var loginResponseValue = loginResponse(); if (!_.isEmpty(member)) { loginResponseValue.alertMessage = 'The member ' + member.userName + ' logged out successfully'; auditMemberLogin(member.userName, undefined, member, loginResponseValue) } removeCookie('loginResponse'); removeCookie('loggedInMember'); removeCookie('showResetPassword'); removeCookie('editSite'); $rootScope.$broadcast('memberLogoutComplete'); } function auditMemberLogin(userName, password, member, loginResponse) { var audit = new MemberAuditService({ userName: userName, password: password, loginTime: DateUtils.nowAsValue(), loginResponse: loginResponse }); if (!_.isEmpty(member)) audit.member = member; return audit.$save(); } function setCookie(key, value) { noLogger.debug('setting cookie ' + key + ' with value ', value); $cookieStore.put(key, value); } function removeCookie(key) { logger.info('removing cookie ' + key); $cookieStore.remove(key); } function getCookie(key) { var object = $cookieStore.get(key); noLogger.debug('getting cookie ' + key + ' with value', object); return object; } function login(userName, password) { return getMemberForUserName(userName) .then(function (member) { removeCookie('showResetPassword'); var loginResponse = {}; if (!_.isEmpty(member)) { loginResponse.memberLoggedIn = false; if (!member.groupMember) { loginResponse.alertMessage = 'Logins for member ' + userName + ' have been disabled. Please'; } else if (member.password !== password) { loginResponse.alertMessage = 'The password was incorrectly entered for ' + userName + '. Please try again or'; } else if (member.expiredPassword) { setCookie('showResetPassword', true); loginResponse.alertMessage = 'The password for ' + userName + ' has expired. You must enter a new password before continuing. Alternatively'; } else { loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The member ' + userName + ' logged in successfully'; setLoggedInMemberCookie(member); } } else { removeCookie('loggedInMember'); loginResponse.alertMessage = 'The member ' + userName + ' was not recognised. Please try again or'; } return {loginResponse: loginResponse, member: member}; }) .then(function (loginData) { setCookie('loginResponse', loginData.loginResponse); return auditMemberLogin(userName, password, loginData.member, loginData.loginResponse) .then(function () { logger.debug('loginResponse =', loginData.loginResponse); return $rootScope.$broadcast('memberLoginComplete'); } ); }, function (response) { throw new Error('Something went wrong...' + response); }) } function setLoggedInMemberCookie(member) { var memberId = member.$id(); var cookie = getCookie('loggedInMember'); if (_.isEmpty(cookie) || (cookie.memberId === memberId)) { var newCookie = angular.extend(member, {memberId: memberId}); logger.debug('saving loggedInMember ->', newCookie); setCookie('loggedInMember', newCookie); } else { logger.debug('not saving member (' + memberId + ') to cookie as not currently logged in member (' + cookie.memberId + ')', member); } } function saveMember(memberToSave, saveCallback, errorSaveCallback) { memberToSave.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback) .then(function () { setLoggedInMemberCookie(memberToSave); }) .then(function () { $rootScope.$broadcast('memberSaveComplete'); }); } function resetPassword(userName, newPassword, newPasswordConfirm) { return getMemberForUserName(userName) .then(validateNewPassword) .then(saveSuccessfulPasswordReset) .then(broadcastMemberLoginComplete) .then(auditPasswordChange); function validateNewPassword(member) { var loginResponse = {memberLoggedIn: false}; var showResetPassword = true; if (member.password === newPassword) { loginResponse.alertMessage = 'The new password was the same as the old one for ' + member.userName + '. Please try again or'; } else if (!newPassword || newPassword.length < 6) { loginResponse.alertMessage = 'The new password needs to be at least 6 characters long. Please try again or'; } else if (newPassword !== newPasswordConfirm) { loginResponse.alertMessage = 'The new password was not confirmed correctly for ' + member.userName + '. Please try again or'; } else { showResetPassword = false; logger.debug('Saving new password for ' + member.userName + ' and removing expired status'); delete member.expiredPassword; delete member.passwordResetId; member.password = newPassword; loginResponse.memberLoggedIn = true; loginResponse.alertMessage = 'The password for ' + member.userName + ' was changed successfully'; } return {loginResponse: loginResponse, member: member, showResetPassword: showResetPassword}; } function saveSuccessfulPasswordReset(resetPasswordData) { logger.debug('saveNewPassword.resetPasswordData:', resetPasswordData); setCookie('loginResponse', resetPasswordData.loginResponse); setCookie('showResetPassword', resetPasswordData.showResetPassword); if (!resetPasswordData.showResetPassword) { return resetPasswordData.member.$update().then(function () { setLoggedInMemberCookie(resetPasswordData.member); return resetPasswordData; }) } else { return resetPasswordData; } } function auditPasswordChange(resetPasswordData) { return auditMemberLogin(userName, resetPasswordData.member.password, resetPasswordData.member, resetPasswordData.loginResponse) } function broadcastMemberLoginComplete(resetPasswordData) { $rootScope.$broadcast('memberLoginComplete'); return resetPasswordData } } function getMemberForUserName(userName) { return MemberService.query({userName: userName.toLowerCase()}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForResetPassword(credentialOne, credentialTwo) { var credentialOneCleaned = credentialOne.toLowerCase().trim(); var credentialTwoCleaned = credentialTwo.toUpperCase().trim(); var orOne = {$or: [{userName: {$eq: credentialOneCleaned}}, {email: {$eq: credentialOneCleaned}}]}; var orTwo = {$or: [{membershipNumber: {$eq: credentialTwoCleaned}}, {postcode: {$eq: credentialTwoCleaned}}]}; var criteria = {$and: [orOne, orTwo]}; logger.info("querying member using", criteria); return MemberService.query(criteria, {limit: 1}) .then(function (queryResults) { logger.info("queryResults:", queryResults); return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function getMemberForMemberId(memberId) { return MemberService.getById(memberId) } function getMemberByPasswordResetId(passwordResetId) { return MemberService.query({passwordResetId: passwordResetId}, {limit: 1}) .then(function (queryResults) { return (queryResults && queryResults.length > 0) ? queryResults[0] : {}; }); } function setPasswordResetId(member) { member.passwordResetId = NumberUtils.generateUid(); logger.debug('member.userName', member.userName, 'member.passwordResetId', member.passwordResetId); return member; } return { auditMemberLogin: auditMemberLogin, setPasswordResetId: setPasswordResetId, getMemberByPasswordResetId: getMemberByPasswordResetId, getMemberForResetPassword: getMemberForResetPassword, getMemberForUserName: getMemberForUserName, getMemberForMemberId: getMemberForMemberId, loggedInMember: loggedInMember, loginResponse: loginResponse, logout: logout, login: login, saveMember: saveMember, resetPassword: resetPassword, memberLoggedIn: memberLoggedIn, allowContentEdits: allowContentEdits, allowMemberAdminEdits: allowMemberAdminEdits, allowWalkAdminEdits: allowWalkAdminEdits, allowSocialAdminEdits: allowSocialAdminEdits, allowSocialDetailView: allowSocialDetailView, allowCommittee: allowCommittee, allowFinanceAdmin: allowFinanceAdmin, allowTreasuryAdmin: allowTreasuryAdmin, allowFileAdmin: allowFileAdmin, showResetPassword: showResetPassword, showLoginPromptWithRouteParameter: showLoginPromptWithRouteParameter }; }] ); /* concatenated from client/src/app/js/loginController.js */ angular.module('ekwgApp') .controller('LoginController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "AuthenticationModalsService", "Notifier", "URLService", "ValidationUtils", "close", function ($log, $scope, $routeParams, LoggedInMemberService, AuthenticationModalsService, Notifier, URLService, ValidationUtils, close) { $scope.notify = {}; var logger = $log.getInstance('LoginController'); $log.logLevels['LoginController'] = $log.LEVEL.OFF; var notify = Notifier($scope.notify); LoggedInMemberService.logout(); $scope.actions = { submittable: function () { var userNamePopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "userName"); var passwordPopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "password"); logger.info("submittable: userNamePopulated", userNamePopulated, "passwordPopulated", passwordPopulated); return passwordPopulated && userNamePopulated; }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, close: function () { close() }, login: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Logging in", message: "using credentials for " + $scope.enteredMemberCredentials.userName + " - please wait" }); LoggedInMemberService.login($scope.enteredMemberCredentials.userName, $scope.enteredMemberCredentials.password).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else if (LoggedInMemberService.showResetPassword()) { return AuthenticationModalsService.showResetPasswordModal($scope.enteredMemberCredentials.userName, "Your password has expired, therefore you need to reset it to a new one before continuing."); } else { notify.showContactUs(true); notify.error({ title: "Login failed", message: loginResponse.alertMessage }); } }); }, } }] ); /* concatenated from client/src/app/js/mailChimpServices.js */ angular.module('ekwgApp') .factory('MailchimpConfig', ["Config", function (Config) { function getConfig() { return Config.getConfig('mailchimp', { mailchimp: { interestGroups: { walks: {interestGroupingId: undefined}, socialEvents: {interestGroupingId: undefined}, general: {interestGroupingId: undefined} }, segments: { walks: {segmentId: undefined}, socialEvents: {segmentId: undefined}, general: { passwordResetSegmentId: undefined, forgottenPasswordSegmentId: undefined, committeeSegmentId: undefined } } } }) } function saveConfig(config, key, saveCallback, errorSaveCallback) { return Config.saveConfig('mailchimp', config, key, saveCallback, errorSaveCallback); } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('MailchimpHttpService', ["$log", "$q", "$http", "MailchimpErrorParserService", function ($log, $q, $http, MailchimpErrorParserService) { var logger = $log.getInstance('MailchimpHttpService'); $log.logLevels['MailchimpHttpService'] = $log.LEVEL.OFF; function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); logger.debug(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); if (errorObject.error) { var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); } else { logger.debug('success', responseData); deferredTask.resolve(responseData); return responseData; } }).catch(function (response) { var responseData = response.data; var errorObject = MailchimpErrorParserService.extractError(responseData); var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error}; logger.debug(errorResponse); deferredTask.reject(errorResponse); }); return deferredTask.promise; } return { call: call } }]) .factory('MailchimpErrorParserService', ["$log", function ($log) { var logger = $log.getInstance('MailchimpErrorParserService'); $log.logLevels['MailchimpErrorParserService'] = $log.LEVEL.OFF; function extractError(responseData) { var error; if (responseData && (responseData.error || responseData.errno)) { error = {error: responseData} } else if (responseData && responseData.errors && responseData.errors.length > 0) { error = { error: _.map(responseData.errors, function (error) { var response = error.error; if (error.email && error.email.email) { response += (': ' + error.email.email); } return response; }).join(', ') } } else { error = {error: undefined} } logger.debug('responseData:', responseData, 'error:', error) return error; } return { extractError: extractError } }]) .factory('MailchimpLinkService', ["$log", "MAILCHIMP_APP_CONSTANTS", function ($log, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MailchimpLinkService'); $log.logLevels['MailchimpLinkService'] = $log.LEVEL.OFF; function campaignPreview(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } function campaignEdit(webId) { return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId; } return { campaignPreview: campaignPreview } }]) .factory('MailchimpGroupService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpGroupService'); $log.logLevels['MailchimpGroupService'] = $log.LEVEL.OFF; var addInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Adding Mailchimp Interest Group for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupAdd', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var deleteInterestGroup = function (listType, interestGroupName, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Group for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupDel', { interestGroupingId: interestGroupingId, interestGroupName: interestGroupName }); }; var addInterestGrouping = function (listType, interestGroupingName, groups) { return MailchimpHttpService.call('Adding Mailchimp Interest Grouping for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupingAdd', { groups: groups, interestGroupingName: interestGroupingName }); }; var deleteInterestGrouping = function (listType, interestGroupingId) { return MailchimpHttpService.call('Deleting Mailchimp Interest Grouping for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupingDel', {interestGroupingId: interestGroupingId}); }; var listInterestGroupings = function (listType) { return MailchimpHttpService.call('Listing Mailchimp Interest Groupings for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/interestGroupings'); }; var updateInterestGrouping = function (listType, interestGroupingId, interestGroupingName, interestGroupingValue) { return MailchimpHttpService.call('Updating Mailchimp Interest Groupings for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupingUpdate', { interestGroupingId: interestGroupingId, interestGroupingName: interestGroupingName, interestGroupingValue: interestGroupingValue }); }; var updateInterestGroup = function (listType, oldName, newName) { return function (config) { var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; return MailchimpHttpService.call('Updating Mailchimp Interest Group for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupUpdate', { interestGroupingId: interestGroupingId, oldName: oldName, newName: newName }) .then(returnInterestGroupingId(interestGroupingId)); } }; var saveInterestGroup = function (listType, oldName, newName) { oldName = oldName.substring(0, 60); newName = newName.substring(0, 60); return MailchimpConfig.getConfig() .then(updateInterestGroup(listType, oldName, newName)) .then(findInterestGroup(listType, newName)); }; var createInterestGroup = function (listType, interestGroupName) { return MailchimpConfig.getConfig() .then(createOrUpdateInterestGroup(listType, interestGroupName)) .then(findInterestGroup(listType, interestGroupName)); }; var createOrUpdateInterestGroup = function (listType, interestGroupName) { return function (config) { logger.debug('createOrUpdateInterestGroup using config', config); var interestGroupingName = s.titleize(s.humanize(listType)); var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId; if (interestGroupingId) { return addInterestGroup(listType, interestGroupName, interestGroupingId) .then(returnInterestGroupingId(interestGroupingId)); } else { return addInterestGrouping(listType, interestGroupingName + ' Interest Groups', [interestGroupName]) .then(saveInterestGroupConfigAndReturnInterestGroupingId(listType, config)); } } }; var returnInterestGroupingId = function (interestGroupingId) { return function (response) { logger.debug('received', response, 'returning', interestGroupingId); return interestGroupingId; } }; var saveInterestGroupConfigAndReturnInterestGroupingId = function (listType, config) { return function (response) { config.mailchimp.interestGroups[listType].interestGroupingId = response.id; logger.debug('saving config', config); return MailchimpConfig.saveConfig(config, function () { logger.debug('config save was successful'); return response.id; }, function (error) { throw Error('config save was not successful. ' + error) }); } }; var findInterestGroup = function (listType, interestGroupName) { return function (interestGroupingId) { logger.debug('finding findInterestGroup ', interestGroupingId); return listInterestGroupings(listType) .then(filterInterestGroupings(interestGroupingId, interestGroupName)); } }; var filterInterestGroupings = function (interestGroupingId, interestGroupName) { return function (interestGroupings) { logger.debug('filterInterestGroupings: interestGroupings passed in ', interestGroupings, 'for interestGroupingId', interestGroupingId); var interestGrouping = _.find(interestGroupings, function (interestGrouping) { return interestGrouping.id === interestGroupingId; }); logger.debug('filterInterestGroupings: interestGrouping returned ', interestGrouping); var interestGroup = _.find(interestGrouping.groups, function (group) { return group.name === interestGroupName; }); logger.debug('filterInterestGroupings: interestGroup returned', interestGroup); return interestGroup; } }; return { createInterestGroup: createInterestGroup, saveInterestGroup: saveInterestGroup } }]) .factory('MailchimpSegmentService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", "StringUtils", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService, StringUtils) { var logger = $log.getInstance('MailchimpSegmentService'); $log.logLevels['MailchimpSegmentService'] = $log.LEVEL.OFF; function addSegment(listType, segmentName) { return MailchimpHttpService.call('Adding Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentAdd', {segmentName: segmentName}); } function resetSegment(listType, segmentId) { return MailchimpHttpService.call('Resetting Mailchimp segment for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/segmentReset', {segmentId: segmentId}); } function deleteSegment(listType, segmentId) { return MailchimpHttpService.call('Deleting Mailchimp segment for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentDel/' + segmentId); } function callRenameSegment(listType, segmentId, segmentName) { return function () { return renameSegment(listType, segmentId, segmentName); } } function renameSegment(listType, segmentId, segmentNameInput) { var segmentName = StringUtils.stripLineBreaks(StringUtils.left(segmentNameInput, 99), true); logger.debug('renaming segment with name=\'' + segmentName + '\' length=' + segmentName.length); return MailchimpHttpService.call('Renaming Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentRename', { segmentId: segmentId, segmentName: segmentName }); } function callAddSegmentMembers(listType, segmentId, segmentMembers) { return function () { return addSegmentMembers(listType, segmentId, segmentMembers); } } function addSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Adding Mailchimp segment members ' + JSON.stringify(segmentMembers) + ' for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentMembersAdd', { segmentId: segmentId, segmentMembers: segmentMembers }); } function callDeleteSegmentMembers(listType, segmentId, segmentMembers) { return function () { return deleteSegmentMembers(listType, segmentId, segmentMembers); } } function deleteSegmentMembers(listType, segmentId, segmentMembers) { return MailchimpHttpService.call('Deleting Mailchimp segment members ' + segmentMembers + ' for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentMembersDel', { segmentId: segmentId, segmentMembers: segmentMembers }); } function listSegments(listType) { return MailchimpHttpService.call('Listing Mailchimp segments for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/segments'); } function buildSegmentMemberData(listType, memberIds, members) { var segmentMembers = _.chain(memberIds) .map(function (memberId) { return MemberService.toMember(memberId, members) }) .filter(function (member) { return member && member.email; }) .map(function (member) { return EmailSubscriptionService.addMailchimpIdentifiersToRequest(member, listType); }) .value(); if (!segmentMembers || segmentMembers.length === 0) throw new Error('No members were added to the ' + listType + ' email segment from the ' + memberIds.length + ' supplied members. Please check that they have a valid email address and are subscribed to ' + listType); return segmentMembers; } function saveSegment(listType, mailchimpConfig, memberIds, segmentName, members) { var segmentMembers = buildSegmentMemberData(listType, memberIds, members); logger.debug('saveSegment:buildSegmentMemberData:', listType, memberIds, segmentMembers); if (mailchimpConfig && mailchimpConfig.segmentId) { var segmentId = mailchimpConfig.segmentId; logger.debug('saveSegment:segmentId', mailchimpConfig); return resetSegment(listType, segmentId) .then(callRenameSegment(listType, segmentId, segmentName)) .then(addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers)) .then(returnAddSegmentResponse({id: segmentId})); } else { return addSegment(listType, segmentName) .then(addSegmentMembersDuringAdd(listType, segmentMembers)) } } function returnAddSegmentResponse(addSegmentResponse) { return function (addSegmentMembersResponse) { return {members: addSegmentMembersResponse.members, segment: addSegmentResponse}; }; } function returnAddSegmentAndMemberResponse(addSegmentResponse) { return function (addMemberResponse) { return ({segment: addSegmentResponse, members: addMemberResponse}); }; } function addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers) { return function (renameSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, segmentId, segmentMembers) .then(returnAddSegmentAndMemberResponse(renameSegmentResponse)); } else { return {segment: renameSegmentResponse.id, members: {}}; } } } function addSegmentMembersDuringAdd(listType, segmentMembers) { return function (addSegmentResponse) { if (segmentMembers.length > 0) { return addSegmentMembers(listType, addSegmentResponse.id, segmentMembers) .then(returnAddSegmentAndMemberResponse(addSegmentResponse)); } else { return {segment: addSegmentResponse, members: {}}; } } } function getMemberSegmentId(member, segmentType) { if (member.mailchimpSegmentIds) return member.mailchimpSegmentIds[segmentType]; } function setMemberSegmentId(member, segmentType, segmentId) { if (!member.mailchimpSegmentIds) member.mailchimpSegmentIds = {}; member.mailchimpSegmentIds[segmentType] = segmentId; } function formatSegmentName(prefix) { var date = ' (' + DateUtils.nowAsValue() + ')'; var segmentName = prefix.substring(0, 99 - date.length) + date; logger.debug('segmentName', segmentName, 'length', segmentName.length); return segmentName; } return { formatSegmentName: formatSegmentName, saveSegment: saveSegment, deleteSegment: deleteSegment, getMemberSegmentId: getMemberSegmentId, setMemberSegmentId: setMemberSegmentId } }]) .factory('MailchimpListService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService) { var logger = $log.getInstance('MailchimpListService'); $log.logLevels['MailchimpListService'] = $log.LEVEL.OFF; var listSubscribers = function (listType) { return MailchimpHttpService.call('Listing Mailchimp subscribers for ' + listType, 'GET', 'mailchimp/lists/' + listType); }; var batchUnsubscribe = function (listType, subscribers) { return MailchimpHttpService.call('Batch unsubscribing members from Mailchimp List for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/batchUnsubscribe', subscribers); }; var batchUnsubscribeMembers = function (listType, allMembers, notificationCallback) { return listSubscribers(listType) .then(filterSubscriberResponsesForUnsubscriptions(listType, allMembers)) .then(batchUnsubscribeForListType(listType, allMembers, notificationCallback)) .then(returnUpdatedMembers); }; function returnUpdatedMembers() { return MemberService.all(); } function batchUnsubscribeForListType(listType, allMembers, notificationCallback) { return function (subscribers) { if (subscribers.length > 0) { return batchUnsubscribe(listType, subscribers) .then(removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback)); } else { notificationCallback('No members needed to be unsubscribed from ' + listType + ' list'); } } } function removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback) { return function () { var updatedMembers = _.chain(subscribers) .map(function (subscriber) { var member = EmailSubscriptionService.responseToMember(listType, allMembers, subscriber); if (member) { member.mailchimpLists[listType] = {subscribed: false, updated: true}; member.$saveOrUpdate(); } else { notificationCallback('Could not find member from ' + listType + ' response containing data ' + JSON.stringify(subscriber)); } return member; }) .filter(function (member) { return member; }) .value(); $q.all(updatedMembers).then(function () { notificationCallback('Successfully unsubscribed ' + updatedMembers.length + ' member(s) from ' + listType + ' list'); return updatedMembers; }) } } function filterSubscriberResponsesForUnsubscriptions(listType, allMembers) { return function (listResponse) { return _.chain(listResponse.data) .filter(function (subscriber) { return EmailSubscriptionService.includeSubscriberInUnsubscription(listType, allMembers, subscriber); }) .map(function (subscriber) { return { email: subscriber.email, euid: subscriber.euid, leid: subscriber.leid }; }) .value(); } } return { batchUnsubscribeMembers: batchUnsubscribeMembers } }]) .factory('MailchimpCampaignService', ["MAILCHIMP_APP_CONSTANTS", "$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function (MAILCHIMP_APP_CONSTANTS, $log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) { var logger = $log.getInstance('MailchimpCampaignService'); $log.logLevels['MailchimpCampaignService'] = $log.LEVEL.OFF; function addCampaign(campaignId, campaignName) { return MailchimpHttpService.call('Adding Mailchimp campaign ' + campaignId + ' with name ' + campaignName, 'POST', 'mailchimp/campaigns/' + campaignId + '/campaignAdd', {campaignName: campaignName}); } function deleteCampaign(campaignId) { return MailchimpHttpService.call('Deleting Mailchimp campaign ' + campaignId, 'DELETE', 'mailchimp/campaigns/' + campaignId + '/delete'); } function getContent(campaignId) { return MailchimpHttpService.call('Getting Mailchimp content for campaign ' + campaignId, 'GET', 'mailchimp/campaigns/' + campaignId + '/content'); } function list(options) { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list', {}, options); } function setContent(campaignId, contentSections) { return contentSections ? MailchimpHttpService.call('Setting Mailchimp content for campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "content", value: contentSections } }) : $q.when({ result: "success", campaignId: campaignId, message: "setContent skipped as no content provided" }) } function setOrClearSegment(replicatedCampaignId, optionalSegmentId) { if (optionalSegmentId) { return setSegmentId(replicatedCampaignId, optionalSegmentId); } else { return clearSegment(replicatedCampaignId) } } function setSegmentId(campaignId, segmentId) { return setSegmentOpts(campaignId, {saved_segment_id: segmentId}); } function clearSegment(campaignId) { return setSegmentOpts(campaignId, []); } function setSegmentOpts(campaignId, value) { return MailchimpHttpService.call('Setting Mailchimp segment opts for campaign ' + campaignId + ' with value ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "segment_opts", value: value } }); } function setCampaignOptions(campaignId, campaignName, otherOptions) { var value = angular.extend({}, { title: campaignName.substring(0, 99), subject: campaignName }, otherOptions); return MailchimpHttpService.call('Setting Mailchimp campaign options for id ' + campaignId + ' with ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', { updates: { name: "options", value: value } }); } function replicateCampaign(campaignId) { return MailchimpHttpService.call('Replicating Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/replicate'); } function sendCampaign(campaignId) { if (!MAILCHIMP_APP_CONSTANTS.allowSendCampaign) throw new Error('You cannot send campaign ' + campaignId + ' as sending has been disabled'); return MailchimpHttpService.call('Sending Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/send'); } function listCampaigns() { return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list'); } function replicateAndSendWithOptions(options) { logger.debug('replicateAndSendWithOptions:options', options); return replicateCampaign(options.campaignId) .then(function (replicateCampaignResponse) { logger.debug('replicateCampaignResponse', replicateCampaignResponse); var replicatedCampaignId = replicateCampaignResponse.id; return setCampaignOptions(replicatedCampaignId, options.campaignName, options.otherSegmentOptions) .then(function (renameResponse) { logger.debug('renameResponse', renameResponse); return setContent(replicatedCampaignId, options.contentSections) .then(function (setContentResponse) { logger.debug('setContentResponse', setContentResponse); return setOrClearSegment(replicatedCampaignId, options.segmentId) .then(function (setSegmentResponse) { logger.debug('setSegmentResponse', setSegmentResponse); return options.dontSend ? replicateCampaignResponse : sendCampaign(replicatedCampaignId) }) }) }) }); } return { replicateAndSendWithOptions: replicateAndSendWithOptions, list: list } }]); /* concatenated from client/src/app/js/mailingPreferencesController.js */ angular.module('ekwgApp') .controller('MailingPreferencesController', ["$log", "$scope", "ProfileConfirmationService", "Notifier", "URLService", "LoggedInMemberService", "memberId", "close", function ($log, $scope, ProfileConfirmationService, Notifier, URLService, LoggedInMemberService, memberId, close) { var logger = $log.getInstance("MailingPreferencesController"); $log.logLevels["MailingPreferencesController"] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); LoggedInMemberService.getMemberForMemberId(memberId) .then(function (member) { logger.info('memberId ->', memberId, 'member ->', member); $scope.member = member; }); function saveOrUpdateUnsuccessful(message) { notify.showContactUs(true); notify.error({ continue: true, title: "Error in saving mailing preferences", message: "Changes to your mailing preferences could not be saved. " + (message || "Please try again later.") }); } $scope.actions = { save: function () { ProfileConfirmationService.confirmProfile($scope.member); LoggedInMemberService.saveMember($scope.member, $scope.actions.close, saveOrUpdateUnsuccessful); }, close: function () { close(); } }; }]); /* concatenated from client/src/app/js/markdownEditor.js */ angular.module('ekwgApp') .component('markdownEditor', { templateUrl: 'partials/components/markdown-editor.html', controller: ["$cookieStore", "$log", "$rootScope", "$scope", "$element", "$attrs", "ContentText", function ($cookieStore, $log, $rootScope, $scope, $element, $attrs, ContentText) { var logger = $log.getInstance('MarkdownEditorController'); $log.logLevels['MarkdownEditorController'] = $log.LEVEL.OFF; var ctrl = this; ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; function assignData(data) { ctrl.data = data; ctrl.originalData = _.clone(data); logger.debug(ctrl.name, 'content retrieved:', data); return data; } function populateContent(type) { if (type) ctrl.userEdits[type + 'InProgress'] = true; return ContentText.forName(ctrl.name).then(function (data) { data = assignData(data); if (type) ctrl.userEdits[type + 'InProgress'] = false; return data; }); } ctrl.edit = function () { ctrl.userEdits.preview = false; }; ctrl.revert = function () { logger.debug('reverting ' + ctrl.name, 'content'); ctrl.data = _.clone(ctrl.originalData); }; ctrl.dirty = function () { var dirty = ctrl.data && ctrl.originalData && (ctrl.data.text !== ctrl.originalData.text); logger.debug(ctrl.name, 'dirty ->', dirty); return dirty; }; ctrl.revertGlyph = function () { return ctrl.userEdits.revertInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-remove markdown-preview-icon" }; ctrl.saveGlyph = function () { return ctrl.userEdits.saveInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-ok markdown-preview-icon" }; ctrl.save = function () { ctrl.userEdits.saveInProgress = true; logger.info('saving', ctrl.name, 'content', ctrl.data, $element, $attrs); ctrl.data.$saveOrUpdate().then(function (data) { ctrl.userEdits.saveInProgress = false; assignData(data); }) }; ctrl.editSite = function () { return $cookieStore.get('editSite'); }; ctrl.rows = function () { var text = _.property(["data", "text"])(ctrl); var rows = text ? text.split(/\r*\n/).length + 1 : 1; logger.info('number of rows in text ', text, '->', rows); return rows; }; ctrl.preview = function () { logger.info('previewing ' + ctrl.name, 'content', $element, $attrs); ctrl.userEdits.preview = true; }; ctrl.$onInit = function () { logger.debug('initialising:', ctrl.name, 'content, editSite:', ctrl.editSite()); if (!ctrl.description) { ctrl.description = ctrl.name; } populateContent(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/meetupServices.js */ angular.module('ekwgApp') .factory('MeetupService', ["$log", "$http", "HTTPResponseService", function ($log, $http, HTTPResponseService) { var logger = $log.getInstance('MeetupService'); $log.logLevels['MeetupService'] = $log.LEVEL.OFF; return { config: function () { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse); }, eventUrlFor: function (meetupEventUrl) { return $http.get('/meetup/config').then(HTTPResponseService.returnResponse).then(function (meetupConfig) { return meetupConfig.url + '/' + meetupConfig.group + '/events/' + meetupEventUrl; }); }, eventsForStatus: function (status) { var queriedStatus = status || 'upcoming'; return $http({ method: 'get', params: { status: queriedStatus, }, url: '/meetup/events' }).then(function (response) { var returnValue = HTTPResponseService.returnResponse(response); logger.debug('eventsForStatus', queriedStatus, returnValue); return returnValue; }) } } }]); /* concatenated from client/src/app/js/memberAdmin.js */ angular.module('ekwgApp') .controller('MemberAdminController', ["$timeout", "$location", "$window", "$log", "$q", "$rootScope", "$routeParams", "$scope", "ModalService", "Upload", "StringUtils", "DbUtils", "URLService", "LoggedInMemberService", "MemberService", "MemberAuditService", "MemberBulkLoadAuditService", "MemberUpdateAuditService", "ProfileConfirmationService", "EmailSubscriptionService", "DateUtils", "MailchimpConfig", "MailchimpSegmentService", "MemberNamingService", "MailchimpCampaignService", "MailchimpListService", "Notifier", "ErrorMessageService", "MemberBulkUploadService", "ContentMetaDataService", "MONGOLAB_CONFIG", "MAILCHIMP_APP_CONSTANTS", function ($timeout, $location, $window, $log, $q, $rootScope, $routeParams, $scope, ModalService, Upload, StringUtils, DbUtils, URLService, LoggedInMemberService, MemberService, MemberAuditService, MemberBulkLoadAuditService, MemberUpdateAuditService, ProfileConfirmationService, EmailSubscriptionService, DateUtils, MailchimpConfig, MailchimpSegmentService, MemberNamingService, MailchimpCampaignService, MailchimpListService, Notifier, ErrorMessageService, MemberBulkUploadService, ContentMetaDataService, MONGOLAB_CONFIG, MAILCHIMP_APP_CONSTANTS) { var logger = $log.getInstance('MemberAdminController'); var noLogger = $log.getInstance('MemberAdminControllerNoLogger'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $log.logLevels['MemberAdminControllerNoLogger'] = $log.LEVEL.OFF; $scope.memberAdminBaseUrl = ContentMetaDataService.baseUrl('memberAdmin'); $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); var DESCENDING = '▼'; var ASCENDING = '▲'; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.currentMember = {}; $scope.display = { saveInProgress: false }; $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.display.emailTypes = [$scope.display.emailType]; $scope.dropSupported = true; $scope.memberAdminOpen = !URLService.hasRouteParameter('expenseId') && (URLService.isArea('member-admin') || URLService.noArea()); $scope.memberBulkLoadOpen = URLService.isArea('member-bulk-load'); $scope.memberAuditOpen = URLService.isArea('member-audit'); LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId'); if (LoggedInMemberService.memberLoggedIn()) { refreshMembers() .then(refreshMemberAudit) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(notify.clearBusy); } else { notify.clearBusy(); } $scope.currentMemberBulkLoadDisplayDate = function () { return DateUtils.currentMemberBulkLoadDisplayDate(); }; $scope.viewMailchimpListEntry = function (item) { $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/lists/members/view?id=" + item, '_blank'); }; $scope.showSendEmailsDialog = function () { $scope.alertTypeResetPassword = false; $scope.display.emailMembers = []; ModalService.showModal({ templateUrl: "partials/admin/send-emails-dialog.html", controller: "MemberAdminSendEmailsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { members: $scope.members } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function handleSaveError(errorResponse) { $scope.display.saveInProgress = false; applyAllowEdits(); var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(message, 'duplicate'); logger.debug('errorResponse', errorResponse, 'duplicate', duplicate); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Email Address, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; $scope.display.duplicate = true; } notify.clearBusy(); notify.error({ title: 'Member could not be saved', message: message }); } function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; return applyAllowEdits(); } $scope.showPasswordResetAlert = function () { return $scope.notify.showAlert && $scope.alertTypeResetPassword; }; $scope.uploadSessionStatuses = [ {title: "All"}, {status: "created", title: "Created"}, {status: "summary", title: "Summary"}, {status: "skipped", title: "Skipped"}, {status: "updated", title: "Updated"}, {status: "error", title: "Error"}]; $scope.filters = { uploadSession: {selected: undefined}, memberUpdateAudit: { query: $scope.uploadSessionStatuses[0], orderByField: 'updateTime', reverseSort: true, sortDirection: DESCENDING }, membersUploaded: { query: '', orderByField: 'email', reverseSort: true, sortDirection: DESCENDING } }; function applySortTo(field, filterSource) { logger.debug('sorting by field', field, 'current value of filterSource', filterSource); if (field === 'member') { filterSource.orderByField = 'memberId | memberIdToFullName : members : "" : true'; } else { filterSource.orderByField = field; } filterSource.reverseSort = !filterSource.reverseSort; filterSource.sortDirection = filterSource.reverseSort ? DESCENDING : ASCENDING; logger.debug('sorting by field', field, 'new value of filterSource', filterSource); } $scope.uploadSessionChanged = function () { notify.setBusy(); notify.hide(); refreshMemberUpdateAudit().then(notify.clearBusy); }; $scope.sortMembersUploadedBy = function (field) { applySortTo(field, $scope.filters.membersUploaded); }; $scope.sortMemberUpdateAuditBy = function (field) { applySortTo(field, $scope.filters.memberUpdateAudit); }; $scope.showMemberUpdateAuditColumn = function (field) { return s.startsWith($scope.filters.memberUpdateAudit.orderByField, field); }; $scope.showMembersUploadedColumn = function (field) { return $scope.filters.membersUploaded.orderByField === field; }; $scope.sortMembersBy = function (field) { applySortTo(field, $scope.filters.members); }; $scope.showMembersColumn = function (field) { return s.startsWith($scope.filters.members.orderByField, field); }; $scope.toGlyphicon = function (status) { if (status === 'created') return "glyphicon glyphicon-plus green-icon"; if (status === 'complete' || status === 'summary') return "glyphicon-ok green-icon"; if (status === 'success') return "glyphicon-ok-circle green-icon"; if (status === 'info') return "glyphicon-info-sign blue-icon"; if (status === 'updated') return "glyphicon glyphicon-pencil green-icon"; if (status === 'error') return "glyphicon-remove-circle red-icon"; if (status === 'skipped') return "glyphicon glyphicon-thumbs-up green-icon"; }; $scope.filters.members = { query: '', orderByField: 'firstName', reverseSort: false, sortDirection: ASCENDING, filterBy: [ { title: "Active Group Member", group: 'Group Settings', filter: function (member) { return member.groupMember; } }, { title: "All Members", filter: function () { return true; } }, { title: "Active Social Member", group: 'Group Settings', filter: MemberService.filterFor.SOCIAL_MEMBERS }, { title: "Membership Date Active/Not set", group: 'From Ramblers Supplied Datas', filter: function (member) { return !member.membershipExpiryDate || (member.membershipExpiryDate >= $scope.today); } }, { title: "Membership Date Expired", group: 'From Ramblers Supplied Data', filter: function (member) { return member.membershipExpiryDate < $scope.today; } }, { title: "Not received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return !member.receivedInLastBulkLoad; } }, { title: "Was received in last Ramblers Bulk Load", group: 'From Ramblers Supplied Data', filter: function (member) { return member.receivedInLastBulkLoad; } }, { title: "Password Expired", group: 'Other Settings', filter: function (member) { return member.expiredPassword; } }, { title: "Walk Admin", group: 'Administrators', filter: function (member) { return member.walkAdmin; } }, { title: "Walk Change Notifications", group: 'Administrators', filter: function (member) { return member.walkChangeNotifications; } }, { title: "Social Admin", group: 'Administrators', filter: function (member) { return member.socialAdmin; } }, { title: "Member Admin", group: 'Administrators', filter: function (member) { return member.memberAdmin; } }, { title: "Finance Admin", group: 'Administrators', filter: function (member) { return member.financeAdmin; } }, { title: "File Admin", group: 'Administrators', filter: function (member) { return member.fileAdmin; } }, { title: "Treasury Admin", group: 'Administrators', filter: function (member) { return member.treasuryAdmin; } }, { title: "Content Admin", group: 'Administrators', filter: function (member) { return member.contentAdmin; } }, { title: "Committee Member", group: 'Administrators', filter: function (member) { return member.committee; } }, { title: "Subscribed to the General emails list", group: 'Email Subscriptions', filter: MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Walks email list", group: 'Email Subscriptions', filter: MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED }, { title: "Subscribed to the Social email list", group: 'Email Subscriptions', filter: MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED } ] }; $scope.filters.members.filterSelection = $scope.filters.members.filterBy[0].filter; $scope.memberAuditTabs = [ {title: "All Member Logins", active: true} ]; applyAllowEdits(); $scope.allowConfirmDelete = false; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.members = []; $scope.memberAudit = []; $scope.memberUpdateAudit = []; $scope.membersUploaded = []; $scope.resetAllBatchSubscriptions = function () { // careful with calling this - it resets all batch subscriptions to default values return EmailSubscriptionService.resetAllBatchSubscriptions($scope.members, false); }; function updateWalksList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('walks', members); } function updateSocialEventsList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('socialEvents', members); } function updateGeneralList(members) { return EmailSubscriptionService.createBatchSubscriptionForList('general', members); } function notifyUpdatesComplete(members) { notify.success({title: 'Mailchimp updates', message: 'Mailchimp lists were updated successfully'}); $scope.members = members; notify.clearBusy(); } $scope.deleteMemberAudit = function (filteredMemberAudit) { removeAllRecordsAndRefresh(filteredMemberAudit, refreshMemberAudit, 'member audit'); }; $scope.deleteMemberUpdateAudit = function (filteredMemberUpdateAudit) { removeAllRecordsAndRefresh(filteredMemberUpdateAudit, refreshMemberUpdateAudit, 'member update audit'); }; function removeAllRecordsAndRefresh(records, refreshFunction, type) { notify.success('Deleting ' + records.length + ' ' + type + ' record(s)'); var removePromises = []; angular.forEach(records, function (record) { removePromises.push(record.$remove()) }); $q.all(removePromises).then(function () { notify.success('Deleted ' + records.length + ' ' + type + ' record(s)'); refreshFunction.apply(); }); } $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshMemberAudit(); refreshMemberBulkLoadAudit() .then(refreshMemberUpdateAudit); }); $scope.$on('memberSaveComplete', function () { refreshMembers(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.createMemberFromAudit = function (memberFromAudit) { var member = new MemberService(memberFromAudit); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); notify.warning({ title: 'Recreating Member', message: "Note that clicking Save immediately on this member is likely to cause the same error to occur as was originally logged in the audit. Therefore make the necessary changes here to allow the member record to be saved successfully" }) }; $scope.addMember = function () { var member = new MemberService(); EmailSubscriptionService.defaultMailchimpSettings(member, true); member.groupMember = true; showMemberDialog(member, 'Add New'); }; $scope.viewMember = function (member) { showMemberDialog(member, 'View'); }; $scope.editMember = function (member) { showMemberDialog(member, 'Edit Existing'); }; $scope.deleteMemberDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; function unsubscribeWalksList() { return MailchimpListService.batchUnsubscribeMembers('walks', $scope.members, notify.success); } function unsubscribeSocialEventsList(members) { return MailchimpListService.batchUnsubscribeMembers('socialEvents', members, notify.success); } function unsubscribeGeneralList(members) { return MailchimpListService.batchUnsubscribeMembers('general', members, notify.success); } $scope.updateMailchimpLists = function () { $scope.display.saveInProgress = true; return $q.when(notify.success('Sending updates to Mailchimp lists', true)) .then(refreshMembers, notify.error, notify.success) .then(updateWalksList, notify.error, notify.success) .then(updateSocialEventsList, notify.error, notify.success) .then(updateGeneralList, notify.error, notify.success) .then(unsubscribeWalksList, notify.error, notify.success) .then(unsubscribeSocialEventsList, notify.error, notify.success) .then(unsubscribeGeneralList, notify.error, notify.success) .then(notifyUpdatesComplete, notify.error, notify.success) .then(resetSendFlags) .catch(mailchimpError); }; function mailchimpError(errorResponse) { resetSendFlags(); notify.error({ title: 'Mailchimp updates failed', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } $scope.confirmDeleteMemberDetails = function () { $scope.currentMember.$remove(hideMemberDialogAndRefreshMembers); }; $scope.cancelMemberDetails = function () { hideMemberDialogAndRefreshMembers(); }; $scope.profileSettingsConfirmedChecked = function () { ProfileConfirmationService.processMember($scope.currentMember); }; $scope.refreshMemberAudit = refreshMemberAudit; $scope.memberUrl = function () { return $scope.currentMember && $scope.currentMember.$id && (MONGOLAB_CONFIG.baseUrl + MONGOLAB_CONFIG.database + '/collections/members/' + $scope.currentMember.$id()); }; $scope.saveMemberDetails = function () { var member = DateUtils.convertDateFieldInObject($scope.currentMember, 'membershipExpiryDate'); $scope.display.saveInProgress = true; if (!member.userName) { member.userName = MemberNamingService.createUniqueUserName(member, $scope.members); logger.debug('creating username', member.userName); } if (!member.displayName) { member.displayName = MemberNamingService.createUniqueDisplayName(member, $scope.members); logger.debug('creating displayName', member.displayName); } function preProcessMemberBeforeSave() { DbUtils.removeEmptyFieldsIn(member); return EmailSubscriptionService.resetUpdateStatusForMember(member); } function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function saveAndHide() { return DbUtils.auditedSaveOrUpdate(member, hideMemberDialogAndRefreshMembers, notify.error) } $q.when(notify.success('Saving member', true)) .then(preProcessMemberBeforeSave, notify.error, notify.success) .then(saveAndHide, notify.error, notify.success) .then(resetSendFlags) .then(function () { return notify.success('Member saved successfully'); }) .catch(handleSaveError) }; $scope.copyDetailsToNewMember = function () { var copiedMember = new MemberService($scope.currentMember); delete copiedMember._id; EmailSubscriptionService.defaultMailchimpSettings(copiedMember, true); ProfileConfirmationService.unconfirmProfile(copiedMember); showMemberDialog(copiedMember, 'Copy Existing'); notify.success('Existing Member copied! Make changes here and save to create new member.') }; function applyAllowEdits() { $scope.allowEdits = LoggedInMemberService.allowMemberAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowMemberAdminEdits(); return true; } function findLastLoginTimeForMember(member) { var memberAudit = _.chain($scope.memberAudit) .filter(function (memberAudit) { return memberAudit.userName === member.userName; }) .sortBy(function (memberAudit) { return memberAudit.lastLoggedIn; }) .last() .value(); return memberAudit === undefined ? undefined : memberAudit.loginTime; } $scope.bulkUploadRamblersDataStart = function () { $('#select-bulk-load-file').click(); }; $scope.resetSendFlagsAndNotifyError = function (error) { logger.error('resetSendFlagsAndNotifyError', error); resetSendFlags(); return notify.error(error); }; $scope.bulkUploadRamblersDataOpenFile = function (file) { if (file) { var fileUpload = file; $scope.display.saveInProgress = true; function bulkUploadRamblersResponse(memberBulkLoadServerResponse) { return MemberBulkUploadService.processMembershipRecords(file, memberBulkLoadServerResponse, $scope.members, notify) } function bulkUploadRamblersProgress(evt) { fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total); logger.debug("bulkUploadRamblersProgress:progress event", evt); } $scope.uploadedFile = Upload.upload({ url: 'uploadRamblersData', method: 'POST', file: file }).then(bulkUploadRamblersResponse, $scope.resetSendFlagsAndNotifyError, bulkUploadRamblersProgress) .then(refreshMemberBulkLoadAudit) .then(refreshMemberUpdateAudit) .then(validateBulkUploadProcessingBeforeMailchimpUpdates) .catch($scope.resetSendFlagsAndNotifyError); } }; function showMemberDialog(member, memberEditMode) { logger.debug('showMemberDialog:', memberEditMode, member); $scope.alertTypeResetPassword = false; var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(memberEditMode, 'Edit'); $scope.allowConfirmDelete = false; $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.memberEditMode = memberEditMode; $scope.currentMember = member; $scope.currentMemberUpdateAudit = []; if ($scope.currentMember.$id()) { logger.debug('querying MemberUpdateAuditService for memberId', $scope.currentMember.$id()); MemberUpdateAuditService.query({memberId: $scope.currentMember.$id()}, {sort: {updateTime: -1}}) .then(function (data) { logger.debug('MemberUpdateAuditService:', data.length, 'events', data); $scope.currentMemberUpdateAudit = data; }); $scope.lastLoggedIn = findLastLoginTimeForMember(member); } else { logger.debug('new member with default values', $scope.currentMember); } $('#member-admin-dialog').modal(); } function hideMemberDialogAndRefreshMembers() { $q.when($('#member-admin-dialog').modal('hide')) .then(refreshMembers) .then(notify.clearBusy) .then(notify.hide) } function refreshMembers() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberService.all() .then(function (refreshedMembers) { $scope.members = refreshedMembers; return $scope.members; }); } } function refreshMemberAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { MemberAuditService.all({limit: 100, sort: {loginTime: -1}}).then(function (memberAudit) { logger.debug('refreshed', memberAudit && memberAudit.length, 'member audit records'); $scope.memberAudit = memberAudit; }); } return true; } function refreshMemberBulkLoadAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { return MemberBulkLoadAuditService.all({limit: 100, sort: {createdDate: -1}}).then(function (uploadSessions) { logger.debug('refreshed', uploadSessions && uploadSessions.length, 'upload sessions'); $scope.uploadSessions = uploadSessions; $scope.filters.uploadSession.selected = _.first(uploadSessions); return $scope.filters.uploadSession.selected; }); } else { return true; } } function migrateAudits() { // temp - remove this! MemberUpdateAuditService.all({ limit: 10000, sort: {updateTime: -1} }).then(function (allMemberUpdateAudit) { logger.debug('temp queried all', allMemberUpdateAudit && allMemberUpdateAudit.length, 'member audit records'); var keys = []; var memberUpdateAuditServicePromises = []; var memberBulkLoadAuditServicePromises = []; var bulkAudits = _.chain(allMemberUpdateAudit) // .filter(function (audit) { // return !audit.uploadSessionId; // }) .map(function (audit) { var auditLog = { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime), auditLog: [ { "status": "complete", "message": "Migrated audit log for upload of file " + audit.fileName } ] }; return auditLog; }) .uniq(JSON.stringify) .map(function (auditLog) { return new MemberBulkLoadAuditService(auditLog).$save() .then(function (auditResponse) { memberBulkLoadAuditServicePromises.push(auditResponse); logger.debug('saved bulk load session id', auditResponse.$id(), 'number', memberBulkLoadAuditServicePromises.length); return auditResponse; }); }) .value(); function saveAudit(audit) { memberUpdateAuditServicePromises.push(audit.$saveOrUpdate()); logger.debug('saved', audit.uploadSessionId, 'to audit number', memberUpdateAuditServicePromises.length); } $q.all(bulkAudits).then(function (savedBulkAuditRecords) { logger.debug('saved bulk load sessions', savedBulkAuditRecords); _.each(allMemberUpdateAudit, function (audit) { var parentBulkAudit = _.findWhere(savedBulkAuditRecords, { fileName: audit.fileName, createdDate: DateUtils.asValueNoTime(audit.updateTime) }); if (parentBulkAudit) { audit.uploadSessionId = parentBulkAudit.$id(); saveAudit(audit); } else { logger.error('no match for audit record', audit); } }); $q.all(memberUpdateAuditServicePromises).then(function (values) { logger.debug('saved', values.length, 'audit records'); }); }); }); } function refreshMemberUpdateAudit() { if (LoggedInMemberService.allowMemberAdminEdits()) { // migrateAudits(); if ($scope.filters.uploadSession.selected && $scope.filters.uploadSession.selected.$id) { var uploadSessionId = $scope.filters.uploadSession.selected.$id(); var query = {uploadSessionId: uploadSessionId}; if ($scope.filters.memberUpdateAudit.query.status) { angular.extend(query, {memberAction: $scope.filters.memberUpdateAudit.query.status}) } logger.debug('querying member audit records with', query); return MemberUpdateAuditService.query(query, {sort: {updateTime: -1}}).then(function (memberUpdateAudit) { $scope.memberUpdateAudit = memberUpdateAudit; logger.debug('refreshed', memberUpdateAudit && memberUpdateAudit.length, 'member audit records'); return $scope.memberUpdateAudit; }); } else { $scope.memberUpdateAudit = []; logger.debug('no member audit records'); return $q.when($scope.memberUpdateAudit); } } } function auditSummary() { return _.groupBy($scope.memberUpdateAudit, function (auditItem) { return auditItem.memberAction || 'unknown'; }); } function auditSummaryFormatted(auditSummary) { var total = _.reduce(auditSummary, function (memo, value) { return memo + value.length; }, 0); var summary = _.map(auditSummary, function (items, key) { return items.length + ':' + key; }).join(', '); return total + " Member audits " + (total ? '(' + summary + ')' : ''); } $scope.memberUpdateAuditSummary = function () { return auditSummaryFormatted(auditSummary()); }; function validateBulkUploadProcessingBeforeMailchimpUpdates() { logger.debug('validateBulkUploadProcessing:$scope.filters.uploadSession', $scope.filters.uploadSession); if ($scope.filters.uploadSession.selected.error) { notify.error({title: 'Bulk upload failed', message: $scope.filters.uploadSession.selected.error}); } else { var summary = auditSummary(); var summaryFormatted = auditSummaryFormatted(summary); logger.debug('summary', summary, 'summaryFormatted', summaryFormatted); if (summary.error) { notify.error({ title: "Bulk upload was not successful", message: "One or more errors occurred - " + summaryFormatted }); return false; } else return $scope.updateMailchimpLists(); } } }] ) ; /* concatenated from client/src/app/js/memberAdminSendEmailsController.js */ angular.module('ekwgApp') .controller('MemberAdminSendEmailsController', ["$log", "$q", "$scope", "$filter", "DateUtils", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "EmailSubscriptionService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "members", "close", function ($log, $q, $scope, $filter, DateUtils, DbUtils, LoggedInMemberService, ErrorMessageService, EmailSubscriptionService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, members, close) { var logger = $log.getInstance('MemberAdminSendEmailsController'); $log.logLevels['MemberAdminSendEmailsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); notify.setBusy(); var CAMPAIGN_TYPE_WELCOME = "welcome"; var CAMPAIGN_TYPE_PASSWORD_RESET = "passwordReset"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING = "expiredMembersWarning"; var CAMPAIGN_TYPE_EXPIRED_MEMBERS = "expiredMembers"; $scope.today = DateUtils.momentNowNoTime().valueOf(); $scope.members = members; $scope.memberFilterDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.memberFilterDateCalendar.opened = true; } }; $scope.showHelp = function (show) { $scope.display.showHelp = show; }; $scope.cancel = function () { close(); }; $scope.display = { showHelp: false, selectableMembers: [], emailMembers: [], saveInProgress: false, monthsInPast: 1, memberFilterDate: undefined, emailType: {name: "(loading)"}, passwordResetCaption: function () { return 'About to send a ' + $scope.display.emailType.name + ' to ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'); }, expiryEmailsSelected: function () { var returnValue = $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING || $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS; logger.debug('expiryEmailsSelected -> ', returnValue); return returnValue; }, recentMemberEmailsSelected: function () { return $scope.display.emailType.type === CAMPAIGN_TYPE_WELCOME || $scope.display.emailType.type === CAMPAIGN_TYPE_PASSWORD_RESET; } }; $scope.populateSelectableMembers = function () { $scope.display.selectableMembers = _.chain($scope.members) .filter(function (member) { return EmailSubscriptionService.includeMemberInEmailList('general', member); }) .map(extendWithInformation) .value(); logger.debug('populateSelectableMembers:found', $scope.display.selectableMembers.length, 'members'); }; $scope.populateSelectableMembers(); $scope.calculateMemberFilterDate = function () { $scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf(); }; $scope.clearDisplayEmailMembers = function () { $scope.display.emailMembers = []; notify.warning({ title: 'Member selection', message: 'current member selection was cleared' }); }; function extendWithInformation(member) { return $scope.display.expiryEmailsSelected() ? extendWithExpiryInformation(member) : extendWithCreatedInformation(member); } function extendWithExpiryInformation(member) { var expiredActive = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var memberGrouping = member.receivedInLastBulkLoad ? expiredActive : 'missing from last bulk load'; var datePrefix = memberGrouping === 'expired' ? ': ' : ', ' + (member.membershipExpiryDate < $scope.today ? 'expired' : 'expiry') + ': '; var text = $filter('fullNameWithAlias')(member) + ' (' + memberGrouping + datePrefix + (DateUtils.displayDate(member.membershipExpiryDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } function extendWithCreatedInformation(member) { var memberGrouping = member.membershipExpiryDate < $scope.today ? 'expired' : 'active'; var text = $filter('fullNameWithAlias')(member) + ' (created ' + (DateUtils.displayDate(member.createdDate) || 'not known') + ')'; return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping}); } $scope.memberGrouping = function (member) { return member.memberGrouping; }; function populateMembersBasedOnFilter(filter) { logger.debug('populateExpiredMembers: display.emailType ->', $scope.display.emailType); notify.setBusy(); notify.warning({ title: 'Automatically adding expired members', message: ' - please wait for list to be populated' }); $scope.display.memberFilterDate = DateUtils.convertDateField($scope.display.memberFilterDate); $scope.display.emailMembers = _($scope.display.selectableMembers) .filter(filter); notify.warning({ title: 'Members added to email selection', message: 'automatically added ' + $scope.display.emailMembers.length + ' members' }); notify.clearBusy(); } $scope.populateMembers = function (recalcMemberFilterDate) { logger.debug('$scope.display.memberSelection', $scope.display.emailType.memberSelection); this.populateSelectableMembers(); switch ($scope.display.emailType.memberSelection) { case 'recently-added': $scope.populateRecentlyAddedMembers(recalcMemberFilterDate); break; case 'expired-members': $scope.populateExpiredMembers(recalcMemberFilterDate); break } }; $scope.populateRecentlyAddedMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && (member.createdDate >= $scope.display.memberFilterDate); }); }; $scope.populateExpiredMembers = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && (member.membershipExpiryDate < $scope.display.memberFilterDate); }); }; $scope.populateMembersMissingFromBulkLoad = function (recalcMemberFilterDate) { if (recalcMemberFilterDate) { $scope.calculateMemberFilterDate(); } populateMembersBasedOnFilter(function (member) { return member.groupMember && member.membershipExpiryDate && !member.receivedInLastBulkLoad; }) }; function displayEmailMembersToMembers() { return _.chain($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }) .filter(function (member) { return member && member.email; }).value(); } function addPasswordResetIdToMembers() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { LoggedInMemberService.setPasswordResetId(member); EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Password reset prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function includeInNextMailchimpListUpdate() { var saveMemberPromises = []; _.map(displayEmailMembersToMembers(), function (member) { EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises).then(function () { return notify.success('Member expiration prepared for ' + saveMemberPromises.length + ' member(s)'); }); } function noAction() { } function removeExpiredMembersFromGroup() { logger.debug('removing ', $scope.display.emailMembers.length, 'members from group'); var saveMemberPromises = []; _($scope.display.emailMembers) .map(function (memberId) { return _.find($scope.members, function (member) { return member.$id() === memberId.id; }) }).map(function (member) { member.groupMember = false; EmailSubscriptionService.resetUpdateStatusForMember(member); saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member)) }); return $q.all(saveMemberPromises) .then(function () { return notify.success('EKWG group membership removed for ' + saveMemberPromises.length + ' member(s)'); }) } $scope.cancelSendEmails = function () { $scope.cancel(); }; $scope.sendEmailsDisabled = function () { return $scope.display.emailMembers.length === 0 }; $scope.sendEmails = function () { $scope.alertTypeResetPassword = true; $scope.display.saveInProgress = true; $scope.display.duplicate = false; $q.when(notify.success('Preparing to email ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'), true)) .then($scope.display.emailType.preSend) .then(updateGeneralList) .then(createOrSaveMailchimpSegment) .then(saveSegmentDataToMailchimpConfig) .then(sendEmailCampaign) .then($scope.display.emailType.postSend) .then(notify.clearBusy) .then($scope.cancel) .then(resetSendFlags) .catch(handleSendError); }; function resetSendFlags() { logger.debug('resetSendFlags'); $scope.display.saveInProgress = false; } function updateGeneralList() { return EmailSubscriptionService.createBatchSubscriptionForList('general', $scope.members).then(function (updatedMembers) { $scope.members = updatedMembers; }); } function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('general', {segmentId: $scope.display.emailType.segmentId}, $scope.display.emailMembers, $scope.display.emailType.name, $scope.members); } function saveSegmentDataToMailchimpConfig(segmentResponse) { logger.debug('saveSegmentDataToMailchimpConfig:segmentResponse', segmentResponse); return MailchimpConfig.getConfig() .then(function (config) { config.mailchimp.segments.general[$scope.display.emailType.type + 'SegmentId'] = segmentResponse.segment.id; return MailchimpConfig.saveConfig(config) .then(function () { logger.debug('saveSegmentDataToMailchimpConfig:returning segment id', segmentResponse.segment.id); return segmentResponse.segment.id; }); }); } function sendEmailCampaign(segmentId) { var members = $scope.display.emailMembers.length + ' member(s)'; notify.success('Sending ' + $scope.display.emailType.name + ' email to ' + members); logger.debug('about to sendEmailCampaign:', $scope.display.emailType.type, 'campaign Id', $scope.display.emailType.campaignId, 'segmentId', segmentId, 'campaignName', $scope.display.emailType.name); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: $scope.display.emailType.campaignId, campaignName: $scope.display.emailType.name, segmentId: segmentId }).then(function () { notify.success('Sending of ' + $scope.display.emailType.name + ' to ' + members + ' was successful'); }); } $scope.emailMemberList = function () { return _($scope.display.emailMembers) .sortBy(function (emailMember) { return emailMember.text; }).map(function (emailMember) { return emailMember.text; }).join(', '); }; function handleSendError(errorResponse) { $scope.display.saveInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } MailchimpConfig.getConfig() .then(function (config) { $scope.display.emailTypes = [ { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_WELCOME, name: config.mailchimp.campaigns.welcome.name, monthsInPast: config.mailchimp.campaigns.welcome.monthsInPast, campaignId: config.mailchimp.campaigns.welcome.campaignId, segmentId: config.mailchimp.segments.general.welcomeSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.welcome.monthsInPast + " month are displayed as a default, as these are most likely to need a welcome email sent" }, { preSend: addPasswordResetIdToMembers, type: CAMPAIGN_TYPE_PASSWORD_RESET, name: config.mailchimp.campaigns.passwordReset.name, monthsInPast: config.mailchimp.campaigns.passwordReset.monthsInPast, campaignId: config.mailchimp.campaigns.passwordReset.campaignId, segmentId: config.mailchimp.segments.general.passwordResetSegmentId, memberSelection: 'recently-added', postSend: noAction, dateTooltip: "All members created in the last " + config.mailchimp.campaigns.passwordReset.monthsInPast + " month are displayed as a default" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING, name: config.mailchimp.campaigns.expiredMembersWarning.name, monthsInPast: config.mailchimp.campaigns.expiredMembersWarning.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembersWarning.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersWarningSegmentId, memberSelection: 'expired-members', postSend: noAction, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date " + config.mailchimp.campaigns.expiredMembersWarning.monthsInPast + " months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" }, { preSend: includeInNextMailchimpListUpdate, type: CAMPAIGN_TYPE_EXPIRED_MEMBERS, name: config.mailchimp.campaigns.expiredMembers.name, monthsInPast: config.mailchimp.campaigns.expiredMembers.monthsInPast, campaignId: config.mailchimp.campaigns.expiredMembers.campaignId, segmentId: config.mailchimp.segments.general.expiredMembersSegmentId, memberSelection: 'expired-members', postSend: removeExpiredMembersFromGroup, dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " + "A date 3 months in the past has been pre-selected, to avoid including members whose membership renewal is still progress" } ]; $scope.display.emailType = $scope.display.emailTypes[0]; $scope.populateMembers(true); }); }] ); /* concatenated from client/src/app/js/memberResources.js */ angular.module('ekwgApp') .factory('MemberResourcesService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberResources'); }]) .factory('MemberResourcesReferenceData', ["$log", "URLService", "ContentMetaDataService", "FileUtils", "LoggedInMemberService", "SiteEditService", function ($log, URLService, ContentMetaDataService, FileUtils, LoggedInMemberService, SiteEditService) { var logger = $log.getInstance('MemberResourcesReferenceData'); $log.logLevels['MemberResourcesReferenceData'] = $log.LEVEL.OFF; const subjects = [ { id: "newsletter", description: "Newsletter" }, { id: "siteReleaseNote", description: "Site Release Note" }, { id: "walkPlanning", description: "Walking Planning Advice" } ]; const resourceTypes = [ { id: "email", description: "Email", action: "View email", icon: function () { return "assets/images/local/mailchimp.ico" }, resourceUrl: function (memberResource) { var data = _.property(['data', 'campaign', 'archive_url_long'])(memberResource); logger.debug('email:resourceUrl for', memberResource, data); return data; } }, { id: "file", description: "File", action: "Download", icon: function (memberResource) { return FileUtils.icon(memberResource, 'data') }, resourceUrl: function (memberResource) { var data = memberResource && memberResource.data.fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl("memberResources") + "/" + memberResource.data.fileNameData.awsFileName : ""; logger.debug('file:resourceUrl for', memberResource, data); return data; } }, { id: "url", action: "View page", description: "External Link", icon: function () { return "assets/images/ramblers/favicon.ico" }, resourceUrl: function () { return "TBA"; } } ]; const accessLevels = [ { id: "hidden", description: "Hidden", filter: function () { return SiteEditService.active() || false; } }, { id: "committee", description: "Committee", filter: function () { return SiteEditService.active() || LoggedInMemberService.allowCommittee(); } }, { id: "loggedInMember", description: "Logged-in member", filter: function () { return SiteEditService.active() || LoggedInMemberService.memberLoggedIn(); } }, { id: "public", description: "Public", filter: function () { return true; } }]; function resourceTypeFor(resourceType) { var type = _.find(resourceTypes, function (type) { return type.id === resourceType; }); logger.debug('resourceType for', type, type); return type; } function accessLevelFor(accessLevel) { var level = _.find(accessLevels, function (level) { return level.id === accessLevel; }); logger.debug('accessLevel for', accessLevel, level); return level; } return { subjects: subjects, resourceTypes: resourceTypes, accessLevels: accessLevels, resourceTypeFor: resourceTypeFor, accessLevelFor: accessLevelFor }; }]); /* concatenated from client/src/app/js/memberServices.js */ angular.module('ekwgApp') .factory('MemberUpdateAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberUpdateAudit'); }]) .factory('MemberBulkLoadAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberBulkLoadAudit'); }]) .factory('MemberAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('memberAudit'); }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('MemberNamingService', ["$log", "StringUtils", function ($log, StringUtils) { var logger = $log.getInstance('MemberNamingService'); $log.logLevels['MemberNamingService'] = $log.LEVEL.OFF; var createUserName = function (member) { return StringUtils.replaceAll(' ', '', (member.firstName + '.' + member.lastName).toLowerCase()); }; function createDisplayName(member) { return member.firstName.trim() + ' ' + member.lastName.trim().substring(0, 1).toUpperCase(); } function createUniqueUserName(member, members) { return createUniqueValueFrom(createUserName, 'userName', member, members) } function createUniqueDisplayName(member, members) { return createUniqueValueFrom(createDisplayName, 'displayName', member, members) } function createUniqueValueFrom(nameFunction, field, member, members) { var attempts = 0; var suffix = ""; while (true) { var createdName = nameFunction(member) + suffix; if (!memberFieldExists(field, createdName, members)) { return createdName } else { attempts++; suffix = attempts; } } } function memberFieldExists(field, value, members) { var member = _(members).find(function (member) { return member[field] === value; }); var returnValue = member && member[field]; logger.debug('field', field, 'matching', value, member, '->', returnValue); return returnValue; } return { createDisplayName: createDisplayName, createUserName: createUserName, createUniqueUserName: createUniqueUserName, createUniqueDisplayName: createUniqueDisplayName }; }]) .factory('MemberService', ["$mongolabResourceHttp", "$log", function ($mongolabResourceHttp, $log) { var logger = $log.getInstance('MemberService'); var noLogger = $log.getInstance('MemberServiceMuted'); $log.logLevels['MemberServiceMuted'] = $log.LEVEL.OFF; $log.logLevels['MemberService'] = $log.LEVEL.OFF; var memberService = $mongolabResourceHttp('members'); memberService.filterFor = { SOCIAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.socialMember && member.mailchimpLists.socialEvents.subscribed }, WALKS_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.walks.subscribed }, GENERAL_MEMBERS_SUBSCRIBED: function (member) { return member.groupMember && member.mailchimpLists.general.subscribed }, GROUP_MEMBERS: function (member) { return member.groupMember; }, COMMITTEE_MEMBERS: function (member) { return member.groupMember && member.committee; }, SOCIAL_MEMBERS: function (member) { return member.groupMember && member.socialMember; }, }; memberService.allLimitedFields = function allLimitedFields(filterFunction) { return memberService.all({ fields: { mailchimpLists: 1, groupMember: 1, socialMember: 1, financeAdmin: 1, treasuryAdmin: 1, fileAdmin: 1, committee: 1, walkChangeNotifications: 1, email: 1, displayName: 1, contactId: 1, mobileNumber: 1, $id: 1, firstName: 1, lastName: 1, nameAlias: 1 } }).then(function (members) { return _.chain(members) .filter(filterFunction) .sortBy(function (member) { return member.firstName + member.lastName; }).value(); }); }; memberService.toMember = function (memberIdOrObject, members) { var memberId = (_.has(memberIdOrObject, 'id') ? memberIdOrObject.id : memberIdOrObject); noLogger.info('toMember:memberIdOrObject', memberIdOrObject, '->', memberId); var member = _.find(members, function (member) { return member.$id() === memberId; }); noLogger.info('toMember:', memberIdOrObject, '->', member); return member; }; memberService.allMemberMembersWithPrivilege = function (privilege, members) { var filteredMembers = _.filter(members, function (member) { return member.groupMember && member[privilege]; }); logger.debug('allMemberMembersWithPrivilege:privilege', privilege, 'filtered from', members.length, '->', filteredMembers.length, 'members ->', filteredMembers); return filteredMembers; }; memberService.allMemberIdsWithPrivilege = function (privilege, members) { return memberService.allMemberMembersWithPrivilege(privilege, members).map(extractMemberId); function extractMemberId(member) { return member.$id() } }; return memberService; }]); /* concatenated from client/src/app/js/notificationUrl.js */ angular.module("ekwgApp") .component("notificationUrl", { templateUrl: "partials/components/notification-url.html", controller: ["$log", "URLService", "FileUtils", function ($log, URLService, FileUtils) { var ctrl = this; var logger = $log.getInstance("NotificationUrlController"); $log.logLevels['NotificationUrlController'] = $log.LEVEL.OFF; ctrl.anchor_href = function () { return URLService.notificationHref(ctrl); }; ctrl.anchor_target = function () { return "_blank"; }; ctrl.anchor_text = function () { var text = (!ctrl.text && ctrl.name) ? FileUtils.basename(ctrl.name) : ctrl.text || ctrl.anchor_href(); logger.debug("text", text); return text; }; }], bindings: { name: "@", text: "@", type: "@", id: "@", area: "@" } }); /* concatenated from client/src/app/js/notifier.js */ angular.module('ekwgApp') .factory('Notifier', ["$log", "ErrorMessageService", function ($log, ErrorMessageService) { var ALERT_ERROR = {class: 'alert-danger', icon: 'glyphicon-exclamation-sign', failure: true}; var ALERT_WARNING = {class: 'alert-warning', icon: 'glyphicon-info-sign'}; var ALERT_INFO = {class: 'alert-success', icon: 'glyphicon-info-sign'}; var ALERT_SUCCESS = {class: 'alert-success', icon: 'glyphicon-ok'}; var logger = $log.getInstance('Notifier'); $log.logLevels['Notifier'] = $log.LEVEL.OFF; return function (scope) { scope.alertClass = ALERT_SUCCESS.class; scope.alert = ALERT_SUCCESS; scope.alertMessages = []; scope.alertHeading = []; scope.ready = false; function setReady() { clearBusy(); return scope.ready = true; } function clearBusy() { logger.debug('clearing busy'); return scope.busy = false; } function setBusy() { logger.debug('setting busy'); return scope.busy = true; } function showContactUs(state) { logger.debug('setting showContactUs', state); return scope.showContactUs = state; } function notifyAlertMessage(alertType, message, append, busy) { var messageText = message && ErrorMessageService.stringify(_.has(message, 'message') ? message.message : message); if (busy) setBusy(); if (!append || alertType === ALERT_ERROR) scope.alertMessages = []; if (messageText) scope.alertMessages.push(messageText); scope.alertTitle = message && _.has(message, 'title') ? message.title : undefined; scope.alert = alertType; scope.alertClass = alertType.class; scope.showAlert = scope.alertMessages.length > 0; scope.alertMessage = scope.alertMessages.join(', '); if (alertType === ALERT_ERROR && !_.has(message, 'continue')) { logger.error('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append); clearBusy(); throw message; } else { return logger.debug('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append, 'showAlert =', scope.showAlert); } } function progress(message, busy) { return notifyAlertMessage(ALERT_INFO, message, false, busy) } function hide() { notifyAlertMessage(ALERT_SUCCESS); return clearBusy(); } function success(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, false, busy) } function successWithAppend(message, busy) { return notifyAlertMessage(ALERT_SUCCESS, message, true, busy) } function error(message, append, busy) { return notifyAlertMessage(ALERT_ERROR, message, append, busy) } function warning(message, append, busy) { return notifyAlertMessage(ALERT_WARNING, message, append, busy) } return { success: success, successWithAppend: successWithAppend, progress: progress, progressWithAppend: successWithAppend, error: error, warning: warning, showContactUs: showContactUs, setBusy: setBusy, clearBusy: clearBusy, setReady: setReady, hide: hide } } }]); /* concatenated from client/src/app/js/profile.js */ angular.module('ekwgApp') .factory('ProfileConfirmationService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) { var confirmProfile = function (member) { if (member) { member.profileSettingsConfirmed = true; member.profileSettingsConfirmedAt = DateUtils.nowAsValue(); member.profileSettingsConfirmedBy = $filter('fullNameWithAlias')(LoggedInMemberService.loggedInMember()); } }; var unconfirmProfile = function (member) { if (member) { delete member.profileSettingsConfirmed; delete member.profileSettingsConfirmedAt; delete member.profileSettingsConfirmedBy; } }; var processMember = function (member) { if (member) { if (member.profileSettingsConfirmed) { confirmProfile(member) } else { unconfirmProfile(member) } } }; return { confirmProfile: confirmProfile, unconfirmProfile: unconfirmProfile, processMember: processMember }; }]) .controller('ProfileController', ["$q", "$rootScope", "$routeParams", "$scope", "LoggedInMemberService", "MemberService", "URLService", "ProfileConfirmationService", "EmailSubscriptionService", "CommitteeReferenceData", function ($q, $rootScope, $routeParams, $scope, LoggedInMemberService, MemberService, URLService, ProfileConfirmationService, EmailSubscriptionService, CommitteeReferenceData) { $scope.showArea = function (area) { URLService.navigateTo('admin', area) }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; function isArea(area) { return (area === $routeParams.area); } var LOGIN_DETAILS = 'login details'; var PERSONAL_DETAILS = 'personal details'; var CONTACT_PREFERENCES = 'contact preferences'; var ALERT_CLASS_DANGER = 'alert-danger'; var ALERT_CLASS_SUCCESS = 'alert-success'; $scope.currentMember = {}; $scope.enteredMemberCredentials = {}; $scope.alertClass = ALERT_CLASS_SUCCESS; $scope.alertType = LOGIN_DETAILS; $scope.alertMessages = []; $scope.personalDetailsOpen = isArea('personal-details'); $scope.loginDetailsOpen = isArea('login-details'); $scope.contactPreferencesOpen = isArea('contact-preferences'); $scope.showAlertPersonalDetails = false; $scope.showAlertLoginDetails = false; $scope.showAlertContactPreferences = false; applyAllowEdits('controller init'); refreshMember(); $scope.$on('memberLoginComplete', function () { $scope.alertMessages = []; refreshMember(); applyAllowEdits('memberLoginComplete'); }); $scope.$on('memberLogoutComplete', function () { $scope.alertMessages = []; applyAllowEdits('memberLogoutComplete'); }); $scope.undoChanges = function () { refreshMember(); }; function saveOrUpdateSuccessful() { $scope.enteredMemberCredentials.newPassword = null; $scope.enteredMemberCredentials.newPasswordConfirm = null; $scope.alertMessages.push('Your ' + $scope.alertType + ' were saved successfully and will be effective on your next login.'); showAlert(ALERT_CLASS_SUCCESS, $scope.alertType); } function saveOrUpdateUnsuccessful(message) { var messageDefaulted = message || 'Please try again later.'; $scope.alertMessages.push('Changes to your ' + $scope.alertType + ' could not be saved. ' + messageDefaulted); showAlert(ALERT_CLASS_DANGER, $scope.alertType); } $scope.saveLoginDetails = function () { $scope.alertMessages = []; validateUserNameExistence(); }; $scope.$on('userNameExistenceCheckComplete', function () { validatePassword(); validateUserName(); if ($scope.alertMessages.length === 0) { saveMemberDetails(LOGIN_DETAILS) } else { showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }); $scope.savePersonalDetails = function () { $scope.alertMessages = []; saveMemberDetails(PERSONAL_DETAILS); }; $scope.saveContactPreferences = function () { $scope.alertMessages = []; ProfileConfirmationService.confirmProfile($scope.currentMember); saveMemberDetails(CONTACT_PREFERENCES); }; $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; function validatePassword() { if ($scope.enteredMemberCredentials.newPassword || $scope.enteredMemberCredentials.newPasswordConfirm) { // console.log('validating password change old=', $scope.enteredMemberCredentials.newPassword, 'new=', $scope.enteredMemberCredentials.newPasswordConfirm); if ($scope.currentMember.password === $scope.enteredMemberCredentials.newPassword) { $scope.alertMessages.push('The new password was the same as the old one.'); } else if ($scope.enteredMemberCredentials.newPassword !== $scope.enteredMemberCredentials.newPasswordConfirm) { $scope.alertMessages.push('The new password was not confirmed correctly.'); } else if ($scope.enteredMemberCredentials.newPassword.length < 6) { $scope.alertMessages.push('The new password needs to be at least 6 characters long.'); } else { $scope.currentMember.password = $scope.enteredMemberCredentials.newPassword; // console.log('validating password change - successful'); } } } function validateUserName() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { $scope.enteredMemberCredentials.userName = $scope.enteredMemberCredentials.userName.trim(); if ($scope.enteredMemberCredentials.userName.length === 0) { $scope.alertMessages.push('The new user name cannot be blank.'); } else { $scope.currentMember.userName = $scope.enteredMemberCredentials.userName; } } } function undoChangesTo(alertType) { refreshMember(); $scope.alertMessages = ['Changes to your ' + alertType + ' were reverted.']; showAlert(ALERT_CLASS_SUCCESS, alertType); } $scope.undoLoginDetails = function () { undoChangesTo(LOGIN_DETAILS); }; $scope.undoPersonalDetails = function () { undoChangesTo(PERSONAL_DETAILS); }; $scope.undoContactPreferences = function () { undoChangesTo(CONTACT_PREFERENCES); }; function saveMemberDetails(alertType) { $scope.alertType = alertType; EmailSubscriptionService.resetUpdateStatusForMember($scope.currentMember); LoggedInMemberService.saveMember($scope.currentMember, saveOrUpdateSuccessful, saveOrUpdateUnsuccessful); } function showAlert(alertClass, alertType) { if ($scope.alertMessages.length > 0) { $scope.alertClass = alertClass; $scope.alertMessage = $scope.alertMessages.join(', '); $scope.showAlertLoginDetails = alertType === LOGIN_DETAILS; $scope.showAlertPersonalDetails = alertType === PERSONAL_DETAILS; $scope.showAlertContactPreferences = alertType === CONTACT_PREFERENCES; } else { $scope.showAlertLoginDetails = false; $scope.showAlertPersonalDetails = false; $scope.showAlertContactPreferences = false; } } function applyAllowEdits(event) { $scope.allowEdits = LoggedInMemberService.memberLoggedIn(); $scope.isAdmin = LoggedInMemberService.allowMemberAdminEdits(); } function refreshMember() { if (LoggedInMemberService.memberLoggedIn()) { LoggedInMemberService.getMemberForUserName(LoggedInMemberService.loggedInMember().userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.currentMember = member; $scope.enteredMemberCredentials = {userName: $scope.currentMember.userName}; } else { $scope.alertMessages.push('Could not refresh member'); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); } }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }) } } function validateUserNameExistence() { if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) { LoggedInMemberService.getMemberForUserName($scope.enteredMemberCredentials.userName) .then(function (member) { if (!_.isEmpty(member)) { $scope.alertMessages.push('The user name ' + $scope.enteredMemberCredentials.userName + ' is already used by another member. Please choose another.'); $scope.enteredMemberCredentials.userName = $scope.currentMember.userName; } $rootScope.$broadcast('userNameExistenceCheckComplete'); }, function (response) { $scope.alertMessages.push('Unexpected error occurred: ' + response); showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS); }); } else { $rootScope.$broadcast('userNameExistenceCheckComplete'); } } }]); /* concatenated from client/src/app/js/ramblersWalksServices.js */ angular.module('ekwgApp') .factory('RamblersHttpService', ["$q", "$http", function ($q, $http) { function call(serviceCallType, method, url, data, params) { var deferredTask = $q.defer(); deferredTask.notify(serviceCallType); $http({ method: method, data: data, params: params, url: url }).then(function (response) { var responseData = response.data; if (responseData.error) { deferredTask.reject(response); } else { deferredTask.notify(responseData.information); deferredTask.resolve(responseData) } }).catch(function (response) { deferredTask.reject(response); }); return deferredTask.promise; } return { call: call } }]) .factory('RamblersWalksAndEventsService', ["$log", "$rootScope", "$http", "$q", "$filter", "DateUtils", "RamblersHttpService", "LoggedInMemberService", "CommitteeReferenceData", function ($log, $rootScope, $http, $q, $filter, DateUtils, RamblersHttpService, LoggedInMemberService, CommitteeReferenceData) { var logger = $log.getInstance('RamblersWalksAndEventsService'); $log.logLevels['RamblersWalksAndEventsService'] = $log.LEVEL.OFF; function uploadRamblersWalks(data) { return RamblersHttpService.call('Upload Ramblers walks', 'POST', 'walksAndEventsManager/uploadWalks', data); } function listRamblersWalks() { return RamblersHttpService.call('List Ramblers walks', 'GET', 'walksAndEventsManager/listWalks'); } var walkDescriptionPrefix = function () { return RamblersHttpService.call('Ramblers description Prefix', 'GET', 'walksAndEventsManager/walkDescriptionPrefix'); }; var walkBaseUrl = function () { return RamblersHttpService.call('Ramblers walk url', 'GET', 'walksAndEventsManager/walkBaseUrl'); }; function exportWalksFileName() { return 'walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv' } function exportableWalks(walkExports) { return _.chain(walkExports) .filter(function (walkExport) { return walkExport.selected; }) .sortBy(function (walkExport) { return walkExport.walk.walkDate; }) .value(); } function exportWalks(walkExports, members) { return _(exportableWalks(walkExports)).pluck('walk').map(function (walk) { return walkToCsvRecord(walk, members) }); } function createWalksForExportPrompt(walks, members) { return listRamblersWalks() .then(updateWalksWithRamblersWalkData(walks)) .then(function (updatedWalks) { return returnWalksExport(updatedWalks, members); }); } function updateWalksWithRamblersWalkData(walks) { var unreferencedList = collectExistingRamblersIdsFrom(walks); logger.debug(unreferencedList.length, ' existing ramblers walk(s) found', unreferencedList); return function (ramblersWalksResponses) { var savePromises = []; _(ramblersWalksResponses.responseData).each(function (ramblersWalksResponse) { var foundWalk = _.find(walks, function (walk) { return DateUtils.asString(walk.walkDate, undefined, 'dddd, Do MMMM YYYY') === ramblersWalksResponse.ramblersWalkDate }); if (!foundWalk) { logger.debug('no match found for ramblersWalksResponse', ramblersWalksResponse); } else { unreferencedList = _.without(unreferencedList, ramblersWalksResponse.ramblersWalkId); if (foundWalk && foundWalk.ramblersWalkId !== ramblersWalksResponse.ramblersWalkId) { logger.debug('updating walk from', foundWalk.ramblersWalkId || 'empty', '->', ramblersWalksResponse.ramblersWalkId, 'on', $filter('displayDate')(foundWalk.walkDate)); foundWalk.ramblersWalkId = ramblersWalksResponse.ramblersWalkId; savePromises.push(foundWalk.$saveOrUpdate()) } else { logger.debug('no update required for walk', foundWalk.ramblersWalkId, foundWalk.walkDate, DateUtils.displayDay(foundWalk.walkDate)); } } }); if (unreferencedList.length > 0) { logger.debug('removing old ramblers walk(s)', unreferencedList, 'from existing walks'); _.chain(unreferencedList) .each(function (ramblersWalkId) { var walk = _.findWhere(walks, {ramblersWalkId: ramblersWalkId}); if (walk) { logger.debug('removing ramblers walk', walk.ramblersWalkId, 'from walk on', $filter('displayDate')(walk.walkDate)); delete walk.ramblersWalkId; savePromises.push(walk.$saveOrUpdate()) } }).value(); } return $q.all(savePromises).then(function () { return walks; }); } } function collectExistingRamblersIdsFrom(walks) { return _.chain(walks) .filter(function (walk) { return walk.ramblersWalkId; }) .map(function (walk) { return walk.ramblersWalkId; }) .value(); } function returnWalksExport(walks, members) { var todayValue = DateUtils.momentNowNoTime().valueOf(); return _.chain(walks) .filter(function (walk) { return (walk.walkDate >= todayValue) && walk.briefDescriptionAndStartPoint; }) .sortBy(function (walk) { return walk.walkDate; }) .map(function (walk) { return validateWalk(walk, members); }) .value(); } function uploadToRamblers(walkExports, members, notify) { notify.setBusy(); logger.debug('sourceData', walkExports); var deleteWalks = _.chain(exportableWalks(walkExports)).pluck('walk') .filter(function (walk) { return walk.ramblersWalkId; }).map(function (walk) { return walk.ramblersWalkId; }).value(); let rows = exportWalks(walkExports, members); let fileName = exportWalksFileName(); var data = { headings: exportColumnHeadings(), rows: rows, fileName: fileName, deleteWalks: deleteWalks, ramblersUser: LoggedInMemberService.loggedInMember().firstName }; logger.debug('exporting', data); notify.warning({ title: 'Ramblers walks upload', message: 'Uploading ' + rows.length + ' walk(s) to Ramblers...' }); return uploadRamblersWalks(data) .then(function (response) { notify.warning({ title: 'Ramblers walks upload', message: 'Upload of ' + rows.length + ' walk(s) to Ramblers has been submitted. Monitor the Walk upload audit tab for progress' }); logger.debug('success response data', response); notify.clearBusy(); return fileName; }) .catch(function (response) { logger.debug('error response data', response); notify.error({ title: 'Ramblers walks upload failed', message: response }); notify.clearBusy(); }); } function validateWalk(walk, members) { var walkValidations = []; if (_.isEmpty(walk)) { walkValidations.push('walk does not exist'); } else { if (_.isEmpty(walkTitle(walk))) walkValidations.push('title is missing'); if (_.isEmpty(walkDistanceMiles(walk))) walkValidations.push('distance is missing'); if (_.isEmpty(walk.startTime)) walkValidations.push('start time is missing'); if (walkStartTime(walk) === 'Invalid date') walkValidations.push('start time [' + walk.startTime + '] is invalid'); if (_.isEmpty(walk.grade)) walkValidations.push('grade is missing'); if (_.isEmpty(walk.longerDescription)) walkValidations.push('description is missing'); if (_.isEmpty(walk.postcode) && _.isEmpty(walk.gridReference)) walkValidations.push('both postcode and grid reference are missing'); if (_.isEmpty(walk.contactId)) { var contactIdMessage = LoggedInMemberService.allowWalkAdminEdits() ? 'this can be supplied for this walk on Walk Leader tab' : 'this will need to be setup for you by ' + CommitteeReferenceData.contactUsField('walks', 'fullName'); walkValidations.push('walk leader has no Ramblers contact Id setup on their member record (' + contactIdMessage + ')'); } if (_.isEmpty(walk.displayName) && _.isEmpty(walk.displayName)) walkValidations.push('displayName for walk leader is missing'); } return { walk: walk, walkValidations: walkValidations, publishedOnRamblers: walk && !_.isEmpty(walk.ramblersWalkId), selected: walk && walkValidations.length === 0 && _.isEmpty(walk.ramblersWalkId) } } var nearestTown = function (walk) { return walk.nearestTown ? 'Nearest Town is ' + walk.nearestTown : ''; }; function walkTitle(walk) { var walkDescription = []; if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint); return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. '); } function walkDescription(walk) { return replaceSpecialCharacters(walk.longerDescription); } function walkType(walk) { return walk.walkType || "Circular"; } function asString(value) { return value ? value : ''; } function contactDisplayName(walk) { return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : ''; } function contactIdLookup(walk, members) { if (walk.contactId) { return walk.contactId; } else { var member = _(members).find(function (member) { return member.$id() === walk.walkLeaderMemberId; }); var returnValue = member && member.contactId; logger.debug('contactId: for walkLeaderMemberId', walk.walkLeaderMemberId, '->', returnValue); return returnValue; } } function replaceSpecialCharacters(value) { return value ? value .replace("’", "'") .replace("é", "e") .replace("’", "'") .replace('…', '…') .replace('–', '–') .replace('’', '’') .replace('“', '“') : ''; } function walkDistanceMiles(walk) { return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : ''; } function walkStartTime(walk) { return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : ''; } function walkGridReference(walk) { return walk.gridReference ? walk.gridReference : ''; } function walkPostcode(walk) { return walk.gridReference ? '' : walk.postcode ? walk.postcode : ''; } function walkDate(walk) { return DateUtils.asString(walk.walkDate, undefined, 'DD-MM-YYYY'); } function exportColumnHeadings() { return [ "Date", "Title", "Description", "Linear or Circular", "Starting postcode", "Starting gridref", "Starting location details", "Show exact starting point", "Start time", "Show exact meeting point?", "Meeting time", "Restriction", "Difficulty", "Local walk grade", "Distance miles", "Contact id", "Contact display name" ]; } function walkToCsvRecord(walk, members) { return { "Date": walkDate(walk), "Title": walkTitle(walk), "Description": walkDescription(walk), "Linear or Circular": walkType(walk), "Starting postcode": walkPostcode(walk), "Starting gridref": walkGridReference(walk), "Starting location details": nearestTown(walk), "Show exact starting point": "Yes", "Start time": walkStartTime(walk), "Show exact meeting point?": "Yes", "Meeting time": walkStartTime(walk), "Restriction": "Public", "Difficulty": asString(walk.grade), "Local walk grade": asString(walk.grade), "Distance miles": walkDistanceMiles(walk), "Contact id": contactIdLookup(walk, members), "Contact display name": contactDisplayName(walk) }; } return { uploadToRamblers: uploadToRamblers, validateWalk: validateWalk, walkDescriptionPrefix: walkDescriptionPrefix, walkBaseUrl: walkBaseUrl, exportWalksFileName: exportWalksFileName, createWalksForExportPrompt: createWalksForExportPrompt, exportWalks: exportWalks, exportableWalks: exportableWalks, exportColumnHeadings: exportColumnHeadings } }] ); /* concatenated from client/src/app/js/resetPasswordController.js */ angular.module("ekwgApp") .controller("ResetPasswordController", ["$q", "$log", "$scope", "AuthenticationModalsService", "ValidationUtils", "LoggedInMemberService", "URLService", "Notifier", "userName", "message", "close", function ($q, $log, $scope, AuthenticationModalsService, ValidationUtils, LoggedInMemberService, URLService, Notifier, userName, message, close) { var logger = $log.getInstance('ResetPasswordController'); $log.logLevels['ResetPasswordController'] = $log.LEVEL.OFF; $scope.notify = {}; $scope.memberCredentials = {userName: userName}; var notify = Notifier($scope.notify); if (message) { notify.progress({ title: "Reset password", message: message }); } $scope.actions = { submittable: function () { var newPasswordPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPassword"); var newPasswordConfirmPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPasswordConfirm"); logger.info("notSubmittable: newPasswordConfirmPopulated", newPasswordConfirmPopulated, "newPasswordPopulated", newPasswordPopulated); return newPasswordPopulated && newPasswordConfirmPopulated; }, close: function () { close() }, resetPassword: function () { notify.showContactUs(false); notify.setBusy(); notify.progress({ busy: true, title: "Reset password", message: "Attempting reset of password for " + $scope.memberCredentials.userName }); LoggedInMemberService.resetPassword($scope.memberCredentials.userName, $scope.memberCredentials.newPassword, $scope.memberCredentials.newPasswordConfirm).then(function () { var loginResponse = LoggedInMemberService.loginResponse(); if (LoggedInMemberService.memberLoggedIn()) { notify.hide(); close(); if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) { return URLService.navigateTo("mailing-preferences"); } return true; } else { notify.showContactUs(true); notify.error({ title: "Reset password failed", message: loginResponse.alertMessage }); } return true; }); } } }] ); /* concatenated from client/src/app/js/resetPasswordFailedController.js */ angular.module('ekwgApp') .controller('ResetPasswordFailedController', ["$log", "$scope", "URLService", "Notifier", "CommitteeReferenceData", "close", function ($log, $scope, URLService, Notifier, CommitteeReferenceData, close) { var logger = $log.getInstance('ResetPasswordFailedController'); $log.logLevels['MemberAdminController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); logger.info("CommitteeReferenceData:", CommitteeReferenceData.ready); notify.showContactUs(true); notify.error({ continue: true, title: "Reset password failed", message: "The password reset link you followed has either expired or is invalid. Click Restart Forgot Password to try again" }); $scope.actions = { close: function () { close() }, forgotPassword: function () { URLService.navigateTo("forgot-password"); }, } }]); /* concatenated from client/src/app/js/services.js */ angular.module('ekwgApp') .factory('DateUtils', ["$log", function ($log) { var logger = $log.getInstance('DateUtils'); $log.logLevels['DateUtils'] = $log.LEVEL.OFF; var formats = { displayDateAndTime: 'ddd DD-MMM-YYYY, h:mm:ss a', displayDateTh: 'MMMM Do YYYY', displayDate: 'ddd DD-MMM-YYYY', displayDay: 'dddd MMMM D, YYYY', ddmmyyyyWithSlashes: 'DD/MM/YYYY', yyyymmdd: 'YYYYMMDD' }; function isDate(value) { return value && asMoment(value).isValid(); } function asMoment(dateValue, inputFormat) { return moment(dateValue, inputFormat).tz("Europe/London"); } function momentNow() { return asMoment(); } function asString(dateValue, inputFormat, outputFormat) { var returnValue = dateValue ? asMoment(dateValue, inputFormat).format(outputFormat) : undefined; logger.debug('asString: dateValue ->', dateValue, 'inputFormat ->', inputFormat, 'outputFormat ->', outputFormat, 'returnValue ->', returnValue); return returnValue; } function asValue(dateValue, inputFormat) { return asMoment(dateValue, inputFormat).valueOf(); } function nowAsValue() { return asMoment(undefined, undefined).valueOf(); } function mailchimpDate(dateValue) { return asString(dateValue, undefined, formats.ddmmyyyyWithSlashes); } function displayDateAndTime(dateValue) { return asString(dateValue, undefined, formats.displayDateAndTime); } function displayDate(dateValue) { return asString(dateValue, undefined, formats.displayDate); } function displayDay(dateValue) { return asString(dateValue, undefined, formats.displayDay); } function asValueNoTime(dateValue, inputFormat) { var returnValue = asMoment(dateValue, inputFormat).startOf('day').valueOf(); logger.debug('asValueNoTime: dateValue ->', dateValue, 'returnValue ->', returnValue, '->', displayDateAndTime(returnValue)); return returnValue; } function currentMemberBulkLoadDisplayDate() { return asString(momentNowNoTime().startOf('month'), undefined, formats.yyyymmdd); } function momentNowNoTime() { return asMoment().startOf('day'); } function convertDateFieldInObject(object, field) { var inputValue = object[field]; object[field] = convertDateField(inputValue); return object; } function convertDateField(inputValue) { if (inputValue) { var dateValue = asValueNoTime(inputValue); if (dateValue !== inputValue) { logger.debug('Converting date from', inputValue, '(' + displayDateAndTime(inputValue) + ') to', dateValue, '(' + displayDateAndTime(dateValue) + ')'); return dateValue; } else { logger.debug(inputValue, inputValue, 'is already in correct format'); return inputValue; } } else { logger.debug(inputValue, 'is not a date - no conversion'); return inputValue; } } return { formats: formats, displayDateAndTime: displayDateAndTime, displayDay: displayDay, displayDate: displayDate, mailchimpDate: mailchimpDate, convertDateFieldInObject: convertDateFieldInObject, convertDateField: convertDateField, isDate: isDate, asMoment: asMoment, nowAsValue: nowAsValue, momentNow: momentNow, momentNowNoTime: momentNowNoTime, asString: asString, asValue: asValue, asValueNoTime: asValueNoTime, currentMemberBulkLoadDisplayDate: currentMemberBulkLoadDisplayDate }; }]) .factory('DbUtils', ["$log", "DateUtils", "LoggedInMemberService", "AUDIT_CONFIG", function ($log, DateUtils, LoggedInMemberService, AUDIT_CONFIG) { var logger = $log.getInstance('DbUtilsLogger'); $log.logLevels['DbUtilsLogger'] = $log.LEVEL.OFF; function removeEmptyFieldsIn(obj) { _.each(obj, function (value, field) { logger.debug('processing', typeof(field), 'field', field, 'value', value); if (_.contains([null, undefined, ""], value)) { logger.debug('removing non-populated', typeof(field), 'field', field); delete obj[field]; } }); } function auditedSaveOrUpdate(resource, updateCallback, errorCallback) { if (AUDIT_CONFIG.auditSave) { if (resource.$id()) { resource.updatedDate = DateUtils.nowAsValue(); resource.updatedBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of existing document', resource); } else { resource.createdDate = DateUtils.nowAsValue(); resource.createdBy = LoggedInMemberService.loggedInMember().memberId; logger.debug('Auditing save of new document', resource); } } else { resource = DateUtils.convertDateFieldInObject(resource, 'createdDate'); logger.debug('Not auditing save of', resource); } return resource.$saveOrUpdate(updateCallback, updateCallback, errorCallback || updateCallback, errorCallback || updateCallback) } return { removeEmptyFieldsIn: removeEmptyFieldsIn, auditedSaveOrUpdate: auditedSaveOrUpdate, } }]) .factory('FileUtils', ["$log", "DateUtils", "URLService", "ContentMetaDataService", function ($log, DateUtils, URLService, ContentMetaDataService) { var logger = $log.getInstance('FileUtils'); $log.logLevels['FileUtils'] = $log.LEVEL.OFF; function basename(path) { return path.split(/[\\/]/).pop() } function path(path) { return path.split(basename(path))[0]; } function attachmentTitle(resource, container, resourceName) { return (resource && _.isEmpty(getFileNameData(resource, container)) ? 'Attach' : 'Replace') + ' ' + resourceName; } function getFileNameData(resource, container) { return container ? resource[container].fileNameData : resource.fileNameData; } function resourceUrl(resource, container, metaDataPathSegment) { var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function previewUrl(memberResource) { if (memberResource) { switch (memberResource.resourceType) { case "email": return memberResource.data.campaign.archive_url_long; case "file": return memberResource.data.campaign.archive_url_long; } } var fileNameData = getFileNameData(resource, container); return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : ''; } function resourceTitle(resource) { logger.debug('resourceTitle:resource =>', resource); return resource ? (DateUtils.asString(resource.resourceDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + (resource.data ? resource.data.fileNameData.title : "")) : ''; } function fileExtensionIs(fileName, extensions) { return _.contains(extensions, fileExtension(fileName)); } function fileExtension(fileName) { return fileName ? _.last(fileName.split('.')).toLowerCase() : ''; } function icon(resource, container) { var icon = 'icon-default.jpg'; var fileNameData = getFileNameData(resource, container); if (fileNameData && fileExtensionIs(fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) { icon = 'icon-' + fileExtension(fileNameData.awsFileName).substring(0, 3) + '.jpg'; } return "assets/images/ramblers/" + icon; } return { fileExtensionIs: fileExtensionIs, fileExtension: fileExtension, basename: basename, path: path, attachmentTitle: attachmentTitle, resourceUrl: resourceUrl, resourceTitle: resourceTitle, icon: icon } }]) .factory('StringUtils', ["DateUtils", "$filter", function (DateUtils, $filter) { function replaceAll(find, replace, str) { return str ? str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace) : str; } function stripLineBreaks(str, andTrim) { var replacedValue = str.replace(/(\r\n|\n|\r)/gm, ''); return andTrim && replacedValue ? replacedValue.trim() : replacedValue; } function left(str, chars) { return str.substr(0, chars); } function formatAudit(who, when, members) { var by = who ? 'by ' + $filter('memberIdToFullName')(who, members) : ''; return (who || when) ? by + (who && when ? ' on ' : '') + DateUtils.displayDateAndTime(when) : '(not audited)'; } return { left: left, replaceAll: replaceAll, stripLineBreaks: stripLineBreaks, formatAudit: formatAudit } }]).factory('ValidationUtils', function () { function fieldPopulated(object, path) { return (_.property(path)(object) || "").length > 0; } return { fieldPopulated: fieldPopulated, } }) .factory('NumberUtils', ["$log", function ($log) { var logger = $log.getInstance('NumberUtils'); $log.logLevels['NumberUtils'] = $log.LEVEL.OFF; function sumValues(items, fieldName) { if (!items) return 0; return _.chain(items).pluck(fieldName).reduce(function (memo, num) { return memo + asNumber(num); }, 0).value(); } function generateUid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } function asNumber(numberString, decimalPlaces) { if (!numberString) return 0; var isNumber = typeof numberString === 'number'; if (isNumber && !decimalPlaces) return numberString; var number = isNumber ? numberString : parseFloat(numberString.replace(/[^\d\.\-]/g, "")); if (isNaN(number)) return 0; var returnValue = (decimalPlaces) ? (parseFloat(number).toFixed(decimalPlaces)) / 1 : number; logger.debug('asNumber:', numberString, decimalPlaces, '->', returnValue); return returnValue; } return { asNumber: asNumber, sumValues: sumValues, generateUid: generateUid }; }]) .factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('contentMetaData'); }]) .factory('ConfigData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('config'); }]) .factory('Config', ["$log", "ConfigData", "ErrorMessageService", function ($log, ConfigData, ErrorMessageService) { var logger = $log.getInstance('Config'); $log.logLevels['Config'] = $log.LEVEL.OFF; function getConfig(key, defaultOnEmpty) { logger.debug('getConfig:', key, 'defaultOnEmpty:', defaultOnEmpty); var queryObject = {}; queryObject[key] = {$exists: true}; return ConfigData.query(queryObject, {limit: 1}) .then(function (results) { if (results && results.length > 0) { return results[0]; } else { queryObject[key] = {}; return new ConfigData(defaultOnEmpty || queryObject); } }, function (response) { throw new Error('Query of ' + key + ' config failed: ' + response); }); } function saveConfig(key, config, saveCallback, errorSaveCallback) { logger.debug('saveConfig:', key); if (_.has(config, key)) { return config.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback || saveCallback, errorSaveCallback || saveCallback); } else { throw new Error('Attempt to save ' + ErrorMessageService.stringify(key) + ' config when ' + ErrorMessageService.stringify(key) + ' parent key not present in data: ' + ErrorMessageService.stringify(config)); } } return { getConfig: getConfig, saveConfig: saveConfig } }]) .factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('expenseClaims'); }]) .factory('RamblersUploadAudit', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('ramblersUploadAudit'); }]) .factory('ErrorTransformerService', ["ErrorMessageService", function (ErrorMessageService) { function transform(errorResponse) { var message = ErrorMessageService.stringify(errorResponse); var duplicate = s.include(errorResponse, 'duplicate'); if (duplicate) { message = 'Duplicate data was detected. A member record must have a unique Contact Email, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.'; } return {duplicate: duplicate, message: message} } return {transform: transform} }]) .factory('ErrorMessageService', function () { function stringify(message) { return _.isObject(message) ? JSON.stringify(message, censor(message)) : message; } function censor(censor) { var i = 0; return function (key, value) { if (i !== 0 && typeof(censor) === 'object' && typeof(value) === 'object' && censor === value) return '[Circular]'; if (i >= 29) // seems to be a hard maximum of 30 serialized objects? return '[Unknown]'; ++i; // so we know we aren't using the original object anymore return value; } } return { stringify: stringify } }); /* concatenated from client/src/app/js/siteEditActions.js */ angular.module('ekwgApp') .component('siteEditActions', { templateUrl: 'partials/components/site-edit.html', controller: ["$log", "SiteEditService", function ($log, SiteEditService){ var logger = $log.getInstance('SiteEditActionsController'); $log.logLevels['SiteEditActionsController'] = $log.LEVEL.OFF; var ctrl = this; logger.info("initialised with SiteEditService.active()", SiteEditService.active()); ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false}; ctrl.editSiteActive = function () { return SiteEditService.active() ? "active" : ""; }; ctrl.editSiteCaption = function () { return SiteEditService.active() ? "editing site" : "edit site"; }; ctrl.toggleEditSite = function () { SiteEditService.toggle(); }; }], bindings: { name: '@', description: '@', } }); /* concatenated from client/src/app/js/siteEditService.js */ angular.module('ekwgApp') .factory('SiteEditService', ["$log", "$cookieStore", "$rootScope", function ($log, $cookieStore, $rootScope) { var logger = $log.getInstance('SiteEditService'); $log.logLevels['SiteEditService'] = $log.LEVEL.OFF; function active() { var active = Boolean($cookieStore.get("editSite")); logger.debug("active:", active); return active; } function toggle() { var priorState = active(); var newState = !priorState; logger.debug("toggle:priorState", priorState, "newState", newState); $cookieStore.put("editSite", newState); return $rootScope.$broadcast("editSite", newState); } return { active: active, toggle: toggle } }]); /* concatenated from client/src/app/js/socialEventNotifications.js */ angular.module('ekwgApp') .controller('SocialEventNotificationsController', ["MAILCHIMP_APP_CONSTANTS", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "socialEvent", "close", function (MAILCHIMP_APP_CONSTANTS, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams, $location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService, ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, CommitteeReferenceData, socialEvent, close) { var logger = $log.getInstance('SocialEventNotificationsController'); $log.logLevels['SocialEventNotificationsController'] = $log.LEVEL.OFF; $scope.notify = {}; var notify = Notifier($scope.notify); notify.setBusy(); logger.debug('created with social event', socialEvent); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.destinationType = ''; $scope.members = []; $scope.selectableRecipients = []; $scope.committeeFiles = []; $scope.alertMessages = []; $scope.allowConfirmDelete = false; $scope.latestYearOpen = true; $scope.roles = {signoff: [], replyTo: []}; $scope.showAlertMessage = function () { return ($scope.notify.alert.class === 'alert-danger') || $scope.userEdits.sendInProgress; }; function initialiseNotification(socialEvent) { if (socialEvent) { $scope.socialEvent = socialEvent; onFirstNotificationOnly(); forEveryNotification(); } else { logger.error('no socialEvent - problem!'); } function onFirstNotificationOnly() { if (!$scope.socialEvent.notification) { $scope.socialEvent.notification = { destinationType: 'all-ekwg-social', recipients: [], addresseeType: 'Hi *|FNAME|*,', items: { title: {include: true}, notificationText: {include: true, value: ''}, description: {include: true}, attendees: {include: socialEvent.attendees.length > 0}, attachment: {include: socialEvent.attachment}, replyTo: { include: $scope.socialEvent.displayName, value: $scope.socialEvent.displayName ? 'organiser' : 'social' }, signoffText: { include: true, value: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,' } } }; logger.debug('onFirstNotificationOnly - creating $scope.socialEvent.notification ->', $scope.socialEvent.notification); } } function forEveryNotification() { $scope.socialEvent.notification.items.signoffAs = { include: true, value: loggedOnRole().type || 'social' }; logger.debug('forEveryNotification - $scope.socialEvent.notification.signoffAs ->', $scope.socialEvent.notification.signoffAs); } } function loggedOnRole() { var memberId = LoggedInMemberService.loggedInMember().memberId; var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) { return role.memberId === memberId }); logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData); return loggedOnRoleData || {}; } function roleForType(type) { var role = _($scope.roles.replyTo).find(function (role) { return role.type === type; }); logger.debug('roleForType for', type, '->', role); return role; } function initialiseRoles() { $scope.roles.signoff = CommitteeReferenceData.contactUsRolesAsArray(); $scope.roles.replyTo = _.clone($scope.roles.signoff); if ($scope.socialEvent.eventContactMemberId) { $scope.roles.replyTo.unshift({ type: 'organiser', fullName: $scope.socialEvent.displayName, memberId: $scope.socialEvent.eventContactMemberId, description: 'Organiser (' + $scope.socialEvent.displayName + ')', email: $scope.socialEvent.contactEmail }); } logger.debug('initialiseRoles -> $scope.roles ->', $scope.roles); } $scope.formattedText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.notificationText.value); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? URLService.baseUrl() + $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.editAllSocialRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.userEdits.socialList(); }; $scope.editAttendeeRecipients = function () { $scope.socialEvent.notification.destinationType = 'custom'; $scope.socialEvent.notification.recipients = $scope.socialEvent.attendees; }; $scope.clearRecipients = function () { $scope.socialEvent.notification.recipients = []; }; $scope.formattedSignoffText = function () { return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.signoffText.value); }; $scope.attendeeList = function () { return _($scope.socialEvent.notification && $scope.socialEvent.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; $scope.memberGrouping = function (member) { return member.memberGrouping; }; function toSelectMember(member) { var memberGrouping; var order; if (member.socialMember && member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Subscribed to social emails'; order = 0; } else if (member.socialMember && !member.mailchimpLists.socialEvents.subscribed) { memberGrouping = 'Not subscribed to social emails'; order = 1; } else if (!member.socialMember) { memberGrouping = 'Not a social member'; order = 2; } else { memberGrouping = 'Unexpected state'; order = 3; } return { id: member.$id(), order: order, memberGrouping: memberGrouping, text: $filter('fullNameWithAlias')(member) }; } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) { $scope.members = members; logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members'); $scope.selectableRecipients = _.chain(members) .map(toSelectMember) .sortBy(function (member) { return member.order + member.text }) .value(); logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients'); notify.clearBusy(); }); } } $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.userEdits = { sendInProgress: false, cancelFlow: false, socialList: function () { return _.chain($scope.members) .filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED) .map(toSelectMember).value(); }, replyToRole: function () { return _($scope.roles.replyTo).find(function (role) { return role.type === $scope.socialEvent.notification.items.replyTo.value; }); }, notReady: function () { return $scope.members.length === 0 || $scope.userEdits.sendInProgress; } }; $scope.cancelSendNotification = function () { close(); $('#social-event-dialog').modal('show'); }; $scope.completeInMailchimp = function () { notify.warning({ title: 'Complete in Mailchimp', message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp' }); $scope.confirmSendNotification(true); }; $scope.confirmSendNotification = function (dontSend) { notify.setBusy(); var campaignName = $scope.socialEvent.briefDescription; logger.debug('sendSocialNotification:notification->', $scope.socialEvent.notification); notify.progress({title: campaignName, message: 'preparing and sending notification'}); $scope.userEdits.sendInProgress = true; $scope.userEdits.cancelFlow = false; function getTemplate() { return $templateRequest($sce.getTrustedResourceUrl('partials/socialEvents/social-notification.html')) } return $q.when(createOrSaveMailchimpSegment()) .then(getTemplate) .then(renderTemplateContent) .then(populateContentSections) .then(sendEmailCampaign) .then(saveSocialEvent) .then(notifyEmailSendComplete) .catch(handleError); function handleError(errorResponse) { $scope.userEdits.sendInProgress = false; notify.error({ title: 'Your notification could not be sent', message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '') }); notify.clearBusy(); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction($scope); $timeout(function () { $scope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function populateContentSections(notificationText) { logger.debug('populateContentSections -> notificationText', notificationText); return { sections: { notification_text: notificationText } }; } function writeSegmentResponseDataToEvent(segmentResponse) { $scope.socialEvent.mailchimp = { segmentId: segmentResponse.segment.id }; if (segmentResponse.members) $scope.socialEvent.mailchimp.members = segmentResponse.members; } function createOrSaveMailchimpSegment() { var members = segmentMembers(); if (members.length > 0) { return MailchimpSegmentService.saveSegment('socialEvents', $scope.socialEvent.mailchimp, members, MailchimpSegmentService.formatSegmentName($scope.socialEvent.briefDescription), $scope.members) .then(writeSegmentResponseDataToEvent) .catch(handleError); } else { logger.debug('not saving segment data as destination type is whole mailing list ->', $scope.socialEvent.notification.destinationType); return true; } } function segmentMembers() { switch ($scope.socialEvent.notification.destinationType) { case 'attendees': return $scope.socialEvent.attendees; case 'custom': return $scope.socialEvent.notification.recipients; default: return []; } } function sendEmailCampaign(contentSections) { var replyToRole = roleForType($scope.socialEvent.notification.items.replyTo.value || 'social'); var otherOptions = ($scope.socialEvent.notification.items.replyTo.include && replyToRole.fullName && replyToRole.email) ? { from_name: replyToRole.fullName, from_email: replyToRole.email } : {}; notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName)); logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.socialEvents.campaignId; switch ($scope.socialEvent.notification.destinationType) { case 'all-ekwg-social': logger.debug('about to replicateAndSendWithOptions to all-ekwg-social with campaignName', campaignName, 'campaign Id', campaignId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); default: if (!$scope.socialEvent.mailchimp) notify.warning('Cant send campaign due to previous request failing. This could be due to network problems - please try this again'); var segmentId = $scope.socialEvent.mailchimp.segmentId; logger.debug('about to replicateAndSendWithOptions to social with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId, otherSegmentOptions: otherOptions, dontSend: dontSend }).then(openInMailchimpIf(dontSend)); } }) } function openInMailchimpIf(dontSend) { return function (replicateCampaignResponse) { logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend); if (dontSend) { return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank'); } else { return true; } } } function saveSocialEvent() { return $scope.socialEvent.$saveOrUpdate(); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful.', false); $scope.userEdits.sendInProgress = false; if (!$scope.userEdits.cancelFlow) { close(); } notify.clearBusy(); } }; refreshMembers(); initialiseNotification(socialEvent); initialiseRoles(CommitteeReferenceData); }] ); /* concatenated from client/src/app/js/socialEvents.js */ angular.module('ekwgApp') .factory('SocialEventsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEvents'); }]) .factory('SocialEventAttendeeService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('socialEventAttendees'); }]) .controller('SocialEventsController', ["$routeParams", "$log", "$q", "$scope", "$filter", "URLService", "Upload", "SocialEventsService", "SiteEditService", "SocialEventAttendeeService", "LoggedInMemberService", "MemberService", "AWSConfig", "ContentMetaDataService", "DateUtils", "MailchimpSegmentService", "ClipboardService", "Notifier", "EKWGFileUpload", "CommitteeReferenceData", "ModalService", function ($routeParams, $log, $q, $scope, $filter, URLService, Upload, SocialEventsService, SiteEditService, SocialEventAttendeeService, LoggedInMemberService, MemberService, AWSConfig, ContentMetaDataService, DateUtils, MailchimpSegmentService, ClipboardService, Notifier, EKWGFileUpload, CommitteeReferenceData, ModalService) { $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, longerDescriptionPreview: true, socialEventLink: function (socialEvent) { return socialEvent && socialEvent.$id() ? URLService.notificationHref({ type: "socialEvent", area: "social", id: socialEvent.$id() }) : undefined; } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; var logger = $log.getInstance('SocialEventsController'); $log.logLevels['SocialEventsController'] = $log.LEVEL.OFF; var notify = Notifier($scope); $scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents'); $scope.selectMembers = []; $scope.display = {attendees: []}; $scope.socialEventsDetailProgrammeOpen = true; $scope.socialEventsBriefProgrammeOpen = true; $scope.socialEventsInformationOpen = true; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); applyAllowEdits('controllerInitialisation'); $scope.eventDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.eventDateCalendar.opened = true; } }; $scope.$on('memberLoginComplete', function () { applyAllowEdits('memberLoginComplete'); refreshMembers(); refreshSocialEvents(); }); $scope.$on('memberLogoutComplete', function () { applyAllowEdits('memberLogoutComplete'); }); $scope.$on('editSite', function () { applyAllowEdits('editSite'); }); $scope.addSocialEvent = function () { showSocialEventDialog(new SocialEventsService({eventDate: $scope.todayValue, attendees: []}), 'Add New'); }; $scope.viewSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'View'); }; $scope.editSocialEvent = function (socialEvent) { showSocialEventDialog(socialEvent, 'Edit Existing'); }; $scope.deleteSocialEventDetails = function () { $scope.allowDelete = false; $scope.allowConfirmDelete = true; }; $scope.cancelSocialEventDetails = function () { hideSocialEventDialogAndRefreshSocialEvents(); }; $scope.saveSocialEventDetails = function () { $q.when(notify.progress({title: 'Save in progress', message: 'Saving social event'}, true)) .then(prepareToSave, notify.error, notify.progress) .then(saveSocialEvent, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; function prepareToSave() { DateUtils.convertDateFieldInObject($scope.currentSocialEvent, 'eventDate'); } function saveSocialEvent() { return $scope.currentSocialEvent.$saveOrUpdate(hideSocialEventDialogAndRefreshSocialEvents, hideSocialEventDialogAndRefreshSocialEvents); } $scope.confirmDeleteSocialEventDetails = function () { $q.when(notify.progress('Deleting social event', true)) .then(deleteMailchimpSegment, notify.error, notify.progress) .then(removeSocialEventHideSocialEventDialogAndRefreshSocialEvents, notify.error, notify.progress) .then(notify.clearBusy, notify.error, notify.progress) .catch(notify.error); }; var deleteMailchimpSegment = function () { if ($scope.currentSocialEvent.mailchimp && $scope.currentSocialEvent.mailchimp.segmentId) { return MailchimpSegmentService.deleteSegment('socialEvents', $scope.currentSocialEvent.mailchimp.segmentId); } }; var removeSocialEventHideSocialEventDialogAndRefreshSocialEvents = function () { $scope.currentSocialEvent.$remove(hideSocialEventDialogAndRefreshSocialEvents) }; $scope.copyDetailsToNewSocialEvent = function () { var copiedSocialEvent = new SocialEventsService($scope.currentSocialEvent); delete copiedSocialEvent._id; delete copiedSocialEvent.mailchimp; DateUtils.convertDateFieldInObject(copiedSocialEvent, 'eventDate'); showSocialEventDialog(copiedSocialEvent, 'Copy Existing'); notify.success({ title: 'Existing social event copied!', message: 'Make changes here and save to create a new social event.' }); }; $scope.selectMemberContactDetails = function () { var socialEvent = $scope.currentSocialEvent; var memberId = socialEvent.eventContactMemberId; if (memberId === null) { delete socialEvent.eventContactMemberId; delete socialEvent.displayName; delete socialEvent.contactPhone; delete socialEvent.contactEmail; // console.log('deleted contact details from', socialEvent); } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); socialEvent.displayName = selectedMember.displayName; socialEvent.contactPhone = selectedMember.mobileNumber; socialEvent.contactEmail = selectedMember.email; // console.log('set contact details on', socialEvent); } }; $scope.dataQueryParameters = { query: '', selectType: '1', newestFirst: 'false' }; $scope.removeAttachment = function () { delete $scope.currentSocialEvent.attachment; delete $scope.currentSocialEvent.attachmentTitle; $scope.uploadedFile = undefined; }; $scope.resetMailchimpData = function () { delete $scope.currentSocialEvent.mailchimp; }; $scope.addOrReplaceAttachment = function () { $('#hidden-input').click(); }; $scope.attachmentTitle = function (socialEvent) { return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : ''; }; $scope.attachmentUrl = function (socialEvent) { return socialEvent && socialEvent.attachment ? $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : ''; }; $scope.onFileSelect = function (file) { if (file) { $scope.uploadedFile = file; EKWGFileUpload.onFileSelect(file, notify, 'socialEvents').then(function (fileNameData) { $scope.currentSocialEvent.attachment = fileNameData; }); } }; function allowSummaryView() { return (LoggedInMemberService.allowSocialAdminEdits() || !LoggedInMemberService.allowSocialDetailView()); } function applyAllowEdits(event) { $scope.allowDelete = false; $scope.allowConfirmDelete = false; $scope.allowDetailView = LoggedInMemberService.allowSocialDetailView(); $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowCopy = LoggedInMemberService.allowSocialAdminEdits(); $scope.allowContentEdits = SiteEditService.active() && LoggedInMemberService.allowContentEdits(); $scope.allowSummaryView = allowSummaryView(); } $scope.showLoginTooltip = function () { return !LoggedInMemberService.memberLoggedIn(); }; $scope.login = function () { if (!LoggedInMemberService.memberLoggedIn()) { URLService.navigateTo("login"); } }; function showSocialEventDialog(socialEvent, socialEventEditMode) { $scope.uploadedFile = undefined; $scope.showAlert = false; $scope.allowConfirmDelete = false; if (!socialEvent.attendees) socialEvent.attendees = []; $scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits(); var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(socialEventEditMode, 'Edit'); $scope.allowCopy = existingRecordEditEnabled; $scope.allowDelete = existingRecordEditEnabled; $scope.socialEventEditMode = socialEventEditMode; $scope.currentSocialEvent = socialEvent; $('#social-event-dialog').modal('show'); } $scope.attendeeCaption = function () { return $scope.currentSocialEvent && $scope.currentSocialEvent.attendees.length + ($scope.currentSocialEvent.attendees.length === 1 ? ' member is attending' : ' members are attending'); }; $scope.attendeeList = function () { return _($scope.display.attendees) .sortBy(function (attendee) { return attendee.text; }).map(function (attendee) { return attendee.text; }).join(', '); }; function hideSocialEventDialogAndRefreshSocialEvents() { $('#social-event-dialog').modal('hide'); refreshSocialEvents(); } function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) { MemberService.allLimitedFields(MemberService.filterFor.SOCIAL_MEMBERS).then(function (members) { $scope.members = members; logger.debug('found', $scope.members.length, 'members'); $scope.selectMembers = _($scope.members).map(function (member) { return {id: member.$id(), text: $filter('fullNameWithAlias')(member)}; }) }); } } $scope.sendSocialEventNotification = function () { $('#social-event-dialog').modal('hide'); ModalService.showModal({ templateUrl: "partials/socialEvents/send-notification-dialog.html", controller: "SocialEventNotificationsController", preClose: function (modal) { logger.debug('preClose event with modal', modal); modal.element.modal('hide'); }, inputs: { socialEvent: $scope.currentSocialEvent } }).then(function (modal) { logger.debug('modal event with modal', modal); modal.element.modal(); modal.close.then(function (result) { logger.debug('close event with result', result); }); }) }; function refreshSocialEvents() { if (URLService.hasRouteParameter('socialEventId')) { return SocialEventsService.getById($routeParams.socialEventId) .then(function (socialEvent) { if (!socialEvent) notify.error('Social event could not be found'); $scope.socialEvents = [socialEvent]; }); } else { var socialEvents = LoggedInMemberService.allowSocialDetailView() ? SocialEventsService.all() : SocialEventsService.all({ fields: { briefDescription: 1, eventDate: 1, thumbnail: 1 } }); socialEvents.then(function (socialEvents) { $scope.socialEvents = _.chain(socialEvents) .filter(function (socialEvent) { return socialEvent.eventDate >= $scope.todayValue }) .sortBy(function (socialEvent) { return socialEvent.eventDate; }) .value(); logger.debug('found', $scope.socialEvents.length, 'social events'); }); } } $q.when(refreshSocialEvents()) .then(refreshMembers) .then(refreshImages); function refreshImages() { ContentMetaDataService.getMetaData('imagesSocialEvents').then(function (contentMetaData) { $scope.interval = 5000; $scope.slides = contentMetaData.files; logger.debug('found', $scope.slides.length, 'slides'); }, function (response) { throw new Error(response); }); } }]); /* concatenated from client/src/app/js/urlServices.js */ angular.module('ekwgApp') .factory('URLService', ["$window", "$rootScope", "$timeout", "$location", "$routeParams", "$log", "PAGE_CONFIG", "ContentMetaDataService", function ($window, $rootScope, $timeout, $location, $routeParams, $log, PAGE_CONFIG, ContentMetaDataService) { var logger = $log.getInstance('URLService'); $log.logLevels['URLService'] = $log.LEVEL.OFF; function baseUrl(optionalUrl) { return _.first((optionalUrl || $location.absUrl()).split('/#')); } function relativeUrl(optionalUrl) { var relativeUrlValue = _.last((optionalUrl || $location.absUrl()).split("/#")); logger.debug("relativeUrlValue:", relativeUrlValue); return relativeUrlValue; } function relativeUrlFirstSegment(optionalUrl) { var relativeUrlValue = relativeUrl(optionalUrl); var index = relativeUrlValue.indexOf("/", 1); var relativeUrlFirstSegment = index === -1 ? relativeUrlValue : relativeUrlValue.substring(0, index); logger.debug("relativeUrl:", relativeUrlValue, "relativeUrlFirstSegment:", relativeUrlFirstSegment); return relativeUrlFirstSegment; } function resourceUrl(area, type, id) { return baseUrl() + '/#/' + area + '/' + type + 'Id/' + id; } function notificationHref(ctrl) { var href = (ctrl.name) ? resourceUrlForAWSFileName(ctrl.name) : resourceUrl(ctrl.area, ctrl.type, ctrl.id); logger.debug("href:", href); return href; } function resourceUrlForAWSFileName(fileName) { return baseUrl() + ContentMetaDataService.baseUrl(fileName); } function hasRouteParameter(parameter) { var hasRouteParameter = !!($routeParams[parameter]); logger.debug('hasRouteParameter', parameter, hasRouteParameter); return hasRouteParameter; } function isArea(areas) { logger.debug('isArea:areas', areas, '$routeParams', $routeParams); return _.some(_.isArray(areas) ? areas : [areas], function (area) { var matched = area === $routeParams.area; logger.debug('isArea', area, 'matched =', matched); return matched; }); } let pageUrl = function (page) { var pageOrEmpty = (page ? page : ""); return s.startsWith(pageOrEmpty, "/") ? pageOrEmpty : "/" + pageOrEmpty; }; function navigateTo(page, area) { $timeout(function () { var url = pageUrl(page) + (area ? "/" + area : ""); logger.info("navigating to page:", page, "area:", area, "->", url); $location.path(url); logger.info("$location.path is now", $location.path()) }, 1); } function navigateBackToLastMainPage() { var lastPage = _.chain($rootScope.pageHistory.reverse()) .find(function (page) { return _.contains(_.values(PAGE_CONFIG.mainPages), relativeUrlFirstSegment(page)); }) .value(); logger.info("navigateBackToLastMainPage:$rootScope.pageHistory", $rootScope.pageHistory, "lastPage->", lastPage); navigateTo(lastPage || "/") } function noArea() { return !$routeParams.area; } function setRoot() { return navigateTo(); } function area() { return $routeParams.area; } return { setRoot: setRoot, navigateBackToLastMainPage: navigateBackToLastMainPage, navigateTo: navigateTo, hasRouteParameter: hasRouteParameter, noArea: noArea, isArea: isArea, baseUrl: baseUrl, area: area, resourceUrlForAWSFileName: resourceUrlForAWSFileName, notificationHref: notificationHref, resourceUrl: resourceUrl, relativeUrlFirstSegment: relativeUrlFirstSegment, relativeUrl: relativeUrl } }]); /* concatenated from client/src/app/js/walkNotifications.js */ angular.module('ekwgApp') .controller('WalkNotificationsController', ["$log", "$scope", "WalkNotificationService", "RamblersWalksAndEventsService", function ($log, $scope, WalkNotificationService, RamblersWalksAndEventsService) { $scope.dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.walk, $scope.status); $scope.validateWalk = RamblersWalksAndEventsService.validateWalk($scope.walk); RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); }]) .factory('WalkNotificationService', ["$sce", "$log", "$timeout", "$filter", "$location", "$rootScope", "$q", "$compile", "$templateRequest", "$routeParams", "$cookieStore", "URLService", "MemberService", "MailchimpConfig", "MailchimpSegmentService", "WalksReferenceService", "MemberAuditService", "RamblersWalksAndEventsService", "MailchimpCampaignService", "LoggedInMemberService", "DateUtils", function ($sce, $log, $timeout, $filter, $location, $rootScope, $q, $compile, $templateRequest, $routeParams, $cookieStore, URLService, MemberService, MailchimpConfig, MailchimpSegmentService, WalksReferenceService, MemberAuditService, RamblersWalksAndEventsService, MailchimpCampaignService, LoggedInMemberService, DateUtils) { var logger = $log.getInstance('WalkNotificationService'); var noLogger = $log.getInstance('WalkNotificationServiceNoLog'); $log.logLevels['WalkNotificationService'] = $log.LEVEL.OFF; $log.logLevels['WalkNotificationServiceNoLog'] = $log.LEVEL.OFF; var basePartialsUrl = 'partials/walks/notifications'; var auditedFields = ['grade', 'walkDate', 'walkType', 'startTime', 'briefDescriptionAndStartPoint', 'longerDescription', 'distance', 'nearestTown', 'gridReference', 'meetupEventUrl', 'meetupEventTitle', 'osMapsRoute', 'osMapsTitle', 'postcode', 'walkLeaderMemberId', 'contactPhone', 'contactEmail', 'contactId', 'displayName', 'ramblersWalkId']; function currentDataValues(walk) { return _.compactObject(_.pick(walk, auditedFields)); } function previousDataValues(walk) { var event = latestWalkEvent(walk); return event && event.data || {}; } function latestWalkEvent(walk) { return (walk.events && _.last(walk.events)) || {}; } function eventsLatestFirst(walk) { var events = walk.events && _(walk.events).clone().reverse() || []; noLogger.info('eventsLatestFirst:', events); return events; } function latestEventWithStatusChange(walk) { return _(eventsLatestFirst(walk)).find(function (event) { return (WalksReferenceService.toEventType(event.eventType) || {}).statusChange; }) || {}; } function dataAuditDelta(walk, status) { if (!walk) return {}; var currentData = currentDataValues(walk); var previousData = previousDataValues(walk); var changedItems = calculateChangedItems(); var eventExists = latestEventWithStatusChangeIs(walk, status); var dataChanged = changedItems.length > 0; var dataAuditDelta = { currentData: currentData, previousData: previousData, changedItems: changedItems, eventExists: eventExists, dataChanged: dataChanged, notificationRequired: dataChanged || !eventExists, eventType: dataChanged && eventExists ? WalksReferenceService.eventTypes.walkDetailsUpdated.eventType : status }; dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta', dataAuditDelta); return dataAuditDelta; function calculateChangedItems() { return _.compact(_.map(auditedFields, function (key) { var currentValue = currentData[key]; var previousValue = previousData[key]; noLogger.info('auditing', key, 'now:', currentValue, 'previous:', previousValue); if (previousValue !== currentValue) return { fieldName: key, previousValue: previousValue, currentValue: currentValue } })); } } function latestEventWithStatusChangeIs(walk, eventType) { if (!walk) return false; return latestEventWithStatusChange(walk).eventType === toEventTypeValue(eventType); } function toEventTypeValue(eventType) { return _.has(eventType, 'eventType') ? eventType.eventType : eventType; } function latestEventForEventType(walk, eventType) { if (walk) { var eventTypeString = toEventTypeValue(eventType); return eventsLatestFirst(walk).find(function (event) { return event.eventType === eventTypeString; }); } } function populateWalkApprovedEventsIfRequired(walks) { return _(walks).map(function (walk) { if (_.isArray(walk.events)) { return walk } else { var event = createEventIfRequired(walk, WalksReferenceService.eventTypes.approved.eventType, 'Marking past walk as approved'); writeEventIfRequired(walk, event); walk.$saveOrUpdate(); return walk; } }) } function createEventIfRequired(walk, status, reason) { var dataAuditDeltaInfo = dataAuditDelta(walk, status); logger.debug('createEventIfRequired:', dataAuditDeltaInfo); if (dataAuditDeltaInfo.notificationRequired) { var event = { "date": DateUtils.nowAsValue(), "memberId": LoggedInMemberService.loggedInMember().memberId, "data": dataAuditDeltaInfo.currentData, "eventType": dataAuditDeltaInfo.eventType }; if (reason) event.reason = reason; if (dataAuditDeltaInfo.dataChanged) event.description = 'Changed: ' + $filter('toAuditDeltaChangedItems')(dataAuditDeltaInfo.changedItems); logger.debug('createEventIfRequired: event created:', event); return event; } else { logger.debug('createEventIfRequired: event creation not necessary'); } } function writeEventIfRequired(walk, event) { if (event) { logger.debug('writing event', event); if (!_.isArray(walk.events)) walk.events = []; walk.events.push(event); } else { logger.debug('no event to write'); } } function createEventAndSendNotifications(members, walk, status, notify, sendNotification, reason) { notify.setBusy(); var event = createEventIfRequired(walk, status, reason); var notificationScope = $rootScope.$new(); notificationScope.walk = walk; notificationScope.members = members; notificationScope.event = event; notificationScope.status = status; var eventType = event && WalksReferenceService.toEventType(event.eventType); if (event && sendNotification) { return sendNotificationsToAllRoles() .then(function () { return writeEventIfRequired(walk, event); }) .then(function () { return true; }) .catch(function (error) { logger.debug('failed with error', error); return notify.error({title: error.message, message: error.error}) }); } else { logger.debug('Not sending notification'); return $q.when(writeEventIfRequired(walk, event)) .then(function () { return false; }); } function renderTemplateContent(templateData) { var task = $q.defer(); var templateFunction = $compile(templateData); var templateElement = templateFunction(notificationScope); $timeout(function () { notificationScope.$digest(); task.resolve(templateElement.html()); }); return task.promise; } function sendNotificationsToAllRoles() { return LoggedInMemberService.getMemberForMemberId(walk.walkLeaderMemberId) .then(function (member) { logger.debug('sendNotification:', 'memberId', walk.walkLeaderMemberId, 'member', member); var walkLeaderName = $filter('fullNameWithAlias')(member); var walkDate = $filter('displayDate')(walk.walkDate); return $q.when(notify.progress('Preparing to send email notifications')) .then(sendLeaderNotifications, notify.error, notify.progress) .then(sendCoordinatorNotifications, notify.error, notify.progress); function sendLeaderNotifications() { if (eventType.notifyLeader) return sendNotificationsTo({ templateUrl: templateForEvent('leader', eventType.eventType), memberIds: [walk.walkLeaderMemberId], segmentType: 'walkLeader', segmentName: MailchimpSegmentService.formatSegmentName('Walk leader notifications for ' + walkLeaderName), emailSubject: 'Your walk on ' + walkDate, destination: 'walk leader' }); logger.debug('not sending leader notification'); } function sendCoordinatorNotifications() { if (eventType.notifyCoordinator) { var memberIds = MemberService.allMemberIdsWithPrivilege('walkChangeNotifications', members); if (memberIds.length > 0) { return sendNotificationsTo({ templateUrl: templateForEvent('coordinator', eventType.eventType), memberIds: memberIds, segmentType: 'walkCoordinator', segmentName: MailchimpSegmentService.formatSegmentName('Walk co-ordinator notifications for ' + walkLeaderName), emailSubject: walkLeaderName + "'s walk on " + walkDate, destination: 'walk co-ordinators' }); } else { logger.debug('not sending coordinator notifications as none are configured with walkChangeNotifications'); } } else { logger.debug('not sending coordinator notifications as event type is', eventType.eventType); } } function templateForEvent(role, eventTypeString) { return basePartialsUrl + '/' + role + '/' + s.dasherize(eventTypeString) + '.html'; } function sendNotificationsTo(templateAndNotificationMembers) { if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications cannot be sent'); var memberFullNames = $filter('memberIdsToFullNames')(templateAndNotificationMembers.memberIds, members); logger.debug('sendNotificationsTo:', templateAndNotificationMembers); var campaignName = templateAndNotificationMembers.emailSubject + ' (' + eventType.description + ')'; var segmentName = templateAndNotificationMembers.segmentName; return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl)) .then(renderTemplateContent, notify.error) .then(populateContentSections, notify.error) .then(sendNotification(templateAndNotificationMembers), notify.error); function populateContentSections(walkNotificationText) { logger.debug('populateContentSections -> walkNotificationText', walkNotificationText); return { sections: { notification_text: walkNotificationText } }; } function sendNotification(templateAndNotificationMembers) { return function (contentSections) { return createOrSaveMailchimpSegment() .then(saveSegmentDataToMember, notify.error, notify.progress) .then(sendEmailCampaign, notify.error, notify.progress) .then(notifyEmailSendComplete, notify.error, notify.success); function createOrSaveMailchimpSegment() { return MailchimpSegmentService.saveSegment('walks', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, members); } function saveSegmentDataToMember(segmentResponse) { MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id); return LoggedInMemberService.saveMember(member); } function sendEmailCampaign() { notify.progress('Sending ' + campaignName); return MailchimpConfig.getConfig() .then(function (config) { var campaignId = config.mailchimp.campaigns.walkNotification.campaignId; var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType); logger.debug('about to send campaign', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId); return MailchimpCampaignService.replicateAndSendWithOptions({ campaignId: campaignId, campaignName: campaignName, contentSections: contentSections, segmentId: segmentId }); }) .then(function () { notify.progress('Sending of ' + campaignName + ' was successful', true); }); } function notifyEmailSendComplete() { notify.success('Sending of ' + campaignName + ' was successful. Check your inbox for details.'); return true; } } } } }); } } return { dataAuditDelta: dataAuditDelta, eventsLatestFirst: eventsLatestFirst, createEventIfRequired: createEventIfRequired, populateWalkApprovedEventsIfRequired: populateWalkApprovedEventsIfRequired, writeEventIfRequired: writeEventIfRequired, latestEventWithStatusChangeIs: latestEventWithStatusChangeIs, latestEventWithStatusChange: latestEventWithStatusChange, createEventAndSendNotifications: createEventAndSendNotifications } }]); /* concatenated from client/src/app/js/walkSlots.js.js */ angular.module('ekwgApp') .controller('WalkSlotsController', ["$rootScope", "$log", "$scope", "$filter", "$q", "WalksService", "WalksQueryService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "DateUtils", "Notifier", function ($rootScope, $log, $scope, $filter, $q, WalksService, WalksQueryService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, DateUtils, Notifier) { var logger = $log.getInstance('WalkSlotsController'); $log.logLevels['WalkSlotsController'] = $log.LEVEL.OFF; $scope.slotsAlert = {}; $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.slot = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.slot.opened = true; }, validDate: function (date) { return DateUtils.isDate(date); }, until: DateUtils.momentNowNoTime().day(7 * 12).valueOf(), bulk: true }; var notify = Notifier($scope.slotsAlert); function createSlots(requiredSlots, confirmAction, prompt) { $scope.requiredWalkSlots = requiredSlots.map(function (date) { var walk = new WalksService({ walkDate: date }); walk.events = [WalkNotificationService.createEventIfRequired(walk, WalksReferenceService.eventTypes.awaitingLeader.eventType, 'Walk slot created')]; return walk; }); logger.debug('$scope.requiredWalkSlots', $scope.requiredWalkSlots); if ($scope.requiredWalkSlots.length > 0) { $scope.confirmAction = confirmAction; notify.warning(prompt) } else { notify.error({title: "Nothing to do!", message: "All slots are already created between today and " + $filter('displayDate')($scope.slot.until)}); delete $scope.confirmAction; } } $scope.addWalkSlots = function () { WalksService.query({walkDate: {$gte: $scope.todayValue}}, {fields: {events: 1, walkDate: 1}, sort: {walkDate: 1}}) .then(function (walks) { var sunday = DateUtils.momentNowNoTime().day(7); var untilDate = DateUtils.asMoment($scope.slot.until).startOf('day'); var weeks = untilDate.clone().diff(sunday, 'weeks'); var allGeneratedSlots = _.times(weeks, function (index) { return DateUtils.asValueNoTime(sunday.clone().add(index, 'week')); }).filter(function (date) { return DateUtils.asString(date, undefined, 'DD-MMM') !== '25-Dec'; }); var existingDates = _.pluck(WalksQueryService.activeWalks(walks), 'walkDate'); logger.debug('sunday', sunday, 'untilDate', untilDate, 'weeks', weeks); logger.debug('existingDatesAsDates', _(existingDates).map($filter('displayDateAndTime'))); logger.debug('allGeneratedSlotsAsDates', _(allGeneratedSlots).map($filter('displayDateAndTime'))); var requiredSlots = _.difference(allGeneratedSlots, existingDates); var requiredDates = $filter('displayDates')(requiredSlots); createSlots(requiredSlots, {addSlots: true}, { title: "Add walk slots", message: " - You are about to add " + requiredSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until) + '. Slots are: ' + requiredDates }); }); }; $scope.addWalkSlot = function () { createSlots([DateUtils.asValueNoTime($scope.slot.single)], {addSlot: true}, { title: "Add walk slots", message: " - You are about to add 1 empty walk slot for " + $filter('displayDate')($scope.slot.single) }); }; $scope.selectBulk = function (bulk) { $scope.slot.bulk = bulk; delete $scope.confirmAction; notify.hide(); }; $scope.allow = { addSlot: function () { return !$scope.confirmAction && !$scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, addSlots: function () { return !$scope.confirmAction && $scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits(); }, close: function () { return !$scope.confirmAction; } }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); }; $scope.confirmAddWalkSlots = function () { notify.success({title: "Add walk slots - ", message: "now creating " + $scope.requiredWalkSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until)}); $q.all($scope.requiredWalkSlots.map(function (slot) { return slot.$saveOrUpdate(); })).then(function () { notify.success({title: "Done!", message: "Choose Close to see your newly created slots"}); delete $scope.confirmAction; }); }; $scope.$on('addWalkSlotsDialogOpen', function () { $('#add-slots-dialog').modal(); delete $scope.confirmAction; notify.hide(); }); $scope.closeWalkSlotsDialog = function () { $('#add-slots-dialog').modal('hide'); $rootScope.$broadcast('walkSlotsCreated'); }; }] ); /* concatenated from client/src/app/js/walks.js */ angular.module('ekwgApp') .factory('WalksService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) { return $mongolabResourceHttp('walks') }]) .factory('WalksQueryService', ["WalkNotificationService", "WalksReferenceService", function (WalkNotificationService, WalksReferenceService) { function activeWalks(walks) { return _.filter(walks, function (walk) { return !WalkNotificationService.latestEventWithStatusChangeIs(walk, WalksReferenceService.eventTypes.deleted) }) } return { activeWalks: activeWalks } }]) .factory('WalksReferenceService', function () { var eventTypes = { awaitingLeader: { statusChange: true, eventType: 'awaitingLeader', description: 'Awaiting walk leader' }, awaitingWalkDetails: { mustHaveLeader: true, statusChange: true, eventType: 'awaitingWalkDetails', description: 'Awaiting walk details from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsRequested: { mustHaveLeader: true, eventType: 'walkDetailsRequested', description: 'Walk details requested from leader', notifyLeader: true, notifyCoordinator: true }, walkDetailsUpdated: { eventType: 'walkDetailsUpdated', description: 'Walk details updated', notifyLeader: true, notifyCoordinator: true }, walkDetailsCopied: { eventType: 'walkDetailsCopied', description: 'Walk details copied' }, awaitingApproval: { mustHaveLeader: true, mustPassValidation: true, statusChange: true, eventType: 'awaitingApproval', readyToBe: 'approved', description: 'Awaiting confirmation of walk details', notifyLeader: true, notifyCoordinator: true }, approved: { mustHaveLeader: true, mustPassValidation: true, showDetails: true, statusChange: true, eventType: 'approved', readyToBe: 'published', description: 'Approved', notifyLeader: true, notifyCoordinator: true }, deleted: { statusChange: true, eventType: 'deleted', description: 'Deleted', notifyLeader: true, notifyCoordinator: true } }; return { toEventType: function (eventTypeString) { if (eventTypeString) { if (_.includes(eventTypeString, ' ')) eventTypeString = s.camelcase(eventTypeString.toLowerCase()); var eventType = eventTypes[eventTypeString]; if (!eventType) throw new Error("Event Type '" + eventTypeString + "' does not exist. Must be one of: " + _.keys(eventTypes).join(', ')); return eventType; } }, walkEditModes: { add: {caption: 'add', title: 'Add new'}, edit: {caption: 'edit', title: 'Edit existing', editEnabled: true}, more: {caption: 'more', title: 'View'}, lead: {caption: 'lead', title: 'Lead this', initialiseWalkLeader: true} }, eventTypes: eventTypes, walkStatuses: _(eventTypes).filter(function (eventType) { return eventType.statusChange; }) } }) .controller('WalksController', ["$sce", "$log", "$routeParams", "$interval", "$rootScope", "$location", "$scope", "$filter", "$q", "RamblersUploadAudit", "WalksService", "WalksQueryService", "URLService", "ClipboardService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "MemberService", "DateUtils", "BatchGeoExportService", "RamblersWalksAndEventsService", "Notifier", "CommitteeReferenceData", "GoogleMapsConfig", "MeetupService", function ($sce, $log, $routeParams, $interval, $rootScope, $location, $scope, $filter, $q, RamblersUploadAudit, WalksService, WalksQueryService, URLService, ClipboardService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, MemberService, DateUtils, BatchGeoExportService, RamblersWalksAndEventsService, Notifier, CommitteeReferenceData, GoogleMapsConfig, MeetupService) { var logger = $log.getInstance('WalksController'); var noLogger = $log.getInstance('WalksControllerNoLogger'); $log.logLevels['WalksControllerNoLogger'] = $log.LEVEL.OFF; $log.logLevels['WalksController'] = $log.LEVEL.OFF; $scope.contactUs = { ready: function () { return CommitteeReferenceData.ready; } }; $scope.$watch('filterParameters.quickSearch', function (quickSearch, oldQuery) { refreshFilteredWalks(); }); $scope.finalStatusError = function () { return _.findWhere($scope.ramblersUploadAudit, {status: "error"}); }; $scope.fileNameChanged = function () { logger.debug('filename changed to', $scope.userEdits.fileName); $scope.refreshRamblersUploadAudit(); }; $scope.refreshRamblersUploadAudit = function (stop) { logger.debug('refreshing audit trail records related to', $scope.userEdits.fileName); return RamblersUploadAudit.query({fileName: $scope.userEdits.fileName}, {sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('Filtering', auditItems.length, 'audit trail records related to', $scope.userEdits.fileName); $scope.ramblersUploadAudit = _.chain(auditItems) .filter(function (auditItem) { return $scope.userEdits.showDetail || auditItem.type !== "detail"; }) .map(function (auditItem) { if (auditItem.status === "complete") { logger.debug('Upload complete'); notifyWalkExport.success("Ramblers upload completed"); $interval.cancel(stop); $scope.userEdits.saveInProgress = false; } return auditItem; }) .value(); }); }; $scope.ramblersUploadAudit = []; $scope.walksForExport = []; $scope.walkEditModes = WalksReferenceService.walkEditModes; $scope.walkStatuses = WalksReferenceService.walkStatuses; $scope.walkAlert = {}; $scope.walkExport = {}; var notify = Notifier($scope); var notifyWalkExport = Notifier($scope.walkExport); var notifyWalkEdit = Notifier($scope.walkAlert); var SHOW_START_POINT = "show-start-point"; var SHOW_DRIVING_DIRECTIONS = "show-driving-directions"; notify.setBusy(); $scope.copyFrom = {walkTemplates: [], walkTemplate: {}}; $scope.userEdits = { copyToClipboard: ClipboardService.copyToClipboard, meetupEvent: {}, copySource: 'copy-selected-walk-leader', copySourceFromWalkLeaderMemberId: undefined, expandedWalks: [], mapDisplay: SHOW_START_POINT, longerDescriptionPreview: true, walkExportActive: function (activeTab) { return activeTab === $scope.walkExportActive; }, walkExportTab0Active: true, walkExportTab1Active: false, walkExportTabActive: 0, status: undefined, sendNotifications: true, saveInProgress: false, fileNames: [], walkLink: function (walk) { return walk && walk.$id() ? URLService.notificationHref({ type: "walk", area: "walks", id: walk.$id() }) : undefined } }; $scope.walks = []; $scope.busy = false; $scope.walksProgrammeOpen = URLService.isArea('programme', 'walkId') || URLService.noArea(); $scope.walksInformationOpen = URLService.isArea('information'); $scope.walksMapViewOpen = URLService.isArea('mapview'); $scope.todayValue = DateUtils.momentNowNoTime().valueOf(); $scope.userEdits.walkDateCalendar = { open: function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.userEdits.walkDateCalendar.opened = true; } }; $scope.addWalk = function () { showWalkDialog(new WalksService({ status: WalksReferenceService.eventTypes.awaitingLeader.eventType, walkType: $scope.type[0], walkDate: $scope.todayValue }), WalksReferenceService.walkEditModes.add); }; $scope.addWalkSlotsDialog = function () { $rootScope.$broadcast('addWalkSlotsDialogOpen'); }; $scope.unlinkRamblersDataFromCurrentWalk = function () { delete $scope.currentWalk.ramblersWalkId; notify.progress('Previous Ramblers walk has now been unlinked.') }; $scope.canUnlinkRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.ramblersWalkExists(); }; $scope.notUploadedToRamblersYet = function () { return !$scope.ramblersWalkExists(); }; $scope.insufficientDataToUploadToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.currentWalk && !($scope.currentWalk.gridReference || $scope.currentWalk.postcode); }; $scope.canExportToRamblers = function () { return LoggedInMemberService.allowWalkAdminEdits() && $scope.validateWalk().selected; }; $scope.validateWalk = function () { return RamblersWalksAndEventsService.validateWalk($scope.currentWalk, $scope.members); }; $scope.walkValidations = function () { var walkValidations = $scope.validateWalk().walkValidations; return 'This walk cannot be included in the Ramblers Walks and Events Manager export due to the following ' + walkValidations.length + ' problem(s): ' + walkValidations.join(", ") + '.'; }; $scope.grades = ['Easy access', 'Easy', 'Leisurely', 'Moderate', 'Strenuous', 'Technical']; $scope.walkTypes = ['Circular', 'Linear']; $scope.meetupEventUrlChange = function (walk) { walk.meetupEventTitle = $scope.userEdits.meetupEvent.title; walk.meetupEventUrl = $scope.userEdits.meetupEvent.url; }; $scope.meetupSelectSync = function (walk) { $scope.userEdits.meetupEvent = _.findWhere($scope.meetupEvents, {url: walk.meetupEventUrl}); }; $scope.ramblersWalkExists = function () { return $scope.validateWalk().publishedOnRamblers }; function loggedInMemberIsLeadingWalk(walk) { return walk && walk.walkLeaderMemberId === LoggedInMemberService.loggedInMember().memberId } $scope.loggedIn = function () { return LoggedInMemberService.memberLoggedIn(); }; $scope.toWalkEditMode = function (walk) { if (LoggedInMemberService.memberLoggedIn()) { if (loggedInMemberIsLeadingWalk(walk) || LoggedInMemberService.allowWalkAdminEdits()) { return WalksReferenceService.walkEditModes.edit; } else if (!walk.walkLeaderMemberId) { return WalksReferenceService.walkEditModes.lead; } } }; $scope.actionWalk = function (walk) { showWalkDialog(walk, $scope.toWalkEditMode(walk)); }; $scope.deleteWalkDetails = function () { $scope.confirmAction = {delete: true}; notifyWalkEdit.warning({ title: 'Confirm delete of walk details.', message: 'If you confirm this, the slot for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ' will be deleted from the site.' }); }; $scope.cancelWalkDetails = function () { $scope.confirmAction = {cancel: true}; notifyWalkEdit.warning({ title: 'Cancel changes.', message: 'Click Confirm to lose any changes you\'ve just made for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ', or Cancel to carry on editing.' }); }; $scope.confirmCancelWalkDetails = function () { hideWalkDialogAndRefreshWalks(); }; function isWalkReadyForStatusChangeTo(eventType) { notifyWalkEdit.hide(); logger.info('isWalkReadyForStatusChangeTo ->', eventType); var walkValidations = $scope.validateWalk().walkValidations; if (eventType.mustHaveLeader && !$scope.currentWalk.walkLeaderMemberId) { notifyWalkEdit.warning( { title: 'Walk leader needed', message: ' - this walk cannot be changed to ' + eventType.description + ' yet.' }); revertToPriorWalkStatus(); return false; } else if (eventType.mustPassValidation && walkValidations.length > 0) { notifyWalkEdit.warning( { title: 'This walk is not ready to be ' + eventType.readyToBe + ' yet due to the following ' + walkValidations.length + ' problem(s): ', message: walkValidations.join(", ") + '. You can still save this walk, then come back later on to complete the rest of the details.' }); revertToPriorWalkStatus(); return false; } else { return true; } } function initiateEvent() { $scope.userEdits.saveInProgress = true; var walk = DateUtils.convertDateFieldInObject($scope.currentWalk, 'walkDate'); return WalkNotificationService.createEventAndSendNotifications($scope.members, walk, $scope.userEdits.status, notifyWalkEdit, $scope.userEdits.sendNotifications && walk.walkLeaderMemberId); } $scope.confirmDeleteWalkDetails = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.deleted.eventType; return initiateEvent() .then(function () { return $scope.currentWalk.$saveOrUpdate(hideWalkDialogAndRefreshWalks, hideWalkDialogAndRefreshWalks); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.saveWalkDetails = function () { return initiateEvent() .then(function (notificationSent) { return $scope.currentWalk.$saveOrUpdate(afterSaveWith(notificationSent), afterSaveWith(notificationSent)); }) .catch(function () { $scope.userEdits.saveInProgress = false; }); }; $scope.requestApproval = function () { logger.info('requestApproval called with current status:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.eventTypes.awaitingApproval)) { $scope.confirmAction = {requestApproval: true}; notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); } }; $scope.contactOther = function () { notifyWalkEdit.warning({ title: 'Confirm walk details complete.', message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.' }); }; $scope.walkStatusChange = function (status) { $scope.userEdits.priorStatus = status; notifyWalkEdit.hide(); logger.info('walkStatusChange - was:', status, 'now:', $scope.userEdits.status); if (isWalkReadyForStatusChangeTo(WalksReferenceService.toEventType($scope.userEdits.status))) switch ($scope.userEdits.status) { case WalksReferenceService.eventTypes.awaitingLeader.eventType: { var walkDate = $scope.currentWalk.walkDate; $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; $scope.currentWalk = new WalksService(_.pick($scope.currentWalk, ['_id', 'events', 'walkDate'])); return notifyWalkEdit.success({ title: 'Walk details reset for ' + $filter('displayDate')(walkDate) + '.', message: 'Status is now ' + WalksReferenceService.eventTypes.awaitingLeader.description }); } case WalksReferenceService.eventTypes.approved.eventType: { return $scope.approveWalkDetails(); } } }; $scope.approveWalkDetails = function () { var walkValidations = $scope.validateWalk().walkValidations; if (walkValidations.length > 0) { notifyWalkEdit.warning({ title: 'This walk still has the following ' + walkValidations.length + ' field(s) that need attention: ', message: walkValidations.join(", ") + '. You\'ll have to get the rest of these details completed before you mark the walk as approved.' }); revertToPriorWalkStatus(); } else { notifyWalkEdit.success({ title: 'Ready to publish walk details!', message: 'All fields appear to be filled in okay, so next time you save this walk it will be published.' }); } }; $scope.confirmRequestApproval = function () { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingApproval.eventType; $scope.saveWalkDetails(); }; $scope.cancelConfirmableAction = function () { delete $scope.confirmAction; notify.hide(); notifyWalkEdit.hide(); }; function revertToPriorWalkStatus() { logger.info('revertToPriorWalkStatus:', $scope.userEdits.status, '->', $scope.userEdits.priorStatus); if ($scope.userEdits.priorStatus) $scope.userEdits.status = $scope.userEdits.priorStatus; } $scope.populateCurrentWalkFromTemplate = function () { var walkTemplate = _.clone($scope.copyFrom.walkTemplate); if (walkTemplate) { var templateDate = $filter('displayDate')(walkTemplate.walkDate); delete walkTemplate._id; delete walkTemplate.events; delete walkTemplate.ramblersWalkId; delete walkTemplate.walkDate; delete walkTemplate.displayName; delete walkTemplate.contactPhone; delete walkTemplate.contactEmail; angular.extend($scope.currentWalk, walkTemplate); var event = WalkNotificationService.createEventIfRequired($scope.currentWalk, WalksReferenceService.eventTypes.walkDetailsCopied.eventType, 'Copied from previous walk on ' + templateDate); WalkNotificationService.writeEventIfRequired($scope.currentWalk, event); notifyWalkEdit.success({ title: 'Walk details were copied from ' + templateDate + '.', message: 'Make any further changes here and save when you are done.' }); } }; $scope.filterParameters = { quickSearch: '', selectType: '1', ascending: "true" }; $scope.selectCopySelectedLeader = function () { $scope.userEdits.copySource = 'copy-selected-walk-leader'; $scope.populateWalkTemplates(); }; $scope.populateWalkTemplates = function (injectedMemberId) { var memberId = $scope.currentWalk.walkLeaderMemberId || injectedMemberId; var criteria; switch ($scope.userEdits.copySource) { case "copy-selected-walk-leader": { criteria = { walkLeaderMemberId: $scope.userEdits.copySourceFromWalkLeaderMemberId, briefDescriptionAndStartPoint: {$exists: true} }; break } case "copy-with-os-maps-route-selected": { criteria = {osMapsRoute: {$exists: true}}; break } default: { criteria = {walkLeaderMemberId: memberId}; } } logger.info('selecting walks', $scope.userEdits.copySource, criteria); WalksService.query(criteria, {sort: {walkDate: -1}}) .then(function (walks) { $scope.copyFrom.walkTemplates = walks; }); }; $scope.walkLeaderMemberIdChanged = function () { notifyWalkEdit.hide(); var walk = $scope.currentWalk; var memberId = walk.walkLeaderMemberId; if (!memberId) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType; delete walk.walkLeaderMemberId; delete walk.contactId; delete walk.displayName; delete walk.contactPhone; delete walk.contactEmail; } else { var selectedMember = _.find($scope.members, function (member) { return member.$id() === memberId; }); if (selectedMember) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.contactId = selectedMember.contactId; walk.displayName = selectedMember.displayName; walk.contactPhone = selectedMember.mobileNumber; walk.contactEmail = selectedMember.email; $scope.populateWalkTemplates(memberId); } } }; $scope.myOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'my' : $scope.currentWalk && $scope.currentWalk.displayName + "'s"; }; $scope.meOrWalkLeader = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'me' : $scope.currentWalk && $scope.currentWalk.displayName; }; $scope.personToNotify = function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) ? walksCoordinatorName() : $scope.currentWalk && $scope.currentWalk.displayName; }; function walksCoordinatorName() { return CommitteeReferenceData.contactUsField('walks', 'fullName'); } function convertWalkDateIfNotNumeric(walk) { var walkDate = DateUtils.asValueNoTime(walk.walkDate); if (walkDate !== walk.walkDate) { logger.info('Converting date from', walk.walkDate, '(' + $filter('displayDateAndTime')(walk.walkDate) + ') to', walkDate, '(' + $filter('displayDateAndTime')(walkDate) + ')'); walk.walkDate = walkDate; } else { logger.info('Walk date', walk.walkDate, 'is already in correct format'); } return walk; } function latestEventWithStatusChangeIs(eventType) { return WalkNotificationService.latestEventWithStatusChangeIs($scope.currentWalk, eventType); } $scope.dataHasChanged = function () { var dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.currentWalk, $scope.userEdits.status); var notificationRequired = dataAuditDelta.notificationRequired; dataAuditDelta.notificationRequired && noLogger.info('dataAuditDelta - eventExists:', dataAuditDelta.eventExists, 'dataChanged:', dataAuditDelta.dataChanged, $filter('toAuditDeltaChangedItems')(dataAuditDelta.changedItems)); dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta - previousData:', dataAuditDelta.previousData, 'currentData:', dataAuditDelta.currentData); return notificationRequired; }; function ownedAndAwaitingWalkDetails() { return loggedInMemberIsLeadingWalk($scope.currentWalk) && $scope.userEdits.status === WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; } function editable() { return !$scope.confirmAction && (LoggedInMemberService.allowWalkAdminEdits() || loggedInMemberIsLeadingWalk($scope.currentWalk)); } function allowSave() { return editable() && $scope.dataHasChanged(); } $scope.allow = { close: function () { return !$scope.userEdits.saveInProgress && !$scope.confirmAction && !allowSave() }, save: allowSave, cancel: function () { return !$scope.userEdits.saveInProgress && editable() && $scope.dataHasChanged(); }, delete: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && $scope.walkEditMode && $scope.walkEditMode.editEnabled; }, notifyConfirmation: function () { return (allowSave() || $scope.confirmAction && $scope.confirmAction.delete) && $scope.currentWalk.walkLeaderMemberId; }, adminEdits: function () { return LoggedInMemberService.allowWalkAdminEdits(); }, edits: editable, historyView: function () { return loggedInMemberIsLeadingWalk($scope.currentWalk) || LoggedInMemberService.allowWalkAdminEdits(); }, detailView: function () { return LoggedInMemberService.memberLoggedIn(); }, approve: function () { return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && latestEventWithStatusChangeIs(WalksReferenceService.eventTypes.awaitingApproval); }, requestApproval: function () { return !$scope.confirmAction && ownedAndAwaitingWalkDetails(); } }; $scope.previewLongerDescription = function () { logger.debug('previewLongerDescription'); $scope.userEdits.longerDescriptionPreview = true; }; $scope.editLongerDescription = function () { logger.debug('editLongerDescription'); $scope.userEdits.longerDescriptionPreview = false; }; $scope.trustSrc = function (src) { return $sce.trustAsResourceUrl(src); }; $scope.showAllWalks = function () { $scope.expensesOpen = true; $location.path('/walks/programme') }; $scope.googleMaps = function (walk) { return $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS ? "https://www.google.com/maps/embed/v1/directions?origin=" + $scope.userEdits.fromPostcode + "&destination=" + walk.postcode + "&key=" + $scope.googleMapsConfig.apiKey : "https://www.google.com/maps/embed/v1/place?q=" + walk.postcode + "&zoom=" + $scope.googleMapsConfig.zoomLevel + "&key=" + $scope.googleMapsConfig.apiKey; }; $scope.autoSelectMapDisplay = function () { var switchToShowStartPoint = $scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS; var switchToShowDrivingDirections = !$scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_START_POINT; if (switchToShowStartPoint) { $scope.userEdits.mapDisplay = SHOW_START_POINT; } else if (switchToShowDrivingDirections) { $scope.userEdits.mapDisplay = SHOW_DRIVING_DIRECTIONS; } }; $scope.drivingDirectionsDisabled = function () { return $scope.userEdits.fromPostcode.length < 3; }; $scope.eventTypeFor = function (walk) { var latestEventWithStatusChange = WalkNotificationService.latestEventWithStatusChange(walk); var eventType = WalksReferenceService.toEventType(latestEventWithStatusChange.eventType) || walk.status || WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; noLogger.info('latestEventWithStatusChange', latestEventWithStatusChange, 'eventType', eventType, 'walk.events', walk.events); return eventType; }; $scope.viewWalkField = function (walk, field) { var eventType = $scope.eventTypeFor(walk); if (eventType.showDetails) { return walk[field] || ''; } else if (field === 'briefDescriptionAndStartPoint') { return eventType.description; } else { return ''; } }; function showWalkDialog(walk, walkEditMode) { delete $scope.confirmAction; $scope.userEdits.sendNotifications = true; $scope.walkEditMode = walkEditMode; $scope.currentWalk = walk; if (walkEditMode.initialiseWalkLeader) { $scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType; walk.walkLeaderMemberId = LoggedInMemberService.loggedInMember().memberId; $scope.walkLeaderMemberIdChanged(); notifyWalkEdit.success({ title: 'Thanks for offering to lead this walk ' + LoggedInMemberService.loggedInMember().firstName + '!', message: 'Please complete as many details you can, then save to allocate this slot on the walks programme. ' + 'It will be published to the public once it\'s approved. If you want to release this slot again, just click cancel.' }); } else { var eventTypeIfExists = WalkNotificationService.latestEventWithStatusChange($scope.currentWalk).eventType; if (eventTypeIfExists) { $scope.userEdits.status = eventTypeIfExists } $scope.userEdits.copySourceFromWalkLeaderMemberId = walk.walkLeaderMemberId || LoggedInMemberService.loggedInMember().memberId; $scope.populateWalkTemplates(); $scope.meetupSelectSync($scope.currentWalk); notifyWalkEdit.hide(); } $('#walk-dialog').modal(); } function walksCriteriaObject() { switch ($scope.filterParameters.selectType) { case '1': return {walkDate: {$gte: $scope.todayValue}}; case '2': return {walkDate: {$lt: $scope.todayValue}}; case '3': return {}; case '4': return {displayName: {$exists: false}}; case '5': return {briefDescriptionAndStartPoint: {$exists: false}}; } } function walksSortObject() { switch ($scope.filterParameters.ascending) { case 'true': return {sort: {walkDate: 1}}; case 'false': return {sort: {walkDate: -1}}; } } function query() { if (URLService.hasRouteParameter('walkId')) { return WalksService.getById($routeParams.walkId) .then(function (walk) { if (!walk) notify.error('Walk could not be found. Try opening again from the link in the notification email, or choose the Show All Walks button'); return [walk]; }); } else { return WalksService.query(walksCriteriaObject(), walksSortObject()); } } function refreshFilteredWalks() { notify.setBusy(); $scope.filteredWalks = $filter('filter')($scope.walks, $scope.filterParameters.quickSearch); var walksCount = ($scope.filteredWalks && $scope.filteredWalks.length) || 0; notify.progress('Showing ' + walksCount + ' walk(s)'); if ($scope.filteredWalks.length > 0) { $scope.userEdits.expandedWalks = [$scope.filteredWalks[0].$id()]; } notify.clearBusy(); } $scope.showTableHeader = function (walk) { return $scope.filteredWalks.indexOf(walk) === 0 || $scope.isExpandedFor($scope.filteredWalks[$scope.filteredWalks.indexOf(walk) - 1]); }; $scope.nextWalk = function (walk) { return walk && walk.$id() === $scope.nextWalkId; }; $scope.durationInFutureFor = function (walk) { return walk && walk.walkDate === $scope.todayValue ? 'today' : (DateUtils.asMoment(walk.walkDate).fromNow()); }; $scope.toggleViewFor = function (walk) { function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele !== value; }); } var walkId = walk.$id(); if (_.contains($scope.userEdits.expandedWalks, walkId)) { $scope.userEdits.expandedWalks = arrayRemove($scope.userEdits.expandedWalks, walkId); logger.debug('toggleViewFor:', walkId, '-> collapsing'); } else { $scope.userEdits.expandedWalks.push(walkId); logger.debug('toggleViewFor:', walkId, '-> expanding'); } logger.debug('toggleViewFor:', walkId, '-> expandedWalks contains', $scope.userEdits.expandedWalks) }; $scope.isExpandedFor = function (walk) { return _.contains($scope.userEdits.expandedWalks, walk.$id()); }; $scope.tableRowOdd = function (walk) { return $scope.filteredWalks.indexOf(walk) % 2 === 0; }; function getNextWalkId(walks) { var nextWalk = _.chain(walks).sortBy('walkDate').find(function (walk) { return walk.walkDate >= $scope.todayValue; }).value(); return nextWalk && nextWalk.$id(); } $scope.refreshWalks = function (notificationSent) { notify.setBusy(); notify.progress('Refreshing walks...'); return query() .then(function (walks) { $scope.nextWalkId = URLService.hasRouteParameter('walkId') ? undefined : getNextWalkId(walks); $scope.walks = URLService.hasRouteParameter('walkId') ? walks : WalksQueryService.activeWalks(walks); refreshFilteredWalks(); notify.clearBusy(); if (!notificationSent) { notifyWalkEdit.hide(); } $scope.userEdits.saveInProgress = false; }); }; $scope.hideWalkDialog = function () { $('#walk-dialog').modal('hide'); delete $scope.confirmAction; }; function hideWalkDialogAndRefreshWalks() { logger.info('hideWalkDialogAndRefreshWalks'); $scope.hideWalkDialog(); $scope.refreshWalks(); } function afterSaveWith(notificationSent) { return function () { if (!notificationSent) $('#walk-dialog').modal('hide'); notifyWalkEdit.clearBusy(); delete $scope.confirmAction; $scope.refreshWalks(notificationSent); $scope.userEdits.saveInProgress = false; } } function refreshRamblersConfig() { RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) { $scope.ramblersWalkBaseUrl = walkBaseUrl; }); } function refreshGoogleMapsConfig() { GoogleMapsConfig.getConfig().then(function (googleMapsConfig) { $scope.googleMapsConfig = googleMapsConfig; $scope.googleMapsConfig.zoomLevel = 12; }); } function refreshMeetupData() { MeetupService.config().then(function (meetupConfig) { $scope.meetupConfig = meetupConfig; }); MeetupService.eventsForStatus('past') .then(function (pastEvents) { MeetupService.eventsForStatus('upcoming') .then(function (futureEvents) { $scope.meetupEvents = _.sortBy(pastEvents.concat(futureEvents), 'date,').reverse(); }); }) } function refreshHomePostcode() { $scope.userEdits.fromPostcode = LoggedInMemberService.memberLoggedIn() ? LoggedInMemberService.loggedInMember().postcode : ""; logger.debug('set from postcode to', $scope.userEdits.fromPostcode); $scope.autoSelectMapDisplay(); } $scope.$on('memberLoginComplete', function () { refreshMembers(); refreshHomePostcode(); }); $scope.$on('walkSlotsCreated', function () { $scope.refreshWalks(); }); function refreshMembers() { if (LoggedInMemberService.memberLoggedIn()) MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS) .then(function (members) { $scope.members = members; return members; }); } $scope.batchGeoDownloadFile = function () { return BatchGeoExportService.exportWalks($scope.walks, $scope.members); }; $scope.batchGeoDownloadFileName = function () { return BatchGeoExportService.exportWalksFileName(); }; $scope.batchGeoDownloadHeader = function () { return BatchGeoExportService.exportColumnHeadings(); }; $scope.exportableWalks = function () { return RamblersWalksAndEventsService.exportableWalks($scope.walksForExport); }; $scope.walksDownloadFile = function () { return RamblersWalksAndEventsService.exportWalks($scope.exportableWalks(), $scope.members); }; $scope.uploadToRamblers = function () { $scope.ramblersUploadAudit = []; $scope.userEdits.walkExportTab0Active = false; $scope.userEdits.walkExportTab1Active = true; $scope.userEdits.saveInProgress = true; RamblersWalksAndEventsService.uploadToRamblers($scope.walksForExport, $scope.members, notifyWalkExport).then(function (fileName) { $scope.userEdits.fileName = fileName; var stop = $interval(callAtInterval, 2000, false); if (!_.contains($scope.userEdits.fileNames, $scope.userEdits.fileName)) { $scope.userEdits.fileNames.push($scope.userEdits.fileName); logger.debug('added', $scope.userEdits.fileName, 'to filenames of', $scope.userEdits.fileNames.length, 'audit trail records'); } delete $scope.finalStatusError; function callAtInterval() { logger.debug("Refreshing audit trail for file", $scope.userEdits.fileName, 'count =', $scope.ramblersUploadAudit.length); $scope.refreshRamblersUploadAudit(stop); } }); }; $scope.walksDownloadFileName = function () { return RamblersWalksAndEventsService.exportWalksFileName(); }; $scope.walksDownloadHeader = function () { return RamblersWalksAndEventsService.exportColumnHeadings(); }; $scope.selectWalksForExport = function () { showWalkExportDialog(); }; $scope.changeWalkExportSelection = function (walk) { if (walk.walkValidations.length === 0) { walk.selected = !walk.selected; notifyWalkExport.hide(); } else { notifyWalkExport.error({ title: 'You can\'t export the walk for ' + $filter('displayDate')(walk.walk.walkDate), message: walk.walkValidations.join(', ') }); } }; $scope.cancelExportWalkDetails = function () { $('#walk-export-dialog').modal('hide'); }; function populateWalkExport(walksForExport) { $scope.walksForExport = walksForExport; notifyWalkExport.success('Found total of ' + $scope.walksForExport.length + ' walk(s), ' + $scope.walksDownloadFile().length + ' preselected for export'); notifyWalkExport.clearBusy(); } function showWalkExportDialog() { $scope.walksForExport = []; notifyWalkExport.warning('Determining which walks to export', true); RamblersUploadAudit.all({limit: 1000, sort: {auditTime: -1}}) .then(function (auditItems) { logger.debug('found total of', auditItems.length, 'audit trail records'); $scope.userEdits.fileNames = _.chain(auditItems).pluck('fileName').unique().value(); logger.debug('unique total of', $scope.userEdits.fileNames.length, 'audit trail records'); }); RamblersWalksAndEventsService.createWalksForExportPrompt($scope.walks, $scope.members) .then(populateWalkExport) .catch(function (error) { logger.debug('error->', error); notifyWalkExport.error({title: 'Problem with Ramblers export preparation', message: JSON.stringify(error)}); }); $('#walk-export-dialog').modal(); } refreshMembers(); $scope.refreshWalks(); refreshRamblersConfig(); refreshGoogleMapsConfig(); refreshMeetupData(); refreshHomePostcode(); }] ) ;
nbarrett/ekwg
dist/app/js/ekwg.js
JavaScript
mit
405,222
angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/]) .config(function ($httpProvider, $routeProvider) { $httpProvider.interceptors.push('TokenInterceptor'); $routeProvider .when('/login', { templateUrl: 'app/login/login', controller: 'loginCtrl', protect: false }) .when('/overview', { templateUrl: 'app/overview/overview', //controller: 'overviewCtrl', protect: true, resolve: { initialData: function (ServerSocket, FetchData, $q) { return $q(function (resolve, reject) { ServerSocket.emit('info'); ServerSocket.once('info', function (data) { console.log(data); FetchData = angular.extend(FetchData, data); resolve(); }); }); } } }) .otherwise({ redirectTo: '/overview' }); }) .run(function ($rootScope, $location, $window, $routeParams, UserAuth) { if (!UserAuth.isLogged) { $location.path('/login'); } $rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) { console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;'); console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', ''); console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;'); console.groupEnd('APP.RUN -> ROUTE CHANGE START'); if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) { $location.path('/login'); console.error('Route protected, user not logged in'); } else if (!nextRoute.protect && UserAuth.isLogged) { $location.path('/overview'); } }); });
frotunato/MEANcraft
client/app/app.js
JavaScript
mit
1,953
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__extends(ScrapbookList, _super); Object.defineProperty(ScrapbookList.prototype, "items", { get: function() { return this._items; }, set: function(value) { this._items = value; this.bindData(); } }); function ScrapbookList() { _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stackLayout.orientation = "horizontal"; stackLayout.bind({ targetProperty: "className", sourceProperty: "$value", expression: "isActive ? 'list-group-item active' : 'list-group-item'" }); var image = new Image(); image.className = "thumb img-circle"; image.bind({ targetProperty: "src", sourceProperty: "image" }); stackLayout.addChild(image); var label = new Label(); label.className = "list-group-item-text"; label.style.width = "100%"; label.textWrap = true; label.bind({ targetProperty: "text", sourceProperty: "title", expression: "(title === null || title === undefined ? 'New' : title + '\\\'s') + ' Scrapbook Page'" }); stackLayout.addChild(label); return stackLayout; }; listView.on(ListView.itemTapEvent, function(args) { onItemTap(this, args.index); }.bind(listView)); this.addChild(listView); this.bindData = function () { listView.bind({ sourceProperty: "$value", targetProperty: "items", twoWay: "true" }, this._items); }; var onItemTap = function(args, index) { this.notify({ eventName: "itemTap", object: this, index: index }); }.bind(this); } return ScrapbookList; })(GridLayout); ScrapbookList.itemTapEvent = "itemTap"; exports.ScrapbookList = ScrapbookList;
mikebranstein/NativeScriptInAction
AppendixB/PetScrapbook/app/views/shared/scrapbook-list/scrapbook-list.js
JavaScript
mit
3,048
import React, {Component} from 'react'; import {Typeahead} from 'react-bootstrap-typeahead'; import {inject, observer} from 'mobx-react'; import {action, toJS, autorunAsync} from 'mobx'; import myClient from '../agents/client' require('react-bootstrap-typeahead/css/ClearButton.css'); require('react-bootstrap-typeahead/css/Loader.css'); require('react-bootstrap-typeahead/css/Token.css'); require('react-bootstrap-typeahead/css/Typeahead.css'); @inject('controlsStore', 'designStore') @observer export default class EroTypeahead extends Component { constructor(props) { super(props); } state = { options: [] }; // this will keep updating the next -ERO options as the ERO changes; disposeOfEroOptionsUpdate = autorunAsync('ero options update', () => { let ep = this.props.controlsStore.editPipe; let submitEro = toJS(ep.ero.hops); // keep track of the last hop; if we've reached Z we shouldn't keep going let lastHop = ep.a; if (ep.ero.hops.length > 0) { lastHop = ep.ero.hops[ep.ero.hops.length - 1]; } else { // if there's _nothing_ in our ERO then ask for options from pipe.a submitEro.push(ep.a); } // if this is the last hop, don't provide any options if (lastHop === ep.z) { this.setState({options: []}); return; } myClient.submit('POST', '/api/pce/nextHopsForEro', submitEro) .then( action((response) => { let nextHops = JSON.parse(response); if (nextHops.length > 0) { let opts = []; nextHops.map(h => { let entry = { id: h.urn, label: h.urn + ' through ' + h.through + ' to ' + h.to, through: h.through, to: h.to }; opts.push(entry); }); this.setState({options: opts}); } })); }, 500); componentWillUnmount() { this.disposeOfEroOptionsUpdate(); } onTypeaheadSelection = selection => { if (selection.length === 0) { return; } let wasAnOption = false; let through = ''; let urn = ''; let to = ''; this.state.options.map(opt => { if (opt.label === selection) { wasAnOption = true; through = opt.through; urn = opt.id; to = opt.to; } }); if (wasAnOption) { let ep = this.props.controlsStore.editPipe; let ero = []; ep.manual.ero.map(e => { ero.push(e); }); ero.push(through); ero.push(urn); ero.push(to); this.props.controlsStore.setParamsForEditPipe({ ero: { hops: ero }, manual: {ero: ero} }); this.typeAhead.getInstance().clear(); } }; render() { return ( <Typeahead minLength={0} ref={(ref) => { this.typeAhead = ref; }} placeholder='choose from selection' options={this.state.options} onInputChange={this.onTypeaheadSelection} clearButton /> ); } }
haniotak/oscars-frontend
src/main/js/components/eroTypeahead.js
JavaScript
mit
3,673
'use strict'; var convert = require('./convert'), func = convert('lt', require('../lt')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
justin-lai/hackd.in
compiled/client/lib/lodash/fp/lt.js
JavaScript
mit
778
PP.lib.shader.shaders.color = { info: { name: 'color adjustement', author: 'Evan Wallace', link: 'https://github.com/evanw/glfx.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, brightness: { type: "f", value: 0.0 }, contrast: { type: "f", value: 0.0 }, hue: { type: "f", value: 0.0 }, saturation: { type: "f", value: 0.0 }, exposure: { type: "f", value: 0.0 }, negative: { type: "i", value: 0 } }, controls: { brightness: {min:-1, max: 1, step:.05}, contrast: {min:-1, max: 1, step:.05}, hue: {min:-1, max: 1, step:.05}, saturation: {min:-1, max: 1, step:.05}, exposure: {min:0, max: 1, step:.05}, negative: {} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float brightness;", "uniform float contrast;", "uniform float hue;", "uniform float saturation;", "uniform float exposure;", "uniform int negative;", "const float sqrtoftwo = 1.41421356237;", "void main() {", "vec4 color = texture2D(textureIn, vUv);", "color.rgb += brightness;", "if (contrast > 0.0) {", "color.rgb = (color.rgb - 0.5) / (1.0 - contrast) + 0.5;", "} else {", "color.rgb = (color.rgb - 0.5) * (1.0 + contrast) + 0.5;", "}", "/* hue adjustment, wolfram alpha: RotationTransform[angle, {1, 1, 1}][{x, y, z}] */", "float angle = hue * 3.14159265;", "float s = sin(angle), c = cos(angle);", "vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;", "float len = length(color.rgb);", "color.rgb = vec3(", "dot(color.rgb, weights.xyz),", "dot(color.rgb, weights.zxy),", "dot(color.rgb, weights.yzx)", ");", "/* saturation adjustment */", "float average = (color.r + color.g + color.b) / 3.0;", "if (saturation > 0.0) {", "color.rgb += (average - color.rgb) * (1.0 - 1.0 / (1.0 - saturation));", "} else {", "color.rgb += (average - color.rgb) * (-saturation);", "}", "if(negative == 1){", " color.rgb = 1.0 - color.rgb;", "}", "if(exposure > 0.0){", " color = log2(vec4(pow(exposure + sqrtoftwo, 2.0))) * color;", "}", "gl_FragColor = color;", "}", ].join("\n") }; PP.lib.shader.shaders.bleach = { info: { name: 'Bleach', author: 'Brian Chirls @bchirls', link: 'https://github.com/brianchirls/Seriously.js' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, amount: { type: "f", value: 1.0 } }, controls: { amount: {min:0, max: 1, step:.1} }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ 'varying vec2 vUv;', 'uniform sampler2D textureIn;', 'uniform float amount;', 'const vec4 one = vec4(1.0);', 'const vec4 two = vec4(2.0);', 'const vec4 lumcoeff = vec4(0.2125,0.7154,0.0721,0.0);', 'vec4 overlay(vec4 myInput, vec4 previousmix, vec4 amount) {', ' float luminance = dot(previousmix,lumcoeff);', ' float mixamount = clamp((luminance - 0.45) * 10.0, 0.0, 1.0);', ' vec4 branch1 = two * previousmix * myInput;', ' vec4 branch2 = one - (two * (one - previousmix) * (one - myInput));', ' vec4 result = mix(branch1, branch2, vec4(mixamount) );', ' return mix(previousmix, result, amount);', '}', 'void main (void) {', ' vec4 pixel = texture2D(textureIn, vUv);', ' vec4 luma = vec4(vec3(dot(pixel,lumcoeff)), pixel.a);', ' gl_FragColor = overlay(luma, pixel, vec4(amount));', '}' ].join("\n") }; PP.lib.shader.shaders.plasma = { info: { name: 'plasma', author: 'iq', link: 'http://www.iquilezles.org' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, saturation: { type: "f", value: 1.0 }, waves: { type: "f", value: .2 }, wiggle: { type: "f", value: 1000.0 }, scale: { type: "f", value: 1.0 } }, controls: { speed: {min:0, max: .1, step:.001}, saturation: {min:0, max: 10, step:.01}, waves: {min:0, max: .4, step:.0001}, wiggle: {min:0, max: 10000, step:1}, scale: {min:0, max: 10, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform float time;", "uniform float saturation;", "uniform vec2 resolution;", "uniform float waves;", "uniform float wiggle;", "uniform float scale;", "void main() {", "float x = gl_FragCoord.x*scale;", "float y = gl_FragCoord.y*scale;", "float mov0 = x+y+cos(sin(time)*2.)*100.+sin(x/100.)*wiggle;", "float mov1 = y / resolution.y / waves + time;", "float mov2 = x / resolution.x / waves;", "float r = abs(sin(mov1+time)/2.+mov2/2.-mov1-mov2+time);", "float g = abs(sin(r+sin(mov0/1000.+time)+sin(y/40.+time)+sin((x+y)/100.)*3.));", "float b = abs(sin(g+cos(mov1+mov2+g)+cos(mov2)+sin(x/1000.)));", "vec3 plasma = vec3(r,g,b) * saturation;", "gl_FragColor = vec4( plasma ,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma2 = { info: { name: 'plasma2', author: 'mrDoob', link: 'http://mrdoob.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 }, qteX: { type: "f", value: 80.0 }, qteY: { type: "f", value: 10.0 }, intensity: { type: "f", value: 10.0 }, hue: { type: "f", value: .25 } }, controls: { speed: {min:0, max: 1, step:.001}, qteX: {min:0, max: 200, step:1}, qteY: {min:0, max: 200, step:1}, intensity: {min:0, max: 50, step:.1}, hue: {min:0, max: 2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform float qteX;", "uniform float qteY;", "uniform float intensity;", "uniform float hue;", "void main() {", "vec2 position = gl_FragCoord.xy / resolution.xy;", "float color = 0.0;", "color += sin( position.x * cos( time / 15.0 ) * qteX ) + cos( position.y * cos( time / 15.0 ) * qteY );", "color += sin( position.y * sin( time / 10.0 ) * 40.0 ) + cos( position.x * sin( time / 25.0 ) * 40.0 );", "color += sin( position.x * sin( time / 5.0 ) * 10.0 ) + sin( position.y * sin( time / 35.0 ) * 80.0 );", "color *= sin( time / intensity ) * 0.5;", "gl_FragColor = vec4( vec3( color, color * (hue*2.0), sin( color + time / (hue*12.0) ) * (hue*3.0) ), 1.0 );", "}" ].join("\n") }; PP.lib.shader.shaders.plasma3 = { info: { name: 'plasma 3', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0x8CC6DA ) }, resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 10.0 }, quantity: { type: "f", value: 5.0 }, lens: { type: "f", value: 2.0 }, intensity: { type: "f", value: .5 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, quantity: {min:0, max: 100, step:1}, lens: {min:0, max: 100, step:1}, intensity: {min:0, max: 5, step:.01} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float quantity;", "uniform float lens;", "uniform float intensity;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "p = p * scale;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "uv.x = 2.0*a/3.1416;", "uv.y = -time+ sin(7.0*r+time) + .7*cos(time+7.0*a);", "float w = intensity+1.0*(sin(time+lens*r)+ 1.0*cos(time+(quantity * 2.0)*a));", "gl_FragColor = vec4(color*w,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma4 = { info: { name: 'plasma 4 (vortex)', author: 'Hakim El Hattab', link: 'http://hakim.se' }, uniforms: { color: { type: "c", value: new THREE.Color( 0xff5200 ) }, // 0x8CC6DA resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.05 }, scale: { type: "f", value: 20.0 }, wobble: { type: "f", value: 1.0 }, ripple: { type: "f", value: 5.0 }, light: { type: "f", value: 2.0 } }, controls: { speed: {min:0, max: 1, step:.001}, scale: {min:0, max: 100, step:.1}, wobble: {min:0, max: 50, step:1}, ripple: {min:0, max: 50, step:.1}, light: {min:1, max: 50, step:1} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform float time;", "uniform vec2 resolution;", "uniform vec3 color;", "uniform float scale;", "uniform float wobble;", "uniform float ripple;", "uniform float light;", "void main() {", "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;", "vec2 uv;", "float a = atan(p.y,p.x);", "float r = sqrt(dot(p,p));", "float u = cos(a*(wobble * 2.0) + ripple * sin(-time + scale * r));", "float intensity = sqrt(pow(abs(p.x),light) + pow(abs(p.y),light));", "vec3 result = u*intensity*color;", "gl_FragColor = vec4(result,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasma5 = { info: { name: 'plasma 5', author: 'Silexars', link: 'http://www.silexars.com' }, uniforms: { resolution: { type: "v2", value: new THREE.Vector2( PP.config.dimension.width, PP.config.dimension.height )}, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .2, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "uniform vec2 resolution;", "uniform float time;", "void main() {", "vec3 col;", "float l,z=time;", "for(int i=0;i<3;i++){", "vec2 uv;", "vec2 p=gl_FragCoord.xy/resolution.xy;", "uv=p;", "p-=.5;", "p.x*=resolution.x/resolution.y;", "z+=.07;", "l=length(p);", "uv+=p/l*(sin(z)+1.)*abs(sin(l*9.-z*2.));", "col[i]=.01/length(abs(mod(uv,1.)-.5));", "}", "gl_FragColor=vec4(col/l,1.0);", "}" ].join("\n") }; PP.lib.shader.shaders.plasmaByTexture = { info: { name: 'plasma by texture', author: 'J3D', link: 'http://www.everyday3d.com/j3d/demo/011_Plasma.html' }, uniforms: { textureIn: { type: "t", value: 0, texture: null }, time: { type: "f", value: 0.0}, speed: { type: "f", value: 0.01 } }, controls: { speed: {min:0, max: .1, step:.001} }, update: function(e){ e.material.uniforms.time.value += e.material.uniforms.speed.value; }, vertexShader: PP.lib.vextexShaderBase.join("\n"), fragmentShader: [ "varying vec2 vUv;", "uniform sampler2D textureIn;", "uniform float time;", "void main() {", "vec2 ca = vec2(0.1, 0.2);", "vec2 cb = vec2(0.7, 0.9);", "float da = distance(vUv, ca);", "float db = distance(vUv, cb);", "float t = time * 0.5;", "float c1 = sin(da * cos(t) * 16.0 + t * 4.0);", "float c2 = cos(vUv.y * 8.0 + t);", "float c3 = cos(db * 14.0) + sin(t);", "float p = (c1 + c2 + c3) / 3.0;", "gl_FragColor = texture2D(textureIn, vec2(p, p));", "}" ].join("\n") };
rdad/PP.js
src/lib/Shader.color.js
JavaScript
mit
20,938
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'de-ch', { toolbar: 'Speichern' } );
waxe/waxe.xml
waxe/xml/static/ckeditor/plugins/save/lang/de-ch.js
JavaScript
mit
225
// Karma configuration // Generated on Tue Sep 09 2014 13:58:24 GMT-0700 (PDT) 'use strict'; var browsers = ['Chrome', 'PhantomJS']; if ( /^win/.test(process.platform) ) { browsers = ['IE']; } if (process.env.TRAVIS ) { browsers = ['PhantomJS']; } module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'mocha'], browserify: { debug: true, transform: ['6to5ify'] }, // list of files / patterns to load in the browser files: [ 'node_modules/chai/chai.js', 'test/front-end/phantomjs-bind-polyfill.js', 'test/front-end/*-spec.js' ], // list of files to exclude exclude: [ '**/*.swp' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*-spec.js': ['browserify'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: browsers, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
chengzh2008/react-starter
karma.conf.js
JavaScript
mit
1,977
"use strict"; var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _ = require("../../../"); var _2 = _interopRequireDefault(_); describe(".toString()", function () { var User = (function (_Model) { _inherits(User, _Model); function User() { _classCallCheck(this, User); _get(Object.getPrototypeOf(User.prototype), "constructor", this).apply(this, arguments); } return User; })(_2["default"]); describe("User.find.one.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.one.where("id", 1).toString().should.eql("User.find.one.where(\"id\", 1)"); }); it("should not matter which order the chain is called in", function () { User.find.where("id", 1).one.toString().should.eql("User.find.one.where(\"id\", 1)"); }); }); describe("User.find.all.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.find.all.where("id", 1).toString().should.eql("User.find.all.where(\"id\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).andWhere("id", ">", 1).andWhere("id", "!=", 3).toString().should.eql("User.find.where(\"id\", \"<\", 10).andWhere(\"id\", \">\", 1).andWhere(\"id\", \"!=\", 3)"); }); }); describe("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orWhere("id", ">", 1).toString().should.eql("User.find.where(\"id\", \"<\", 10).orWhere(\"id\", \">\", 1)"); }); }); describe("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).groupBy("categoryId").toString().should.eql("User.find.where(\"id\", \"<\", 10).groupBy(\"categoryId\")"); }); }); describe("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\")", function () { it("should return a string representation of the chain", function () { User.find.where("id", "<", 10).orderBy("categoryId", "desc").toString().should.eql("User.find.where(\"id\", \"<\", 10).orderBy(\"categoryId\", \"desc\")"); }); }); describe("User.find.where(\"id\", \">\", 2).limit(4)", function () { it("should return a string representation of the chain", function () { User.find.where("id", ">", 2).limit(4).toString().should.eql("User.find.where(\"id\", \">\", 2).limit(4)"); }); }); describe("User.count.where(\"id\", 1)", function () { it("should return a string representation of the chain", function () { User.count.where("id", 1).toString().should.eql("User.count.where(\"id\", 1)"); }); }); });
FreeAllMedia/dovima
es5/spec/model/toString.spec.js
JavaScript
mit
4,683
import React, { PropTypes } from 'react'; class Link extends React.Component { render() { return <article key={this.props.item.id} className="List-Item"> <header className="List-Item-Header"> <cite className="List-Item-Title"><a href={this.props.item.href}>{this.props.item.title}</a></cite> </header> <p className="List-Item-Description List-Item-Description--Short">{this.props.item.short_description}</p> </article> } } export default Link;
Shroder/essential-javascript-links
src/modules/List/components/Link/index.js
JavaScript
mit
484
import Vue from 'vue'; import merge from 'element-ui/src/utils/merge'; import PopupManager from 'element-ui/src/utils/popup/popup-manager'; import getScrollBarWidth from '../scrollbar-width'; let idSeed = 1; const transitions = []; const hookTransition = (transition) => { if (transitions.indexOf(transition) !== -1) return; const getVueInstance = (element) => { let instance = element.__vue__; if (!instance) { const textNode = element.previousSibling; if (textNode.__vue__) { instance = textNode.__vue__; } } return instance; }; Vue.transition(transition, { afterEnter(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterOpen && instance.doAfterOpen(); } }, afterLeave(el) { const instance = getVueInstance(el); if (instance) { instance.doAfterClose && instance.doAfterClose(); } } }); }; let scrollBarWidth; const getDOM = function(dom) { if (dom.nodeType === 3) { dom = dom.nextElementSibling || dom.nextSibling; getDOM(dom); } return dom; }; export default { model: { prop: 'visible', event: 'visible-change' }, props: { visible: { type: Boolean, default: false }, transition: { type: String, default: '' }, openDelay: {}, closeDelay: {}, zIndex: {}, modal: { type: Boolean, default: false }, modalFade: { type: Boolean, default: true }, modalClass: {}, modalAppendToBody: { type: Boolean, default: false }, lockScroll: { type: Boolean, default: true }, closeOnPressEscape: { type: Boolean, default: false }, closeOnClickModal: { type: Boolean, default: false } }, created() { if (this.transition) { hookTransition(this.transition); } }, beforeMount() { this._popupId = 'popup-' + idSeed++; PopupManager.register(this._popupId, this); }, beforeDestroy() { PopupManager.deregister(this._popupId); PopupManager.closeModal(this._popupId); if (this.modal && this.bodyOverflow !== null && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, data() { return { opened: false, bodyOverflow: null, bodyPaddingRight: null, rendered: false }; }, watch: { visible(val) { if (val) { if (this._opening) return; if (!this.rendered) { this.rendered = true; Vue.nextTick(() => { this.open(); }); } else { this.open(); } } else { this.close(); } } }, methods: { open(options) { if (!this.rendered) { this.rendered = true; this.$emit('visible-change', true); } const props = merge({}, this.$props || this, options); if (this._closeTimer) { clearTimeout(this._closeTimer); this._closeTimer = null; } clearTimeout(this._openTimer); const openDelay = Number(props.openDelay); if (openDelay > 0) { this._openTimer = setTimeout(() => { this._openTimer = null; this.doOpen(props); }, openDelay); } else { this.doOpen(props); } }, doOpen(props) { if (this.$isServer) return; if (this.willOpen && !this.willOpen()) return; if (this.opened) return; this._opening = true; this.$emit('visible-change', true); const dom = getDOM(this.$el); const modal = props.modal; const zIndex = props.zIndex; if (zIndex) { PopupManager.zIndex = zIndex; } if (modal) { if (this._closing) { PopupManager.closeModal(this._popupId); this._closing = false; } PopupManager.openModal(this._popupId, PopupManager.nextZIndex(), this.modalAppendToBody ? undefined : dom, props.modalClass, props.modalFade); if (props.lockScroll) { if (!this.bodyOverflow) { this.bodyPaddingRight = document.body.style.paddingRight; this.bodyOverflow = document.body.style.overflow; } scrollBarWidth = getScrollBarWidth(); let bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight; if (scrollBarWidth > 0 && bodyHasOverflow) { document.body.style.paddingRight = scrollBarWidth + 'px'; } document.body.style.overflow = 'hidden'; } } if (getComputedStyle(dom).position === 'static') { dom.style.position = 'absolute'; } dom.style.zIndex = PopupManager.nextZIndex(); this.opened = true; this.onOpen && this.onOpen(); if (!this.transition) { this.doAfterOpen(); } }, doAfterOpen() { this._opening = false; }, close() { if (this.willClose && !this.willClose()) return; if (this._openTimer !== null) { clearTimeout(this._openTimer); this._openTimer = null; } clearTimeout(this._closeTimer); const closeDelay = Number(this.closeDelay); if (closeDelay > 0) { this._closeTimer = setTimeout(() => { this._closeTimer = null; this.doClose(); }, closeDelay); } else { this.doClose(); } }, doClose() { this.$emit('visible-change', false); this._closing = true; this.onClose && this.onClose(); if (this.lockScroll) { setTimeout(() => { if (this.modal && this.bodyOverflow !== 'hidden') { document.body.style.overflow = this.bodyOverflow; document.body.style.paddingRight = this.bodyPaddingRight; } this.bodyOverflow = null; this.bodyPaddingRight = null; }, 200); } this.opened = false; if (!this.transition) { this.doAfterClose(); } }, doAfterClose() { PopupManager.closeModal(this._popupId); this._closing = false; } } }; export { PopupManager };
JavascriptTips/element
src/utils/popup/index.js
JavaScript
mit
6,321
(function () { 'use strict'; /** * @ngdoc function * @name app.test:homeTest * @description * # homeTest * Test of the app */ describe('homeCtrl', function () { var controller = null, $scope = null, $location; beforeEach(function () { module('g4mify-client-app'); }); beforeEach(inject(function ($controller, $rootScope, _$location_) { $scope = $rootScope.$new(); $location = _$location_; controller = $controller('HomeCtrl', { $scope: $scope }); })); it('Should HomeCtrl must be defined', function () { expect(controller).toBeDefined(); }); it('Should match the path Module name', function () { $location.path('/home'); expect($location.path()).toBe('/home'); }); }); })();
ltouroumov/amt-g4mify
client/app/modules/home/home-test.js
JavaScript
mit
739
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(context) { if(context.message && context.message){ if(context.message.type === 'COLLABROOM'){ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } } } } if(!isDeleteRequest){ callback(false); return false; } console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(function(er) { if(er) console.warn('ep_push2delete', er) callback([null]); }) } } exports.eejsBlock_editbarMenuRight = function(hook_name, args, cb) { if(!args.renderContext.req.url.match(/^\/(p\/r\..{16})/)) { args.content = eejs.require('ep_push2delete/templates/delete_button.ejs') + args.content; } cb(); };
marcelklehr/ep_push2delete
index.js
JavaScript
mit
1,374
version https://git-lfs.github.com/spec/v1 oid sha256:355954a2b585f8b34c53b8bea9346fabde06b161ec86b87e9b829bea4acb87e9 size 108190
yogeshsaroya/new-cdnjs
ajax/libs/materialize/0.95.0/js/materialize.min.js
JavaScript
mit
131
/** * Copyright (c) 2015, Alexander Orzechowski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Currently in beta stage. Changes can and will be made to the core mechanic * making this not backwards compatible. * * Github: https://github.com/Need4Speed402/tessellator */ Tessellator.TextureDummy = function (ready){ this.super(null); if (ready){ this.setReady(); }; }; Tessellator.extend(Tessellator.TextureDummy, Tessellator.Texture); Tessellator.TextureDummy.prototype.configure = Tessellator.EMPTY_FUNC; Tessellator.TextureDummy.prototype.bind = Tessellator.EMPTY_FUNC;
Need4Speed402/tessellator
src/textures/TextureDummy.js
JavaScript
mit
1,646
'use strict'; module.exports = function(sequelize, DataTypes) { var Student = sequelize.define('Student', { name: DataTypes.STRING, timeReq: DataTypes.INTEGER, }, { classMethods: { associate: function() { } } }); return Student; };
troops2devs/minutes
models/student.js
JavaScript
mit
268
const {xObjectForm} = require('./xObjectForm'); exports._getPathOptions = function _getPathOptions(options = {}, originX, originY) { this.current = this.current || {}; const colorspace = options.colorspace || this.options.colorspace; const colorName = options.colorName; const pathOptions = { originX, originY, font: this._getFont(options), size: options.size || this.current.defaultFontSize, charSpace: options.charSpace || 0, underline: false, color: this._transformColor(options.color, {colorspace:colorspace, colorName:options.colorName}), colorspace, colorName, colorArray: [], lineCap: this._lineCap(), lineJoin: this._lineJoin(), miterLimit: 1.414, width: 2, align: options.align }; if (options.opacity == void(0) || isNaN(options.opacity)) { options.opacity = 1; } else { options.opacity = (options.opacity < 0) ? 0 : (options.opacity > 1) ? 1 : options.opacity; } pathOptions.opacity = options.opacity; const extGStates = this._createExtGStates(options.opacity); pathOptions.strokeGsId = extGStates.stroke; pathOptions.fillGsId = extGStates.fill; if (options.size || options.fontSize) { const size = options.size || options.fontSize; if (!isNaN(size)) { pathOptions.size = (size <= 0) ? 1 : size; } } if (options.width || options.lineWidth) { const width = options.width || options.lineWidth; if (!isNaN(width)) { pathOptions.width = (width <= 0) ? 1 : width; } } const colorOpts = {colorspace:colorspace, wantColorModel:true, colorName: options.colorName}; if (options.stroke) { pathOptions.strokeModel = this._transformColor(options.stroke, colorOpts); pathOptions.stroke = pathOptions.strokeModel.color; } if (options.fill) { pathOptions.fillModel = this._transformColor(options.fill, colorOpts); pathOptions.fill = pathOptions.fillModel.color; } pathOptions.colorModel = this._transformColor((options.color || options.colour), colorOpts); pathOptions.color = pathOptions.colorModel.color; pathOptions.colorspace = pathOptions.colorModel.colorspace; // rotation if (options.rotation !== void(0)) { const rotation = parseFloat(options.rotation); pathOptions.rotation = rotation; pathOptions.rotationOrigin = options.rotationOrigin || null; } // skew if (options.skewX !== void(0)) { pathOptions.skewX = options.skewX; } if (options.skewY != void(0)) { pathOptions.skewY = options.skewY; } // Page 127 of PDF 1.7 specification pathOptions.dash = (Array.isArray(options.dash)) ? options.dash : []; pathOptions.dashPhase = (!isNaN(options.dashPhase)) ? options.dashPhase : 0; if (pathOptions.dash[0] == 0 && pathOptions.dash[1] == 0) { pathOptions.dash = []; // no dash, solid unbroken line pathOptions.dashPhase = 0; } // Page 125-126 of PDF 1.7 specification if (options.lineJoin !== void(0)) { pathOptions.lineJoin = this._lineJoin(options.lineJoin); } if (options.lineCap !== void(0)) { pathOptions.lineCap = this._lineCap(options.lineCap); } if (options.miterLimit !== void(0)) { if (!isNaN(options.miterLimit)) { pathOptions.miterLimit = options.miterLimit; } } return pathOptions; }; exports._getDistance = function _getDistance(coordA, coordB) { const disX = Math.abs(coordB[0] - coordA[0]); const disY = Math.abs(coordB[1] - coordB[1]); const distance = Math.sqrt(((disX * disX) + (disY * disY))); return distance; }; exports._getTransformParams = getTransformParams; function getTransformParams(inAngle, x, y, offsetX, offsetY) { const theta = toRadians(inAngle); const cosTheta = Math.cos(theta); const sinTheta = Math.sin(theta); const nx = (cosTheta * -offsetX) + (sinTheta * -offsetY); const ny = (cosTheta * -offsetY) - (sinTheta * -offsetX); return [cosTheta, -sinTheta, sinTheta, cosTheta, x - nx, y - ny]; } exports._setRotationContext = function _setRotationTransform(context, x, y, options) { const deltaY = (options.deltaY) ? options.deltaY : 0; if (options.rotation === undefined || options.rotation === 0) { context.cm(1, 0, 0, 1, x, y-deltaY); // no rotation } else { let rotationOrigin; if (!hasRotation(options)) { rotationOrigin = [options.originX, options.originY]; // supply default } else { if (options.useGivenCoords) { rotationOrigin = options.rotationOrigin; } else { const orig = this._calibrateCoordinate(options.rotationOrigin[0], options.rotationOrigin[1]); rotationOrigin = [orig.nx, orig.ny]; } } const rm = getTransformParams( // rotation matrix options.rotation, rotationOrigin[0], rotationOrigin[1], x - rotationOrigin[0], y - rotationOrigin[1] - deltaY ); context.cm(rm[0], rm[1], rm[2], rm[3], rm[4], rm[5]); } }; function hasRotation(options) { return options.rotationOrigin && Array.isArray(options.rotationOrigin) && options.rotationOrigin.length === 2; } function toRadians(angle) { return 2 * Math.PI * ((angle % 360) / 360); } function getSkewTransform(skewXAngle= 0 , skewYAngle = 0) { const alpha = toRadians(skewXAngle); const beta = toRadians(skewYAngle); const tanAlpha = Math.tan(alpha); const tanBeta = Math.tan(beta); return [1, tanAlpha, tanBeta, 1, 0, 0]; } exports._setSkewContext = function _setSkewTransform(context, options) { if (options.skewX || options.skewY) { const sm = getSkewTransform(options.skewX, options.skewY); context.cm(sm[0], sm[1], sm[2], sm[3], sm[4], sm[5]); } }; exports._setScalingTransform = function _setScalingTransform(context, options) { if (options.ratio) { context.cm(options.ratio[0], 0, 0, options.ratio[1], 0, 0); } }; exports._drawObject = function _drawObject(self, x, y, width, height, options, callback) { let xObject = options.xObject; // allows caller to supply existing form object if (!xObject) { self.pauseContext(); xObject = new xObjectForm(self.writer, width, height); const xObjectCtx = xObject.getContentContext(); xObjectCtx.q(); callback(xObjectCtx, xObject); xObjectCtx.Q(); xObject.end(); self.resumeContext(); } const context = self.pageContext; context.q(); self._setRotationContext(context, x, y, options); self._setSkewContext(context, options); self._setScalingTransform(context, options); context .doXObject(xObject) .Q(); }; exports._lineCap = function _lineCap(type) { const round = 1; let cap = round; if (type) { const capStyle = ['butt', 'round', 'square']; const capType = capStyle.indexOf(type); cap = (capType !== -1) ? capType : round; } return cap; }; exports._lineJoin = function _lineJoin(type) { const round = 1; let join = round; if (type) { const joinStyle = ['miter', 'round', 'bevel']; const joinType = joinStyle.indexOf(type); join = (joinType !== -1) ? joinType : round; } return join; };
chunyenHuang/hummusRecipe
lib/vector.helper.js
JavaScript
mit
7,549
test('has a constructor for initialization', () => { // Create an Animal class // Add a constructor that takes one param, the name. // Set this.name to the name passed in const animal = new Animal() const dog = new Animal('Dog') expect(animal.name).toBeUndefined() expect(dog.name).toBe('Dog') }) test('constructor can have default param values', () => { // Create an Animal class with a constructor // Make your class default (using default params) the name to 'Honey Badger' const animal = new Animal() const dog = new Animal('Dog') expect(animal.name).toBe('Honey Badger') expect(dog.name).toBe('Dog') }) test('can have instance methods', () => { // Create an Animal class, pass in the name to the constructor, and add a sayName function to the class definition const animal = new Animal() expect(animal.sayName).toBeDefined() expect(Animal.sayName).toBeUndefined() expect(animal.sayName()).toBe('My name is: Honey Badger') }) test('can have static methods', () => { // Create an Animal class, pass in the name to the constructor, // and add a create method that takes a name and returns an instance const animal = new Animal() expect(animal.create).toBeUndefined() expect(Animal.create).toBeDefined() }) test('can extend another class', () => { // Create an Animal class // Create a Dog class that extends Animal // Add sayName to Animal const dog = new Dog('Fido') expect(dog instanceof Dog).toBe(true) expect(dog instanceof Animal).toBe(true) }) test('can use property setters and getters', () => { // Create an Animal class (don't pass name into constructor) // Add property setter for name // Add property getter for name const animal = new Animal() animal.name = 'Dog' expect(animal.name).toBe('Dog type of animal') animal.name = 'Cat' expect(animal.name).toBe('Cat type of animal') }) //////// EXTRA CREDIT //////// // If you get this far, try adding a few more tests, then file a pull request to add them to the extra credit! // Learn more here: https://github.com/kentcdodds/es6-workshop/blob/master/CONTRIBUTING.md#development
wizzy25/es6-workshop
exercises/10_class.test.js
JavaScript
mit
2,133
 var report_test_url = "reports\\BSV_GC_n_08_du_22_octobre_2013.pdf"; var report_dir = "files/"; var report_extension = ".pdf"; /***************************************************************************************************************************/ /* report_panel */ function report_panel(panel, report_panel){//, on_search_report) { report_panel.report_list = report_panel.find("#report_list"); report_panel.report_list_count = report_panel.find("#report_list_count"); report_panel.report_total_count = report_panel.find("#report_total_count"); report_panel.report_filter = report_panel.find("#report_filter"); report_panel.report_filter_years = report_panel.find("#report_filter_years"); report_panel.report_filter_areas = report_panel.find("#report_filter_areas"); report_panel.report_filter_reset = report_panel.find(".filter_reset"); report_panel.report_sorter_panel = report_panel.find("#report_sorter").hide(); report_panel.report_sorters = report_panel.report_sorter_panel.find(".report_sorter_item"); report_panel.current_sort = "date"; report_panel.report_text_filter = report_panel.find("#report_text_filter").hide(); report_panel.btn_filter_text = report_panel.find("#btn_filter_text"); report_panel.opened_report_ids = new Array(); // Init filter reset report_panel.report_filter.hide(); report_panel.find("#filter_reset_years").click(function () { jQuery("#report_filter_years div").removeClass("selected"); report_panel.selected_year = null; report_panel.filter_on_change(); }); report_panel.find("#filter_reset_areas").click(function () { jQuery("#report_filter_areas div").removeClass("selected"); report_panel.selected_area = null; report_panel.filter_on_change(); }); // Sorters report_panel.report_sorters.click(function () { report_panel.sort_changed(jQuery(this)); }); report_panel.cover_up = panel.get_waiting_cover_up(report_panel, 100); /* List management *********************************************************/ // Search succeeded report_panel.search_succeeded = function (response) { console.time("[Report list] Create DOM on new search"); report_panel.opened_report_ids = new Array(); report_panel.selected_year = null; report_panel.selected_area = null; report_panel.report_sorter_panel.show(); report_panel.report_text_filter.show(); report_panel.clear_list(); report_panel.reports = response.Reports; if (report_panel.current_sort != "date") report_panel.sort_reports_array(report_panel.current_sort); report_panel.set_counts(); report_panel.create_list(response); report_panel.create_filters(response); console.timeEnd("[Report list] Create DOM on new search"); report_panel.cover_up.doFadeOut(); } /* Report list DOM creation *********************************************************/ // Show report list report_panel.set_counts = function () { report_panel.report_list_count.text(report_panel.reports.length); report_panel.report_total_count.text(report_panel.reports.length); } // Show report list report_panel.create_list = function () { var html = ""; for (i = 0; i < report_panel.reports.length; i++) { html += report_panel.create_report_item(report_panel.reports[i],i); } report_panel.report_list.html(html); jQuery("#report_list a").click(function () { var report_item = jQuery(this).parent().parent(); report_panel.opened_report_ids.push(report_item.attr("id_report")); report_item.addClass("opened"); }); } // Create report item list report_panel.create_report_item = function (data, index) { var opened = jQuery.inArray("" + data.Id, report_panel.opened_report_ids) != -1; var report_item = "<div class='report_item" + ( (index % 2 == 1) ? " alt" : "") + ((opened) ? " opened" : "") + "' year='" + data.Year + "' id_area='" + data.Id_Area + "' id_report='" + data.Id + "' >" + "<div class='report_area'>" + "<div class='cube'></div>" + "<div class='report_area_name'>" + data.AreaName + "</div>" + "<div class='report_date'>" + data.DateString + "</div>" + "</div>" + "<div class='report_name'>" + "<a href='" + report_dir + data.Name + report_extension + "' target='_blank' title='" + data.Name + "'>" + data.Name + "</a>" + "<div class='report_pdf'></div>" + "</div>" + "</div>" return report_item; } // Clear list report_panel.clear_list = function () { report_panel.report_list.empty(); report_panel.report_filter_areas.empty(); report_panel.report_filter_years.empty(); report_panel.report_list_count.text("0"); report_panel.report_total_count.text("0"); } /* Filter Methods *********************************************************/ // Filters creation report_panel.create_filters = function (response) { var reports_by_year = d3.nest() .key(function (d) { return d.Year; }) .rollup(function (g) { return g.length; }) .entries(response.Reports); for (i = 0; i < response.Years.length; i++) { var year_item = jQuery("<div year='" + reports_by_year[i].key + "'></div>") .append("<span class='filter_year_item_text'>" + reports_by_year[i].key + "</span>") .append("<span class='filter_year_item_count'>(" + reports_by_year[i].values + ")</span>") .click(function () { jQuery("#report_filter_years div").removeClass("selected"); jQuery(this).addClass("selected"); report_panel.selected_year = jQuery(this).attr("year"); report_panel.filter_on_change(); }) .appendTo(report_panel.report_filter_years); } report_panel.report_filter.show(); } report_panel.filter_area = function (id_area) { report_panel.selected_area = id_area; report_panel.filter_on_change(); } // On filter selection report_panel.filter_on_change = function () { report_panel.report_list.find(".report_item").hide(); var class_to_show = ".report_item"; if (report_panel.selected_area != null) class_to_show += "[id_area='" + report_panel.selected_area + "']"; if (report_panel.selected_year != null) class_to_show += "[year='" + report_panel.selected_year + "']"; var to_show = report_panel.report_list.find(class_to_show); to_show.show(); report_panel.report_list_count.text(to_show.length); } /* Sort Methods *********************************************************/ // on Sort report_panel.sort_changed = function (sorter) { report_panel.report_sorters.removeClass("selected"); sorter.addClass("selected") var previous_sort = report_panel.current_sort; report_panel.current_sort = sorter.attr("sort"); if (previous_sort == report_panel.current_sort) { if (report_panel.current_sort.indexOf("_desc") != -1) { report_panel.current_sort = report_panel.current_sort.replace("_desc", ""); } else { report_panel.current_sort = report_panel.current_sort + "_desc"; } } report_panel.cover_up.fadeIn(duration_fade_short, function () { report_panel.sort_list(report_panel.current_sort); report_panel.cover_up.fadeOut(duration_fade_short); }); } // Sort list report_panel.sort_list = function (sort_type) { report_panel.report_list.empty(); report_panel.sort_reports_array(report_panel.current_sort); report_panel.create_list(); report_panel.filter_on_change(); } // Data sorting function report_panel.sort_reports_array = function (sort_type) { var sort_func = null; if (sort_type == "name") { sort_func = report_panel.sort_name; } else if (sort_type == "name_desc") { sort_func = report_panel.sort_name_desc; } else if (sort_type == "area_name") { sort_func = report_panel.sort_area_name; } else if (sort_type == "area_name_desc") { sort_func = report_panel.sort_area_name_desc; } else if (sort_type == "date") { sort_func = report_panel.sort_date; } else if (sort_type == "date_desc") { sort_func = report_panel.sort_date_desc; } report_panel.reports.sort(sort_func); } // Date sort delegate report_panel.sort_date = function (e_1, e_2) { var a1 = parseInt(e_1.Date.substr(6)), b1 = parseInt(e_2.Date.substr(6)); if (a1 == b1) return 0; return a1 > b1 ? 1 : -1; } // Arean name sort delegate report_panel.sort_area_name = function (e_1, e_2) { var a1 = e_1.AreaName, b1 = e_2.AreaName; if (a1 == b1) return 0; return a1 > b1 ? 1 : -1; } // file name sort delegate report_panel.sort_name = function (e_1, e_2) { var a1 = e_1.Name.toLowerCase(), b1 = e_2.Name.toLowerCase(); if (a1 == b1) return 0; return a1 > b1 ? 1 : -1; } // Date sort delegate report_panel.sort_date_desc = function (e_1, e_2) { var a1 = parseInt(e_1.Date.substr(6)), b1 = parseInt(e_2.Date.substr(6)); if (a1 == b1) return 0; return a1 < b1 ? 1 : -1; } // Arean name sort delegate report_panel.sort_area_name_desc = function (e_1, e_2) { var a1 = e_1.AreaName, b1 = e_2.AreaName; if (a1 == b1) return 0; return a1 < b1 ? 1 : -1; } // file name sort delegate report_panel.sort_name_desc = function (e_1, e_2) { var a1 = e_1.Name.toLowerCase(), b1 = e_2.Name.toLowerCase(); if (a1 == b1) return 0; return a1 < b1 ? 1 : -1; } report_panel.open_report = function (id_report) { var report_item_anchor = report_panel.find("#report_list .report_item[id_report='" + id_report + "'] a"); report_item_anchor.click(); window.open(report_item_anchor.attr("href"), "_blank"); } return report_panel; }
win-stub/PestObserver
web/scripts/report_panel.js
JavaScript
mit
11,254
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'about', 'pt-br', { copy: 'Copyright &copy; $1. Todos os direitos reservados.', dlgTitle: 'Sobre o CKEditor 4', moreInfo: 'Para informações sobre a licença por favor visite o nosso site:' } );
otto-torino/gino
ckeditor/plugins/about/lang/pt-br.js
JavaScript
mit
400
var bind = require('bind'); var debug = require('debug')('uj:app'); var Entity = require('./entity'); var inherit = require('inherit'); /** * Initialize a new `App` with `options`. * * @param {Object} options */ function App (options) { this.defaults = {} this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(App, Entity); /** * Load saved app `id` or `traits` from storage. */ App.prototype.load = function () { Entity.prototype.load.call(this); }; /** * Expose the app singleton. */ module.exports = bind.all(new App()); /** * Expose the `App` constructor. */ module.exports.App = App;
prateekbhatt/userjoy
apps/cdn/lib/app.js
JavaScript
mit
655
//================================================================ // RS_ChangeWindowTextColorSafely.js // --------------------------------------------------------------- // The MIT License // Copyright (c) 2017 biud436 // --------------------------------------------------------------- // Free for commercial and non commercial use. //================================================================ /*:ko * @target MV * @plugindesc 특정 창의 텍스트 색상을 원하는 색상으로 변경할 수 있습니다 <RS_ChangeWindowTextColorSafely> * @author biud436 * * @param windowList * @text 사용자 정의 색상 * @type note * @desc 도움말을 참고하세요! * @default "" * * @help * ============================================================================= * 사용 방법 * ============================================================================= * 각 창에 서로 다른 텍스트 색상을 적용하려면, * 사용자 정의 색상 매개변수에 다음 노트 태그를 입력해야 합니다. * * <Window_ItemList normalColor #ff0000> * <Window_SkillList normalColor #ffff00> * <Window_SkillList crisisColor #ff0000> * * 노트 태그는 클래스 이름과 해당 클래스의 메소드 이름 그리고 색상 값을 제공해야 하므로, * 정확히 입력하시기 바랍니다. * * 정말 많은 메소드를 바꿀 수 있지만 모두 표기하진 않았습니다. * * 바뀐 색상은 게임 내에서 확인할 수 있습니다. * * ============================================================================= * 변경 기록 * ============================================================================= * 2017.12.21 (v1.0.0) - First Release. */ /*: * @target MV * @plugindesc This plugin allows you to change the text color for window as you desired. <RS_ChangeWindowTextColorSafely> * @author biud436 * * @param windowList * @text Window List * @type note * @desc Refer to a help documentation * @default "" * * @help * * We're going to define each window a different special color. To quickly define, * We must use to define a notetag in the plugin parameter called 'Window List' * * <Window_ItemList normalColor #ff0000> * <Window_SkillList normalColor #ffff00> * <Window_SkillList crisisColor #ff0000> * * Note tags provide the information likes as a class name and method name, * color value for window. You can see how the text color for window that is * changed in the game. * * ============================================================================= * Change Log * ============================================================================= * 2017.12.21 (v1.0.0) - First Release. */ var Imported = Imported || {}; Imported.RS_ChangeWindowTextColorSafely = true; var RS = RS || {}; RS.Utils = RS.Utils || {}; (() => { let parameters = $plugins.filter(function (i) { return i.description.contains("<RS_ChangeWindowTextColorSafely>"); }); parameters = parameters.length > 0 && parameters[0].parameters; RS.Utils.jsonParse = function (str) { const retData = JSON.parse(str, function (k, v) { try { return RS.Utils.jsonParse(v); } catch (e) { return v; } }); return retData; }; const defaultWindowClasses = RS.Utils.jsonParse(parameters["windowList"]); Utils.changeWindowTextColorSafely = function (NOTETAGS) { let clsName = ""; let funcName = ""; let color = ""; let done = false; const notetags = NOTETAGS.split(/[\r\n]+/); notetags.forEach((note) => { if (note.match(/<(.*)[ ](.*)[ ](.*)>/)) { clsName = String(RegExp.$1); funcName = String(RegExp.$2); color = String(RegExp.$3); done = true; } if (done) { const CLASS_NAME = window[clsName]; const FUNC_NAME = funcName.slice(0); const COLOR_NAME = color.slice(0); if (typeof CLASS_NAME === "function") { const prototypeName = CLASS_NAME.prototype[FUNC_NAME]; if (typeof prototypeName === "function") { CLASS_NAME.prototype[funcName] = function () { return COLOR_NAME; }; } } } }); }; Utils.changeWindowTextColorSafely(defaultWindowClasses); })();
biud436/MV
RS_ChangeWindowTextColorSafely.js
JavaScript
mit
4,574
'use strict'; var defaultEnvConfig = require('./default'); module.exports = { db: { uri: process.env.MONGOHQ_URL || process.env.MONGODB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/flipflop-test', options: { user: '', pass: '' }, // Enable mongoose debug mode debug: process.env.MONGODB_DEBUG || false }, log: { // logging with Morgan - https://github.com/expressjs/morgan // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny' // format: 'dev' // fileLogger: { // directoryPath: process.cwd(), // fileName: 'app.log', // maxsize: 10485760, // maxFiles: 2, // json: false // } }, port: process.env.PORT || 3001, app: { title: defaultEnvConfig.app.title + ' - Test Environment' }, uploads: { profile: { image: { dest: './modules/users/client/img/profile/uploads/', limits: { fileSize: 100000 // Limit filesize (100kb) for testing purposes } } } }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/api/auth/facebook/callback' }, twitter: { username: '@TWITTER_USERNAME', clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/api/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/api/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/api/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/api/auth/github/callback' }, paypal: { clientID: process.env.PAYPAL_ID || 'CLIENT_ID', clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET', callbackURL: '/api/auth/paypal/callback', sandbox: true }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } }, seedDB: { seed: process.env.MONGO_SEED === 'true', options: { logResults: process.env.MONGO_SEED_LOG_RESULTS !== 'false', seedUser: { username: process.env.MONGO_SEED_USER_USERNAME || 'seeduser', provider: 'local', email: process.env.MONGO_SEED_USER_EMAIL || 'user@localhost.com', firstName: 'User', lastName: 'Local', displayName: 'User Local', roles: ['user'] }, seedAdmin: { username: process.env.MONGO_SEED_ADMIN_USERNAME || 'seedadmin', provider: 'local', email: process.env.MONGO_SEED_ADMIN_EMAIL || 'admin@localhost.com', firstName: 'Admin', lastName: 'Local', displayName: 'Admin Local', roles: ['user', 'admin'] } } } };
tonymullen/flipflop
config/env/test.js
JavaScript
mit
3,286
'use strict'; const { messages, ruleName } = require('..'); testRule({ ruleName, config: [ { border: 2, '/^margin/': 1, }, ], accept: [ { code: 'a { margin: 0; }', }, { code: 'a { margin: 1px; }', }, { code: 'a { margin: var(--foo); }', description: 'deals with CSS variables', }, { code: 'a { margin: 1px /* 3px */; }', description: 'ignore values in comments', }, { code: 'a { margin-inline: 1px; }', }, { code: 'a { margin: ; }', }, { code: 'a { border: 1px; }', }, { code: 'a { border: 1px solid; }', }, { code: 'a { transition: margin-right 2s ease-in-out; }', description: 'irrelevant shorthand', }, ], reject: [ { code: 'a { margin: 1px 2px; }', message: messages.rejected('margin', 1), line: 1, column: 5, }, { code: 'a { margin-inline: 1px 2px; }', message: messages.rejected('margin-inline', 1), line: 1, column: 5, }, { code: 'a { margin: var(--foo) var(--bar); }', message: messages.rejected('margin', 1), line: 1, column: 5, description: 'deals with CSS variables', }, { code: 'a { margin: 1px 2px 3px 4px; }', message: messages.rejected('margin', 1), line: 1, column: 5, }, { code: 'a { margin: 0 0 0 0; }', message: messages.rejected('margin', 1), line: 1, column: 5, }, { code: 'a { border: 1px solid blue; }', message: messages.rejected('border', 2), line: 1, column: 5, }, ], });
stylelint/stylelint
lib/rules/declaration-property-max-values/__tests__/index.js
JavaScript
mit
1,491
// Regular expression that matches all symbols in the `Kaithi` script as per Unicode v6.0.0: /\uD804[\uDC80-\uDCC1]/;
mathiasbynens/unicode-data
6.0.0/scripts/Kaithi-regex.js
JavaScript
mit
117
import React from 'react'; import HomeLayout from '../layouts/HomeLayout'; import BookEditor from '../components/BookEditor'; import { get } from '../utils/request'; class BookEdit extends React.Component { constructor(props) { super(props); this.state = { book: null }; } componentWillMount() { const bookId = this.context.router.params.id; get('http://localhost:3000/book/' + bookId) .then(res => { this.setState({ book: res }); }); } render() { const { book } = this.state; return book ? <BookEditor editTarget={book} /> : <span>加载中...</span>; } } BookEdit.contextTypes = { router: React.PropTypes.object.isRequired }; export default BookEdit;
prodigalyijun/demo-by-antd
src/pages/BookEdit.js
JavaScript
mit
829
var Peer = require('../lib/Peer'); var Connection = require('../lib/Connection'); var dns = require('dns'); // get a peer from dns seed dns.resolve('dnsseed.bluematt.me', function(err, seeds) { // use the first peer var peer = new Peer(seeds[0], 8608); //Custom peer: //var peer = new Peer('180.153.139.246', '8888'); // create a connection without an existing socket // but specify a socks5 proxy to create a socket // that's bound to that proxy in it's place var connection = new Connection(null, peer, { proxy: { host: '127.0.0.1', port: 9050 } }); connection.open(); connection.on('connect', function(data) { console.log('connected through socks5!'); }); connection.on('error', function(err) { console.log('There was an error running this example.'); console.log('Are you running Tor? Tor must running for this example to work.'); console.log('If you still get an error, you may need to use a different proxy from here:'); console.log('http://sockslist.net/'); //console.log(err); }); });
Bushstar/bitcore
examples/ConnectionTor.js
JavaScript
mit
1,072
import {Utils} from "../service/Utils"; Template.registerHelper( "displayHours", function (date) { return new moment(date).format("H[h]"); } ); Template.registerHelper( "displayHoursMinute", function (date) { return new moment(date).format("H[h]mm"); } ); Template.registerHelper( "displayHoursMinuteSeconde", function (date) { return new moment(date).format("H[h]mm ss[sec]"); } ); Template.registerHelper( "displayDateTime", function (date) { return new moment(date).format("ddd DD MMM HH[h]mm"); } ); Template.registerHelper( "displayDay", function (date) { return new moment(date).format("DD MMM"); } ); Template.registerHelper( "skillLabel", function () { return Skills.findOne({_id: this.toString()}).label; } ); Template.registerHelper( "onUpdateError", function (error) { return function (error) { Utils.onUpdateError(error.reason) } }); Template.registerHelper( "onUpdateSuccess", function (message) { return function (message) { Utils.onUpdateSuccess(message); } }); Template.registerHelper( "onDeleteError", function (error) { return function (error) { Utils.onUpdateError(error.reason) } }); Template.registerHelper( "onDeleteSuccess", function (message) { return function (message) { Utils.onUpdateSuccess(message); } }); Template.registerHelper( "allTeams", function () { return Teams.find(); } ); Template.registerHelper('equals', function (a, b) { return a === b; }); Template.registerHelper('adds', function (a, b) { return a + b; }); Template.registerHelper( "allOptionsTeams", function () { return Teams.find({ name: { $ne: ASSIGNMENTREADYTEAM } }); } ); Template.registerHelper( "allSkills", function (userId) { var userTeams = Meteor.users.findOne({_id: userId}).teams; return Skills.find({ teams: { $in: userTeams } }); } ); Template.registerHelper('ifNotEmpty', function (item, options) { if (item) { if (item instanceof Array) { if (item.length > 0) { return options.fn(this); } else { return options.inverse(this); } } else { if (item.fetch().length > 0) { return options.fn(this); } else { return options.inverse(this); } } } else { return options.inverse(this); } }); Template.registerHelper("equals", function (a, b) { return a === b; } ); Template.registerHelper("isMore", function (a, b) { return a > b; } ); Template.registerHelper("displayValidationState", function (state) { return DisplayedValidationState[state]; }); Template.registerHelper("RolesEnum", function () { return RolesEnum; }); Template.registerHelper( "currentUserId", function () { return Meteor.users.findOne({_id: Meteor.userId()})._id; } ); Template.registerHelper( "isCurrentUserTheOneLogged", function (currentUserId) { return currentUserId === Meteor.users.findOne({_id: Meteor.userId()})._id; } ) Template.registerHelper( "currentUserIdObject", function () { return { _id: Meteor.users.findOne({_id: Meteor.userId()})._id } } ); Template.registerHelper("cursorLength", function (array) { return array.fetch().length; } );
assomaker/manifmaker
app/client/helpers-events/global-helpers.js
JavaScript
mit
3,295
"use strict"; /* * Copyright (c) 2013-2019 Bert Freudenberg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ Object.extend(Squeak.Primitives.prototype, 'ScratchPluginAdditions', { // methods not handled by generated ScratchPlugin scratch_primitiveOpenURL: function(argCount) { var url = this.stackNonInteger(0).bytesAsString(); if (url == "") return false; if (/^\/SqueakJS\//.test(url)) { url = url.slice(10); // remove file root var path = Squeak.splitFilePath(url), template = Squeak.Settings["squeak-template:" + path.dirname]; if (template) url = JSON.parse(template).url + "/" + path.basename; } window.open(url, "_blank"); // likely blocked as pop-up, but what can we do? return this.popNIfOK(argCount); }, scratch_primitiveGetFolderPath: function(argCount) { var index = this.stackInteger(0); if (!this.success) return false; var path; switch (index) { case 1: path = '/'; break; // home dir // case 2: path = '/desktop'; break; // desktop // case 3: path = '/documents'; break; // documents // case 4: path = '/pictures'; break; // my pictures // case 5: path = '/music'; break; // my music } if (!path) return false; this.vm.popNandPush(argCount + 1, this.makeStString(this.filenameToSqueak(path))); return true; }, });
bertfreudenberg/SqueakJS
vm.plugins.scratch.browser.js
JavaScript
mit
2,534
const React = require('react'); const { ViewPropTypes } = ReactNative = require('react-native'); const { View, Animated, StyleSheet, ScrollView, Text, Platform, Dimensions, I18nManager } = ReactNative; const Button = require('./Button'); //import { PropTypes } from 'react' const WINDOW_WIDTH = Dimensions.get('window').width; const ScrollableTabBar = React.createClass({ propTypes: { goToPage: React.PropTypes.func, activeTab: React.PropTypes.number, tabs: React.PropTypes.array, backgroundColor: React.PropTypes.string, activeTextColor: React.PropTypes.string, inactiveTextColor: React.PropTypes.string, scrollOffset: React.PropTypes.number, //style: ViewPropTypes.style, //tabStyle: ViewPropTypes.style, //tabsContainerStyle: ViewPropTypes.style, //tabStyle: ViewPropTypes.style, textStyle: Text.propTypes.style, renderTab: React.PropTypes.func, //underlineStyle: ViewPropTypes.style, onScroll:React.PropTypes.func, }, getDefaultProps() { return { scrollOffset: 52, activeTextColor: 'navy', inactiveTextColor: 'black', backgroundColor: null, style: {}, tabStyle: {}, tabsContainerStyle: {}, tabStyle: {}, underlineStyle: {}, }; }, getInitialState() { this._tabsMeasurements = []; return { _leftTabUnderline: new Animated.Value(0), _widthTabUnderline: new Animated.Value(0), _containerWidth: null, }; }, componentDidMount() { this.props.scrollValue.addListener(this.updateView); }, updateView(offset) { //console.log("updateView="+JSON.stringify(offset)); //console.log("updateView="+JSON.stringify(this.props)); const position = Math.floor(offset.value); const pageOffset = offset.value % 1; const tabCount = this.props.tabs.length; const lastTabPosition = tabCount - 1; if (tabCount === 0 || offset.value < 0 || offset.value > lastTabPosition) { return; } if (this.necessarilyMeasurementsCompleted(position, position === lastTabPosition)) { this.updateTabPanel(position, pageOffset); this.updateTabUnderline(position, pageOffset, tabCount); } }, necessarilyMeasurementsCompleted(position, isLastTab) { return this._tabsMeasurements[position] && (isLastTab || this._tabsMeasurements[position + 1]) && this._tabContainerMeasurements && this._containerMeasurements; }, updateTabPanel(position, pageOffset) { const containerWidth = this._containerMeasurements.width; const tabWidth = this._tabsMeasurements[position].width; //console.log("containerWidth="+containerWidth+" tabWidth="+tabWidth); const nextTabMeasurements = this._tabsMeasurements[position + 1]; const nextTabWidth = nextTabMeasurements && nextTabMeasurements.width || 0; const tabOffset = this._tabsMeasurements[position].left; const absolutePageOffset = pageOffset * tabWidth; let newScrollX = tabOffset + absolutePageOffset; // center tab and smooth tab change (for when tabWidth changes a lot between two tabs) newScrollX -= (containerWidth - (1 - pageOffset) * tabWidth - pageOffset * nextTabWidth) / 2; newScrollX = newScrollX >= 0 ? newScrollX : 0; if (Platform.OS === 'android') { this._scrollView.scrollTo({x: newScrollX, y: 0, animated: false, }); } else { const rightBoundScroll = this._tabContainerMeasurements.width - (this._containerMeasurements.width); newScrollX = newScrollX > rightBoundScroll ? rightBoundScroll : newScrollX; this._scrollView.scrollTo({x: newScrollX, y: 0, animated: false, }); } }, updateTabUnderline(position, pageOffset, tabCount) { const tabPad = this.props.underlineAlignText?this.props.tabPadding:0; const lineLeft = this._tabsMeasurements[position].left; const lineRight = this._tabsMeasurements[position].right; if (position < tabCount - 1) { const nextTabLeft = this._tabsMeasurements[position + 1].left; const nextTabRight = this._tabsMeasurements[position + 1].right; const newLineLeft = (pageOffset * nextTabLeft + (1 - pageOffset) * lineLeft); const newLineRight = (pageOffset * nextTabRight + (1 - pageOffset) * lineRight); this.state._leftTabUnderline.setValue(newLineLeft+tabPad); this.state._widthTabUnderline.setValue(newLineRight - newLineLeft -tabPad*2); } else { this.state._leftTabUnderline.setValue(lineLeft+tabPad); this.state._widthTabUnderline.setValue(lineRight - lineLeft-tabPad*2); } }, renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler) { const { activeTextColor, inactiveTextColor, textStyle, } = this.props; const textColor = isTabActive ? activeTextColor : inactiveTextColor; const fontWeight = isTabActive ? 'bold' : 'normal'; return <Button key={`${name}_${page}`} accessible={true} accessibilityLabel={name} accessibilityTraits='button' onPress={() => onPressHandler(page)} onLayout={onLayoutHandler} > <View style={[this.props.tabStyle||styles.tab, ]}> <Text style={[{color: textColor, fontWeight, }, textStyle, ]}> {name} </Text> </View> </Button>; }, measureTab(page, event) { console.log("measureTab="+page+"layout "+JSON.stringify(event.nativeEvent.layout)); const { x, width, height, } = event.nativeEvent.layout; this._tabsMeasurements[page] = {left: x, right: x + width, width, height, }; this.updateView({value: this.props.scrollValue._value, }); }, render() { const tabUnderlineStyle = { position: 'absolute', height: 1, backgroundColor: 'navy', bottom: 0, }; const key = I18nManager.isRTL ? 'right' : 'left'; const dynamicTabUnderline = { [`${key}`]: this.state._leftTabUnderline, width: this.state._widthTabUnderline } return <View style={[this.props.tabsContainerStyle||styles.container, ]} onLayout={this.onContainerLayout} > <ScrollView automaticallyAdjustContentInsets={false} ref={(scrollView) => { this._scrollView = scrollView; }} horizontal={true} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} directionalLockEnabled={true} onScroll={this.props.onScroll} bounces={false} scrollsToTop={false} > <View style={[styles.tabs, {width: this.state._containerWidth, }, ]} ref={'tabContainer'} onLayout={this.onTabContainerLayout} > {this.props.tabs.map((name, page) => { const isTabActive = this.props.activeTab === page; const renderTab = this.props.renderTab || this.renderTab; return renderTab(name, page, isTabActive, this.props.goToPage, this.measureTab.bind(this, page)); })} <Animated.View style={[tabUnderlineStyle, dynamicTabUnderline, this.props.underlineStyle, ]} /> </View> </ScrollView> </View>; }, componentWillReceiveProps(nextProps) { // If the tabs change, force the width of the tabs container to be recalculated if (JSON.stringify(this.props.tabs) !== JSON.stringify(nextProps.tabs) && this.state._containerWidth) { this.setState({ _containerWidth: null, }); } }, onTabContainerLayout(e) { this._tabContainerMeasurements = e.nativeEvent.layout; let width = this._tabContainerMeasurements.width; if (width < WINDOW_WIDTH) { width = WINDOW_WIDTH; } this.setState({ _containerWidth: width, }); this.updateView({value: this.props.scrollValue._value, }); }, onContainerLayout(e) { this._containerMeasurements = e.nativeEvent.layout; this.updateView({value: this.props.scrollValue._value, }); }, }); module.exports = ScrollableTabBar; const styles = StyleSheet.create({ tab: { height: 49, alignItems: 'center', justifyContent: 'center', paddingLeft: 20, paddingRight: 20, }, container: { height: 50, borderWidth: 1, borderTopWidth: 0, borderLeftWidth: 0, borderRightWidth: 0, borderColor: '#ccc', }, tabs: { flexDirection: 'row', // justifyContent: 'space-around', android设备可能撞车 }, });
jackuhan/react-native-viewpager-indicator
ScrollableTabBar.js
JavaScript
mit
8,319
var expect = require('chai').expect, sinon = require('sinon'), EventEmitter = require('../src/EventEmitter'); describe('EventEmitter tests', function() { var emitter, foo, bar; beforeEach(function() { emitter = new EventEmitter(); foo = sinon.spy(); bar = sinon.spy(); }); describe('.on', function() { it('should throw error if foo is not a function', function() { var fn = emitter.on.bind(null, 'abc', 'abc'); expect(fn).to.throw(TypeError); }); it('should register event with emitter._events', function() { emitter.on('data', foo); expect(emitter._events.data[0]).to.equal(foo); }); it('should be able to register multiple foos', function() { emitter.on('data', foo); emitter.on('data', bar); expect(emitter._events.data[0]).to.equal(foo); expect(emitter._events.data[1]).to.equal(bar); }); it('should return itself', function() { expect(emitter.on('data', foo)).to.equal(emitter); }); it('emits newListener event with event name and listener args', function() { var emitSpy = sinon.spy(emitter, 'emit'); emitter.on('foo', foo); sinon.assert.calledOnce(emitSpy); sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo); }); }); describe('.emit', function() { beforeEach(function() { emitter.on('data', foo); emitter.on('data', bar); }); it('should trigger listeners bound to event', function() { emitter.emit('data'); expect(foo.calledOnce).to.be.true; expect(bar.calledOnce).to.be.true; }); it('should trigger listeners in order', function() { emitter.emit('data'); expect(foo.calledBefore(bar)).to.be.true; }); it('should apply arguments to each listener', function() { var arg1 = 1, arg2 = '2', arg3 = {}; emitter.emit('data', arg1, arg2, arg3); sinon.assert.calledWithExactly(foo, arg1, arg2, arg3); }); it('should bind "this" to the emitter in listener', function(done) { var fn = function() { expect(this).to.equal(emitter); done(); }; emitter.on('data', fn); emitter.emit('data'); }); it('should return true if listeners were fired', function() { expect(emitter.emit('data')).to.be.true; }); it('should return false if no listeners fired', function() { expect(emitter.emit('adf')).to.be.false; }); }); describe('.removeAllListeners', function() { beforeEach(function() { emitter.on('foo', foo); emitter.on('foo', function() {}); emitter.on('bar', bar); }); it('should remove all listeners if no parameter', function() { emitter.removeAllListeners(); expect(emitter._events).to.be.empty; }); it('should only remove listeners to specified event', function() { emitter.removeAllListeners('foo'); expect(emitter._events.foo).to.be.undefined; expect(emitter._events.bar).to.not.be.undefined; }); it('should return the emitter', function() { expect(emitter.removeAllListeners()).to.equal(emitter); }); }); describe('.removeListener', function() { var baz; beforeEach(function() { baz = sinon.spy(); emitter.on('foo', foo); emitter.on('foo', baz); emitter.on('bar', bar); }); it('should remove only one listener for event', function() { emitter.removeListener('foo', baz); expect(emitter._events.foo.length).to.equal(1); expect(emitter._events.foo[0]).to.equal(foo); }); it('should throw error if listener is not a function', function() { var fn = emitter.removeListener.bind(emitter, 'foo', 'foo'); expect(fn).to.throw(TypeError); }); it('should return the emitter', function() { expect(emitter.removeListener('foo', foo)).to.equal(emitter); }); it('should be able to remove listener added by .once', function() { var qux = sinon.spy(); emitter.once('bar', qux); emitter.removeListener('bar', qux); expect(emitter._events.bar.length).to.equal(1); expect(emitter._events.bar[0]).to.equal(bar); }); it('should emit removeListener event with event name and listener args', function() { var emitSpy = sinon.spy(emitter, 'emit'); emitter.removeListener('foo', foo); sinon.assert.calledOnce(emitSpy); sinon.assert.calledWith(emitSpy, 'removeListener', 'foo', foo); }); }); describe('.once', function() { it('should throw error if listener is not a function', function() { var fn = emitter.once.bind(null, 'abc', 'abc'); expect(fn).to.throw(TypeError); }); it('should register a listener', function() { emitter.once('foo', foo); expect(emitter._events.foo.length).to.equal(1); }); it('should run registered function', function() { emitter.once('foo', foo); emitter.emit('foo'); expect(foo.calledOnce).to.be.true; }); it('should remove listener after .emit', function() { emitter.once('foo', foo); emitter.emit('foo'); expect(emitter._events.foo).to.be.empty; }); it('should pass all parameters from listener', function() { var arg1 = 1, arg2 = '2', arg3 = {}; emitter.once('foo', foo); emitter.emit('foo', arg1, arg2, arg3); sinon.assert.calledWithExactly(foo, arg1, arg2, arg3); }); it('should return the emitter', function() { expect(emitter.once('foo', foo)).to.equal(emitter); }); it('emits newListener event with event name and listener args', function() { var emitSpy = sinon.spy(emitter, 'emit'); emitter.once('foo', foo); sinon.assert.calledOnce(emitSpy); sinon.assert.calledWith(emitSpy, 'newListener', 'foo', foo); }); }); describe('.listeners', function() { beforeEach(function() { emitter.on('foo', foo); emitter.on('bar', bar); }); it('should return an array of listeners for an event', function() { expect(emitter.listeners('foo')).to.deep.equal([foo]); }); it('should return an empty array for unregistered events', function() { expect(emitter.listeners('abcd')).to.deep.equal([]); }); }); describe('.addListener', function() { it('should be alias to .on', function() { expect(emitter.addListener).to.equal(emitter.on); }); }); describe('.off', function() { it('should alias to .removeListener', function() { expect(emitter.off).to.equal(emitter.removeListener); }); }); describe('EventEmitter.listenerCount', function() { beforeEach(function() { emitter.on('foo', foo); emitter.on('foo', function() {}); emitter.on('bar', bar); }); it('should return 0 for non emitters', function() { expect(EventEmitter.listenerCount(1)).to.equal(0); }); it('should return 0 for no listeners', function() { expect(EventEmitter.listenerCount(emitter, 'baz')).to.equal(0); }); it('should return number of listeners', function() { expect(EventEmitter.listenerCount(emitter, 'foo')).to.equal(2); }); }); });
jimgswang/EventEmitter
test/EventEmitter.test.js
JavaScript
mit
8,204
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @extends {WebInspector.Object} * @param {string} id * @param {string} name */ WebInspector.ProfileType = function(id, name) { WebInspector.Object.call(this); this._id = id; this._name = name; /** @type {!Array.<!WebInspector.ProfileHeader>} */ this._profiles = []; /** @type {?WebInspector.ProfileHeader} */ this._profileBeingRecorded = null; this._nextProfileUid = 1; window.addEventListener("unload", this._clearTempStorage.bind(this), false); } /** * @enum {string} */ WebInspector.ProfileType.Events = { AddProfileHeader: "add-profile-header", ProfileComplete: "profile-complete", RemoveProfileHeader: "remove-profile-header", ViewUpdated: "view-updated" } WebInspector.ProfileType.prototype = { /** * @return {boolean} */ hasTemporaryView: function() { return false; }, /** * @return {?string} */ fileExtension: function() { return null; }, get statusBarItems() { return []; }, get buttonTooltip() { return ""; }, get id() { return this._id; }, get treeItemTitle() { return this._name; }, get name() { return this._name; }, /** * @return {boolean} */ buttonClicked: function() { return false; }, get description() { return ""; }, /** * @return {boolean} */ isInstantProfile: function() { return false; }, /** * @return {boolean} */ isEnabled: function() { return true; }, /** * @return {!Array.<!WebInspector.ProfileHeader>} */ getProfiles: function() { /** * @param {!WebInspector.ProfileHeader} profile * @return {boolean} * @this {WebInspector.ProfileType} */ function isFinished(profile) { return this._profileBeingRecorded !== profile; } return this._profiles.filter(isFinished.bind(this)); }, /** * @return {?Element} */ decorationElement: function() { return null; }, /** * @nosideeffects * @param {number} uid * @return {?WebInspector.ProfileHeader} */ getProfile: function(uid) { for (var i = 0; i < this._profiles.length; ++i) { if (this._profiles[i].uid === uid) return this._profiles[i]; } return null; }, /** * @param {!File} file */ loadFromFile: function(file) { var name = file.name; if (name.endsWith(this.fileExtension())) name = name.substr(0, name.length - this.fileExtension().length); var profile = this.createProfileLoadedFromFile(name); profile.setFromFile(); this.setProfileBeingRecorded(profile); this.addProfile(profile); profile.loadFromFile(file); }, /** * @param {string} title * @return {!WebInspector.ProfileHeader} */ createProfileLoadedFromFile: function(title) { throw new Error("Needs implemented."); }, /** * @param {!WebInspector.ProfileHeader} profile */ addProfile: function(profile) { this._profiles.push(profile); this.dispatchEventToListeners(WebInspector.ProfileType.Events.AddProfileHeader, profile); }, /** * @param {!WebInspector.ProfileHeader} profile */ removeProfile: function(profile) { var index = this._profiles.indexOf(profile); if (index === -1) return; this._profiles.splice(index, 1); this._disposeProfile(profile); }, _clearTempStorage: function() { for (var i = 0; i < this._profiles.length; ++i) this._profiles[i].removeTempFile(); }, /** * @nosideeffects * @return {?WebInspector.ProfileHeader} */ profileBeingRecorded: function() { return this._profileBeingRecorded; }, /** * @param {?WebInspector.ProfileHeader} profile */ setProfileBeingRecorded: function(profile) { if (this._profileBeingRecorded) this._profileBeingRecorded.target().profilingLock.release(); if (profile) profile.target().profilingLock.acquire(); this._profileBeingRecorded = profile; }, profileBeingRecordedRemoved: function() { }, _reset: function() { var profiles = this._profiles.slice(0); for (var i = 0; i < profiles.length; ++i) this._disposeProfile(profiles[i]); this._profiles = []; this._nextProfileUid = 1; }, /** * @param {!WebInspector.ProfileHeader} profile */ _disposeProfile: function(profile) { this.dispatchEventToListeners(WebInspector.ProfileType.Events.RemoveProfileHeader, profile); profile.dispose(); if (this._profileBeingRecorded === profile) { this.profileBeingRecordedRemoved(); this.setProfileBeingRecorded(null); } }, __proto__: WebInspector.Object.prototype } /** * @interface */ WebInspector.ProfileType.DataDisplayDelegate = function() { } WebInspector.ProfileType.DataDisplayDelegate.prototype = { /** * @param {?WebInspector.ProfileHeader} profile * @return {?WebInspector.View} */ showProfile: function(profile) { }, /** * @param {!HeapProfilerAgent.HeapSnapshotObjectId} snapshotObjectId * @param {string} perspectiveName */ showObject: function(snapshotObjectId, perspectiveName) { } } /** * @constructor * @extends {WebInspector.TargetAwareObject} * @param {!WebInspector.Target} target * @param {!WebInspector.ProfileType} profileType * @param {string} title */ WebInspector.ProfileHeader = function(target, profileType, title) { WebInspector.TargetAwareObject.call(this, target); this._profileType = profileType; this.title = title; this.uid = profileType._nextProfileUid++; this._fromFile = false; } /** * @constructor * @param {?string} subtitle * @param {boolean|undefined} wait */ WebInspector.ProfileHeader.StatusUpdate = function(subtitle, wait) { /** @type {?string} */ this.subtitle = subtitle; /** @type {boolean|undefined} */ this.wait = wait; } WebInspector.ProfileHeader.Events = { UpdateStatus: "UpdateStatus", ProfileReceived: "ProfileReceived" } WebInspector.ProfileHeader.prototype = { /** * @return {!WebInspector.ProfileType} */ profileType: function() { return this._profileType; }, /** * @param {?string} subtitle * @param {boolean=} wait */ updateStatus: function(subtitle, wait) { this.dispatchEventToListeners(WebInspector.ProfileHeader.Events.UpdateStatus, new WebInspector.ProfileHeader.StatusUpdate(subtitle, wait)); }, /** * Must be implemented by subclasses. * @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate * @return {!WebInspector.ProfileSidebarTreeElement} */ createSidebarTreeElement: function(dataDisplayDelegate) { throw new Error("Needs implemented."); }, /** * @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate * @return {!WebInspector.View} */ createView: function(dataDisplayDelegate) { throw new Error("Not implemented."); }, removeTempFile: function() { if (this._tempFile) this._tempFile.remove(); }, dispose: function() { }, /** * @param {!Function} callback */ load: function(callback) { }, /** * @return {boolean} */ canSaveToFile: function() { return false; }, saveToFile: function() { throw new Error("Needs implemented"); }, /** * @param {!File} file */ loadFromFile: function(file) { throw new Error("Needs implemented"); }, /** * @return {boolean} */ fromFile: function() { return this._fromFile; }, setFromFile: function() { this._fromFile = true; }, __proto__: WebInspector.TargetAwareObject.prototype } /** * @constructor * @implements {WebInspector.Searchable} * @implements {WebInspector.ProfileType.DataDisplayDelegate} * @extends {WebInspector.PanelWithSidebarTree} */ WebInspector.ProfilesPanel = function() { WebInspector.PanelWithSidebarTree.call(this, "profiles"); this.registerRequiredCSS("panelEnablerView.css"); this.registerRequiredCSS("heapProfiler.css"); this.registerRequiredCSS("profilesPanel.css"); this._target = /** @type {!WebInspector.Target} */ (WebInspector.targetManager.activeTarget()); this._target.profilingLock.addEventListener(WebInspector.Lock.Events.StateChanged, this._onProfilingStateChanged, this); this._searchableView = new WebInspector.SearchableView(this); var mainView = new WebInspector.VBox(); this._searchableView.show(mainView.element); mainView.show(this.mainElement()); this.profilesItemTreeElement = new WebInspector.ProfilesSidebarTreeElement(this); this.sidebarTree.appendChild(this.profilesItemTreeElement); this.profileViews = document.createElement("div"); this.profileViews.id = "profile-views"; this.profileViews.classList.add("vbox"); this._searchableView.element.appendChild(this.profileViews); var statusBarContainer = document.createElementWithClass("div", "profiles-status-bar"); mainView.element.insertBefore(statusBarContainer, mainView.element.firstChild); this._statusBarElement = statusBarContainer.createChild("div", "status-bar"); this.sidebarElement().classList.add("profiles-sidebar-tree-box"); var statusBarContainerLeft = document.createElementWithClass("div", "profiles-status-bar"); this.sidebarElement().insertBefore(statusBarContainerLeft, this.sidebarElement().firstChild); this._statusBarButtons = statusBarContainerLeft.createChild("div", "status-bar"); this.recordButton = new WebInspector.StatusBarButton("", "record-profile-status-bar-item"); this.recordButton.addEventListener("click", this.toggleRecordButton, this); this._statusBarButtons.appendChild(this.recordButton.element); this.clearResultsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Clear all profiles."), "clear-status-bar-item"); this.clearResultsButton.addEventListener("click", this._reset, this); this._statusBarButtons.appendChild(this.clearResultsButton.element); this._profileTypeStatusBarItemsContainer = this._statusBarElement.createChild("div"); this._profileViewStatusBarItemsContainer = this._statusBarElement.createChild("div"); this._profileGroups = {}; this._launcherView = new WebInspector.MultiProfileLauncherView(this); this._launcherView.addEventListener(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected, this._onProfileTypeSelected, this); this._profileToView = []; this._typeIdToSidebarSection = {}; var types = WebInspector.ProfileTypeRegistry.instance.profileTypes(); for (var i = 0; i < types.length; i++) this._registerProfileType(types[i]); this._launcherView.restoreSelectedProfileType(); this.profilesItemTreeElement.select(); this._showLauncherView(); this._createFileSelectorElement(); this.element.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); this._registerShortcuts(); this._configureCpuProfilerSamplingInterval(); WebInspector.settings.highResolutionCpuProfiling.addChangeListener(this._configureCpuProfilerSamplingInterval, this); } /** * @constructor */ WebInspector.ProfileTypeRegistry = function() { this._profileTypes = []; this.cpuProfileType = new WebInspector.CPUProfileType(); this._addProfileType(this.cpuProfileType); this.heapSnapshotProfileType = new WebInspector.HeapSnapshotProfileType(); this._addProfileType(this.heapSnapshotProfileType); this.trackingHeapSnapshotProfileType = new WebInspector.TrackingHeapSnapshotProfileType(); this._addProfileType(this.trackingHeapSnapshotProfileType); HeapProfilerAgent.enable(); if (Capabilities.isMainFrontend && WebInspector.experimentsSettings.canvasInspection.isEnabled()) { this.canvasProfileType = new WebInspector.CanvasProfileType(); this._addProfileType(this.canvasProfileType); } } WebInspector.ProfileTypeRegistry.prototype = { /** * @param {!WebInspector.ProfileType} profileType */ _addProfileType: function(profileType) { this._profileTypes.push(profileType); }, /** * @return {!Array.<!WebInspector.ProfileType>} */ profileTypes: function() { return this._profileTypes; } } WebInspector.ProfilesPanel.prototype = { /** * @return {!WebInspector.SearchableView} */ searchableView: function() { return this._searchableView; }, _createFileSelectorElement: function() { if (this._fileSelectorElement) this.element.removeChild(this._fileSelectorElement); this._fileSelectorElement = WebInspector.createFileSelectorElement(this._loadFromFile.bind(this)); this.element.appendChild(this._fileSelectorElement); }, _findProfileTypeByExtension: function(fileName) { var types = WebInspector.ProfileTypeRegistry.instance.profileTypes(); for (var i = 0; i < types.length; i++) { var type = types[i]; var extension = type.fileExtension(); if (!extension) continue; if (fileName.endsWith(type.fileExtension())) return type; } return null; }, _registerShortcuts: function() { this.registerShortcuts(WebInspector.ShortcutsScreen.ProfilesPanelShortcuts.StartStopRecording, this.toggleRecordButton.bind(this)); }, _configureCpuProfilerSamplingInterval: function() { var intervalUs = WebInspector.settings.highResolutionCpuProfiling.get() ? 100 : 1000; ProfilerAgent.setSamplingInterval(intervalUs, didChangeInterval); function didChangeInterval(error) { if (error) WebInspector.messageSink.addErrorMessage(error, true); } }, /** * @param {!File} file */ _loadFromFile: function(file) { this._createFileSelectorElement(); var profileType = this._findProfileTypeByExtension(file.name); if (!profileType) { var extensions = []; var types = WebInspector.ProfileTypeRegistry.instance.profileTypes(); for (var i = 0; i < types.length; i++) { var extension = types[i].fileExtension(); if (!extension || extensions.indexOf(extension) !== -1) continue; extensions.push(extension); } WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load file. Only files with extensions '%s' can be loaded.", extensions.join("', '"))); return; } if (!!profileType.profileBeingRecorded()) { WebInspector.messageSink.addMessage(WebInspector.UIString("Can't load profile while another profile is recording.")); return; } profileType.loadFromFile(file); }, /** * @return {boolean} */ toggleRecordButton: function() { if (!this.recordButton.enabled()) return true; var type = this._selectedProfileType; var isProfiling = type.buttonClicked(); this._updateRecordButton(isProfiling); if (isProfiling) { this._launcherView.profileStarted(); if (type.hasTemporaryView()) this.showProfile(type.profileBeingRecorded()); } else { this._launcherView.profileFinished(); } return true; }, _onProfilingStateChanged: function() { this._updateRecordButton(this.recordButton.toggled); }, /** * @param {boolean} toggled */ _updateRecordButton: function(toggled) { var enable = toggled || !this._target.profilingLock.isAcquired(); this.recordButton.setEnabled(enable); this.recordButton.toggled = toggled; if (enable) this.recordButton.title = this._selectedProfileType ? this._selectedProfileType.buttonTooltip : ""; else this.recordButton.title = WebInspector.UIString("Another profiler is already active"); if (this._selectedProfileType) this._launcherView.updateProfileType(this._selectedProfileType, enable); }, _profileBeingRecordedRemoved: function() { this._updateRecordButton(false); this._launcherView.profileFinished(); }, /** * @param {!WebInspector.Event} event */ _onProfileTypeSelected: function(event) { this._selectedProfileType = /** @type {!WebInspector.ProfileType} */ (event.data); this._updateProfileTypeSpecificUI(); }, _updateProfileTypeSpecificUI: function() { this._updateRecordButton(this.recordButton.toggled); this._profileTypeStatusBarItemsContainer.removeChildren(); var statusBarItems = this._selectedProfileType.statusBarItems; if (statusBarItems) { for (var i = 0; i < statusBarItems.length; ++i) this._profileTypeStatusBarItemsContainer.appendChild(statusBarItems[i]); } }, _reset: function() { WebInspector.Panel.prototype.reset.call(this); var types = WebInspector.ProfileTypeRegistry.instance.profileTypes(); for (var i = 0; i < types.length; i++) types[i]._reset(); delete this.visibleView; delete this.currentQuery; this.searchCanceled(); this._profileGroups = {}; this._updateRecordButton(false); this._launcherView.profileFinished(); this.sidebarTree.element.classList.remove("some-expandable"); this._launcherView.detach(); this.profileViews.removeChildren(); this._profileViewStatusBarItemsContainer.removeChildren(); this.removeAllListeners(); this.recordButton.visible = true; this._profileViewStatusBarItemsContainer.classList.remove("hidden"); this.clearResultsButton.element.classList.remove("hidden"); this.profilesItemTreeElement.select(); this._showLauncherView(); }, _showLauncherView: function() { this.closeVisibleView(); this._profileViewStatusBarItemsContainer.removeChildren(); this._launcherView.show(this.profileViews); this.visibleView = this._launcherView; }, _garbageCollectButtonClicked: function() { HeapProfilerAgent.collectGarbage(); }, /** * @param {!WebInspector.ProfileType} profileType */ _registerProfileType: function(profileType) { this._launcherView.addProfileType(profileType); var profileTypeSection = new WebInspector.ProfileTypeSidebarSection(this, profileType); this._typeIdToSidebarSection[profileType.id] = profileTypeSection this.sidebarTree.appendChild(profileTypeSection); profileTypeSection.childrenListElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), true); /** * @param {!WebInspector.Event} event * @this {WebInspector.ProfilesPanel} */ function onAddProfileHeader(event) { this._addProfileHeader(/** @type {!WebInspector.ProfileHeader} */ (event.data)); } /** * @param {!WebInspector.Event} event * @this {WebInspector.ProfilesPanel} */ function onRemoveProfileHeader(event) { this._removeProfileHeader(/** @type {!WebInspector.ProfileHeader} */ (event.data)); } /** * @param {!WebInspector.Event} event * @this {WebInspector.ProfilesPanel} */ function profileComplete(event) { this.showProfile(/** @type {!WebInspector.ProfileHeader} */ (event.data)); } profileType.addEventListener(WebInspector.ProfileType.Events.ViewUpdated, this._updateProfileTypeSpecificUI, this); profileType.addEventListener(WebInspector.ProfileType.Events.AddProfileHeader, onAddProfileHeader, this); profileType.addEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader, onRemoveProfileHeader, this); profileType.addEventListener(WebInspector.ProfileType.Events.ProfileComplete, profileComplete, this); var profiles = profileType.getProfiles(); for (var i = 0; i < profiles.length; i++) this._addProfileHeader(profiles[i]); }, /** * @param {?Event} event */ _handleContextMenuEvent: function(event) { var element = event.srcElement; while (element && !element.treeElement && element !== this.element) element = element.parentElement; if (!element) return; if (element.treeElement && element.treeElement.handleContextMenuEvent) { element.treeElement.handleContextMenuEvent(event, this); return; } var contextMenu = new WebInspector.ContextMenu(event); if (this.visibleView instanceof WebInspector.HeapSnapshotView) { this.visibleView.populateContextMenu(contextMenu, event); } if (element !== this.element || event.srcElement === this.sidebarElement()) { contextMenu.appendItem(WebInspector.UIString("Load\u2026"), this._fileSelectorElement.click.bind(this._fileSelectorElement)); } contextMenu.show(); }, showLoadFromFileDialog: function() { this._fileSelectorElement.click(); }, /** * @param {!WebInspector.ProfileHeader} profile */ _addProfileHeader: function(profile) { var profileType = profile.profileType(); var typeId = profileType.id; this._typeIdToSidebarSection[typeId].addProfileHeader(profile); if (!this.visibleView || this.visibleView === this._launcherView) this.showProfile(profile); }, /** * @param {!WebInspector.ProfileHeader} profile */ _removeProfileHeader: function(profile) { if (profile.profileType()._profileBeingRecorded === profile) this._profileBeingRecordedRemoved(); var i = this._indexOfViewForProfile(profile); if (i !== -1) this._profileToView.splice(i, 1); var profileType = profile.profileType(); var typeId = profileType.id; var sectionIsEmpty = this._typeIdToSidebarSection[typeId].removeProfileHeader(profile); // No other item will be selected if there aren't any other profiles, so // make sure that view gets cleared when the last profile is removed. if (sectionIsEmpty) { this.profilesItemTreeElement.select(); this._showLauncherView(); } }, /** * @param {?WebInspector.ProfileHeader} profile * @return {?WebInspector.View} */ showProfile: function(profile) { if (!profile || (profile.profileType().profileBeingRecorded() === profile) && !profile.profileType().hasTemporaryView()) return null; var view = this._viewForProfile(profile); if (view === this.visibleView) return view; this.closeVisibleView(); view.show(this.profileViews); this.visibleView = view; var profileTypeSection = this._typeIdToSidebarSection[profile.profileType().id]; var sidebarElement = profileTypeSection.sidebarElementForProfile(profile); sidebarElement.revealAndSelect(); this._profileViewStatusBarItemsContainer.removeChildren(); var statusBarItems = view.statusBarItems; if (statusBarItems) for (var i = 0; i < statusBarItems.length; ++i) this._profileViewStatusBarItemsContainer.appendChild(statusBarItems[i]); return view; }, /** * @param {!HeapProfilerAgent.HeapSnapshotObjectId} snapshotObjectId * @param {string} perspectiveName */ showObject: function(snapshotObjectId, perspectiveName) { var heapProfiles = WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles(); for (var i = 0; i < heapProfiles.length; i++) { var profile = heapProfiles[i]; // FIXME: allow to choose snapshot if there are several options. if (profile.maxJSObjectId >= snapshotObjectId) { this.showProfile(profile); var view = this._viewForProfile(profile); view.highlightLiveObject(perspectiveName, snapshotObjectId); break; } } }, /** * @param {!WebInspector.ProfileHeader} profile * @return {!WebInspector.View} */ _viewForProfile: function(profile) { var index = this._indexOfViewForProfile(profile); if (index !== -1) return this._profileToView[index].view; var view = profile.createView(this); view.element.classList.add("profile-view"); this._profileToView.push({ profile: profile, view: view}); return view; }, /** * @param {!WebInspector.ProfileHeader} profile * @return {number} */ _indexOfViewForProfile: function(profile) { for (var i = 0; i < this._profileToView.length; i++) { if (this._profileToView[i].profile === profile) return i; } return -1; }, closeVisibleView: function() { if (this.visibleView) this.visibleView.detach(); delete this.visibleView; }, /** * @param {string} query * @param {boolean} shouldJump * @param {boolean=} jumpBackwards */ performSearch: function(query, shouldJump, jumpBackwards) { this.searchCanceled(); var visibleView = this.visibleView; if (!visibleView) return; /** * @this {WebInspector.ProfilesPanel} */ function finishedCallback(view, searchMatches) { if (!searchMatches) return; this._searchableView.updateSearchMatchesCount(searchMatches); this._searchResultsView = view; if (shouldJump) { if (jumpBackwards) view.jumpToLastSearchResult(); else view.jumpToFirstSearchResult(); this._searchableView.updateCurrentMatchIndex(view.currentSearchResultIndex()); } } visibleView.currentQuery = query; visibleView.performSearch(query, finishedCallback.bind(this)); }, jumpToNextSearchResult: function() { if (!this._searchResultsView) return; if (this._searchResultsView !== this.visibleView) return; this._searchResultsView.jumpToNextSearchResult(); this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex()); }, jumpToPreviousSearchResult: function() { if (!this._searchResultsView) return; if (this._searchResultsView !== this.visibleView) return; this._searchResultsView.jumpToPreviousSearchResult(); this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex()); }, searchCanceled: function() { if (this._searchResultsView) { if (this._searchResultsView.searchCanceled) this._searchResultsView.searchCanceled(); this._searchResultsView.currentQuery = null; this._searchResultsView = null; } this._searchableView.updateSearchMatchesCount(0); }, /** * @param {!Event} event * @param {!WebInspector.ContextMenu} contextMenu * @param {!Object} target */ appendApplicableItems: function(event, contextMenu, target) { if (!(target instanceof WebInspector.RemoteObject)) return; if (WebInspector.inspectorView.currentPanel() !== this) return; var object = /** @type {!WebInspector.RemoteObject} */ (target); var objectId = object.objectId; if (!objectId) return; var heapProfiles = WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles(); if (!heapProfiles.length) return; /** * @this {WebInspector.ProfilesPanel} */ function revealInView(viewName) { HeapProfilerAgent.getHeapObjectId(objectId, didReceiveHeapObjectId.bind(this, viewName)); } /** * @this {WebInspector.ProfilesPanel} */ function didReceiveHeapObjectId(viewName, error, result) { if (WebInspector.inspectorView.currentPanel() !== this) return; if (!error) this.showObject(result, viewName); } if (WebInspector.settings.showAdvancedHeapSnapshotProperties.get()) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in Dominators view" : "Reveal in Dominators View"), revealInView.bind(this, "Dominators")); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in Summary view" : "Reveal in Summary View"), revealInView.bind(this, "Summary")); }, __proto__: WebInspector.PanelWithSidebarTree.prototype } /** * @constructor * @extends {WebInspector.SidebarSectionTreeElement} * @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate * @param {!WebInspector.ProfileType} profileType */ WebInspector.ProfileTypeSidebarSection = function(dataDisplayDelegate, profileType) { WebInspector.SidebarSectionTreeElement.call(this, profileType.treeItemTitle, null, true); this._dataDisplayDelegate = dataDisplayDelegate; this._profileTreeElements = []; this._profileGroups = {}; this.hidden = true; } /** * @constructor */ WebInspector.ProfileTypeSidebarSection.ProfileGroup = function() { this.profileSidebarTreeElements = []; this.sidebarTreeElement = null; } WebInspector.ProfileTypeSidebarSection.prototype = { /** * @param {!WebInspector.ProfileHeader} profile */ addProfileHeader: function(profile) { this.hidden = false; var profileType = profile.profileType(); var sidebarParent = this; var profileTreeElement = profile.createSidebarTreeElement(this._dataDisplayDelegate); this._profileTreeElements.push(profileTreeElement); if (!profile.fromFile() && profileType.profileBeingRecorded() !== profile) { var profileTitle = profile.title; var group = this._profileGroups[profileTitle]; if (!group) { group = new WebInspector.ProfileTypeSidebarSection.ProfileGroup(); this._profileGroups[profileTitle] = group; } group.profileSidebarTreeElements.push(profileTreeElement); var groupSize = group.profileSidebarTreeElements.length; if (groupSize === 2) { // Make a group TreeElement now that there are 2 profiles. group.sidebarTreeElement = new WebInspector.ProfileGroupSidebarTreeElement(this._dataDisplayDelegate, profile.title); var firstProfileTreeElement = group.profileSidebarTreeElements[0]; // Insert at the same index for the first profile of the group. var index = this.children.indexOf(firstProfileTreeElement); this.insertChild(group.sidebarTreeElement, index); // Move the first profile to the group. var selected = firstProfileTreeElement.selected; this.removeChild(firstProfileTreeElement); group.sidebarTreeElement.appendChild(firstProfileTreeElement); if (selected) firstProfileTreeElement.revealAndSelect(); firstProfileTreeElement.small = true; firstProfileTreeElement.mainTitle = WebInspector.UIString("Run %d", 1); this.treeOutline.element.classList.add("some-expandable"); } if (groupSize >= 2) { sidebarParent = group.sidebarTreeElement; profileTreeElement.small = true; profileTreeElement.mainTitle = WebInspector.UIString("Run %d", groupSize); } } sidebarParent.appendChild(profileTreeElement); }, /** * @param {!WebInspector.ProfileHeader} profile * @return {boolean} */ removeProfileHeader: function(profile) { var index = this._sidebarElementIndex(profile); if (index === -1) return false; var profileTreeElement = this._profileTreeElements[index]; this._profileTreeElements.splice(index, 1); var sidebarParent = this; var group = this._profileGroups[profile.title]; if (group) { var groupElements = group.profileSidebarTreeElements; groupElements.splice(groupElements.indexOf(profileTreeElement), 1); if (groupElements.length === 1) { // Move the last profile out of its group and remove the group. var pos = sidebarParent.children.indexOf(group.sidebarTreeElement); this.insertChild(groupElements[0], pos); groupElements[0].small = false; groupElements[0].mainTitle = group.sidebarTreeElement.title; this.removeChild(group.sidebarTreeElement); } if (groupElements.length !== 0) sidebarParent = group.sidebarTreeElement; } sidebarParent.removeChild(profileTreeElement); profileTreeElement.dispose(); if (this.children.length) return false; this.hidden = true; return true; }, /** * @param {!WebInspector.ProfileHeader} profile * @return {?WebInspector.ProfileSidebarTreeElement} */ sidebarElementForProfile: function(profile) { var index = this._sidebarElementIndex(profile); return index === -1 ? null : this._profileTreeElements[index]; }, /** * @param {!WebInspector.ProfileHeader} profile * @return {number} */ _sidebarElementIndex: function(profile) { var elements = this._profileTreeElements; for (var i = 0; i < elements.length; i++) { if (elements[i].profile === profile) return i; } return -1; }, __proto__: WebInspector.SidebarSectionTreeElement.prototype } /** * @constructor * @implements {WebInspector.ContextMenu.Provider} */ WebInspector.ProfilesPanel.ContextMenuProvider = function() { } WebInspector.ProfilesPanel.ContextMenuProvider.prototype = { /** * @param {!Event} event * @param {!WebInspector.ContextMenu} contextMenu * @param {!Object} target */ appendApplicableItems: function(event, contextMenu, target) { WebInspector.inspectorView.panel("profiles").appendApplicableItems(event, contextMenu, target); } } /** * @constructor * @extends {WebInspector.SidebarTreeElement} * @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate * @param {!WebInspector.ProfileHeader} profile * @param {string} className */ WebInspector.ProfileSidebarTreeElement = function(dataDisplayDelegate, profile, className) { this._dataDisplayDelegate = dataDisplayDelegate; this.profile = profile; WebInspector.SidebarTreeElement.call(this, className, profile.title, "", profile, false); this.refreshTitles(); profile.addEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this); if (profile.canSaveToFile()) this._createSaveLink(); else profile.addEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this); } WebInspector.ProfileSidebarTreeElement.prototype = { _createSaveLink: function() { this._saveLinkElement = this.titleContainer.createChild("span", "save-link"); this._saveLinkElement.textContent = WebInspector.UIString("Save"); this._saveLinkElement.addEventListener("click", this._saveProfile.bind(this), false); }, _onProfileReceived: function(event) { this._createSaveLink(); }, /** * @param {!WebInspector.Event} event */ _updateStatus: function(event) { var statusUpdate = event.data; if (statusUpdate.subtitle !== null) this.subtitle = statusUpdate.subtitle; if (typeof statusUpdate.wait === "boolean") this.wait = statusUpdate.wait; this.refreshTitles(); }, dispose: function() { this.profile.removeEventListener(WebInspector.ProfileHeader.Events.UpdateStatus, this._updateStatus, this); this.profile.removeEventListener(WebInspector.ProfileHeader.Events.ProfileReceived, this._onProfileReceived, this); }, onselect: function() { this._dataDisplayDelegate.showProfile(this.profile); }, /** * @return {boolean} */ ondelete: function() { this.profile.profileType().removeProfile(this.profile); return true; }, /** * @param {!Event} event * @param {!WebInspector.ProfilesPanel} panel */ handleContextMenuEvent: function(event, panel) { var profile = this.profile; var contextMenu = new WebInspector.ContextMenu(event); // FIXME: use context menu provider contextMenu.appendItem(WebInspector.UIString("Load\u2026"), panel._fileSelectorElement.click.bind(panel._fileSelectorElement)); if (profile.canSaveToFile()) contextMenu.appendItem(WebInspector.UIString("Save\u2026"), profile.saveToFile.bind(profile)); contextMenu.appendItem(WebInspector.UIString("Delete"), this.ondelete.bind(this)); contextMenu.show(); }, _saveProfile: function(event) { this.profile.saveToFile(); }, __proto__: WebInspector.SidebarTreeElement.prototype } /** * @constructor * @extends {WebInspector.SidebarTreeElement} * @param {!WebInspector.ProfileType.DataDisplayDelegate} dataDisplayDelegate * @param {string} title * @param {string=} subtitle */ WebInspector.ProfileGroupSidebarTreeElement = function(dataDisplayDelegate, title, subtitle) { WebInspector.SidebarTreeElement.call(this, "profile-group-sidebar-tree-item", title, subtitle, null, true); this._dataDisplayDelegate = dataDisplayDelegate; } WebInspector.ProfileGroupSidebarTreeElement.prototype = { onselect: function() { if (this.children.length > 0) this._dataDisplayDelegate.showProfile(this.children[this.children.length - 1].profile); }, __proto__: WebInspector.SidebarTreeElement.prototype } /** * @constructor * @extends {WebInspector.SidebarTreeElement} * @param {!WebInspector.ProfilesPanel} panel */ WebInspector.ProfilesSidebarTreeElement = function(panel) { this._panel = panel; this.small = false; WebInspector.SidebarTreeElement.call(this, "profile-launcher-view-tree-item", WebInspector.UIString("Profiles"), "", null, false); } WebInspector.ProfilesSidebarTreeElement.prototype = { onselect: function() { this._panel._showLauncherView(); }, get selectable() { return true; }, __proto__: WebInspector.SidebarTreeElement.prototype } importScript("../sdk/CPUProfileModel.js"); importScript("CPUProfileDataGrid.js"); importScript("CPUProfileBottomUpDataGrid.js"); importScript("CPUProfileTopDownDataGrid.js"); importScript("CPUProfileFlameChart.js"); importScript("CPUProfileView.js"); importScript("HeapSnapshotCommon.js"); importScript("HeapSnapshotProxy.js"); importScript("HeapSnapshotDataGrids.js"); importScript("HeapSnapshotGridNodes.js"); importScript("HeapSnapshotView.js"); importScript("ProfileLauncherView.js"); importScript("CanvasProfileView.js"); importScript("CanvasReplayStateView.js"); WebInspector.ProfileTypeRegistry.instance = new WebInspector.ProfileTypeRegistry();
buglloc/ios-debug-proxy-devtools
profiler/ProfilesPanel.js
JavaScript
mit
42,236
//============================================================================= // Darken Region // LAX_DarkenRegion.js // v0.02 //============================================================================= //============================================================================= /*: * @plugindesc v0.02 Use regions to black out areas. * @author LuciusAxelrod * * * @help * Place regions on the map in the editor, then either add them to the default * list or add them to the dark region list using the add command listed below. * Note: Tiles without a region are in region 0. Adding region 0 to the dark * region list will black out every tile * * Plugin Commands: * DarkenRegion add [region list] # Adds the listed regions to the dark * region list. The list is space * separated. For example: * DarkenRegion add 1 3 5 78 * DarkenRegion remove [region list] # Removes the listed regions from the * dark region list. The list is space * separated. For example: * DarkenRegion remove 4 7 200 2 * DarkenRegion toggle [region list] # Toggle on/off each of the listed * regions. For example: * DarkenRegion toggle 1 5 7 112 250 * DarkenRegion clear # Clears the dark region list. */ //============================================================================= //============================================================================= // Parameter Variables //============================================================================= (function() { var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { _Game_Interpreter_pluginCommand.call(this, command, args); if (command === 'DarkenRegion') { if(args[0] === 'add') { for(var i = 1; i < args.length; i++) { $gameSystem.addToDarkList(args[i]); } } else if(args[0] === 'remove') { for(var i = 1; i < args.length; i++) { $gameSystem.removeFromDarkList(args[i]); } } else if(args[0] === 'toggle') { for(var i = 1; i < args.length; i++) { if($gameSystem.isDarkRegion(args[i])) { $gameSystem.removeFromDarkList(args[i]); } else { $gameSystem.addToDarkList(args[i]); } } } else if(args[0] === 'clear') { $gameSystem.clearDarkList(); } } }; Game_System.prototype.isDarkRegion = function(regionId) { if(this._darkList) { return !!this._darkList[regionId]; } } Game_System.prototype.addToDarkList = function(regionId) { if(!this._darkList) { this.clearDarkList(); } this._darkList[Number(regionId)] = true; } Game_System.prototype.removeFromDarkList = function(regionId) { if(this._darkList) { this._darkList[Number(regionId)] = false; } } Game_System.prototype.clearDarkList = function() { this._darkList = []; } Tilemap.prototype._paintTiles = function(startX, startY, x, y) { var tableEdgeVirtualId = 10000; var darkRegionVirtualId = 10000; var mx = startX + x; var my = startY + y; var dx = (mx * this._tileWidth).mod(this._layerWidth); var dy = (my * this._tileHeight).mod(this._layerHeight); var lx = dx / this._tileWidth; var ly = dy / this._tileHeight; var tileId0 = this._readMapData(mx, my, 0); var tileId1 = this._readMapData(mx, my, 1); var tileId2 = this._readMapData(mx, my, 2); var tileId3 = this._readMapData(mx, my, 3); var tileId5 = this._readMapData(mx, my, 5); var shadowBits = this._readMapData(mx, my, 4); var upperTileId1 = this._readMapData(mx, my - 1, 1); var lowerTiles = []; var upperTiles = []; if (this._isHigherTile(tileId0)) { upperTiles.push(tileId0); } else { lowerTiles.push(tileId0); } if (this._isHigherTile(tileId1)) { upperTiles.push(tileId1); } else { lowerTiles.push(tileId1); } lowerTiles.push(-shadowBits); if (this._isTableTile(upperTileId1) && !this._isTableTile(tileId1)) { if (!Tilemap.isShadowingTile(tileId0)) { lowerTiles.push(tableEdgeVirtualId + upperTileId1); } } if (this._isOverpassPosition(mx, my)) { upperTiles.push(tileId2); upperTiles.push(tileId3); } else { if (this._isHigherTile(tileId2)) { upperTiles.push(tileId2); } else { lowerTiles.push(tileId2); } if (this._isHigherTile(tileId3)) { upperTiles.push(tileId3); } else { lowerTiles.push(tileId3); } if($gameSystem.isDarkRegion(tileId5)){ upperTiles.push(darkRegionVirtualId + tileId5); } } var lastLowerTiles = this._readLastTiles(0, lx, ly); if (!lowerTiles.equals(lastLowerTiles) || (Tilemap.isTileA1(tileId0) && this._frameUpdated)) { this._lowerBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); for (var i = 0; i < lowerTiles.length; i++) { var lowerTileId = lowerTiles[i]; if (lowerTileId < 0) { this._drawShadow(this._lowerBitmap, shadowBits, dx, dy); } else if (lowerTileId >= tableEdgeVirtualId) { this._drawTableEdge(this._lowerBitmap, upperTileId1, dx, dy); } else { this._drawTile(this._lowerBitmap, lowerTileId, dx, dy); } } this._writeLastTiles(0, lx, ly, lowerTiles); } var lastUpperTiles = this._readLastTiles(1, lx, ly); if (!upperTiles.equals(lastUpperTiles)) { this._upperBitmap.clearRect(dx, dy, this._tileWidth, this._tileHeight); for (var j = 0; j < upperTiles.length; j++) { if(upperTiles[j] >= darkRegionVirtualId) { this._drawDarkness(this._upperBitmap, dx, dy); } else { this._drawTile(this._upperBitmap, upperTiles[j], dx, dy); } } this._writeLastTiles(1, lx, ly, upperTiles); } }; Tilemap.prototype._drawDarkness = function(bitmap, dx, dy) { var w = this._tileWidth; var h = this._tileHeight; var color = 'rgba(0,0,0,1)'; bitmap.fillRect(dx, dy, w, h, color); }; })();
LuciusAxelrod/LAX_Plugins
LAX_DarkenRegion/v0.02/LAX_DarkenRegion.js
JavaScript
mit
6,112
"use strict"; (function() { function get_promise(endpoint) { return function($http) { return $http.get(endpoint); }; } angular.module('pagerbot-admin', ['ngRoute', 'ngTable', 'angular-loading-bar']) .config(function ($routeProvider) { $routeProvider .when('/intro', { templateUrl: 'views/intro.html', controller: 'PagerdutyCtrl', resolve: { pd: function(pagerduty_promise) { return pagerduty_promise; } } }) .when('/chatbot-settings', { templateUrl: 'views/bot.html', controller: 'BotSetupCtrl', resolve: { bot_info: get_promise('/api/bot') } }) .when('/plugin-setup', { templateUrl: 'views/plugins.html', controller: 'PluginSetupCtrl', resolve: { plugin_info: get_promise('/api/plugins') } }) .when('/user-aliases', { templateUrl: 'views/users.html', controller: 'UserAliasCtrl', resolve: { users: get_promise('/api/users') } }) .when('/schedule-aliases', { templateUrl: 'views/schedules.html', controller: 'ScheduleAliasCtrl', resolve: { schedules: get_promise('/api/schedules') } }) .when('/deploy', { templateUrl: 'views/deploy.html', controller: 'DeployCtrl' }) .otherwise({ redirectTo: '/intro' }); }); })();
stripe-contrib/pagerbot
public/js/app.js
JavaScript
mit
1,579
module.exports = { project: { server: { basePath: '', ip: '0.0.0.0', request: { sesskey: 'sid', limit: 5000, parameters: 60 }, render: 'swig', path: { routes: 'app/routes', views: 'app/views', public: 'public/', docs: false }, views: { extension: 'swig', errors: 'errors/' } } }, environment: { server: { debug: true, host: 'localhost', port: 3000, request: { secret: new Date().getTime() + '' + Math.random(), cors: true, geolocation: false }, views: { cache: false } } } };
PearlVentures/Crux
boilerplate/server/config.js
JavaScript
mit
699
import React from "react"; import styled from 'styled-components' import Link from './link'; const nextArrow = "/icons/next-arrow.png"; const prevArrow = "/icons/prev-arrow.png"; const PatternLink = styled.span` width: 100%; display: flex; flex-direction: column; padding: 1em; float: ${props => props.previous ? 'left' : 'right'} @media(min-width: $width-tablet) { width: auto; } `; const ImageContainer = styled.span` height: 50px; `; const Image = styled.img` height: 100%; background-color: white; float: ${props => props.previous ? 'right' : 'left'} `; const ArrowContainer = styled.div` display: flex; flex-direction: ${props => props.previous ? 'row-reverse' : 'row'}; align-items: center; `; const Name = styled.p` padding: 10px 0; `; const Arrow = styled.img` height: 10px; flex-direction: row-reverse; padding: ${props => props.previous ? '0 10px 0 0' : '0 0 0 10px'}; `; const NextPrevPattern = ({pattern, direction}) => { const previous = direction === "previous" return ( <Link href={pattern.url}> <PatternLink previous={previous}> <ImageContainer> <Image previous={previous} src={pattern.painted || pattern.lineDrawing} /> </ImageContainer> <ArrowContainer previous={previous}> <Name>{pattern.name}</Name> { (direction === "next") && <Arrow src={nextArrow}/> } { (direction === "previous") && <Arrow previous src={prevArrow} /> } </ArrowContainer> </PatternLink> </Link> ) }; export default NextPrevPattern;
redfieldstefan/kibaktile.com
src/components/next-prev-pattern.js
JavaScript
mit
1,640
#!/usr/bin/node --harmony 'use strict' const noble = require('noble'), program = require('commander') program .version('0.0.1') .option('-p, --prefix <integer>', 'Manufacturer identifier prefixed to all fan commands', parseInt) .option('-t, --target [mac]', 'MAC address of devices to target', function(val){ return val.toLowerCase() }) .option('-s, --service <uuid>', 'UUID of fan controller BLE service') .option('-w, --write <uuid>', 'UUID of fan controller BLE write characteristic') .option('-n, --notify <uuid>', 'UUID of fan controller BLE notify characteristic') class FanRequest { writeInto(buffer) { throw new TypeError('Must override method') } toBuffer() { var buffer if (program.prefix > 0) { buffer = new Buffer(13) buffer.writeUInt8(program.prefix) this.writeInto(buffer.slice(1)) } else { buffer = new Buffer(12) this.writeInto(buffer) } const checksum = buffer.slice(0, buffer.length - 1).reduce(function(a, b){ return a + b }, 0) & 255 buffer.writeUInt8(checksum, buffer.length - 1) return buffer } } class FanGetStateRequest extends FanRequest { writeInto(buffer) { buffer.fill(0) buffer.writeUInt8(160) } } Math.clamp = function(number, min, max) { return Math.max(min, Math.min(number, max)) } class FanUpdateLightRequest extends FanRequest { constructor(isOn, level) { super() this.on = isOn ? 1 : 0 this.level = Math.clamp(level, 0, 100) } writeInto(buffer) { buffer.fill(0) buffer.writeUInt8(161) buffer.writeUInt8(255, 4) buffer.writeUInt8(100, 5) buffer.writeUInt8((this.on << 7) | this.level, 6) buffer.fill(255, 7, 10) } } class FanUpdateLevelRequest extends FanRequest { constructor(level) { super() this.level = Math.clamp(level, 0, 3) } writeInto(buffer) { buffer.fill(0) buffer.writeUInt8(161) buffer.writeUInt8(this.level, 4) buffer.fill(255, 5, 10) } } class FanResponse { static fromBuffer(buffer) { if (program.prefix > 0) { buffer = buffer.slice(1) } if (buffer.readUInt8(0) != 176) { return null } const response = new FanResponse() const windVelocity = buffer.readUInt8(2) response.supportsFanReversal = (windVelocity & 0b00100000) != 0 response.maximumFanLevel = windVelocity & 0b00011111 const currentWindVelocity = buffer.readUInt8(4) response.isFanReversed = (currentWindVelocity & 0b10000000) != 0 response.fanLevel = currentWindVelocity & 0b00011111 const currentBrightness = buffer.readUInt8(6) response.lightIsOn = (currentBrightness & 0b10000000) != 0 response.lightBrightness = (currentBrightness & 0b01111111) return response } } // MARK: - var command program .command('current') .description('print current state') .action(function(env, options) { command = new FanGetStateRequest() }) program .command('fan') .description('adjusts the fan') .option('-l --level <size>', 'Fan speed', /^(off|low|medium|high)$/i, 'high') .action(function(env, options) { var level switch (env.level) { case 'low': level = 1 break case 'medium': level = 2 break case 'high': level = 3 break default: level = 0 break } command = new FanUpdateLevelRequest(level) }) program .command('light <on|off>') .description('adjusts the light') .option('-l, --level <percent>', 'Light brightness', parseInt, 100) .action(function(env, options) { command = new FanUpdateLightRequest(env !== 'off', options.level) }) program.parse(process.argv); if (!command) { program.help(); } if (!program.target) { throw new Error('MAC address required') } const serviceUUID = program.service || '539c681361a021374f79bf1a11984790' const writeUUID = program.write || '539c681361a121374f79bf1a11984790' const notifyUUID = program.notify || '539c681361a221374f79bf1a11984790' noble.on('stateChange', function(state) { if (state === 'poweredOn') { console.log('scanning.') noble.startScanning([ serviceUUID ], false) } else { noble.stopScanning() } }) noble.on('discover', function(peripheral) { console.log('found ' + peripheral.address) if (peripheral.address !== program.target) { return } noble.stopScanning() explore(peripheral) }); function bail(error) { console.log('failed: ' + error); process.exit(1) } function explore(peripheral) { console.log('connecting.') peripheral.once('disconnect', function() { peripheral.removeAllListeners() explore(peripheral) }) peripheral.connect(function(error) { if (error) { bail(error); } peripheral.discoverSomeServicesAndCharacteristics([ serviceUUID ], [ writeUUID, notifyUUID ], function(error, services, characteristics) { if (error) { bail(error); } var service = services[0] var write = characteristics[0], notify = characteristics[1] notify.on('data', function(data, isNotification) { const response = FanResponse.fromBuffer(data) if (response) { console.log(response) } else { console.log('sent') } process.exit() }) notify.subscribe(function(error) { if (error) { bail(error); } console.log('sending') const buffer = command.toBuffer() write.write(buffer, false, function(error){ if (error) { bail(error); } }) }) }) }) }
zwaldowski/homebridge-satellite-fan
test/poc.js
JavaScript
mit
5,557
const HEX_SHORT = /^#([a-fA-F0-9]{3})$/; const HEX = /^#([a-fA-F0-9]{6})$/; function roundColors(obj, round) { if (!round) return obj; const o = {}; for (let k in obj) { o[k] = Math.round(obj[k]); } return o; } function hasProp(obj, key) { return obj.hasOwnProperty(key); } function isRgb(obj) { return hasProp(obj, "r") && hasProp(obj, "g") && hasProp(obj, "b"); } export default class Color { static normalizeHex(hex) { if (HEX.test(hex)) { return hex; } else if (HEX_SHORT.test(hex)) { const r = hex.slice(1, 2); const g = hex.slice(2, 3); const b = hex.slice(3, 4); return `#${r + r}${g + g}${b + b}`; } return null; } static hexToRgb(hex) { const normalizedHex = this.normalizeHex(hex); if (normalizedHex == null) { return null; } const m = normalizedHex.match(HEX); const i = parseInt(m[1], 16); const r = (i >> 16) & 0xFF; const g = (i >> 8) & 0xFF; const b = i & 0xFF; return { r, g, b }; } static rgbToHex(rgb) { const { r, g, b} = rgb; const i = ((Math.round(r) & 0xFF) << 16) + ((Math.round(g) & 0xFF) << 8) + (Math.round(b) & 0xFF); const s = i.toString(16).toLowerCase(); return `#${"000000".substring(s.length) + s}`; } static rgbToHsv(rgb, round = true) { const { r, g, b } = rgb; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; const hsv = {}; if (max === 0) { hsv.s = 0; } else { hsv.s = (delta / max * 1000) / 10; } if (max === min) { hsv.h = 0; } else if (r === max) { hsv.h = (g - b) / delta; } else if (g === max) { hsv.h = 2 + (b - r) / delta; } else { hsv.h = 4 + (r - g) / delta; } hsv.h = Math.min(hsv.h * 60, 360); hsv.h = hsv.h < 0 ? hsv.h + 360 : hsv.h; hsv.v = ((max / 255) * 1000) / 10; return roundColors(hsv, round); } static rgbToXyz(rgb, round = true) { const r = rgb.r / 255; const g = rgb.g / 255; const b = rgb.b / 255; const rr = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : r / 12.92; const gg = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : g / 12.92; const bb = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : b / 12.92; const x = (rr * 0.4124 + gg * 0.3576 + bb * 0.1805) * 100; const y = (rr * 0.2126 + gg * 0.7152 + bb * 0.0722) * 100; const z = (rr * 0.0193 + gg * 0.1192 + bb * 0.9505) * 100; return roundColors({ x, y, z }, round); } static rgbToLab(rgb, round = true) { const xyz = Color.rgbToXyz(rgb, false); let { x, y, z } = xyz; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return roundColors({ l, a, b }, round); } constructor(value) { this.original = value; if (isRgb(value)) { this.rgb = value; this.hex = Color.rgbToHex(value); } else { this.hex = Color.normalizeHex(value); this.rgb = Color.hexToRgb(this.hex); } this.hsv = Color.rgbToHsv(this.rgb); } }
tsuyoshiwada/color-classifier
src/utils/color.js
JavaScript
mit
3,342
export { default } from 'ember-validation/components/ember-validation-error-list';
ajile/ember-validation
app/components/ember-validation-error-list.js
JavaScript
mit
83
/*global window */ /** * @license countdown.js v2.5.2 http://countdownjs.org * Copyright (c)2006-2014 Stephen M. McKamey. * Licensed under The MIT License. */ /*jshint bitwise:false */ /** * @public * @type {Object|null} */ var module; /** * API entry * @public * @param {function(Object)|Date|number} start the starting date * @param {function(Object)|Date|number} end the ending date * @param {number} units the units to populate * @return {Object|number} */ var countdown = ( /** * @param {Object} module CommonJS Module */ function(module) { /*jshint smarttabs:true */ 'use strict'; /** * @private * @const * @type {number} */ var MILLISECONDS = 0x001; /** * @private * @const * @type {number} */ var SECONDS = 0x002; /** * @private * @const * @type {number} */ var MINUTES = 0x004; /** * @private * @const * @type {number} */ var HOURS = 0x008; /** * @private * @const * @type {number} */ var DAYS = 0x010; /** * @private * @const * @type {number} */ var WEEKS = 0x020; /** * @private * @const * @type {number} */ var MONTHS = 0x040; /** * @private * @const * @type {number} */ var YEARS = 0x080; /** * @private * @const * @type {number} */ var DECADES = 0x100; /** * @private * @const * @type {number} */ var CENTURIES = 0x200; /** * @private * @const * @type {number} */ var MILLENNIA = 0x400; /** * @private * @const * @type {number} */ var DEFAULTS = YEARS|MONTHS|DAYS|HOURS|MINUTES|SECONDS; /** * @private * @const * @type {number} */ var MILLISECONDS_PER_SECOND = 1000; /** * @private * @const * @type {number} */ var SECONDS_PER_MINUTE = 60; /** * @private * @const * @type {number} */ var MINUTES_PER_HOUR = 60; /** * @private * @const * @type {number} */ var HOURS_PER_DAY = 24; /** * @private * @const * @type {number} */ var MILLISECONDS_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND; /** * @private * @const * @type {number} */ var DAYS_PER_WEEK = 7; /** * @private * @const * @type {number} */ var MONTHS_PER_YEAR = 12; /** * @private * @const * @type {number} */ var YEARS_PER_DECADE = 10; /** * @private * @const * @type {number} */ var DECADES_PER_CENTURY = 10; /** * @private * @const * @type {number} */ var CENTURIES_PER_MILLENNIUM = 10; /** * @private * @param {number} x number * @return {number} */ var ceil = Math.ceil; /** * @private * @param {number} x number * @return {number} */ var floor = Math.floor; /** * @private * @param {Date} ref reference date * @param {number} shift number of months to shift * @return {number} number of days shifted */ function borrowMonths(ref, shift) { var prevTime = ref.getTime(); // increment month by shift ref.setMonth( ref.getMonth() + shift ); // this is the trickiest since months vary in length return Math.round( (ref.getTime() - prevTime) / MILLISECONDS_PER_DAY ); } /** * @private * @param {Date} ref reference date * @return {number} number of days */ function daysPerMonth(ref) { var a = ref.getTime(); // increment month by 1 var b = new Date(a); b.setMonth( ref.getMonth() + 1 ); // this is the trickiest since months vary in length return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY ); } /** * @private * @param {Date} ref reference date * @return {number} number of days */ function daysPerYear(ref) { var a = ref.getTime(); // increment year by 1 var b = new Date(a); b.setFullYear( ref.getFullYear() + 1 ); // this is the trickiest since years (periodically) vary in length return Math.round( (b.getTime() - a) / MILLISECONDS_PER_DAY ); } /** * Applies the Timespan to the given date. * * @private * @param {Timespan} ts * @param {Date=} date * @return {Date} */ function addToDate(ts, date) { date = (date instanceof Date) || ((date !== null) && isFinite(date)) ? new Date(+date) : new Date(); if (!ts) { return date; } // if there is a value field, use it directly var value = +ts.value || 0; if (value) { date.setTime(date.getTime() + value); return date; } value = +ts.milliseconds || 0; if (value) { date.setMilliseconds(date.getMilliseconds() + value); } value = +ts.seconds || 0; // if (value) { date.setSeconds(date.getSeconds() + value); // } value = +ts.minutes || 0; if (value) { date.setMinutes(date.getMinutes() + value); } value = +ts.hours || 0; if (value) { date.setHours(date.getHours() + value); } value = +ts.weeks || 0; if (value) { value *= DAYS_PER_WEEK; } value += +ts.days || 0; if (value) { date.setDate(date.getDate() + value); } value = +ts.months || 0; if (value) { date.setMonth(date.getMonth() + value); } value = +ts.millennia || 0; if (value) { value *= CENTURIES_PER_MILLENNIUM; } value += +ts.centuries || 0; if (value) { value *= DECADES_PER_CENTURY; } value += +ts.decades || 0; if (value) { value *= YEARS_PER_DECADE; } value += +ts.years || 0; if (value) { date.setFullYear(date.getFullYear() + value); } return date; } /** * @private * @const * @type {number} */ var LABEL_MILLISECONDS = 0; /** * @private * @const * @type {number} */ var LABEL_SECONDS = 1; /** * @private * @const * @type {number} */ var LABEL_MINUTES = 2; /** * @private * @const * @type {number} */ var LABEL_HOURS = 3; /** * @private * @const * @type {number} */ var LABEL_DAYS = 4; /** * @private * @const * @type {number} */ var LABEL_WEEKS = 5; /** * @private * @const * @type {number} */ var LABEL_MONTHS = 6; /** * @private * @const * @type {number} */ var LABEL_YEARS = 7; /** * @private * @const * @type {number} */ var LABEL_DECADES = 8; /** * @private * @const * @type {number} */ var LABEL_CENTURIES = 9; /** * @private * @const * @type {number} */ var LABEL_MILLENNIA = 10; /** * @private * @type {Array} */ var LABELS_SINGLUAR; /** * @private * @type {Array} */ var LABELS_PLURAL; /** * @private * @type {string} */ var LABEL_LAST; /** * @private * @type {string} */ var LABEL_DELIM; /** * @private * @type {string} */ var LABEL_NOW; /** * Formats a number as a string * * @private * @param {number} value * @return {string} */ var formatNumber; /** * @private * @param {number} value * @param {number} unit unit index into label list * @return {string} */ function plurality(value, unit) { return formatNumber(value)+((value === 1) ? LABELS_SINGLUAR[unit] : LABELS_PLURAL[unit]); } /** * Formats the entries with singular or plural labels * * @private * @param {Timespan} ts * @return {Array} */ var formatList; /** * Timespan representation of a duration of time * * @private * @this {Timespan} * @constructor */ function Timespan() {} /** * Formats the Timespan as a sentence * * @param {string=} emptyLabel the string to use when no values returned * @return {string} */ Timespan.prototype.toString = function(emptyLabel) { var label = formatList(this); var count = label.length; if (!count) { return emptyLabel ? ''+emptyLabel : LABEL_NOW; } if (count === 1) { return label[0]; } var last = LABEL_LAST+label.pop(); return label.join(LABEL_DELIM)+last; }; /** * Formats the Timespan as a sentence in HTML * * @param {string=} tag HTML tag name to wrap each value * @param {string=} emptyLabel the string to use when no values returned * @return {string} */ Timespan.prototype.toHTML = function(tag, emptyLabel) { tag = tag || 'span'; var label = formatList(this); var count = label.length; if (!count) { emptyLabel = emptyLabel || LABEL_NOW; return emptyLabel ? '<'+tag+'>'+emptyLabel+'</'+tag+'>' : emptyLabel; } for (var i=0; i<count; i++) { // wrap each unit in tag label[i] = '<'+tag+'>'+label[i]+'</'+tag+'>'; } if (count === 1) { return label[0]; } var last = LABEL_LAST+label.pop(); return label.join(LABEL_DELIM)+last; }; /** * Applies the Timespan to the given date * * @param {Date=} date the date to which the timespan is added. * @return {Date} */ Timespan.prototype.addTo = function(date) { return addToDate(this, date); }; /** * Formats the entries as English labels * * @private * @param {Timespan} ts * @return {Array} */ formatList = function(ts) { var list = []; var value = ts.millennia; if (value) { list.push(plurality(value, LABEL_MILLENNIA)); } value = ts.centuries; if (value) { list.push(plurality(value, LABEL_CENTURIES)); } value = ts.decades; if (value) { list.push(plurality(value, LABEL_DECADES)); } value = ts.years; if (value) { list.push(plurality(value, LABEL_YEARS)); } value = ts.months; if (value) { list.push(plurality(value, LABEL_MONTHS)); } value = ts.weeks; if (value) { list.push(plurality(value, LABEL_WEEKS)); } value = ts.days; if (value) { list.push(plurality(value, LABEL_DAYS)); } value = ts.hours; if (value) { list.push(plurality(value, LABEL_HOURS)); } value = ts.minutes; if (value) { list.push(plurality(value, LABEL_MINUTES)); } value = ts.seconds; // if (value) { list.push(plurality(value, LABEL_SECONDS)); // } value = ts.milliseconds; if (value) { list.push(plurality(value, LABEL_MILLISECONDS)); } return list; }; /** * Borrow any underflow units, carry any overflow units * * @private * @param {Timespan} ts * @param {string} toUnit */ function rippleRounded(ts, toUnit) { switch (toUnit) { case 'seconds': if (ts.seconds !== SECONDS_PER_MINUTE || isNaN(ts.minutes)) { return; } // ripple seconds up to minutes ts.minutes++; ts.seconds = 0; /* falls through */ case 'minutes': if (ts.minutes !== MINUTES_PER_HOUR || isNaN(ts.hours)) { return; } // ripple minutes up to hours ts.hours++; ts.minutes = 0; /* falls through */ case 'hours': if (ts.hours !== HOURS_PER_DAY || isNaN(ts.days)) { return; } // ripple hours up to days ts.days++; ts.hours = 0; /* falls through */ case 'days': if (ts.days !== DAYS_PER_WEEK || isNaN(ts.weeks)) { return; } // ripple days up to weeks ts.weeks++; ts.days = 0; /* falls through */ case 'weeks': if (ts.weeks !== daysPerMonth(ts.refMonth)/DAYS_PER_WEEK || isNaN(ts.months)) { return; } // ripple weeks up to months ts.months++; ts.weeks = 0; /* falls through */ case 'months': if (ts.months !== MONTHS_PER_YEAR || isNaN(ts.years)) { return; } // ripple months up to years ts.years++; ts.months = 0; /* falls through */ case 'years': if (ts.years !== YEARS_PER_DECADE || isNaN(ts.decades)) { return; } // ripple years up to decades ts.decades++; ts.years = 0; /* falls through */ case 'decades': if (ts.decades !== DECADES_PER_CENTURY || isNaN(ts.centuries)) { return; } // ripple decades up to centuries ts.centuries++; ts.decades = 0; /* falls through */ case 'centuries': if (ts.centuries !== CENTURIES_PER_MILLENNIUM || isNaN(ts.millennia)) { return; } // ripple centuries up to millennia ts.millennia++; ts.centuries = 0; /* falls through */ } } /** * Ripple up partial units one place * * @private * @param {Timespan} ts timespan * @param {number} frac accumulated fractional value * @param {string} fromUnit source unit name * @param {string} toUnit target unit name * @param {number} conversion multiplier between units * @param {number} digits max number of decimal digits to output * @return {number} new fractional value */ function fraction(ts, frac, fromUnit, toUnit, conversion, digits) { if (ts[fromUnit] >= 0) { frac += ts[fromUnit]; delete ts[fromUnit]; } frac /= conversion; if (frac + 1 <= 1) { // drop if below machine epsilon return 0; } if (ts[toUnit] >= 0) { // ensure does not have more than specified number of digits ts[toUnit] = +(ts[toUnit] + frac).toFixed(digits); rippleRounded(ts, toUnit); return 0; } return frac; } /** * Ripple up partial units to next existing * * @private * @param {Timespan} ts * @param {number} digits max number of decimal digits to output */ function fractional(ts, digits) { var frac = fraction(ts, 0, 'milliseconds', 'seconds', MILLISECONDS_PER_SECOND, digits); if (!frac) { return; } frac = fraction(ts, frac, 'seconds', 'minutes', SECONDS_PER_MINUTE, digits); if (!frac) { return; } frac = fraction(ts, frac, 'minutes', 'hours', MINUTES_PER_HOUR, digits); if (!frac) { return; } frac = fraction(ts, frac, 'hours', 'days', HOURS_PER_DAY, digits); if (!frac) { return; } frac = fraction(ts, frac, 'days', 'weeks', DAYS_PER_WEEK, digits); if (!frac) { return; } frac = fraction(ts, frac, 'weeks', 'months', daysPerMonth(ts.refMonth)/DAYS_PER_WEEK, digits); if (!frac) { return; } frac = fraction(ts, frac, 'months', 'years', daysPerYear(ts.refMonth)/daysPerMonth(ts.refMonth), digits); if (!frac) { return; } frac = fraction(ts, frac, 'years', 'decades', YEARS_PER_DECADE, digits); if (!frac) { return; } frac = fraction(ts, frac, 'decades', 'centuries', DECADES_PER_CENTURY, digits); if (!frac) { return; } frac = fraction(ts, frac, 'centuries', 'millennia', CENTURIES_PER_MILLENNIUM, digits); // should never reach this with remaining fractional value if (frac) { throw new Error('Fractional unit overflow'); } } /** * Borrow any underflow units, carry any overflow units * * @private * @param {Timespan} ts */ function ripple(ts) { var x; if (ts.milliseconds < 0) { // ripple seconds down to milliseconds x = ceil(-ts.milliseconds / MILLISECONDS_PER_SECOND); ts.seconds -= x; ts.milliseconds += x * MILLISECONDS_PER_SECOND; } else if (ts.milliseconds >= MILLISECONDS_PER_SECOND) { // ripple milliseconds up to seconds ts.seconds += floor(ts.milliseconds / MILLISECONDS_PER_SECOND); ts.milliseconds %= MILLISECONDS_PER_SECOND; } if (ts.seconds < 0) { // ripple minutes down to seconds x = ceil(-ts.seconds / SECONDS_PER_MINUTE); ts.minutes -= x; ts.seconds += x * SECONDS_PER_MINUTE; } else if (ts.seconds >= SECONDS_PER_MINUTE) { // ripple seconds up to minutes ts.minutes += floor(ts.seconds / SECONDS_PER_MINUTE); ts.seconds %= SECONDS_PER_MINUTE; } if (ts.minutes < 0) { // ripple hours down to minutes x = ceil(-ts.minutes / MINUTES_PER_HOUR); ts.hours -= x; ts.minutes += x * MINUTES_PER_HOUR; } else if (ts.minutes >= MINUTES_PER_HOUR) { // ripple minutes up to hours ts.hours += floor(ts.minutes / MINUTES_PER_HOUR); ts.minutes %= MINUTES_PER_HOUR; } if (ts.hours < 0) { // ripple days down to hours x = ceil(-ts.hours / HOURS_PER_DAY); ts.days -= x; ts.hours += x * HOURS_PER_DAY; } else if (ts.hours >= HOURS_PER_DAY) { // ripple hours up to days ts.days += floor(ts.hours / HOURS_PER_DAY); ts.hours %= HOURS_PER_DAY; } while (ts.days < 0) { // NOTE: never actually seen this loop more than once // ripple months down to days ts.months--; ts.days += borrowMonths(ts.refMonth, 1); } // weeks is always zero here if (ts.days >= DAYS_PER_WEEK) { // ripple days up to weeks ts.weeks += floor(ts.days / DAYS_PER_WEEK); ts.days %= DAYS_PER_WEEK; } if (ts.months < 0) { // ripple years down to months x = ceil(-ts.months / MONTHS_PER_YEAR); ts.years -= x; ts.months += x * MONTHS_PER_YEAR; } else if (ts.months >= MONTHS_PER_YEAR) { // ripple months up to years ts.years += floor(ts.months / MONTHS_PER_YEAR); ts.months %= MONTHS_PER_YEAR; } // years is always non-negative here // decades, centuries and millennia are always zero here if (ts.years >= YEARS_PER_DECADE) { // ripple years up to decades ts.decades += floor(ts.years / YEARS_PER_DECADE); ts.years %= YEARS_PER_DECADE; if (ts.decades >= DECADES_PER_CENTURY) { // ripple decades up to centuries ts.centuries += floor(ts.decades / DECADES_PER_CENTURY); ts.decades %= DECADES_PER_CENTURY; if (ts.centuries >= CENTURIES_PER_MILLENNIUM) { // ripple centuries up to millennia ts.millennia += floor(ts.centuries / CENTURIES_PER_MILLENNIUM); ts.centuries %= CENTURIES_PER_MILLENNIUM; } } } } /** * Remove any units not requested * * @private * @param {Timespan} ts * @param {number} units the units to populate * @param {number} max number of labels to output * @param {number} digits max number of decimal digits to output */ function pruneUnits(ts, units, max, digits) { var count = 0; // Calc from largest unit to smallest to prevent underflow if (!(units & MILLENNIA) || (count >= max)) { // ripple millennia down to centuries ts.centuries += ts.millennia * CENTURIES_PER_MILLENNIUM; delete ts.millennia; } else if (ts.millennia) { count++; } if (!(units & CENTURIES) || (count >= max)) { // ripple centuries down to decades ts.decades += ts.centuries * DECADES_PER_CENTURY; delete ts.centuries; } else if (ts.centuries) { count++; } if (!(units & DECADES) || (count >= max)) { // ripple decades down to years ts.years += ts.decades * YEARS_PER_DECADE; delete ts.decades; } else if (ts.decades) { count++; } if (!(units & YEARS) || (count >= max)) { // ripple years down to months ts.months += ts.years * MONTHS_PER_YEAR; delete ts.years; } else if (ts.years) { count++; } if (!(units & MONTHS) || (count >= max)) { // ripple months down to days if (ts.months) { ts.days += borrowMonths(ts.refMonth, ts.months); } delete ts.months; if (ts.days >= DAYS_PER_WEEK) { // ripple day overflow back up to weeks ts.weeks += floor(ts.days / DAYS_PER_WEEK); ts.days %= DAYS_PER_WEEK; } } else if (ts.months) { count++; } if (!(units & WEEKS) || (count >= max)) { // ripple weeks down to days ts.days += ts.weeks * DAYS_PER_WEEK; delete ts.weeks; } else if (ts.weeks) { count++; } if (!(units & DAYS) || (count >= max)) { //ripple days down to hours ts.hours += ts.days * HOURS_PER_DAY; delete ts.days; } else if (ts.days) { count++; } if (!(units & HOURS) || (count >= max)) { // ripple hours down to minutes ts.minutes += ts.hours * MINUTES_PER_HOUR; delete ts.hours; } else if (ts.hours) { count++; } if (!(units & MINUTES) || (count >= max)) { // ripple minutes down to seconds ts.seconds += ts.minutes * SECONDS_PER_MINUTE; delete ts.minutes; } else if (ts.minutes) { count++; } if (!(units & SECONDS) || (count >= max)) { // ripple seconds down to milliseconds ts.milliseconds += ts.seconds * MILLISECONDS_PER_SECOND; delete ts.seconds; } else if (ts.seconds) { count++; } // nothing to ripple milliseconds down to // so ripple back up to smallest existing unit as a fractional value if (!(units & MILLISECONDS) || (count >= max)) { fractional(ts, digits); } } /** * Populates the Timespan object * * @private * @param {Timespan} ts * @param {?Date} start the starting date * @param {?Date} end the ending date * @param {number} units the units to populate * @param {number} max number of labels to output * @param {number} digits max number of decimal digits to output */ function populate(ts, start, end, units, max, digits) { var now = new Date(); ts.start = start = start || now; ts.end = end = end || now; ts.units = units; ts.value = end.getTime() - start.getTime(); if (ts.value < 0) { // swap if reversed var tmp = end; end = start; start = tmp; } // reference month for determining days in month ts.refMonth = new Date(start.getFullYear(), start.getMonth(), 15, 12, 0, 0); try { // reset to initial deltas ts.millennia = 0; ts.centuries = 0; ts.decades = 0; ts.years = end.getFullYear() - start.getFullYear(); ts.months = end.getMonth() - start.getMonth(); ts.weeks = 0; ts.days = end.getDate() - start.getDate(); ts.hours = end.getHours() - start.getHours(); ts.minutes = end.getMinutes() - start.getMinutes(); ts.seconds = end.getSeconds() - start.getSeconds(); ts.milliseconds = end.getMilliseconds() - start.getMilliseconds(); ripple(ts); pruneUnits(ts, units, max, digits); } finally { delete ts.refMonth; } return ts; } /** * Determine an appropriate refresh rate based upon units * * @private * @param {number} units the units to populate * @return {number} milliseconds to delay */ function getDelay(units) { if (units & MILLISECONDS) { // refresh very quickly return MILLISECONDS_PER_SECOND / 30; //30Hz } if (units & SECONDS) { // refresh every second return MILLISECONDS_PER_SECOND; //1Hz } if (units & MINUTES) { // refresh every minute return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE; } if (units & HOURS) { // refresh hourly return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR; } if (units & DAYS) { // refresh daily return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY; } // refresh the rest weekly return MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK; } /** * API entry point * * @public * @param {Date|number|Timespan|null|function(Timespan,number)} start the starting date * @param {Date|number|Timespan|null|function(Timespan,number)} end the ending date * @param {number=} units the units to populate * @param {number=} max number of labels to output * @param {number=} digits max number of decimal digits to output * @return {Timespan|number} */ function countdown(start, end, units, max, digits) { var callback; // ensure some units or use defaults units = +units || DEFAULTS; // max must be positive max = (max > 0) ? max : NaN; // clamp digits to an integer between [0, 20] digits = (digits > 0) ? (digits < 20) ? Math.round(digits) : 20 : 0; // ensure start date var startTS = null; if ('function' === typeof start) { callback = start; start = null; } else if (!(start instanceof Date)) { if ((start !== null) && isFinite(start)) { start = new Date(+start); } else { if ('object' === typeof startTS) { startTS = /** @type{Timespan} */(start); } start = null; } } // ensure end date var endTS = null; if ('function' === typeof end) { callback = end; end = null; } else if (!(end instanceof Date)) { if ((end !== null) && isFinite(end)) { end = new Date(+end); } else { if ('object' === typeof end) { endTS = /** @type{Timespan} */(end); } end = null; } } // must wait to interpret timespans until after resolving dates if (startTS) { start = addToDate(startTS, end); } if (endTS) { end = addToDate(endTS, start); } if (!start && !end) { // used for unit testing return new Timespan(); } if (!callback) { return populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits)); } // base delay off units var delay = getDelay(units), timerId, fn = function() { callback( populate(new Timespan(), /** @type{Date} */(start), /** @type{Date} */(end), /** @type{number} */(units), /** @type{number} */(max), /** @type{number} */(digits)), timerId ); }; fn(); return (timerId = setInterval(fn, delay)); } /** * @public * @const * @type {number} */ countdown.MILLISECONDS = MILLISECONDS; /** * @public * @const * @type {number} */ countdown.SECONDS = SECONDS; /** * @public * @const * @type {number} */ countdown.MINUTES = MINUTES; /** * @public * @const * @type {number} */ countdown.HOURS = HOURS; /** * @public * @const * @type {number} */ countdown.DAYS = DAYS; /** * @public * @const * @type {number} */ countdown.WEEKS = WEEKS; /** * @public * @const * @type {number} */ countdown.MONTHS = MONTHS; /** * @public * @const * @type {number} */ countdown.YEARS = YEARS; /** * @public * @const * @type {number} */ countdown.DECADES = DECADES; /** * @public * @const * @type {number} */ countdown.CENTURIES = CENTURIES; /** * @public * @const * @type {number} */ countdown.MILLENNIA = MILLENNIA; /** * @public * @const * @type {number} */ countdown.DEFAULTS = DEFAULTS; /** * @public * @const * @type {number} */ countdown.ALL = MILLENNIA|CENTURIES|DECADES|YEARS|MONTHS|WEEKS|DAYS|HOURS|MINUTES|SECONDS|MILLISECONDS; /** * Override the unit labels * @public * @param {string|Array=} singular a pipe ('|') delimited list of singular unit name overrides * @param {string|Array=} plural a pipe ('|') delimited list of plural unit name overrides * @param {string=} last a delimiter before the last unit (default: ' and ') * @param {string=} delim a delimiter to use between all other units (default: ', ') * @param {string=} empty a label to use when all units are zero (default: '') * @param {function(number):string=} formatter a function which formats numbers as a string */ countdown.setLabels = function(singular, plural, last, delim, empty, formatter) { singular = singular || []; if (singular.split) { singular = singular.split('|'); } plural = plural || []; if (plural.split) { plural = plural.split('|'); } for (var i=LABEL_MILLISECONDS; i<=LABEL_MILLENNIA; i++) { // override any specified units LABELS_SINGLUAR[i] = singular[i] || LABELS_SINGLUAR[i]; LABELS_PLURAL[i] = plural[i] || LABELS_PLURAL[i]; } LABEL_LAST = ('string' === typeof last) ? last : LABEL_LAST; LABEL_DELIM = ('string' === typeof delim) ? delim : LABEL_DELIM; LABEL_NOW = ('string' === typeof empty) ? empty : LABEL_NOW; formatNumber = ('function' === typeof formatter) ? formatter : formatNumber; }; /** * Revert to the default unit labels * @public */ var resetLabels = countdown.resetLabels = function() { LABELS_SINGLUAR = ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium'.split('|'); LABELS_PLURAL = ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia'.split('|'); LABEL_LAST = ' and '; LABEL_DELIM = ', '; LABEL_NOW = ''; formatNumber = function(value) { return '<span class="contest_timedelta">' + value + "</span>"; }; }; resetLabels(); if (module && module.exports) { module.exports = countdown; } else if (typeof window.define === 'function' && typeof window.define.amd !== 'undefined') { window.define('countdown', [], function() { return countdown; }); } return countdown; })(module);
entpy/beauty-and-pics
beauty_and_pics/website/static/website/js/vendor/countdown.js
JavaScript
mit
27,520
var formMode="detail"; /*formMode 页面模式 页面有三种模式 detail add modify*/ var panelType="form"; /*panelType 面板类型 form表单 search 查询 child 从表对象*/ var editIndex = undefined; /*datagrid 编辑对象的行号*/ var dg1EditIndex = undefined; var objName=label.objName; /*页面管理对象名称*/ var lblDetailStr=label.detailStr; /*在不同的语种下应该不同*/ var lblAddStr=label.addStr; /*在不同的语种下应该不同*/ var lblEditStr=label.editStr; /*在不同的语种下应该不同*/ var pageName=null; /*根据pageName能够取得按钮定义*/ var pageHeight=0; /*pageHeight 页面高度*/ var topHeight=366; /*datagrid高度*/ var dgHeadHeight=28; /*datagrid 收缩后高度*/ var downHeight=30; /*底部高度*/ var paddingHeight=11; /*页面内补丁高度 paddingTop+paddingBottom*/ var gridToolbar = null; /*按钮定义 */ var dgConf=null; /*dgConf配置信息*/ var dg1Conf=null; function initConf(){} /*在此初始化本页面的所有配置信息*/ function initButton(){ for(var i=0;i<gridToolbar.length;i++){ var b=gridToolbar[i];/*首次运行时所有按钮都是disable状态*/ $("#"+b.id).linkbutton({iconCls: b.iconCls,text:b.text,disabled:true,handler:b.handler,plain:1}); } } function initBtnDisabled() { var btnDisabled=[{"id":"btn_refresh"},{"id":"btn_search"}]; for(var i=0;i<btnDisabled.length;i++) { $('#'+btnDisabled[i].id).linkbutton('enable'); } } function component() { initConf(); if(window.innerHeight) pageHeight=window.innerHeight; else pageHeight=document.documentElement.clientHeight; $('#middle').css("height",pageHeight-topHeight-downHeight-paddingHeight); $('#tab').tabs({ onSelect:tab_select, fit:true }); /*这时候可能还没有key 所以不能直接绑定dom对象,只能使用dom id*/ installKey("btn_collapse",Keys.f1,null,null,null); installKey("btn_edit",Keys.f2,null,null,null); installKey("btn_search",Keys.f3,null,null,null); installKey("btn_add",Keys.f4,null,null,null); installKey("btn_delete",Keys.del,null,null,null); installKey("btn2_save",Keys.s,true,null,null); installKey("btn2_search",Keys.q,true,null,null); installKey("btn2_edit",Keys.e,true,null,null); document.onhelp=function(){return false}; /*为了屏蔽IE的F1按键*/ window.onhelp=function(){return false}; /*为了屏蔽IE的F1按键*/ $('#btn2_save').linkbutton({iconCls: 'icon-save'}).click(btn2_save); $('#btn2_edit').linkbutton({iconCls: 'icon-save'}).click(btn2_update), $('#btn2_search').linkbutton({iconCls: 'icon-search'}).click(btn2_search); $('#btn2_addItem').linkbutton({iconCls: 'icon-add'}).click(btn2_addItem); $('#btn2_editItem').linkbutton({iconCls: 'icon-edit'}).click(btn2_editItem); $('#btn2_rmItem').linkbutton({iconCls: 'icon-remove'}).click(btn2_rmItem); $('#btn2_ok').linkbutton({iconCls: 'icon-ok'}).click(btn2_ok); dgConf.toolbar='#tb'; dgConf.onCollapse=dg_collapse; dgConf.onSelect=dg_select; dgConf.singleSelect=true; dgConf.onLoadSuccess=dg_load; dgConf.onClickRow=dg_click; dgConf.onDblClickRow=dg_dbl; dgConf.onExpand=dg_expand; dgConf.collapsible=true; dgConf.collapseID="btn_collapse"; dgConf.pagination=true; dgConf.fit=true; dgConf.rownumbers=true; dgConf.singleSelect=true; dg1Conf.onClickRow=dg1_click; dg1Conf.onDblClickRow=dg1_dbl; $("#dg").datagrid(dgConf); initButton(); initBtnDisabled(); $('#top').css("height","auto"); lov_init(); $(".formChild").height(pageHeight-topHeight-downHeight-paddingHeight-dgHeadHeight-1); //$("#ff1 input").attr("readonly",1); /*详细表单的输入框只读*/ } function showChildGrid(param){/*dg 选中事件触发*/ $("#dg1").datagrid(dg1Conf); } function showForm(row){/*dg 选中事件触发*/ //$("#ff1").form("load",row); //$("#ff2").form("load",row);; } function dg_collapse(){/*收缩后 总是要修改tabs 会触发tab_select事件 那么前面就需要将panel的selected属性设为true*/ var panel=$("#tab").tabs("getSelected"); /*先获取selected对象*/ if(panel!=null) panel.panel({selected:1}); $('#middle').css("height",pageHeight-dgHeadHeight-downHeight-paddingHeight); $(".formChild").height(pageHeight-dgHeadHeight-downHeight-paddingHeight-dgHeadHeight-1); $("#tab").tabs({fit:true,stopSelect:true});/*tab发生变化了 会触发tab_select事件 */ if(panel!=null) panel.panel({selected:0}); } function dg_expand(){ var panel=$("#tab").tabs("getSelected"); if(panel!=null) panel.panel({selected:1}); $('#middle').css("height",pageHeight-topHeight-downHeight-paddingHeight); $(".formChild").height(pageHeight-topHeight-downHeight-paddingHeight-dgHeadHeight-1); $("#tab").tabs({fit:true,stopSelect:true}); if(panel!=null) panel.panel({selected:0}); } function dg_load(){/*选中第一行*/ $('#mask').css('display', "none"); $('#dg').datagrid('selectRow', 0); } function dg_select(rowIndex, rowData){/*选中事件 填充ff1 ff2 dg1*/ showChildGrid(rowData);/*子表模式下,重绘子表列表*/ showForm(rowData,"add"); useDetailMode(); } function dg_add(){/*列表新增按钮事件*/ useAddMode(); } function dg_edit(){/*列表编辑按钮触发事件*/ var row=$('#dg').datagrid('getSelected'); if(row){ useEditMode(); } else $.messager.alert('选择提示', '请选择您编辑的数据!',"info"); } function dg_delete(){/*列表删除按钮触发事件*/ var confirmBack=function(r){ if(!r) return; var p=$('#dg').datagrid('getRowIndex',$('#dg').datagrid('getSelected')); /*执行服务器请求,完成服务端数据的删除 然后完成前端的删除*/ if (p == undefined){return} $('#dg').datagrid('cancelEdit', p) .datagrid('deleteRow', p); /*删除成功后应该刷新页面 并把下一条选中*/ var currRows=$('#dg').datagrid('getRows').length; if(p>=currRows) p--; if(p>=0) $('#dg').datagrid('selectRow', p);/*如果已经到末尾则 选中p-1 */ } var row=$('#dg').datagrid('getSelected'); if(row) $.messager.confirm('确认提示', '您确认要删除这条数据吗?', confirmBack); else $.messager.alert('选择提示', '请选择您要删除的数据!',"info"); } function dg_refresh(){/*列表刷新按钮事件*/ } function dg_search(){/*列表搜索事件 search模式不再禁用其他面板*/ panelType="search"; $('#tab').tabs("select",1); } function dg_click(index){ /*切换回详细信息模式 首先判断tab的当前选项*/ if(panelType=="search"){ $('#tab').tabs("select",0); } } function dg_dbl(){/*列表双击事件 双击进入编辑模式*/ document.getElementById("btn_edit").click();/*双击等同于点击编辑按钮*/ } function tab_select(title,index){/*选项卡的切换 需要更改按钮的显示*/ $('#down a').css("display","none"); if(index==0){/*根据grid的状态来生成按钮 add edit*/ $('#btn2_addItem').css("display","inline-block");/*新增行按钮*/ $('#btn2_editItem').css("display","inline-block");/*删除行按钮*/ $('#btn2_rmItem').css("display","inline-block");/*删除行按钮*/ $('#btn2_ok').css("display","inline-block");/*commit按钮*/ } else if(index==1){/*查询选项卡 切换到查询页签等同于按钮 search被点击*/ panelType="search"; $('#btn2_search').css("display","inline-block");/*搜索按钮*/ } } function useDetailMode(row){ //formMode="detail"; //$('#ff2').css("display","none"); //$('#ff1').css("display","block"); //if(panelType=="search") $('#tab').tabs("select",0); //else tab_select(); } function btn2_addItem(){ if(dg1_endEditing()){/*结束编辑状态成功*/ var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected')); /*执行服务器请求,完成服务端数据的删除 然后完成前端的删除*/ if (p == undefined){return} $('#dg1').datagrid('unselectAll'); $('#dg1').datagrid('insertRow',{index:p+1,row:{}}) .datagrid('beginEdit', p+1) .datagrid('selectRow', p+1); dg1EditIndex=p+1; } else{ $('#dg1').datagrid('selectRow', dg1EditIndex); } } function btn2_editItem(){ var index=$('#dg1').datagrid('getRowIndex', $('#dg1').datagrid('getSelected')); if (dg1EditIndex != index){ if (dg1_endEditing()){ $('#dg1').datagrid('selectRow', index) .datagrid('beginEdit', index); dg1EditIndex = index; } else { $('#dg1').datagrid('selectRow', dg1EditIndex); } } } function btn2_rmItem(){ var confirmBack=function(r){ if(!r) return; var p=$('#dg1').datagrid('getRowIndex',$('#dg1').datagrid('getSelected')); if (p == undefined){return} $('#dg1').datagrid('cancelEdit', p) .datagrid('deleteRow', p); var currRows=$('#dg1').datagrid('getRows').length; if(p>=currRows) p--; if(p>=0) $('#dg1').datagrid('selectRow', p);/*如果已经到末尾则 选中p-1 */ } var row=$('#dg1').datagrid('getSelected'); if(row) $.messager.confirm('确认提示', '您确认要删除这条数据吗?', confirmBack); else $.messager.alert('选择提示', '请选择您要删除的数据!',"info"); } function dg1_endEditing(){ if (dg1EditIndex == undefined){return true} var flag=$('#dg1').datagrid('validateRow',dg1EditIndex); if(flag){/*如果校验通过 允许结束编辑状态*/ $('#dg1').datagrid('endEdit', dg1EditIndex); dg1EditIndex = undefined; return true; } return false; } function dg1_click(index){/*从表单击事件 在编辑模式下打开编辑*/ if (dg1EditIndex != index){ dg1_endEditing(); } } function dg1_dbl(index){/*从表双击事件 双击进入编辑模式*/ document.getElementById("btn2_editItem").click();/*双击等同于点击编辑按钮*/ } function useAddMode(){}; function useEditMode(){}; function form_change(type){}/*type= add|edit*/ function removeValidate(){}/*type= enable|remove*/ function btn2_save(){} function btn2_update(){} function btn2_search(){} function btn2_ok(){} function lov_init(){}/*绑定值列表*/
ldjking/wbscreen
web/wb/2tp/template/js/common/copy/a3.js
JavaScript
mit
9,914
/** * HTTP.test */ "use strict"; /* Node modules */ /* Third-party modules */ var steeplejack = require("steeplejack"); /* Files */ describe("HTTPError test", function () { var HTTPError; beforeEach(function () { injector(function (_HTTPError_) { HTTPError = _HTTPError_; }); }); describe("Instantation tests", function () { it("should extend the steeplejack Fatal exception", function () { var obj = new HTTPError("text"); expect(obj).to.be.instanceof(HTTPError) .to.be.instanceof(steeplejack.Exceptions.Fatal); expect(obj.type).to.be.equal("HTTPError"); expect(obj.message).to.be.equal("text"); expect(obj.httpCode).to.be.equal(500); expect(obj.getHttpCode()).to.be.equal(500); }); it("should set the HTTP code in the first input", function () { var obj = new HTTPError(401); expect(obj.httpCode).to.be.equal(401); expect(obj.getHttpCode()).to.be.equal(401); }); }); });
riggerthegeek/steeplejack-errors
test/unit/errors/HTTP.test.js
JavaScript
mit
1,103
var gulp = require('gulp'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var rename = require("gulp-rename"); var uglify = require("gulp-uglify"); var cssmin = require("gulp-cssmin"); var ngAnnotate = require('gulp-ng-annotate'); var nib = require("nib"); var watch = require('gulp-watch'); function compileJs(devOnly) { var othersUmd = gulp.src(['src/**/*.js', '!src/main.js']) .pipe(babel({ modules: 'umdStrict', moduleRoot: 'angular-chatbar', moduleIds: true })), mainUmd = gulp.src('src/main.js') .pipe(babel({ modules: 'umdStrict', moduleIds: true, moduleId: 'angular-chatbar' })), stream = merge(othersUmd, mainUmd) .pipe(concat('angular-chatbar.umd.js')) .pipe(gulp.dest('dist')) ; if (!devOnly) { stream = stream .pipe(ngAnnotate()) .pipe(uglify()) .pipe(rename('angular-chatbar.umd.min.js')) .pipe(gulp.dest('dist')); } return stream; } function compileCss(name, devOnly) { var stream = gulp.src('styles/' + name + '.styl') .pipe(stylus({use: nib()})) .pipe(rename('angular-' + name + '.css')) .pipe(gulp.dest('dist')) ; if (!devOnly) { stream = stream.pipe(cssmin()) .pipe(rename('angular-' + name + '.min.css')) .pipe(gulp.dest('dist')); } return stream; } function compileAllCss(devOnly) { var streams = []; ['chatbar', 'chatbar.default-theme', 'chatbar.default-animations'].forEach(function (name) { streams.push(compileCss(name, devOnly)); }); return merge.apply(null, streams); } gulp.task('default', function() { return merge.apply(compileJs(), compileAllCss()); }); gulp.task('_watch', function() { watch('styles/**/*.styl', function () { compileAllCss(true); }); watch('src/**/*.js', function () { compileJs(true); }); }); gulp.task('watch', ['default', '_watch']);
jlowcs/angular-chatbar
gulpfile.js
JavaScript
mit
1,878
// @flow import { StyleSheet } from 'react-native'; import { colors } from '../../themes'; const styles = StyleSheet.create({ divider: { height: 1, marginHorizontal: 0, backgroundColor: colors.darkDivider, }, }); export default styles;
Dennitz/Timetable
src/components/styles/HorizontalDividerList.styles.js
JavaScript
mit
254
'use strict'; const _ = require('lodash'); const co = require('co'); const Promise = require('bluebird'); const AWS = require('aws-sdk'); AWS.config.region = 'us-east-1'; const cloudwatch = Promise.promisifyAll(new AWS.CloudWatch()); const Lambda = new AWS.Lambda(); const START_TIME = new Date('2017-06-07T01:00:00.000Z'); const DAYS = 2; const ONE_DAY = 24 * 60 * 60 * 1000; let addDays = (startDt, n) => new Date(startDt.getTime() + ONE_DAY * n); let getFuncStats = co.wrap(function* (funcName) { let getStats = co.wrap(function* (startTime, endTime) { let req = { MetricName: 'Duration', Namespace: 'AWS/Lambda', Period: 60, Dimensions: [ { Name: 'FunctionName', Value: funcName } ], Statistics: [ 'Maximum' ], Unit: 'Milliseconds', StartTime: startTime, EndTime: endTime }; let resp = yield cloudwatch.getMetricStatisticsAsync(req); return resp.Datapoints.map(dp => { return { timestamp: dp.Timestamp, value: dp.Maximum }; }); }); let stats = []; for (let i = 0; i < DAYS; i++) { // CloudWatch only allows us to query 1440 data points per request, which // at 1 min period is 24 hours let startTime = addDays(START_TIME, i); let endTime = addDays(startTime, 1); let oneDayStats = yield getStats(startTime, endTime); stats = stats.concat(oneDayStats); } return _.sortBy(stats, s => s.timestamp); }); let listFunctions = co.wrap(function* (marker, acc) { acc = acc || []; let resp = yield Lambda.listFunctions({ Marker: marker, MaxItems: 100 }).promise(); let functions = resp.Functions .map(f => f.FunctionName) .filter(fn => fn.includes("aws-coldstart") && !fn.endsWith("run")); acc = acc.concat(functions); if (resp.NextMarker) { return yield listFunctions(resp.NextMarker, acc); } else { return acc; } }); listFunctions() .then(co.wrap(function* (funcs) { for (let func of funcs) { let stats = yield getFuncStats(func); stats.forEach(stat => console.log(`${func},${stat.timestamp},${stat.value}`)); } }));
theburningmonk/lambda-coldstart-comparison
download-stats.js
JavaScript
mit
2,153
// @flow (require('../../lib/git'): any).rebaseRepoMaster = jest.fn(); import { _clearCustomCacheDir as clearCustomCacheDir, _setCustomCacheDir as setCustomCacheDir, } from '../../lib/cacheRepoUtils'; import {copyDir, mkdirp} from '../../lib/fileUtils'; import {parseDirString as parseFlowDirString} from '../../lib/flowVersion'; import { add as gitAdd, commit as gitCommit, init as gitInit, setLocalConfig as gitConfig, } from '../../lib/git'; import {fs, path, child_process} from '../../lib/node'; import {getNpmLibDefs} from '../../lib/npm/npmLibDefs'; import {testProject} from '../../lib/TEST_UTILS'; import { _determineFlowVersion as determineFlowVersion, _installNpmLibDefs as installNpmLibDefs, _installNpmLibDef as installNpmLibDef, run, } from '../install'; const BASE_FIXTURE_ROOT = path.join(__dirname, '__install-fixtures__'); function _mock(mockFn) { return ((mockFn: any): JestMockFn<*, *>); } async function touchFile(filePath) { await fs.close(await fs.open(filePath, 'w')); } async function writePkgJson(filePath, pkgJson) { await fs.writeJson(filePath, pkgJson); } describe('install (command)', () => { describe('determineFlowVersion', () => { it('infers version from path if arg not passed', () => { return testProject(async ROOT_DIR => { const ARBITRARY_PATH = path.join(ROOT_DIR, 'some', 'arbitrary', 'path'); await Promise.all([ mkdirp(ARBITRARY_PATH), touchFile(path.join(ROOT_DIR, '.flowconfig')), writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }), ]); const flowVer = await determineFlowVersion(ARBITRARY_PATH); expect(flowVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 40, patch: 0, prerel: null, }, }); }); }); it('uses explicitly specified version', async () => { const explicitVer = await determineFlowVersion('/', '0.7.0'); expect(explicitVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 7, patch: 0, prerel: null, }, }); }); it("uses 'v'-prefixed explicitly specified version", async () => { const explicitVer = await determineFlowVersion('/', 'v0.7.0'); expect(explicitVer).toEqual({ kind: 'specific', ver: { major: 0, minor: 7, patch: 0, prerel: null, }, }); }); }); describe('installNpmLibDefs', () => { const origConsoleError = console.error; beforeEach(() => { (console: any).error = jest.fn(); }); afterEach(() => { (console: any).error = origConsoleError; }); it('errors if unable to find a project root (.flowconfig)', () => { return testProject(async ROOT_DIR => { const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: [], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(1); expect(_mock(console.error).mock.calls).toEqual([ [ 'Error: Unable to find a flow project in the current dir or any of ' + "it's parent dirs!\n" + 'Please run this command from within a Flow project.', ], ]); }); }); it( "errors if an explicitly specified libdef arg doesn't match npm " + 'pkgver format', () => { return testProject(async ROOT_DIR => { await touchFile(path.join(ROOT_DIR, '.flowconfig')); await writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }); const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: ['INVALID'], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(1); expect(_mock(console.error).mock.calls).toEqual([ [ 'ERROR: Package not found from package.json.\n' + 'Please specify version for the package in the format of `foo@1.2.3`', ], ]); }); }, ); it('warns if 0 dependencies are found in package.json', () => { return testProject(async ROOT_DIR => { await Promise.all([ touchFile(path.join(ROOT_DIR, '.flowconfig')), writePkgJson(path.join(ROOT_DIR, 'package.json'), { name: 'test', }), ]); const result = await installNpmLibDefs({ cwd: ROOT_DIR, flowVersion: parseFlowDirString('flow_v0.40.0'), explicitLibDefs: [], libdefDir: 'flow-typed', verbose: false, overwrite: false, skip: false, ignoreDeps: [], useCacheUntil: 1000 * 60, }); expect(result).toBe(0); expect(_mock(console.error).mock.calls).toEqual([ ["No dependencies were found in this project's package.json!"], ]); }); }); }); describe('installNpmLibDef', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'installNpmLibDef'); const FIXTURE_FAKE_CACHE_REPO_DIR = path.join( FIXTURE_ROOT, 'fakeCacheRepo', ); const origConsoleLog = console.log; beforeEach(() => { (console: any).log = jest.fn(); }); afterEach(() => { (console: any).log = origConsoleLog; }); it('installs scoped libdefs within a scoped directory', () => { return testProject(async ROOT_DIR => { const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache'); const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]); await Promise.all([ copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR), touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.40.0', }, }), ]); await gitInit(FAKE_CACHE_REPO_DIR), await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions'); await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST'); setCustomCacheDir(FAKE_CACHE_DIR); const availableLibDefs = await getNpmLibDefs( path.join(FAKE_CACHE_REPO_DIR, 'definitions'), ); await installNpmLibDef(availableLibDefs[0], FLOWTYPED_DIR, false); }); }); }); describe('end-to-end tests', () => { const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'end-to-end'); const FIXTURE_FAKE_CACHE_REPO_DIR = path.join( FIXTURE_ROOT, 'fakeCacheRepo', ); const origConsoleLog = console.log; const origConsoleError = console.error; beforeEach(() => { (console: any).log = jest.fn(); (console: any).error = jest.fn(); }); afterEach(() => { (console: any).log = origConsoleLog; (console: any).error = origConsoleError; }); async function fakeProjectEnv(runTest) { return await testProject(async ROOT_DIR => { const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache'); const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]); await copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR); await gitInit(FAKE_CACHE_REPO_DIR), await Promise.all([ gitConfig(FAKE_CACHE_REPO_DIR, 'user.name', 'Test Author'), gitConfig(FAKE_CACHE_REPO_DIR, 'user.email', 'test@flow-typed.org'), ]); await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions'); await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST'); setCustomCacheDir(FAKE_CACHE_DIR); const origCWD = process.cwd; (process: any).cwd = () => FLOWPROJ_DIR; try { await runTest(FLOWPROJ_DIR); } finally { (process: any).cwd = origCWD; clearCustomCacheDir(); } }); } it('installs available libdefs', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: [], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([true, true]); // Signs installed libdefs const fooLibDefContents = await fs.readFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), 'utf8', ); expect(fooLibDefContents).toContain('// flow-typed signature: '); expect(fooLibDefContents).toContain('// flow-typed version: '); }); }); it('installs available libdefs using PnP', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', installConfig: { pnp: true, }, devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { // Use local foo for initial install foo: 'file:./foo', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'foo')), ]); await writePkgJson(path.join(FLOWPROJ_DIR, 'foo/package.json'), { name: 'foo', version: '1.2.3', }); // Yarn install so PnP file resolves to local foo await child_process.execP('yarn install', {cwd: FLOWPROJ_DIR}); // Overwrite foo dep so it's like we installed from registry instead writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', installConfig: { pnp: true, }, devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: [], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([true, true]); // Signs installed libdefs const fooLibDefRawContents = await fs.readFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ); const fooLibDefContents = fooLibDefRawContents.toString(); expect(fooLibDefContents).toContain('// flow-typed signature: '); expect(fooLibDefContents).toContain('// flow-typed version: '); }); }); it('ignores libdefs in dev, bundled, optional or peer dependencies when flagged', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { foo: '1.2.3', }, peerDependencies: { 'flow-bin': '^0.43.0', }, optionalDependencies: { foo: '2.0.0', }, bundledDependencies: { bar: '^1.6.9', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'bar')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, ignoreDeps: ['dev', 'optional', 'bundled'], explicitLibDefs: [], }); // Installs libdefs expect( await Promise.all([ fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'flow-bin_v0.x.x.js', ), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'bar_v1.x.x.js'), ), ]), ).toEqual([true, true, false]); }); }); it('stubs unavailable libdefs', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { someUntypedDep: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); // Installs a stub for someUntypedDep expect( await fs.exists( path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'someUntypedDep_vx.x.x.js', ), ), ).toBe(true); }); }); it("doesn't stub unavailable libdefs when --skip is passed", () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { someUntypedDep: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: true, explicitLibDefs: [], }); // Installs a stub for someUntypedDep expect( await fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')), ).toBe(true); }); }); it('overwrites stubs when libdef becomes available (with --overwrite)', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); await fs.writeFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'), '', ); // Run the install command await run({ overwrite: true, verbose: false, skip: false, explicitLibDefs: [], }); // Replaces the stub with the real typedef expect( await Promise.all([ fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'), ), fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ]), ).toEqual([false, true]); }); }); it("doesn't overwrite tweaked libdefs (without --overwrite)", () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); const libdefFilePath = path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js', ); // Tweak the libdef for foo const libdefFileContent = (await fs.readFile(libdefFilePath, 'utf8')) + '\n// TWEAKED!'; await fs.writeFile(libdefFilePath, libdefFileContent); // Run install command again await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); // Verify that the tweaked libdef file wasn't overwritten expect(await fs.readFile(libdefFilePath, 'utf8')).toBe( libdefFileContent, ); }); }); it('overwrites tweaked libdefs when --overwrite is passed', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, explicitLibDefs: [], }); const libdefFilePath = path.join( FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js', ); // Tweak the libdef for foo const libdefFileContent = await fs.readFile(libdefFilePath, 'utf8'); await fs.writeFile(libdefFilePath, libdefFileContent + '\n// TWEAKED!'); // Run install command again await run({ overwrite: true, skip: false, verbose: false, explicitLibDefs: [], }); // Verify that the tweaked libdef file wasn't overwritten expect(await fs.readFile(libdefFilePath, 'utf8')).toBe( libdefFileContent, ); }); }); it('uses flow-bin defined in another package.json', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), writePkgJson(path.join(FLOWPROJ_DIR, '..', 'package.json'), { name: 'parent', devDependencies: { 'flow-bin': '^0.45.0', }, }), mkdirp(path.join(FLOWPROJ_DIR, '..', 'node_modules', 'flow-bin')), ]); // Run the install command await run({ overwrite: false, verbose: false, skip: false, packageDir: path.join(FLOWPROJ_DIR, '..'), explicitLibDefs: [], }); // Installs libdef expect( await fs.exists( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), ).toEqual(true); }); }); it('uses .flowconfig from specified root directory', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ mkdirp(path.join(FLOWPROJ_DIR, 'src')), writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { name: 'test', devDependencies: { 'flow-bin': '^0.43.0', }, dependencies: { foo: '1.2.3', }, }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), ]); await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); // Run the install command await run({ overwrite: false, verbose: false, skip: false, rootDir: path.join(FLOWPROJ_DIR, 'src'), explicitLibDefs: [], }); // Installs libdef expect( await fs.exists( path.join( FLOWPROJ_DIR, 'src', 'flow-typed', 'npm', 'foo_v1.x.x.js', ), ), ).toEqual(true); }); }); }); });
splodingsocks/FlowTyped
cli/src/commands/__tests__/install-test.js
JavaScript
mit
23,904
import React, { Component } from 'react' import PropTypes from 'prop-types' import { assign } from 'lodash' import autoBind from '../utils/autoBind' const styles = { 'ClosedPanelWrapper': { height: '40px' }, 'PanelWrapper': { position: 'relative' }, 'Over': { border: '1px dashed white', overflowY: 'hidden' }, 'PanelTitle': { width: '100%', height: '40px', lineHeight: '40px', backgroundColor: '#000', color: '#fff', paddingLeft: '10px', position: 'relative', whiteSpace: 'nowrap', overflowX: 'hidden', textOverflow: 'ellipsis', paddingRight: '8px', cursor: 'pointer', WebkitUserSelect: 'none', userSelect: 'none' }, 'Handle': { cursor: '-webkit-grab', position: 'absolute', zIndex: '2', color: 'white', right: '10px', fontSize: '16px', top: '12px' }, 'OpenPanel': { position: 'relative', zIndex: '2', top: '0', left: '0', padding: '7px', paddingTop: '5px', maxHeight: '30%', display: 'block' }, 'ClosedPanel': { height: '0', position: 'relative', zIndex: '2', top: '-1000px', left: '0', overflow: 'hidden', maxHeight: '0', display: 'none' } } class Panel extends Component { constructor() { super() this.state = { dragIndex: null, overIndex: null, isOver: false } autoBind(this, [ 'handleTitleClick', 'handleDragStart', 'handleDragOver', 'handleDragEnter', 'handleDragLeave', 'handleDrop', 'handleDragEnd' ]) } handleTitleClick() { const { index, isOpen, openPanel } = this.props openPanel(isOpen ? -1 : index) } handleDragStart(e) { // e.target.style.opacity = '0.4'; // this / e.target is the source node. e.dataTransfer.setData('index', e.target.dataset.index) } handleDragOver(e) { if (e.preventDefault) { e.preventDefault() // Necessary. Allows us to drop. } return false } handleDragEnter(e) { const overIndex = e.target.dataset.index if (e.dataTransfer.getData('index') !== overIndex) { // e.target.classList.add('Over') // e.target is the current hover target. this.setState({ isOver: true }) } } handleDragLeave() { this.setState({ isOver: false }) // e.target.classList.remove('Over') // e.target is previous target element. } handleDrop(e) { if (e.stopPropagation) { e.stopPropagation() // stops the browser from redirecting. } const dragIndex = e.dataTransfer.getData('index') const dropIndex = this.props.index.toString() if (dragIndex !== dropIndex) { this.props.reorder(dragIndex, dropIndex) } return false } handleDragEnd() { this.setState({ isOver: false, dragIndex: null, overIndex: null }) } render() { const { isOpen, orderable } = this.props const { isOver } = this.state return ( <div style={assign({}, styles.PanelWrapper, isOpen ? {} : styles.ClosedPanelWrapper, isOver ? styles.Over : {})} onDragStart={this.handleDragStart} onDragEnter={this.handleDragEnter} onDragOver={this.handleDragOver} onDragLeave={this.handleDragLeave} onDrop={this.handleDrop} onDragEnd={this.handleDragEnd} > <div style={styles.PanelTitle} onClick={this.handleTitleClick} draggable={orderable} data-index={this.props.index} > {this.props.header} {orderable && (<i className="fa fa-th" style={styles.Handle}></i>)} </div> { isOpen && ( <div style={isOpen ? styles.OpenPanel : styles.ClosedPanel}> {this.props.children} </div> ) } </div> ) } } Panel.propTypes = { children: PropTypes.any, index: PropTypes.any, openPanel: PropTypes.func, isOpen: PropTypes.any, header: PropTypes.any, orderable: PropTypes.any, reorder: PropTypes.func } Panel.defaultProps = { isOpen: false, header: '', orderable: false } export default Panel
jcgertig/react-struct-editor
src/components/Panel.js
JavaScript
mit
4,120
'use strict'; // src\services\message\hooks\timestamp.js // // Use this hook to manipulate incoming or outgoing data. // For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html const defaults = {}; module.exports = function(options) { options = Object.assign({}, defaults, options); return function(hook) { const usr = hook.params.user; const txt = hook.data.text; hook.data = { text: txt, createdBy: usr._id, createdAt: Date.now() } }; };
zorqie/bfests
src/services/message/hooks/timestamp.js
JavaScript
mit
488
const electron = window.require('electron'); const events = window.require('events'); const { ipcRenderer } = electron; const { EventEmitter } = events; class Emitter extends EventEmitter {} window.Events = new Emitter(); module.exports = () => { let settings = window.localStorage.getItem('settings'); if (settings === null) { const defaultSettings = { general: { launch: true, clipboard: true }, images: { copy: false, delete: true }, notifications: { enabled: true } }; window.localStorage.setItem('settings', JSON.stringify(defaultSettings)); settings = defaultSettings; } ipcRenderer.send('settings', JSON.parse(settings)); };
vevix/focus
app/js/init.js
JavaScript
mit
740
import React from 'react'; import { Link } from 'react-router'; import HotdotActions from '../actions/HotdotActions'; import HotdotObjStore from '../stores/HotdotObjStore'; import MyInfoNavbar from './MyInfoNavbar'; import Weixin from './Weixin'; class Hotdot extends React.Component { constructor(props) { super(props); this.state = HotdotObjStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HotdotActions.getHotdotDatas(); $(".month-search").hide(); $(".navbar-hotdot").on("touchend",function(){ var index = $(this).index(); if(index==0){ //本周 $(".month-search").hide(); $(".week-search").show(); }else{ //本月 $(".month-search").show(); $(".week-search").hide(); } }); HotdotObjStore.listen(this.onChange); Weixin.getUrl(); Weixin.weixinReady(); } componentWillUnmount() { HotdotObjStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } getUpOrDown(curData,preData,isWeek){ var preDataItem = isWeek ? preData.week:preData.month; if(preData==false || preData == [] || preDataItem==undefined){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ for(var i = 0;i < preDataItem.length;i++){ if(preDataItem[i].word == curData.word){ if(preDataItem[i].value < curData.value){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-down"></span> <span className="badge" style={{backgroundColor:"#4F81E3"}}>{curData.value}</span></span>); } } } } return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); } render() { var hotdotData = (this.state.data); var firstHotData = hotdotData[0]; var preHotData ; if(hotdotData.length > 7){ preHotData = hotdotData[7]; }else{ preHotData = []; } if(firstHotData){ var weekList = firstHotData.week.map((weekItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(weekItem,preHotData,true)} {weekItem.word} </li> )); if(weekList.length==0){ weekList = <div className = "noData">数据还没有准备好,要不去其他页面瞅瞅?</div> } var monthList = firstHotData.month.map((monthItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(monthItem,preHotData,false)} {monthItem.word} </li> )); if(monthList.length==0){ monthList = <div className = "noData">Whops,这个页面的数据没有准备好,去其他页面瞅瞅?</div> } }else{ var weekList = (<span>正在构建,敬请期待...</span>); var monthList = (<span>正在构建,敬请期待...</span>); } return (<div> <div className="content-container"> <div className="week-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本周关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week navbar-hotdot-active">本周</span> <span className="navbar-hotdot navbar-month">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {weekList} </ul> </div> </div> </div> <div className="month-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本月关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week">本周</span> <span className="navbar-hotdot navbar-month navbar-hotdot-active">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {monthList} </ul> </div> </div> </div> </div> </div>); } } export default Hotdot;
kongchun/BigData-Web
app/m_components/Hotdot.js
JavaScript
mit
5,621
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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. */ import 'babel-polyfill'; import ReactDOM from 'react-dom'; import React from 'react'; import FastClick from 'fastclick'; import Router from './routes'; import Location from './core/Location'; import { addEventListener, removeEventListener } from './core/DOMUtils'; import { ApolloClient, createNetworkInterface } from 'react-apollo'; function getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } const networkInterface = createNetworkInterface('/graphql', { credentials: 'same-origin', uri: '/graphql', headers: { Cookie: getCookie("id_token") } }); const client = new ApolloClient({ connectToDevTools: true, networkInterface: networkInterface, }); let cssContainer = document.getElementById('css'); const appContainer = document.getElementById('app'); const context = { insertCss: styles => styles._insertCss(), onSetTitle: value => (document.title = value), onSetMeta: (name, content) => { // Remove and create a new <meta /> tag in order to make it work // with bookmarks in Safari const elements = document.getElementsByTagName('meta'); Array.from(elements).forEach((element) => { if (element.getAttribute('name') === name) { element.parentNode.removeChild(element); } }); const meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); document .getElementsByTagName('head')[0] .appendChild(meta); }, client }; // Google Analytics tracking. Don't send 'pageview' event after the first // rendering, as it was already sent by the Html component. let trackPageview = () => (trackPageview = () => window.ga('send', 'pageview')); function render(state) { Router.dispatch(state, (newState, component) => { ReactDOM.render( component, appContainer, () => { // Restore the scroll position if it was saved into the state if (state.scrollY !== undefined) { window.scrollTo(state.scrollX, state.scrollY); } else { window.scrollTo(0, 0); } trackPageview(); // Remove the pre-rendered CSS because it's no longer used // after the React app is launched if (cssContainer) { cssContainer.parentNode.removeChild(cssContainer); cssContainer = null; } }); }); } function run() { let currentLocation = null; let currentState = null; // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); // Re-render the app when window.location changes const unlisten = Location.listen(location => { currentLocation = location; currentState = Object.assign({}, location.state, { path: location.pathname, query: location.query, state: location.state, context, }); render(currentState); }); // Save the page scroll position into the current location's state const supportPageOffset = window.pageXOffset !== undefined; const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat'); const setPageOffset = () => { currentLocation.state = currentLocation.state || Object.create(null); if (supportPageOffset) { currentLocation.state.scrollX = window.pageXOffset; currentLocation.state.scrollY = window.pageYOffset; } else { currentLocation.state.scrollX = isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; currentLocation.state.scrollY = isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; } }; addEventListener(window, 'scroll', setPageOffset); addEventListener(window, 'pagehide', () => { removeEventListener(window, 'scroll', setPageOffset); unlisten(); }); } // Run the application when both DOM is ready and page content is loaded if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) { run(); } else { document.addEventListener('DOMContentLoaded', run, false); }
reicheltp/Sonic
src/client.js
JavaScript
mit
4,372