code stringlengths 2 1.05M |
|---|
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
/*
Project: sql-ajax-web-doc-reader
Author: Christopher Anzalone
File: xmlHttpReqDB.js
*/
var x = new XMLHttpRequest;
var chapter = 0;
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200) {
var infoRet = JSON.parse(x.responseText);
document.getElementById('infoDoc').innerHTML =
infoRet.name + " <br /> by " + infoRet.author; // places text in info area, parsed
}
};
x.open('GET', '/"PATH TO YOUR PAGESERVER.PHP FILE-REMOVE QUOTES"?name=dracula&function=info&file=dracula', true); // prepare the request
x.send(); //send the request
//load chapter 0 when page loads
var chapZeroReq = new XMLHttpRequest;
chapZeroReq.onreadystatechange = function () {
if (chapZeroReq.readyState == 4 && chapZeroReq.status == 200) {
document.getElementById('contentArea').innerHTML = chapZeroReq.responseText;
}
};
chapZeroReq.open('GET', '/"PATH TO YOUR PAGESERVER.PHP FILE-REMOVE QUOTES"?name=dracula&function=getchapter&file=dracula&chapter=0', true);
chapZeroReq.send(null);
var asyncRequest = new XMLHttpRequest;
function getChapter(c) {
chapter = c;
asyncRequest.onreadystatechange = function () {
if (asyncRequest.readyState == 4 && asyncRequest.status == 200) {
document.getElementById('contentArea').innerHTML = asyncRequest.responseText;
}
};
asyncRequest.open('GET', '/"PATH TO YOUR PAGESERVER.PHP FILE-REMOVE QUOTES"?name=dracula&function=getchapter&file=dracula&chapter=' + chapter, true);
asyncRequest.send(null);
if (c == 0)
document.getElementById('prevButton').disabled = true;
else
document.getElementById('prevButton').disabled = false;
if (c == 27)
document.getElementById('nextButton').disabled = true;
else
document.getElementById('nextButton').disabled = false;
document.getElementById('chapDisplay').innerHTML = c;
} |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
import styled from 'styled-components';
import color from '~/css/base/colors.scss';
import { LogoutIcon } from './icons';
const {
func, shape, number, string
} = PropTypes;
const FlassUserAppBarView = styled.div`
overflow: auto;
vertical-align: center;
`;
const UserName = styled.span`
font-family: NotoSansCJKkr;
letter-spacing: 0.3571rem;
font-size: 1.38rem;;
font-weight: 500;
color: #5F7477;
color: ${color['slate-grey-two']};
`;
const LogoutBtn = styled.span`
position: relative;
width: 1.19rem;
height: 1.19rem;
margin-left: 1.2rem;
`;
const LogoutBtnIcon = styled.img`
width: 1.19rem;
height: 1.19rem;
cursor: pointer;
margin-bottom: 5px;
`;
const propTypes = {
user: shape({
id: number.isRequired,
userName: string.isRequired,
email: string.isRequired
}).isRequired,
onClickLogoutBtn: func.isRequired
};
const defaultProps = {};
class UserAppBar extends Component {
componentDidMount() { }
render() {
const { user } = this.props;
return (
<FlassUserAppBarView>
<UserName>{user.userName}</UserName>
<LogoutBtn>
<LogoutBtnIcon
src={LogoutIcon}
alt="logout button"
onClick={this.onClickLogoutBtn} />
</LogoutBtn>
</FlassUserAppBarView>
);
}
@autobind
onClickLogoutBtn() {
this.props.onClickLogoutBtn();
}
}
UserAppBar.propTypes = propTypes;
UserAppBar.defaultProps = defaultProps;
function mapStateToProps(state) {
return {
user: { ...state.flass.user }
};
}
function mapDispatchToProps(dispatch) {
return {};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserAppBar);
|
import '@storybook/react/addons';
import register from '../src/manager';
// data export url used by storybook to fetch component data
register({ dataUrl: 'https://assets.brand.ai/brand-ai/style/style-data.json?exportFormat=list' });
|
'use babel';
import Beckifier from '../lib/beckifier';
// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
describe('Beckifier', () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage('beckifier');
});
describe('when the beckifier:beckify event is triggered', () => {
it('hides and shows the modal panel', () => {
// Before the activation event the view is not on the DOM, and no panel
// has been created
expect(workspaceElement.querySelector('.beckifier')).not.toExist();
// This is an activation event, triggering it will cause the package to be
// activated.
atom.commands.dispatch(workspaceElement, 'beckifier:beckify');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
expect(workspaceElement.querySelector('.beckifier')).toExist();
let beckifierElement = workspaceElement.querySelector('.beckifier');
expect(beckifierElement).toExist();
let beckifierPanel = atom.workspace.panelForItem(beckifierElement);
expect(beckifierPanel.isVisible()).toBe(true);
atom.commands.dispatch(workspaceElement, 'beckifier:beckify');
expect(beckifierPanel.isVisible()).toBe(false);
});
});
it('hides and shows the view', () => {
// This test shows you an integration test testing at the view level.
// Attaching the workspaceElement to the DOM is required to allow the
// `toBeVisible()` matchers to work. Anything testing visibility or focus
// requires that the workspaceElement is on the DOM. Tests that attach the
// workspaceElement to the DOM are generally slower than those off DOM.
jasmine.attachToDOM(workspaceElement);
expect(workspaceElement.querySelector('.beckifier')).not.toExist();
// This is an activation event, triggering it causes the package to be
// activated.
atom.commands.dispatch(workspaceElement, 'beckifier:beckify');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
// Now we can test for view visibility
let beckifierElement = workspaceElement.querySelector('.beckifier');
expect(beckifierElement).toBeVisible();
atom.commands.dispatch(workspaceElement, 'beckifier:beckify');
expect(beckifierElement).not.toBeVisible();
});
});
});
});
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var util = require('util');
var inspect = function(obj) {
console.log("INSPECT: "+util.inspect(obj, { colors: true }));
};
var setupServer = function setupServer(appConf, log4js) {
var logger = log4js.getLogger('app');
var app = express();
app.set('env', (appConf.server.env || 'production'));
// inspect(process.env);
logger.info('Configuring server ');
logger.warn('SERVER IN MODE: ' + app.get('env'));
app.set('port', (appConf.server.port || process.env.PORT) || 8080);
express.db = new (require('./lib/datasource'))(appConf.db);
logger.info('Configuring view engine');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// app.use(favicon());
logger.info('Configuring logging engine');
if (app.get('env') === 'development') {
var devFormat = ':method :url - Status: :status Content-length: :content-length';
app.use(log4js.connectLogger(log4js.getLogger("http"), { format: devFormat, level: 'auto' }));
} else if (app.get('env') === 'test') {
var devFormat = ':method :url - Status: :status Content-length: :content-length';
//app.use(log4js.connectLogger(log4js.getLogger("http"), { format: devFormat, level: 'auto' }));
} else
app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));
var webroot = appConf.app.webroot || path.join(__dirname, 'public');
logger.info('Setting webroot to ' + webroot);
app.use(express.static(webroot));
logger.info('Setting application routes');
var index = require('./routes/index');
var api = require('./routes/api');
app.use('/', index);
app.use('/tests', api);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
return app;
};
//module.exports = setupServer(appConf, logger);
module.exports = setupServer; |
import { t } from '../../src/locale';
export default {
methods: {
t(...args) {
return t.apply(this, args);
}
}
};
|
var bitcoin = require('bitcoin');
var crypto = require('crypto');
var fs = require('fs');
var jsonfile = require('jsonfile')
var request = require('request')
var client = new bitcoin.Client({
host: 'localhost',
port: '8332',
user: 'fred',
pass: 'fred'
});
var address1 = "mkqCZE3X1Yab7pHkg3FnVNvaYSx8p8N3Zs"
var address = "mjH9KTBnNyzdLifkr6xch5FkXnGdbf27mq"
var signature1 = ""
var file = "./PDF-Contract-PromissoryNotePlaceholder.pdf"
var algo = "sha256";
var shasum = crypto.createHash(algo);
var s = fs.ReadStream(file);
var samplePayloadObject = {}
var jsonObject = {}
// jsonfile.readFile('payload.json', function(err, obj){
// //console.log(JSON.stringify(obj))
// obj.entries.map((document) => {
// var shasum1 = crypto.createHash(algo);
// //console.log(JSON.stringify(document.payload, null, 2))
// var hashedvalues
// for (var key in document.payload){
// if (key != "iss"){
// shasum1.update(Buffer.from(document.payload[key].toString()))
// }
// }
// request(document.payload.iss,function(error, response, body){
// if(!error && response.statusCode == 200){
// var buf = (Buffer.from(body.toString()))
// }
// })
// .on('error', function(err){
// console.log(err)
// })
// .on('data',function(response){
// shasum1.update(response)
// })
// .on('end',function(response){
// console.log("done")
// hashedvalues = shasum1.digest('hex')
// console.log(hashedvalues)
// //console.log(hashedvalues)
// //console.log("fuck",document)
// client.signMessage(address, hashedvalues, function(err,signature){
// //console.log(signature)
// //console.log(address1)
// document.signatures.push({"address":address, "signature": signature, "hashedPayload": hashedvalues})
// //console.log(JSON.stringify(document.signatures))
// //console.log(JSON.stringify(obj, null, 2))
// fs.writeFile("payload.json", JSON.stringify(obj, null, 2), function(err){
// if (err) return console.log(err);
//
// })
//
// })
// })
//
//
// })
// })
s.on('data', function(d){ shasum.update(d); jsonObject["rawdata"]+=d.toJSON('base64')});
s.on('end', function(){
var d = shasum.digest('hex');
console.log(d)
jsonObject["data"] = d;
jsonObject["algo"] = algo;
jsonObject["address"] = address1
client.signMessage(address1,d, function(err, signature){
if(err){
return console.error(err);
}
jsonObject["signature"] = signature
console.log(jsonObject)
signature1 = signature;
client.verifyMessage(address1, signature1, d, function(err, boolVal){
if (err){
return console.error(err);
}
console.log(address)
console.log(d)
console.log(signature1)
console.log(boolVal)
});
// console.log("signature "+signature)
})
})
|
import { argv } from 'yargs'
import config from '../config'
import webpackConfig from './webpack.config'
import _debug from 'debug'
const debug = _debug('app:karma')
debug('Create configuration.')
const karmaConfig = {
basePath: '../', // project root in relation to bin/karma.js
files: [
{
pattern: `./${config.dir_test}/test-bundler.js`,
watched: false,
served: true,
included: true
}
],
singleRun: !argv.watch,
frameworks: ['mocha'],
reporters: ['mocha'],
preprocessors: {
[`${config.dir_test}/test-bundler.js`]: ['webpack']
},
browsers: ['PhantomJS'],
webpack: {
devtool: 'cheap-module-source-map',
resolve: {
...webpackConfig.resolve,
alias: {
...webpackConfig.resolve.alias,
sinon: 'sinon/pkg/sinon.js'
}
},
plugins: webpackConfig.plugins,
module: {
noParse: [
/\/sinon\.js/
],
loaders: webpackConfig.module.loaders.concat([
{
test: /sinon(\\|\/)pkg(\\|\/)sinon\.js/,
loader: 'imports?define=>false,require=>false'
}
])
},
// Enzyme fix, see:
// https://github.com/airbnb/enzyme/issues/47
externals: {
...webpackConfig.externals,
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': 'window'
},
sassLoader: webpackConfig.sassLoader
},
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
reporters: config.coverage_reporters
}
}
if (config.coverage_enabled) {
karmaConfig.reporters.push('coverage')
karmaConfig.webpack.module.preLoaders = [{
test: /\.(js|jsx)$/,
include: new RegExp(config.dir_client),
loader: 'isparta',
exclude: /node_modules/
}]
}
// cannot use `export default` because of Karma.
module.exports = (cfg) => cfg.set(karmaConfig)
|
'use strict';
var logToConsole = require('./modules/test.js');
logToConsole('Hello world!'); |
"use strict"
var SimpleSelector = require("./SimpleSelector.js")
class SimpleSelector_Tag extends SimpleSelector
{
constructor(content)
{
super(content)
this.symbol = "<"
this.type = "Tag"
}
/**
* @inheritDoc
*/
toCSS()
{
return this.content
}
}
module.exports = SimpleSelector_Tag |
'use strict';
var init = require('../base/init');
var error = require('../base/error');
var expb = require('../express/express-base');
var userb = require('../user/user-base');
var usera = require('../user/user-auth');
expb.core.delete('/api/users/:id([0-9]+)', function (req, res, done) {
usera.checkUser(res, function (err, user) {
if (err) return done(err);
var id = parseInt(req.params.id) || 0;
usera.checkUpdatable(user, id, function (err) {
if (err) return done(err);
userb.users.updateOne({ _id: id }, { $set: { status: 'd' } }, function (err, cnt) {
if (err) return done(err);
if (!cnt) {
return done(error('USER_NOT_FOUND'));
}
userb.deleteCache(id);
usera.logout(req, res);
res.json({});
});
});
});
});
expb.core.get('/users/deactivate', function (req, res, done) {
usera.checkUser(res, function (err, user) {
if (err) return done(err);
res.render('user/user-deactivate');
});
});
|
const read_directory = require('read-directory')
const EventEmitter = require('events')
const chokidar = require('chokidar')
const yaml = require('js-yaml')
const utilities = require('./utilities.js')
const logging = require('homeautomation-js-lib/logging.js')
const _ = require('lodash')
const git = require('simple-git/promise')
const rimraf = require('rimraf')
var configs = []
var config_path = null
var git_url = null
module.exports = new EventEmitter()
const loadGIT = function() {
if (_.isNil(git_url)) {
return
}
rimraf.sync('rules')
config_path = 'rules'
git().silent(false)
.clone(git_url, 'rules')
.then(() => {
logging.info('Successfully cloned rules')
load_rule_config()
})
.catch((err) => console.error('Failed to clone rules: ', err))
}
module.exports.load_path = function(in_path) {
if (!_.isNil(in_path) && (
_.startsWith(in_path, 'https') ||
_.startsWith(in_path, 'http') ||
_.startsWith(in_path, 'git'))) {
git_url = in_path
loadGIT()
} else {
config_path = in_path
// Watch Path
const watcher = chokidar.watch(config_path, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
}).on('all', (event, path) => {
load_rule_config()
})
}
}
module.exports.reload = function() {
if (!_.isNil(git_url)) {
loadGIT()
} else {
load_rule_config()
}
}
module.exports.get_configs = function() {
return configs
}
module.exports.set_override_configs = function(overrideConfigs) {
configs = overrideConfigs
}
module.exports.ruleIterator = function(callback) {
if (_.isNil(configs)) {
return
}
configs.forEach(function(config_item) {
if (_.isNil(config_item)) {
return
}
Object.keys(config_item).forEach(function(key) {
try {
return callback(key, config_item[key])
} catch (error) {
logging.error('Failed callback for rule: ' + key + ' error: ' + error)
}
}, this)
}, this)
}
const print_rule_config = function() {
if (_.isNil(configs)) {
return
}
configs.forEach(function(config_item) {
if (_.isNil(config_item)) {
return
}
Object.keys(config_item).forEach(function(key) {
logging.debug(' Rule [' + key + ']')
}, this)
}, this)
}
const _load_rule_config = function() {
logging.info(' => Really updating rules')
read_directory(config_path, function(err, files) {
configs = []
logging.info('Loading rules at path: ' + config_path)
if (err) {
throw err
}
const fileNames = Object.keys(files)
fileNames.forEach(file => {
if (file.includes('._')) {
return
}
if (file.includes('.yml') || file.includes('.yaml')) {
logging.info(' - Loading: ' + file)
const doc = yaml.safeLoad(files[file])
const category_name = file.split('.')[0] + '_'
if (!_.isNil(doc)) {
var namespacedRules = {}
Object.keys(doc).forEach(rule_key => {
const namespaced_key = utilities.update_topic_for_expression(category_name + rule_key)
namespacedRules[namespaced_key] = doc[rule_key]
})
configs.push(namespacedRules)
}
} else {
logging.info(' - Skipping: ' + file)
}
})
logging.info('...done loading rules')
print_rule_config()
module.exports.emit('rules-loaded')
})
}
const secondsToDefer = 5
var delayedUpdate = null
const load_rule_config = function() {
logging.info('Updating rules (deferring for ' + secondsToDefer + ' seconds)')
if (!_.isNil(delayedUpdate)) {
clearTimeout(delayedUpdate)
delayedUpdate = null
}
delayedUpdate = _.delay(_load_rule_config, secondsToDefer * 1000)
} |
// 手机号码验证
jQuery.validator.addMethod("isTel", function (value, element) {
var tel = /^1[3|4|5|7|8]\d{9}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的手机号码");
//邮箱 表单验证规则
jQuery.validator.addMethod("isUICEmail", function (value, element) {
//var mail = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/;
//var mail = /^[a-z0-9._%-]+@uic.edu.hk$ | ^[a-z0-9._%-]+@mail.uic.edu.hk$/;
//var mail = /^[a-z0-9._%-]+@uic.edu.hk$ | ^[a-z][0-9]{9}@mail.uic.edu.hk$/;
//var mail = /^[a-z][0-9]{9}@mail.uic.edu.hk$|^[a-z0-9._%-]+@uic.edu.hk$/ ;
var mail = /^[a-z][0-9]{9}@mail.uic.edu.hk$/ ;
return this.optional(element) || (mail.test(value));
}, "请输入 UIC 学生邮箱"); |
'use strict';
const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const CI = process.env.CI === 'true';
const OPTIONS_ISTANBUL = {
dir: './shippable/codecoverage/',
reportOpts: {cobertura: {dir: './shippable/codecoverage/', file: 'api-test-unit-cobertura.xml'}},
reporters: CI ? ['cobertura'] : ['text']
};
gulp.task('coverage-before', () => gulp
.src(['src/api/**/*.js'])
.pipe(istanbul())
.pipe(istanbul.hookRequire())
);
gulp.task('coverage-after', () => gulp
.src(['src/api-test/**/*spec.js'], {read: false})
.pipe(istanbul.writeReports(OPTIONS_ISTANBUL))
);
|
version https://git-lfs.github.com/spec/v1
oid sha256:58daeac864a688375b09f988c851f2aa42ed7091a173a6e644b80fa7424d7b78
size 2187
|
import * as types from '../constants/ActionTypes';
export function setOrderPage(data) {
return {
type: types.SET_ORDERPAGE,
orderPage: data
};
}
export function exchangeOrderPage(bfIdx, afIdx) {
return (dispatch, getState) => {
// exchange order
const data = [...getState().orderPage];
data.splice(afIdx, 0, ...data.splice(bfIdx, 1));
dispatch(setOrderPage(data));
};
}
|
/* istanbul ignore next */
import dbf from '@mhkeller/dbf'
export default function (file, writeOptions) {
writeOptions = writeOptions || {}
function toBuffer (ab) {
var buffer = new Buffer(ab.byteLength)
var view = new Uint8Array(ab)
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i]
}
return buffer
}
var buf = dbf.structure(file)
return toBuffer(buf.buffer)
}
|
/**
* @flow
*/
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
StatusBar,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import SectionTitle from './sectiontitle';
import Section from './section';
import Separator from './separator';
import NavigationButtonRow from './navigationbuttonrow';
import AboutSettings from './about';
import UserGuide from './userguide';
type Props = {
navigator: any;
};
class Settings extends Component {
props: Props;
constructor(props: Props) {
super(props);
(this: any).close = this.close.bind(this);
}
render() {
return (
<View style={styles.container}>
<StatusBar barStyle='default' backgroundColor='#000' />
<SectionTitle text={'HELP'} />
<Section>
<NavigationButtonRow text={'User Guide'} component={UserGuide} navigator={this.props.navigator} />
<Separator />
<NavigationButtonRow text={'About'} component={AboutSettings} navigator={this.props.navigator} />
</Section>
</View>
);
}
close() {
this.props.navigator.close();
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#f8f8f8',
marginTop: 64,
}
});
module.exports = Settings;
|
import 'https://static.codepen.io/assets/embed/ei.js';
import { modules } from 'https://unpkg.com/wq';
import { renderers } from 'https://unpkg.com/@wq/markdown@next';
const React = modules.react;
const Code = renderers.code;
const COMMENT = `// wq.init(config).then(...);
/*
Note: when using wq locally, replace 'https://unpkg.com/wq' with:
- './wq.js' for wq.app without npm, or
- '@wq/app' for @wq/cra-template or @wq/rollup-plugin
When using @wq/app, third party imports should also be changed, e.g. from
const React = modules['react'];
to
import React from 'react';
The following code is only needed to initialize the demo environment.
*/
`;
const INIT = `
wq.use({
components: startPage ? {
Header() { return null },
Footer() { return null },
} : {},
ajax(url, data, method) {
if (method === "GET") {
return Promise.resolve([]);
} else {
throw new Error("Sync not supported in demo")
}
}
});
wq.init({
...config,
router: {base_url: window.location.pathname},
map: mapConfig,
}).then(() => wq.nav(startPage));
`;
const MAP_CONF = `
const mapConfig = {
bounds: [[-90, -90], [90, 90]],
maps: {
basemaps: [{
"name": "MapTiler Topo",
"type": "vector-tile",
// NOTE: You must supply your own key
"url": "https://api.maptiler.com/maps/topo/style.json?key=95ZPyiJrDMkmRUoEfSjt"
}]
}
};
`;
function wrapCode(code) {
const match = code.match(/\/\/ navigate to (.*)/),
startPage = match ? match[1].replace(/^\//, '') : '',
config = code.indexOf('config =') === -1 ? 'const config = {};\n' : '',
mapConfig =
code.indexOf('map') === -1 ? 'const mapConfig = {};\n' : MAP_CONF,
init = `${COMMENT}\const startPage = '${startPage}';\n${config}${mapConfig}${INIT}`;
return code
.replace(
"import wq from './wq.js';",
"import wq from 'https://unpkg.com/wq'; // See note below"
)
.replace(
"import { modules } from './wq.js';",
"import { modules } from 'https://unpkg.com/wq'; // See note below"
)
.replace('wq.init(config).then(...);', init);
}
export default function CodeDetect(props) {
const { language, value } = props;
if (
(language === 'javascript' || language === 'js') &&
value.indexOf("import wq from './wq.js';") !== -1 &&
value.indexOf('wq.init(config).then(...);') !== -1
) {
return React.createElement(CodePen, { code: value });
} else {
return React.createElement(Code, props);
}
}
function CodePen({ code }) {
React.useEffect(() => {
window.__CPEmbed();
}, [code]);
return React.createElement(
'div',
{
className: 'codepen',
'data-editable': true,
'data-prefill': JSON.stringify({
title: 'wq Framework demo',
stylesheets: code.match(/map/)
? [
'https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css',
'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.2.0/mapbox-gl-draw.css',
]
: [],
}),
'data-default-tab': 'js,result',
'data-height': code.match(/map/) ? 480 : 360,
},
React.createElement('pre', { 'data-lang': 'babel' }, wrapCode(code))
);
}
|
/**
* Created by Riven on 2016/12/15.
*/
var path = require('path');
var http = require('http');
var url = require('url');
var crypt = require('crypto');
var fs = require('fs-extra');
var ResourceServer = function(){
this._server = null;
};
module.exports = ResourceServer;
ResourceServer.prototype.getSpriteSkin = function(spriteId){
var targets = window.vm.runtime.targets;
for(var i=0;i<targets.length;i++){
var ele = targets[i];
if(ele.id==spriteId){
var skin = ele.sprite.costumes[0].skin;
return skin;
}
}
return "";
};
ResourceServer.prototype.copyToWorkspace = function (srcmd5,mediapath,workspacepath) {
var src = path.resolve(mediapath,'medialibraries/',srcmd5);
var dst = path.resolve(workspacepath,srcmd5);
fs.copySync(src, dst);
};
ResourceServer.prototype.startServer = function(workspacePath,mediapath){
this._server = http.createServer(function (req, res) {
var request = url.parse(req.url, true);
var action = request.pathname;
var resourcepath = workspacePath;
if(action.indexOf("medialibraries/")>-1){
resourcepath = mediapath;
}
if (action.indexOf(".png") > -1 ) {
var img = fs.readFileSync(resourcepath + action); // remove slash
res.writeHead(200, {'Content-Type': 'image/png'});
res.end(img, 'binary');
}else if(action.indexOf(".svg") > -1){
var img = fs.readFileSync(resourcepath + action); // remove slash
res.writeHead(200, {'Content-Type': 'image/svg+xml'});
res.end(img, 'binary');
} else if(action.indexOf(".json") > -1){
var json = fs.readFileSync(resourcepath + action); // remove slash
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(json, 'binary');
}else{
console.log("server: " + action);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World \n');
}
});
this._server.on("clientError", function (err, socket) {
console.log("client error " + err);
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
this._server.on('listening', function () {
console.log('resource server is running');
});
this._server.listen(9234);
};
|
import React from "react";
import styled, { keyframes } from "styled-components";
import style from "../../assets/global-style";
const dance = keyframes`
0%, 40%, 100%{
transform: scaleY (0.4);
transform-origin: center 100%;
}
20%{
transform: scaleY (1);
}
`;
const Loading = styled.div`
height: 10px;
width: 100%;
margin: auto;
text-align: center;
font-size: 10px;
> div {
display: inline-block;
background-color: ${style["theme-color"]};
height: 100%;
width: 1px;
margin-right: 2px;
animation: ${dance} 1s infinite;
}
> div:nth-child(2) {
animation-delay: -0.4s;
}
> div:nth-child(3) {
animation-delay: -0.6s;
}
> div:nth-child(4) {
animation-delay: -0.5s;
}
> div:nth-child(5) {
animation-delay: -0.2s;
}
`;
function LoadingV2() {
return (
<Loading>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<span> 拼命加载中...</span>
</Loading>
);
}
export default React.memo(LoadingV2);
|
'use strict';
angular.module('graphAlgViz.version.version-directive', [])
.directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}]);
|
module.exports = {
"key": "shelmet",
"moves": [
{
"learn_type": "tutor",
"name": "bug-bite"
},
{
"learn_type": "tutor",
"name": "gastro-acid"
},
{
"learn_type": "tutor",
"name": "signal-beam"
},
{
"learn_type": "tutor",
"name": "sleep-talk"
},
{
"learn_type": "tutor",
"name": "snore"
},
{
"learn_type": "level up",
"level": 16,
"name": "struggle-bug"
},
{
"learn_type": "level up",
"level": 56,
"name": "final-gambit"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "machine",
"name": "venoshock"
},
{
"learn_type": "egg move",
"name": "guard-split"
},
{
"learn_type": "machine",
"name": "energy-ball"
},
{
"learn_type": "level up",
"level": 44,
"name": "bug-buzz"
},
{
"learn_type": "level up",
"level": 52,
"name": "guard-swap"
},
{
"learn_type": "egg move",
"name": "feint"
},
{
"learn_type": "level up",
"level": 25,
"name": "yawn"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "machine",
"name": "rain-dance"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "egg move",
"name": "pursuit"
},
{
"learn_type": "egg move",
"name": "encore"
},
{
"learn_type": "egg move",
"name": "baton-pass"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "egg move",
"name": "endure"
},
{
"learn_type": "level up",
"level": 37,
"name": "giga-drain"
},
{
"learn_type": "egg move",
"name": "spikes"
},
{
"learn_type": "egg move",
"name": "mud-slap"
},
{
"learn_type": "machine",
"name": "sludge-bomb"
},
{
"learn_type": "level up",
"level": 28,
"name": "protect"
},
{
"learn_type": "level up",
"level": 13,
"name": "curse"
},
{
"learn_type": "egg move",
"name": "mind-reader"
},
{
"learn_type": "machine",
"name": "substitute"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "level up",
"level": 32,
"name": "acid-armor"
},
{
"learn_type": "level up",
"level": 1,
"name": "leech-life"
},
{
"learn_type": "level up",
"level": 8,
"name": "bide"
},
{
"learn_type": "level up",
"level": 49,
"name": "recover"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "level up",
"level": 20,
"name": "mega-drain"
},
{
"learn_type": "level up",
"level": 4,
"name": "acid"
},
{
"learn_type": "egg move",
"name": "double-edge"
},
{
"learn_type": "level up",
"level": 40,
"name": "body-slam"
}
]
}; |
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('save-button').addEventListener('click', function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id,{cmd: "save"});
});
});
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('restore-button').addEventListener('click', function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id,{cmd: "restore"});
});
});
});
|
import Ember from 'ember';
import { validator, buildValidations } from 'ember-cp-validations';
import ValidationErrorDisplay from 'ilios/mixins/validation-error-display';
import config from 'ilios/config/environment';
const { Mixin, RSVP } = Ember;
const { Promise } = RSVP;
const Validations = buildValidations({
title: [
validator('html-presence', true),
validator('length', {
min: 3,
max: 65000
}),
]
});
export default Mixin.create(ValidationErrorDisplay, Validations, {
didReceiveAttrs(){
this._super(...arguments);
this.set('title', this.get('objective').get('title'));
},
editorParams: config.froalaEditorDefaults,
tagName: 'tr',
classNameBindings: ['showRemoveConfirmation:confirm-removal'],
objective: null,
title: null,
isSaving: false,
showRemoveConfirmation: false,
actions: {
saveTitleChanges() {
this.send('addErrorDisplayFor', 'title');
const title = this.get('title');
const objective = this.get('objective');
return new Promise((resolve, reject) => {
this.validate().then(({validations}) => {
if (validations.get('isValid')) {
objective.set('title', title);
objective.save().then(()=> {
this.send('removeErrorDisplayFor', 'title');
resolve();
});
} else {
reject();
}
});
});
},
revertTitleChanges() {
const objective = this.get('objective');
this.set('title', objective.get('title'));
},
changeTitle(event, editor){
this.send('addErrorDisplayFor', 'title');
if(editor){
const contents = editor.html.get();
this.set('title', contents);
}
},
}
});
|
var express = require('express');
var router = express.Router();
var requirements = require('../../../lib/express_requirements');
router.get('/test', requirements.validate('route.simple_get'), function(req, res, next) {
return res.status(200).json({
success: true
});
});
router.get('/test/:id', requirements.validate('route.fancy_get'), function(req, res, next) {
return res.status(200).json({
success: true
});
});
module.exports = router; |
'use strict'
angular.module('app.ui', ['ui.router']);
angular.module('app.ui').config(function($stateProvider){
$stateProvider
.state('app.ui', {
abstract: true,
data: {
title: 'UI Elements'
}
})
.state('app.ui.general', {
url: '/ui/general',
data: {
title: 'General Elements'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/general-elements.html',
controller: 'GeneralElementsCtrl'
}
}
})
.state('app.ui.buttons', {
url: '/ui/buttons',
data: {
title: 'Buttons'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/buttons.html',
controller: 'GeneralElementsCtrl'
}
}
})
.state('app.ui.iconsFa', {
url: '/ui/icons-font-awesome',
data: {
title: 'Font Awesome'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/icons-fa.html'
}
}
})
.state('app.ui.iconsGlyph', {
url: '/ui/icons-glyph',
data: {
title: 'Glyph Icons'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/icons-glyph.html'
}
}
})
.state('app.ui.iconsFlags', {
url: '/ui/icons-flags',
data: {
title: 'Flags'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/icons-flags.html'
}
}
})
.state('app.ui.grid', {
url: '/ui/grid',
data: {
title: 'Grid'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/grid.html'
}
}
})
.state('app.ui.treeView', {
url: '/ui/tree-view',
data: {
title: 'Tree View'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/tree-view.html',
controller: 'TreeviewCtrl'
}
}
})
.state('app.ui.nestableLists', {
url: '/ui/nestable-lists',
data: {
title: 'Nestable Lists'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/nestable-lists.html'
}
},
resolve: {
srcipts: function(lazyScript){
return lazyScript.register([
'build/vendor.ui.js'
])
}
}
})
.state('app.ui.jqueryUi', {
url: '/ui/jquery-ui',
data: {
title: 'JQuery UI'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/jquery-ui.html',
controller: 'JquiCtrl'
}
},
resolve: {
srcipts: function(lazyScript){
return lazyScript.register([
'build/vendor.ui.js'
])
}
}
})
.state('app.ui.typography', {
url: '/ui/typography',
data: {
title: 'JQuery UI'
},
views: {
"content@app": {
templateUrl: 'app/ui/views/typography.html'
}
}
})
}); |
contract('Access', function(accounts){
it('should set an address as solved', function(done){
var access = Access.deployed();
access.authorize( accounts[0], {
from:accounts[0],
gas:2000000
}).then(function(result){
}).then(done).catch(done)
});
it('should return that the address is solved', function(done){
var access = Access.deployed();
access.isSolved(accounts[0], {
from:accounts[0],
gas:2000000
}).then(function(result){
assert( result === true);
}).then(done).catch(done);
})
}) |
/**
* Very simple in-browser unit-test library, with zero deps.
*
* Background turns green if all tests pass, otherwise red.
* View the JavaScript console to see failure reasons.
*
* Example:
*
* adder.js (code under test)
*
* function add(a, b) {
* return a + b;
* }
*
* adder-test.html (tests - just open a browser to see results)
*
* <script src="tinytest.js"></script>
* <script src="adder.js"></script>
* <script>
*
* tests({
*
* 'adds numbers': function() {
* eq(6, add(2, 4));
* eq(6.6, add(2.6, 4));
* },
*
* 'subtracts numbers': function() {
* eq(-2, add(2, -4));
* },
*
* });
* </script>
*
* That's it. Stop using over complicated frameworks that get in your way.
*
* -Joe Walnes
* MIT License. See https://github.com/joewalnes/jstinytest/
*/
//TODO: Get successess to be green.
//TODO: Make failures red.
//TODO: Show stack traces for failures.
//TODO: Only show stack traces if you click expand.
var TinyTest = {
run: function(tests) {
debugger;
var failures = 0;
for (var testName in tests) {
var testAction = tests[testName];
try {
testAction.apply(this);
console.log('Test:', testName, 'OK');
} catch (e) {
failures++;
console.error('Test:', testName, 'FAILED', e);
console.error(e.stack);
}
}
setTimeout(function() { // Give document a chance to complete
if (window.document && document.body) {
document.body.style.backgroundColor = (failures == 0 ? '#99ff99' : '#ff9999');
}
}, 0);
},
fail: function(msg) {
throw new Error('fail(): ' + msg);
},
assert: function(value, msg) {
if (!value) {
throw new Error('assert(): ' + msg);
}
},
assertEquals: function(expected, actual) {
if (expected != actual) {
throw new Error('assertEquals() "' + expected + '" != "' + actual + '"');
}
},
assertStrictEquals: function(expected, actual) {
if (expected !== actual) {
throw new Error('assertStrictEquals() "' + expected + '" !== "' + actual + '"');
}
},
};
var fail = TinyTest.fail.bind(TinyTest),
assert = TinyTest.assert.bind(TinyTest),
assertEquals = TinyTest.assertEquals.bind(TinyTest),
eq = TinyTest.assertEquals.bind(TinyTest), // alias for assertEquals
assertStrictEquals = TinyTest.assertStrictEquals.bind(TinyTest),
tests = TinyTest.run.bind(TinyTest);
|
/*
* module_template.js
* Template for browser feature modules
*
* Michael S. Mikowski - mike.mikowski@gmail.com
* Copyright (c) 2011-2012 Manning Publications Co.
*/
/*jslint browser : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars : false,
white : true
*/
/*global $, app */
app.geomap = (function () {
//---------------- BEGIN MODULE SCOPE VARIABLES --------------
var
configMap = {
url: 'https://api.tiles.mapbox.com/v4/markwstroud.c423c181/{z}/{x}/{y}.png',
center : [40.712, -74.007],
zoom : 14
},
settings = {
baseDataUrl: 'http://www.fodors.com/maps/geojson.cfm?entity_id=474684&dest=1128&class_id=',
'sites' : '20001',
'restaurants': '20002',
'hotels' : '20003',
'nightlife' : '20004',
'shopping' : '20005'
},
stateMap = { $container : null },
jqueryMap = {},
mapLayers = {},
icons = {},
geoMap,
restaurantsLyr,
sitesLyr,
hotelsLyr,
nightlifeLyr,
shoppingLyr,
setJqueryMap, configModule, initModule, togglePois;
//----------------- END MODULE SCOPE VARIABLES ---------------
//------------------- BEGIN UTILITY METHODS ------------------
// example : getTrimmedString
onEachFeature = function(feature, layer){
var popupHtml = '<h5>' + feature.properties.title + '</h5>' +
'<p>Price - ' + feature.properties.price + ' ' +
feature.properties.pricesymbol + '</p>' +
'<p>' + feature.properties.desc + '</p>' +
'<a href="' + feature.properties.url + '">Fodors Review</a>'
layer.bindPopup(popupHtml);
}
//-------------------- END UTILITY METHODS -------------------
//--------------------- BEGIN DOM METHODS --------------------
// Begin DOM method /setJqueryMap/
setJqueryMap = function () {
var $container = stateMap.$container;
jqueryMap = { $container : $container };
};
// End DOM method /setJqueryMap/
//---------------------- END DOM METHODS ---------------------
//------------------- BEGIN EVENT HANDLERS -------------------
// example: onClickButton = ...
//-------------------- END EVENT HANDLERS --------------------
//------------------- BEGIN PUBLIC METHODS -------------------
// Begin method add POI
// Purpose : add pois to the map from a geoJson url
// Arguments : url of the geojson data points
// Returns : layer name
togglePois = function ( objData ){
var dataUrl,
category = objData.category,
markerLyrGroup = mapLayers[category];
if(objData.on){
dataUrl = settings.baseDataUrl + settings[category];
$.ajax({
url:dataUrl,
crossDomain:true,
dataType:"json",
success : function(data){
markerLyrGroup.addLayer(
L.geoJson(data, {
pointToLayer : function(feature, latlng){
return L.marker(latlng, {icon: icons[category]});
},
onEachFeature: onEachFeature
})
);
},
error : function(xhr, status, err){
console.log(err);
}
});
}
else{
markerLyrGroup.clearLayers();
}
};
configModule = function ( input_map ) {
return true;
};
// End public method /configModule/
// Begin public method /initModule/
// Purpose : Initializes module
// Arguments :
// * $container the jquery element used by this feature
// Returns : true
// Throws : none
//
initModule = function ( $container ) {
stateMap.$container = $container;
setJqueryMap();
//add the layer groups each poi is a layer in leaflet
restaurantsLyr = L.layerGroup();
sitesLyr = L.layerGroup();
hotelsLyr = L.layerGroup();
nightlifeLyr = L.layerGroup();
shoppingLyr = L.layerGroup();
//set map layers object
mapLayers = {
"restaurants" : restaurantsLyr,
"sites" : sitesLyr,
"hotels" : hotelsLyr,
"nightlife" : nightlifeLyr,
"shopping" : shoppingLyr
}
//set icons object
icons = {
"hotels" : new app.icons.baseIcon({iconUrl:'img/pin-hotels.png'}),
"sites" : new app.icons.baseIcon({iconUrl:'img/pin-sites.png'}),
"shopping" : new app.icons.baseIcon({iconUrl:'img/pin-shopping.png'}),
"restaurants" : new app.icons.baseIcon({iconUrl:'img/pin-restaurants_cl.png'}),
"nightlife" : new app.icons.baseIcon({iconUrl:'img/pin-nightlife.png'})
};
geoMap = L.map(jqueryMap.$container.attr('id'), {
center : configMap.center,
zoom: configMap.zoom,
layers : [restaurantsLyr, sitesLyr, hotelsLyr, nightlifeLyr, shoppingLyr]
});
//add tms layer to map
L.tileLayer(configMap.url).addTo(geoMap);
//add category layers
return true;
};
// End public method /initModule/
// return public methods
return {
configModule : configModule,
initModule : initModule,
togglePois : togglePois
};
//------------------- END PUBLIC METHODS ---------------------
}()); |
import _ from 'underscore';
import Vue from 'vue';
import SidebarMediator from '~/sidebar/sidebar_mediator';
import SidebarStore from '~/sidebar/stores/sidebar_store';
import SidebarService from '~/sidebar/services/sidebar_service';
import Mock from './mock_data';
describe('Sidebar mediator', function() {
beforeEach(() => {
Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
this.mediator = new SidebarMediator(Mock.mediator);
});
afterEach(() => {
SidebarService.singleton = null;
SidebarStore.singleton = null;
SidebarMediator.singleton = null;
Vue.http.interceptors = _.without(Vue.http.interceptors, Mock.sidebarMockInterceptor);
});
it('assigns yourself ', () => {
this.mediator.assignYourself();
expect(this.mediator.store.currentUser).toEqual(Mock.mediator.currentUser);
expect(this.mediator.store.assignees[0]).toEqual(Mock.mediator.currentUser);
});
it('saves assignees', (done) => {
this.mediator.saveAssignees('issue[assignee_ids]')
.then((resp) => {
expect(resp.status).toEqual(200);
done();
})
.catch(done.fail);
});
it('fetches the data', (done) => {
const mockData = Mock.responseMap.GET['/gitlab-org/gitlab-shell/issues/5.json?serializer=sidebar'];
spyOn(this.mediator, 'processFetchedData').and.callThrough();
this.mediator.fetch()
.then(() => {
expect(this.mediator.processFetchedData).toHaveBeenCalledWith(mockData);
})
.then(done)
.catch(done.fail);
});
it('processes fetched data', () => {
const mockData = Mock.responseMap.GET['/gitlab-org/gitlab-shell/issues/5.json?serializer=sidebar'];
this.mediator.processFetchedData(mockData);
expect(this.mediator.store.assignees).toEqual(mockData.assignees);
expect(this.mediator.store.humanTimeEstimate).toEqual(mockData.human_time_estimate);
expect(this.mediator.store.humanTotalTimeSpent).toEqual(mockData.human_total_time_spent);
expect(this.mediator.store.participants).toEqual(mockData.participants);
expect(this.mediator.store.subscribed).toEqual(mockData.subscribed);
expect(this.mediator.store.timeEstimate).toEqual(mockData.time_estimate);
expect(this.mediator.store.totalTimeSpent).toEqual(mockData.total_time_spent);
});
it('sets moveToProjectId', () => {
const projectId = 7;
spyOn(this.mediator.store, 'setMoveToProjectId').and.callThrough();
this.mediator.setMoveToProjectId(projectId);
expect(this.mediator.store.setMoveToProjectId).toHaveBeenCalledWith(projectId);
});
it('fetches autocomplete projects', (done) => {
const searchTerm = 'foo';
spyOn(this.mediator.service, 'getProjectsAutocomplete').and.callThrough();
spyOn(this.mediator.store, 'setAutocompleteProjects').and.callThrough();
this.mediator.fetchAutocompleteProjects(searchTerm)
.then(() => {
expect(this.mediator.service.getProjectsAutocomplete).toHaveBeenCalledWith(searchTerm);
expect(this.mediator.store.setAutocompleteProjects).toHaveBeenCalled();
})
.then(done)
.catch(done.fail);
});
it('moves issue', (done) => {
const moveToProjectId = 7;
this.mediator.store.setMoveToProjectId(moveToProjectId);
spyOn(this.mediator.service, 'moveIssue').and.callThrough();
const visitUrl = spyOnDependency(SidebarMediator, 'visitUrl');
this.mediator.moveIssue()
.then(() => {
expect(this.mediator.service.moveIssue).toHaveBeenCalledWith(moveToProjectId);
expect(visitUrl).toHaveBeenCalledWith('/root/some-project/issues/5');
})
.then(done)
.catch(done.fail);
});
it('toggle subscription', (done) => {
this.mediator.store.setSubscribedState(false);
spyOn(this.mediator.service, 'toggleSubscription').and.callThrough();
this.mediator.toggleSubscription()
.then(() => {
expect(this.mediator.service.toggleSubscription).toHaveBeenCalled();
expect(this.mediator.store.subscribed).toEqual(true);
})
.then(done)
.catch(done.fail);
});
});
|
export default Ember.Route.extend(
Ember.SimpleAuth.AuthenticatedRouteMixin, {
model: function() {
return this.store.createRecord('job');
},
actions: {
save: function(model) {
var _this = this;
model.save().then(function() {
_this.transitionTo('jobs.show', model);
}, function(response) {
_this.set('errors', response.errors);
});
},
cancel: function() {
this.transitionTo('jobs.index');
},
willTransition: function() {
var model = this.get('controller.model');
if (model.get('isNew')) {
model.deleteRecord();
}
}
}
});
|
<script type="text/html" class="pluginConfigForm" id="state">
<ul class="list-group">
<form class="form-horizontal" role="form">
<form role="form">
<li class="list-group-item">
<h3>State</h3>
</li>
<li class="list-group-item">
<div class="controls">
<input class="form-control" type="text" id="state" style="display:none;">
<label class="control-label" for="stateSelect">Select state</label>
<select id="stateSelect"class="form-control">
<option value="pre">PRE</option>
<option value="ready">READY</option>
<option value="post">POST</option>
</select>
</div>
</li>
</form>
</ul>
</script>
|
import {EMPTY, Subject, animationFrameScheduler, debounceTime, distinctUntilChanged, fromEvent, interval, map, mapTo, scan, switchMap, takeWhile, withLatestFrom} from 'rxjs'
import {compose} from 'compose'
import {v4 as uuid} from 'uuid'
import Keybinding from 'widget/keybinding'
import PropTypes from 'prop-types'
import React, {Component} from 'react'
import _ from 'lodash'
import flexy from './flexy.module.css'
import styles from './scrollable.module.css'
import withSubscriptions from 'subscription'
const ScrollableContainerContext = React.createContext()
export class ScrollableContainer extends React.Component {
ref = React.createRef()
state = {
height: 0
}
render() {
const {className, children} = this.props
const {height} = this.state
return (
<div ref={this.ref} className={[flexy.container, className].join(' ')}>
<ScrollableContainerContext.Provider value={{height}}>
{children}
</ScrollableContainerContext.Provider>
</div>
)
}
updateHeight(height) {
this.setState(prevState => prevState.height !== height ? {height} : null)
}
componentDidUpdate() {
this.updateHeight(this.ref.current.clientHeight)
}
}
ScrollableContainer.propTypes = {
children: PropTypes.any.isRequired,
className: PropTypes.string
}
export const Unscrollable = ({className, children}) => {
return (
<div className={[flexy.rigid, styles.unscrollable, className].join(' ')}>
{children}
</div>
)
}
Unscrollable.propTypes = {
children: PropTypes.any,
className: PropTypes.string
}
const ScrollableContext = React.createContext()
const ANIMATION_SPEED = .2
const PIXEL_PER_LINE = 45
const lerp = rate =>
(value, targetValue) => value + (targetValue - value) * rate
class _Scrollable extends Component {
ref = React.createRef()
verticalScroll$ = new Subject()
horizontalScroll$ = new Subject()
state = {
key: null
}
render() {
return (
<ScrollableContainerContext.Consumer>
{({height}) => this.renderScrollable(height)}
</ScrollableContainerContext.Consumer>
)
}
renderScrollable(containerHeight) {
const {className, direction, children} = this.props
const {key} = this.state
const scrollable = {
containerHeight,
getOffset: (direction = 'y') => this.getOffset(direction),
getContainerHeight: this.getContainerHeight.bind(this),
getClientHeight: this.getClientHeight.bind(this),
getScrollableHeight: this.getScrollableHeight.bind(this),
setOffset: this.setOffset.bind(this),
scrollTo: this.scrollTo.bind(this),
scrollToTop: this.scrollToTop.bind(this),
scrollToBottom: this.scrollToBottom.bind(this),
scrollPage: this.scrollPage.bind(this),
scrollLine: this.scrollLine.bind(this),
reset: this.reset.bind(this),
centerElement: this.centerElement.bind(this),
getElement: this.getScrollableElement.bind(this)
}
const keymap = {
ArrowUp: () => scrollable.scrollLine(-1),
ArrowDown: () => scrollable.scrollLine(1),
'Shift+ ': () => scrollable.scrollPage(-1),
' ': () => scrollable.scrollPage(1)
}
return (
<div
key={key}
ref={this.ref}
className={[flexy.elastic, styles.scrollable, styles[direction], className].join(' ')}>
<ScrollableContext.Provider value={scrollable}>
<Keybinding keymap={keymap}>
{_.isFunction(children) ? children(scrollable) : children}
</Keybinding>
</ScrollableContext.Provider>
</div>
)
}
getScrollableElement() {
return this.ref.current
}
setOffset(offset, direction = 'y') {
if (direction === 'y') {
this.getScrollableElement().scrollTop = offset
} else {
this.getScrollableElement().scrollLeft = offset
}
}
getOffset(direction) {
if (direction === 'y') {
return this.getScrollableElement().scrollTop
} else {
return this.getScrollableElement().scrollLeft
}
}
getContainerHeight() {
return this.getScrollableElement().offsetHeight
}
getClientHeight() {
return this.getScrollableElement().clientHeight
}
getClientWidth() {
return this.getScrollableElement().clientWidth
}
getScrollableHeight() {
return this.getScrollableElement().scrollHeight
}
getScrollableWidth() {
return this.getScrollableElement().scrollWidth
}
scrollTo(offset, direction = 'y') {
if (direction === 'y') {
this.verticalScroll$.next(offset)
} else {
this.horizontalScroll$.next(offset)
}
}
scrollToTop() {
this.scrollTo(0)
}
scrollToBottom() {
this.scrollTo(this.getScrollableHeight() - this.getClientHeight())
}
scrollPage(pages) {
this.scrollTo(this.getScrollableElement().scrollTop + pages * this.getClientHeight())
}
scrollLine(lines) {
this.scrollTo(this.getScrollableElement().scrollTop + lines * PIXEL_PER_LINE)
}
centerElement(element) {
if (element) {
this.scrollTo(element.offsetTop - (this.getClientHeight() - element.clientHeight) / 2)
}
}
reset(callback) {
const verticalOffset = this.getOffset('y')
const horizontalOffset = this.getOffset('x')
this.setState({key: uuid()},
() => {
this.setOffset(verticalOffset, 'y')
this.setOffset(horizontalOffset, 'x')
callback()
}
)
}
handleHover() {
const {onHover, addSubscription} = this.props
if (onHover) {
const mouseCoords$ = fromEvent(document, 'mousemove').pipe(
map(e => ([e.clientX, e.clientY]))
)
const debouncedScroll$ = fromEvent(this.ref.current, 'scroll').pipe(
debounceTime(50)
)
const highlight$ = debouncedScroll$.pipe(
withLatestFrom(mouseCoords$),
map(([, [x, y]]) => document.elementFromPoint(x, y)),
distinctUntilChanged()
)
addSubscription(
highlight$.subscribe(
element => onHover(element)
)
)
}
}
handleScroll() {
const {addSubscription} = this.props
const animationFrame$ = interval(0, animationFrameScheduler)
const scroll$ = (scroll$, direction) => scroll$.pipe(
map(targetOffset => Math.round(targetOffset)),
switchMap(targetOffset =>
Math.round(this.getOffset(direction)) === targetOffset
? EMPTY
: animationFrame$.pipe(
mapTo(targetOffset),
scan(lerp(ANIMATION_SPEED), this.getOffset(direction)),
map(offset => Math.round(offset)),
distinctUntilChanged(),
takeWhile(offset => offset !== targetOffset)
)
)
)
addSubscription(
scroll$(this.verticalScroll$, 'y').subscribe(
offset => this.setOffset(offset, 'y')
),
scroll$(this.horizontalScroll$, 'x').subscribe(
offset => this.setOffset(offset, 'x')
),
)
}
componentDidMount() {
this.handleHover()
this.handleScroll()
}
}
export const Scrollable = compose(
_Scrollable,
withSubscriptions()
)
Scrollable.defaultProps = {
direction: 'y'
}
Scrollable.propTypes = {
children: PropTypes.any,
className: PropTypes.string,
direction: PropTypes.oneOf(['x', 'y', 'xy']),
onScroll: PropTypes.func
}
export const withScrollable = () =>
WrappedComponent =>
class HigherOrderComponent extends React.Component {
render() {
return (
<ScrollableContext.Consumer>
{scrollable =>
<WrappedComponent {...this.props} scrollable={scrollable}/>
}
</ScrollableContext.Consumer>
)
}
}
|
/*!
* QUnit 1.20.0
* http://qunitjs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-10-27T17:53Z
*/
(function( global ) {
var QUnit = {};
var Date = global.Date;
var now = Date.now || function() {
return new Date().getTime();
};
var setTimeout = global.setTimeout;
var clearTimeout = global.clearTimeout;
// Store a local window from the global to allow direct references.
var window = global.window;
var defined = {
document: window && window.document !== undefined,
setTimeout: setTimeout !== undefined,
sessionStorage: (function() {
var x = "qunit-test-string";
try {
sessionStorage.setItem( x, x );
sessionStorage.removeItem( x );
return true;
} catch ( e ) {
return false;
}
}() )
};
var fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" );
var globalStartCalled = false;
var runStarted = false;
var toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var i, j,
result = a.slice();
for ( i = 0; i < result.length; i++ ) {
for ( j = 0; j < b.length; j++ ) {
if ( result[ i ] === b[ j ] ) {
result.splice( i, 1 );
i--;
break;
}
}
}
return result;
}
// from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
/**
* Makes a clone of an object using only Array or Object as base,
* and copies over the own enumerable properties.
*
* @param {Object} obj
* @return {Object} New object with only the own properties (recursively).
*/
function objectValues ( obj ) {
var key, val,
vals = QUnit.is( "array", obj ) ? [] : {};
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
val = obj[ key ];
vals[ key ] = val === Object( val ) ? objectValues( val ) : val;
}
}
return vals;
}
function extend( a, b, undefOnly ) {
for ( var prop in b ) {
if ( hasOwn.call( b, prop ) ) {
// Avoid "Member not found" error in IE8 caused by messing with window.constructor
// This block runs on every environment, so `global` is being used instead of `window`
// to avoid errors on node.
if ( prop !== "constructor" || a !== global ) {
if ( b[ prop ] === undefined ) {
delete a[ prop ];
} else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
a[ prop ] = b[ prop ];
}
}
}
}
return a;
}
function objectType( obj ) {
if ( typeof obj === "undefined" ) {
return "undefined";
}
// Consider: typeof null === object
if ( obj === null ) {
return "null";
}
var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ),
type = match && match[ 1 ];
switch ( type ) {
case "Number":
if ( isNaN( obj ) ) {
return "nan";
}
return "number";
case "String":
case "Boolean":
case "Array":
case "Set":
case "Map":
case "Date":
case "RegExp":
case "Function":
case "Symbol":
return type.toLowerCase();
}
if ( typeof obj === "object" ) {
return "object";
}
}
// Safe object type checking
function is( type, obj ) {
return QUnit.objectType( obj ) === type;
}
var getUrlParams = function() {
var i, current;
var urlParams = {};
var location = window.location;
var params = location.search.slice( 1 ).split( "&" );
var length = params.length;
if ( params[ 0 ] ) {
for ( i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
if ( urlParams[ current[ 0 ] ] ) {
urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
} else {
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
}
return urlParams;
};
// Doesn't support IE6 to IE9, it will return undefined on these browsers
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
function extractStacktrace( e, offset ) {
offset = offset === undefined ? 4 : offset;
var stack, include, i;
if ( e.stack ) {
stack = e.stack.split( "\n" );
if ( /^error$/i.test( stack[ 0 ] ) ) {
stack.shift();
}
if ( fileName ) {
include = [];
for ( i = offset; i < stack.length; i++ ) {
if ( stack[ i ].indexOf( fileName ) !== -1 ) {
break;
}
include.push( stack[ i ] );
}
if ( include.length ) {
return include.join( "\n" );
}
}
return stack[ offset ];
// Support: Safari <=6 only
} else if ( e.sourceURL ) {
// exclude useless self-reference for generated Error objects
if ( /qunit.js$/.test( e.sourceURL ) ) {
return;
}
// for actual exceptions, this is useful
return e.sourceURL + ":" + e.line;
}
}
function sourceFromStacktrace( offset ) {
var error = new Error();
// Support: Safari <=7 only, IE <=10 - 11 only
// Not all browsers generate the `stack` property for `new Error()`, see also #636
if ( !error.stack ) {
try {
throw error;
} catch ( err ) {
error = err;
}
}
return extractStacktrace( error, offset );
}
/**
* Config object: Maintain internal state
* Later exposed as QUnit.config
* `config` initialized at top of scope
*/
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
// HTML Reporter: collapse every test except the first failing test
// If false, all failing tests will be expanded
collapse: true,
// by default, scroll to top of the page when suite is done
scrolltop: true,
// depth up-to which object will be dumped
maxDepth: 5,
// when enabled, all tests must call expect()
requireExpects: false,
// add checkboxes that are persisted in the query-string
// when enabled, the id is set to `true` as a `QUnit.config` property
urlConfig: [
{
id: "hidepassed",
label: "Hide passed tests",
tooltip: "Only show tests and assertions that fail. Stored as query-strings."
},
{
id: "noglobals",
label: "Check for Globals",
tooltip: "Enabling this will test if any test introduces new properties on the " +
"global object (`window` in Browsers). Stored as query-strings."
},
{
id: "notrycatch",
label: "No try-catch",
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " +
"exceptions in IE reasonable. Stored as query-strings."
}
],
// Set of all modules.
modules: [],
// Stack of nested modules
moduleStack: [],
// The first unnamed module
currentModule: {
name: "",
tests: []
},
callbacks: {}
};
var urlParams = defined.document ? getUrlParams() : {};
// Push a loose unnamed module to the modules collection
config.modules.push( config.currentModule );
if ( urlParams.filter === true ) {
delete urlParams.filter;
}
// String search anywhere in moduleName+testName
config.filter = urlParams.filter;
config.testId = [];
if ( urlParams.testId ) {
// Ensure that urlParams.testId is an array
urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," );
for (var i = 0; i < urlParams.testId.length; i++ ) {
config.testId.push( urlParams.testId[ i ] );
}
}
var loggingCallbacks = {};
// Register logging callbacks
function registerLoggingCallbacks( obj ) {
var i, l, key,
callbackNames = [ "begin", "done", "log", "testStart", "testDone",
"moduleStart", "moduleDone" ];
function registerLoggingCallback( key ) {
var loggingCallback = function( callback ) {
if ( objectType( callback ) !== "function" ) {
throw new Error(
"QUnit logging methods require a callback function as their first parameters."
);
}
config.callbacks[ key ].push( callback );
};
// DEPRECATED: This will be removed on QUnit 2.0.0+
// Stores the registered functions allowing restoring
// at verifyLoggingCallbacks() if modified
loggingCallbacks[ key ] = loggingCallback;
return loggingCallback;
}
for ( i = 0, l = callbackNames.length; i < l; i++ ) {
key = callbackNames[ i ];
// Initialize key collection of logging callback
if ( objectType( config.callbacks[ key ] ) === "undefined" ) {
config.callbacks[ key ] = [];
}
obj[ key ] = registerLoggingCallback( key );
}
}
function runLoggingCallbacks( key, args ) {
var i, l, callbacks;
callbacks = config.callbacks[ key ];
for ( i = 0, l = callbacks.length; i < l; i++ ) {
callbacks[ i ]( args );
}
}
// DEPRECATED: This will be removed on 2.0.0+
// This function verifies if the loggingCallbacks were modified by the user
// If so, it will restore it, assign the given callback and print a console warning
function verifyLoggingCallbacks() {
var loggingCallback, userCallback;
for ( loggingCallback in loggingCallbacks ) {
if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
userCallback = QUnit[ loggingCallback ];
// Restore the callback function
QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
// Assign the deprecated given callback
QUnit[ loggingCallback ]( userCallback );
if ( global.console && global.console.warn ) {
global.console.warn(
"QUnit." + loggingCallback + " was replaced with a new value.\n" +
"Please, check out the documentation on how to apply logging callbacks.\n" +
"Reference: http://api.qunitjs.com/category/callbacks/"
);
}
}
}
}
( function() {
if ( !defined.document ) {
return;
}
// `onErrorFnPrev` initialized at top of scope
// Preserve other handlers
var onErrorFnPrev = window.onerror;
// Cover uncaught exceptions
// Returning true will suppress the default browser handler,
// returning false will let it run.
window.onerror = function( error, filePath, linerNr ) {
var ret = false;
if ( onErrorFnPrev ) {
ret = onErrorFnPrev( error, filePath, linerNr );
}
// Treat return value as window.onerror itself does,
// Only do our handling if not suppressed.
if ( ret !== true ) {
if ( QUnit.config.current ) {
if ( QUnit.config.current.ignoreGlobalErrors ) {
return true;
}
QUnit.pushFailure( error, filePath + ":" + linerNr );
} else {
QUnit.test( "global failure", extend(function() {
QUnit.pushFailure( error, filePath + ":" + linerNr );
}, { validTest: true } ) );
}
return false;
}
return ret;
};
} )();
QUnit.urlParams = urlParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !( defined.document && window.location.protocol !== "file:" );
// Expose the current QUnit version
QUnit.version = "1.20.0";
extend( QUnit, {
// call on start of module test to prepend name to all tests
module: function( name, testEnvironment, executeNow ) {
var module, moduleFns;
var currentModule = config.currentModule;
if ( arguments.length === 2 ) {
if ( testEnvironment instanceof Function ) {
executeNow = testEnvironment;
testEnvironment = undefined;
}
}
// DEPRECATED: handles setup/teardown functions,
// beforeEach and afterEach should be used instead
if ( testEnvironment && testEnvironment.setup ) {
testEnvironment.beforeEach = testEnvironment.setup;
delete testEnvironment.setup;
}
if ( testEnvironment && testEnvironment.teardown ) {
testEnvironment.afterEach = testEnvironment.teardown;
delete testEnvironment.teardown;
}
module = createModule();
moduleFns = {
beforeEach: setHook( module, "beforeEach" ),
afterEach: setHook( module, "afterEach" )
};
if ( executeNow instanceof Function ) {
config.moduleStack.push( module );
setCurrentModule( module );
executeNow.call( module.testEnvironment, moduleFns );
config.moduleStack.pop();
module = module.parentModule || currentModule;
}
setCurrentModule( module );
function createModule() {
var parentModule = config.moduleStack.length ?
config.moduleStack.slice( -1 )[ 0 ] : null;
var moduleName = parentModule !== null ?
[ parentModule.name, name ].join( " > " ) : name;
var module = {
name: moduleName,
parentModule: parentModule,
tests: []
};
var env = {};
if ( parentModule ) {
extend( env, parentModule.testEnvironment );
delete env.beforeEach;
delete env.afterEach;
}
extend( env, testEnvironment );
module.testEnvironment = env;
config.modules.push( module );
return module;
}
function setCurrentModule( module ) {
config.currentModule = module;
}
},
// DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
asyncTest: asyncTest,
test: test,
skip: skip,
only: only,
// DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
// In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
start: function( count ) {
var globalStartAlreadyCalled = globalStartCalled;
if ( !config.current ) {
globalStartCalled = true;
if ( runStarted ) {
throw new Error( "Called start() outside of a test context while already started" );
} else if ( globalStartAlreadyCalled || count > 1 ) {
throw new Error( "Called start() outside of a test context too many times" );
} else if ( config.autostart ) {
throw new Error( "Called start() outside of a test context when " +
"QUnit.config.autostart was true" );
} else if ( !config.pageLoaded ) {
// The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it
config.autostart = true;
return;
}
} else {
// If a test is running, adjust its semaphore
config.current.semaphore -= count || 1;
// If semaphore is non-numeric, throw error
if ( isNaN( config.current.semaphore ) ) {
config.current.semaphore = 0;
QUnit.pushFailure(
"Called start() with a non-numeric decrement.",
sourceFromStacktrace( 2 )
);
return;
}
// Don't start until equal number of stop-calls
if ( config.current.semaphore > 0 ) {
return;
}
// throw an Error if start is called more often than stop
if ( config.current.semaphore < 0 ) {
config.current.semaphore = 0;
QUnit.pushFailure(
"Called start() while already started (test's semaphore was 0 already)",
sourceFromStacktrace( 2 )
);
return;
}
}
resumeProcessing();
},
// DEPRECATED: QUnit.stop() will be removed in QUnit 2.0.
stop: function( count ) {
// If there isn't a test running, don't allow QUnit.stop() to be called
if ( !config.current ) {
throw new Error( "Called stop() outside of a test context" );
}
// If a test is running, adjust its semaphore
config.current.semaphore += count || 1;
pauseProcessing();
},
config: config,
is: is,
objectType: objectType,
extend: extend,
load: function() {
config.pageLoaded = true;
// Initialize the configuration options
extend( config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: 0,
updateRate: 1000,
autostart: true,
filter: ""
}, true );
config.blocking = false;
if ( config.autostart ) {
resumeProcessing();
}
},
stack: function( offset ) {
offset = ( offset || 0 ) + 2;
return sourceFromStacktrace( offset );
}
});
registerLoggingCallbacks( QUnit );
function begin() {
var i, l,
modulesLog = [];
// If the test run hasn't officially begun yet
if ( !config.started ) {
// Record the time of the test run's beginning
config.started = now();
verifyLoggingCallbacks();
// Delete the loose unnamed module if unused.
if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) {
config.modules.shift();
}
// Avoid unnecessary information by not logging modules' test environments
for ( i = 0, l = config.modules.length; i < l; i++ ) {
modulesLog.push({
name: config.modules[ i ].name,
tests: config.modules[ i ].tests
});
}
// The test run is officially beginning now
runLoggingCallbacks( "begin", {
totalTests: Test.count,
modules: modulesLog
});
}
config.blocking = false;
process( true );
}
function process( last ) {
function next() {
process( last );
}
var start = now();
config.depth = ( config.depth || 0 ) + 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 ||
( ( now() - start ) < config.updateRate ) ) {
if ( config.current ) {
// Reset async tracking for each phase of the Test lifecycle
config.current.usedAsync = false;
}
config.queue.shift()();
} else {
setTimeout( next, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function pauseProcessing() {
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout( config.timeout );
config.timeout = setTimeout(function() {
if ( config.current ) {
config.current.semaphore = 0;
QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) );
} else {
throw new Error( "Test timed out" );
}
resumeProcessing();
}, config.testTimeout );
}
}
function resumeProcessing() {
runStarted = true;
// A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
if ( defined.setTimeout ) {
setTimeout(function() {
if ( config.current && config.current.semaphore > 0 ) {
return;
}
if ( config.timeout ) {
clearTimeout( config.timeout );
}
begin();
}, 13 );
} else {
begin();
}
}
function done() {
var runtime, passed;
config.autorun = true;
// Log the last module results
if ( config.previousModule ) {
runLoggingCallbacks( "moduleDone", {
name: config.previousModule.name,
tests: config.previousModule.tests,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all,
runtime: now() - config.moduleStats.started
});
}
delete config.previousModule;
runtime = now() - config.started;
passed = config.stats.all - config.stats.bad;
runLoggingCallbacks( "done", {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
});
}
function setHook( module, hookName ) {
if ( module.testEnvironment === undefined ) {
module.testEnvironment = {};
}
return function( callback ) {
module.testEnvironment[ hookName ] = callback;
};
}
var focused = false;
function Test( settings ) {
var i, l;
++Test.count;
extend( this, settings );
this.assertions = [];
this.semaphore = 0;
this.usedAsync = false;
this.module = config.currentModule;
this.stack = sourceFromStacktrace( 3 );
// Register unique strings
for ( i = 0, l = this.module.tests; i < l.length; i++ ) {
if ( this.module.tests[ i ].name === this.testName ) {
this.testName += " ";
}
}
this.testId = generateHash( this.module.name, this.testName );
this.module.tests.push({
name: this.testName,
testId: this.testId
});
if ( settings.skip ) {
// Skipped tests will fully ignore any sent callback
this.callback = function() {};
this.async = false;
this.expected = 0;
} else {
this.assert = new Assert( this );
}
}
Test.count = 0;
Test.prototype = {
before: function() {
if (
// Emit moduleStart when we're switching from one module to another
this.module !== config.previousModule ||
// They could be equal (both undefined) but if the previousModule property doesn't
// yet exist it means this is the first test in a suite that isn't wrapped in a
// module, in which case we'll just emit a moduleStart event for 'undefined'.
// Without this, reporters can get testStart before moduleStart which is a problem.
!hasOwn.call( config, "previousModule" )
) {
if ( hasOwn.call( config, "previousModule" ) ) {
runLoggingCallbacks( "moduleDone", {
name: config.previousModule.name,
tests: config.previousModule.tests,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all,
runtime: now() - config.moduleStats.started
});
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0, started: now() };
runLoggingCallbacks( "moduleStart", {
name: this.module.name,
tests: this.module.tests
});
}
config.current = this;
if ( this.module.testEnvironment ) {
delete this.module.testEnvironment.beforeEach;
delete this.module.testEnvironment.afterEach;
}
this.testEnvironment = extend( {}, this.module.testEnvironment );
this.started = now();
runLoggingCallbacks( "testStart", {
name: this.testName,
module: this.module.name,
testId: this.testId
});
if ( !config.pollution ) {
saveGlobal();
}
},
run: function() {
var promise;
config.current = this;
if ( this.async ) {
QUnit.stop();
}
this.callbackStarted = now();
if ( config.notrycatch ) {
runTest( this );
return;
}
try {
runTest( this );
} catch ( e ) {
this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " +
this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
function runTest( test ) {
promise = test.callback.call( test.testEnvironment, test.assert );
test.resolvePromise( promise );
}
},
after: function() {
checkPollution();
},
queueHook: function( hook, hookName ) {
var promise,
test = this;
return function runHook() {
config.current = test;
if ( config.notrycatch ) {
callHook();
return;
}
try {
callHook();
} catch ( error ) {
test.pushFailure( hookName + " failed on " + test.testName + ": " +
( error.message || error ), extractStacktrace( error, 0 ) );
}
function callHook() {
promise = hook.call( test.testEnvironment, test.assert );
test.resolvePromise( promise, hookName );
}
};
},
// Currently only used for module level hooks, can be used to add global level ones
hooks: function( handler ) {
var hooks = [];
function processHooks( test, module ) {
if ( module.parentModule ) {
processHooks( test, module.parentModule );
}
if ( module.testEnvironment &&
QUnit.objectType( module.testEnvironment[ handler ] ) === "function" ) {
hooks.push( test.queueHook( module.testEnvironment[ handler ], handler ) );
}
}
// Hooks are ignored on skipped tests
if ( !this.skip ) {
processHooks( this, this.module );
}
return hooks;
},
finish: function() {
config.current = this;
if ( config.requireExpects && this.expected === null ) {
this.pushFailure( "Expected number of assertions to be defined, but expect() was " +
"not called.", this.stack );
} else if ( this.expected !== null && this.expected !== this.assertions.length ) {
this.pushFailure( "Expected " + this.expected + " assertions, but " +
this.assertions.length + " were run", this.stack );
} else if ( this.expected === null && !this.assertions.length ) {
this.pushFailure( "Expected at least one assertion, but none were run - call " +
"expect(0) to accept zero assertions.", this.stack );
}
var i,
bad = 0;
this.runtime = now() - this.started;
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
for ( i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[ i ].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
runLoggingCallbacks( "testDone", {
name: this.testName,
module: this.module.name,
skipped: !!this.skip,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length,
runtime: this.runtime,
// HTML Reporter use
assertions: this.assertions,
testId: this.testId,
// Source of Test
source: this.stack,
// DEPRECATED: this property will be removed in 2.0.0, use runtime instead
duration: this.runtime
});
// QUnit.reset() is deprecated and will be replaced for a new
// fixture reset function on QUnit 2.0/2.1.
// It's still called here for backwards compatibility handling
QUnit.reset();
config.current = undefined;
},
queue: function() {
var priority,
test = this;
if ( !this.valid() ) {
return;
}
function run() {
// each of these can by async
synchronize([
function() {
test.before();
},
test.hooks( "beforeEach" ),
function() {
test.run();
},
test.hooks( "afterEach" ).reverse(),
function() {
test.after();
},
function() {
test.finish();
}
]);
}
// Prioritize previously failed tests, detected from sessionStorage
priority = QUnit.config.reorder && defined.sessionStorage &&
+sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName );
return synchronize( run, priority );
},
push: function( result, actual, expected, message, negative ) {
var source,
details = {
module: this.module.name,
name: this.testName,
result: result,
message: message,
actual: actual,
expected: expected,
testId: this.testId,
negative: negative || false,
runtime: now() - this.started
};
if ( !result ) {
source = sourceFromStacktrace();
if ( source ) {
details.source = source;
}
}
runLoggingCallbacks( "log", details );
this.assertions.push({
result: !!result,
message: message
});
},
pushFailure: function( message, source, actual ) {
if ( !( this instanceof Test ) ) {
throw new Error( "pushFailure() assertion outside test context, was " +
sourceFromStacktrace( 2 ) );
}
var details = {
module: this.module.name,
name: this.testName,
result: false,
message: message || "error",
actual: actual || null,
testId: this.testId,
runtime: now() - this.started
};
if ( source ) {
details.source = source;
}
runLoggingCallbacks( "log", details );
this.assertions.push({
result: false,
message: message
});
},
resolvePromise: function( promise, phase ) {
var then, message,
test = this;
if ( promise != null ) {
then = promise.then;
if ( QUnit.objectType( then ) === "function" ) {
QUnit.stop();
then.call(
promise,
function() { QUnit.start(); },
function( error ) {
message = "Promise rejected " +
( !phase ? "during" : phase.replace( /Each$/, "" ) ) +
" " + test.testName + ": " + ( error.message || error );
test.pushFailure( message, extractStacktrace( error, 0 ) );
// else next test will carry the responsibility
saveGlobal();
// Unblock
QUnit.start();
}
);
}
}
},
valid: function() {
var include,
filter = config.filter && config.filter.toLowerCase(),
module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
function testInModuleChain( testModule ) {
var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
if ( testModuleName === module ) {
return true;
} else if ( testModule.parentModule ) {
return testInModuleChain( testModule.parentModule );
} else {
return false;
}
}
// Internally-generated tests are always valid
if ( this.callback && this.callback.validTest ) {
return true;
}
if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) {
return false;
}
if ( module && !testInModuleChain( this.module ) ) {
return false;
}
if ( !filter ) {
return true;
}
include = filter.charAt( 0 ) !== "!";
if ( !include ) {
filter = filter.slice( 1 );
}
// If the filter matches, we need to honour include
if ( fullName.indexOf( filter ) !== -1 ) {
return include;
}
// Otherwise, do the opposite
return !include;
}
};
// Resets the test setup. Useful for tests that modify the DOM.
/*
DEPRECATED: Use multiple tests instead of resetting inside a test.
Use testStart or testDone for custom cleanup.
This method will throw an error in 2.0, and will be removed in 2.1
*/
QUnit.reset = function() {
// Return on non-browser environments
// This is necessary to not break on node tests
if ( !defined.document ) {
return;
}
var fixture = defined.document && document.getElementById &&
document.getElementById( "qunit-fixture" );
if ( fixture ) {
fixture.innerHTML = config.fixture;
}
};
QUnit.pushFailure = function() {
if ( !QUnit.config.current ) {
throw new Error( "pushFailure() assertion outside test context, in " +
sourceFromStacktrace( 2 ) );
}
// Gets current test obj
var currentTest = QUnit.config.current;
return currentTest.pushFailure.apply( currentTest, arguments );
};
// Based on Java's String.hashCode, a simple but not
// rigorously collision resistant hashing function
function generateHash( module, testName ) {
var hex,
i = 0,
hash = 0,
str = module + "\x1C" + testName,
len = str.length;
for ( ; i < len; i++ ) {
hash = ( ( hash << 5 ) - hash ) + str.charCodeAt( i );
hash |= 0;
}
// Convert the possibly negative integer hash code into an 8 character hex string, which isn't
// strictly necessary but increases user understanding that the id is a SHA-like hash
hex = ( 0x100000000 + hash ).toString( 16 );
if ( hex.length < 8 ) {
hex = "0000000" + hex;
}
return hex.slice( -8 );
}
function synchronize( callback, priority ) {
var last = !priority;
if ( QUnit.objectType( callback ) === "array" ) {
while ( callback.length ) {
synchronize( callback.shift() );
}
return;
}
if ( priority ) {
priorityFill( callback );
} else {
config.queue.push( callback );
}
if ( config.autorun && !config.blocking ) {
process( last );
}
}
// Place previously failed tests on a queue priority line, respecting the order they get assigned.
function priorityFill( callback ) {
var queue, prioritizedQueue;
queue = config.queue.slice( priorityFill.pos );
prioritizedQueue = config.queue.slice( 0, -config.queue.length + priorityFill.pos );
queue.unshift( callback );
queue.unshift.apply( queue, prioritizedQueue );
config.queue = queue;
priorityFill.pos += 1;
}
priorityFill.pos = 0;
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in global ) {
if ( hasOwn.call( global, key ) ) {
// in Opera sometimes DOM element ids show up here, ignore them
if ( /^qunit-test-output/.test( key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
}
function checkPollution() {
var newGlobals,
deletedGlobals,
old = config.pollution;
saveGlobal();
newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
}
deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
}
}
// Will be exposed as QUnit.asyncTest
function asyncTest( testName, expected, callback ) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test( testName, expected, callback, true );
}
// Will be exposed as QUnit.test
function test( testName, expected, callback, async ) {
if ( focused ) { return; }
var newTest;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
newTest = new Test({
testName: testName,
expected: expected,
async: async,
callback: callback
});
newTest.queue();
}
// Will be exposed as QUnit.skip
function skip( testName ) {
if ( focused ) { return; }
var test = new Test({
testName: testName,
skip: true
});
test.queue();
}
// Will be exposed as QUnit.only
function only( testName, expected, callback, async ) {
var newTest;
if ( focused ) { return; }
QUnit.config.queue.length = 0;
focused = true;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
newTest = new Test({
testName: testName,
expected: expected,
async: async,
callback: callback
});
newTest.queue();
}
function Assert( testContext ) {
this.test = testContext;
}
// Assert helpers
QUnit.assert = Assert.prototype = {
// Specify the number of expected assertions to guarantee that failed test
// (no assertions are run at all) don't slip through.
expect: function( asserts ) {
if ( arguments.length === 1 ) {
this.test.expected = asserts;
} else {
return this.test.expected;
}
},
// Increment this Test's semaphore counter, then return a function that
// decrements that counter a maximum of once.
async: function( count ) {
var test = this.test,
popped = false,
acceptCallCount = count;
if ( typeof acceptCallCount === "undefined" ) {
acceptCallCount = 1;
}
test.semaphore += 1;
test.usedAsync = true;
pauseProcessing();
return function done() {
if ( popped ) {
test.pushFailure( "Too many calls to the `assert.async` callback",
sourceFromStacktrace( 2 ) );
return;
}
acceptCallCount -= 1;
if ( acceptCallCount > 0 ) {
return;
}
test.semaphore -= 1;
popped = true;
resumeProcessing();
};
},
// Exports test.push() to the user API
push: function( /* result, actual, expected, message, negative */ ) {
var assert = this,
currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current;
// Backwards compatibility fix.
// Allows the direct use of global exported assertions and QUnit.assert.*
// Although, it's use is not recommended as it can leak assertions
// to other tests from async tests, because we only get a reference to the current test,
// not exactly the test where assertion were intended to be called.
if ( !currentTest ) {
throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) );
}
if ( currentTest.usedAsync === true && currentTest.semaphore === 0 ) {
currentTest.pushFailure( "Assertion after the final `assert.async` was resolved",
sourceFromStacktrace( 2 ) );
// Allow this assertion to continue running anyway...
}
if ( !( assert instanceof Assert ) ) {
assert = currentTest.assert;
}
return assert.test.push.apply( assert.test, arguments );
},
ok: function( result, message ) {
message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
QUnit.dump.parse( result ) );
this.push( !!result, result, true, message );
},
notOk: function( result, message ) {
message = message || ( !result ? "okay" : "failed, expected argument to be falsy, was: " +
QUnit.dump.parse( result ) );
this.push( !result, result, false, message, true );
},
equal: function( actual, expected, message ) {
/*jshint eqeqeq:false */
this.push( expected == actual, actual, expected, message );
},
notEqual: function( actual, expected, message ) {
/*jshint eqeqeq:false */
this.push( expected != actual, actual, expected, message, true );
},
propEqual: function( actual, expected, message ) {
actual = objectValues( actual );
expected = objectValues( expected );
this.push( QUnit.equiv( actual, expected ), actual, expected, message );
},
notPropEqual: function( actual, expected, message ) {
actual = objectValues( actual );
expected = objectValues( expected );
this.push( !QUnit.equiv( actual, expected ), actual, expected, message, true );
},
deepEqual: function( actual, expected, message ) {
this.push( QUnit.equiv( actual, expected ), actual, expected, message );
},
notDeepEqual: function( actual, expected, message ) {
this.push( !QUnit.equiv( actual, expected ), actual, expected, message, true );
},
strictEqual: function( actual, expected, message ) {
this.push( expected === actual, actual, expected, message );
},
notStrictEqual: function( actual, expected, message ) {
this.push( expected !== actual, actual, expected, message, true );
},
"throws": function( block, expected, message ) {
var actual, expectedType,
expectedOutput = expected,
ok = false,
currentTest = ( this instanceof Assert && this.test ) || QUnit.config.current;
// 'expected' is optional unless doing string comparison
if ( message == null && typeof expected === "string" ) {
message = expected;
expected = null;
}
currentTest.ignoreGlobalErrors = true;
try {
block.call( currentTest.testEnvironment );
} catch (e) {
actual = e;
}
currentTest.ignoreGlobalErrors = false;
if ( actual ) {
expectedType = QUnit.objectType( expected );
// we don't want to validate thrown error
if ( !expected ) {
ok = true;
expectedOutput = null;
// expected is a regexp
} else if ( expectedType === "regexp" ) {
ok = expected.test( errorString( actual ) );
// expected is a string
} else if ( expectedType === "string" ) {
ok = expected === errorString( actual );
// expected is a constructor, maybe an Error constructor
} else if ( expectedType === "function" && actual instanceof expected ) {
ok = true;
// expected is an Error object
} else if ( expectedType === "object" ) {
ok = actual instanceof expected.constructor &&
actual.name === expected.name &&
actual.message === expected.message;
// expected is a validation function which returns true if validation passed
} else if ( expectedType === "function" && expected.call( {}, actual ) === true ) {
expectedOutput = null;
ok = true;
}
}
currentTest.assert.push( ok, actual, expectedOutput, message );
}
};
// Provide an alternative to assert.throws(), for environments that consider throws a reserved word
// Known to us are: Closure Compiler, Narwhal
(function() {
/*jshint sub:true */
Assert.prototype.raises = Assert.prototype[ "throws" ];
}());
function errorString( error ) {
var name, message,
resultErrorString = error.toString();
if ( resultErrorString.substring( 0, 7 ) === "[object" ) {
name = error.name ? error.name.toString() : "Error";
message = error.message ? error.message.toString() : "";
if ( name && message ) {
return name + ": " + message;
} else if ( name ) {
return name;
} else if ( message ) {
return message;
} else {
return "Error";
}
} else {
return resultErrorString;
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = (function() {
// Stack to decide between skip/abort functions
var callers = [];
// Stack to avoiding loops from circular referencing
var parents = [];
var parentsB = [];
function useStrictEquality( b, a ) {
/*jshint eqeqeq:false */
if ( b instanceof a.constructor || a instanceof b.constructor ) {
// To catch short annotation VS 'new' annotation of a declaration. e.g.:
// `var i = 1;`
// `var j = new Number(1);`
return a == b;
} else {
return a === b;
}
}
function compareConstructors( a, b ) {
var getProto = Object.getPrototypeOf || function( obj ) {
/*jshint proto: true */
return obj.__proto__;
};
var protoA = getProto( a );
var protoB = getProto( b );
// Comparing constructors is more strict than using `instanceof`
if ( a.constructor === b.constructor ) {
return true;
}
// Ref #851
// If the obj prototype descends from a null constructor, treat it
// as a null prototype.
if ( protoA && protoA.constructor === null ) {
protoA = null;
}
if ( protoB && protoB.constructor === null ) {
protoB = null;
}
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if ( ( protoA === null && protoB === Object.prototype ) ||
( protoB === null && protoA === Object.prototype ) ) {
return true;
}
return false;
}
var callbacks = {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"symbol": useStrictEquality,
"nan": function( b ) {
return isNaN( b );
},
"date": function( b, a ) {
return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function( b, a ) {
return QUnit.objectType( b ) === "regexp" &&
// The regex itself
a.source === b.source &&
// And its modifiers
a.global === b.global &&
// (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline &&
a.sticky === b.sticky;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function() {
var caller = callers[ callers.length - 1 ];
return caller !== Object && typeof caller !== "undefined";
},
"array": function( b, a ) {
var i, j, len, loop, aCircular, bCircular;
// b could be an object literal here
if ( QUnit.objectType( b ) !== "array" ) {
return false;
}
len = a.length;
if ( len !== b.length ) {
// safe and faster
return false;
}
// Track reference to avoid circular references
parents.push( a );
parentsB.push( b );
for ( i = 0; i < len; i++ ) {
loop = false;
for ( j = 0; j < parents.length; j++ ) {
aCircular = parents[ j ] === a[ i ];
bCircular = parentsB[ j ] === b[ i ];
if ( aCircular || bCircular ) {
if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
loop = true;
} else {
parents.pop();
parentsB.pop();
return false;
}
}
}
if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
parents.pop();
parentsB.pop();
return false;
}
}
parents.pop();
parentsB.pop();
return true;
},
"set": function( b, a ) {
var aArray, bArray;
// `b` could be any object here
if ( QUnit.objectType( b ) !== "set" ) {
return false;
}
aArray = [];
a.forEach( function( v ) {
aArray.push( v );
});
bArray = [];
b.forEach( function( v ) {
bArray.push( v );
});
return innerEquiv( bArray, aArray );
},
"map": function( b, a ) {
var aArray, bArray;
// `b` could be any object here
if ( QUnit.objectType( b ) !== "map" ) {
return false;
}
aArray = [];
a.forEach( function( v, k ) {
aArray.push( [ k, v ] );
});
bArray = [];
b.forEach( function( v, k ) {
bArray.push( [ k, v ] );
});
return innerEquiv( bArray, aArray );
},
"object": function( b, a ) {
var i, j, loop, aCircular, bCircular;
// Default to true
var eq = true;
var aProperties = [];
var bProperties = [];
if ( compareConstructors( a, b ) === false ) {
return false;
}
// Stack constructor before traversing properties
callers.push( a.constructor );
// Track reference to avoid circular references
parents.push( a );
parentsB.push( b );
// Be strict: don't ensure hasOwnProperty and go deep
for ( i in a ) {
loop = false;
for ( j = 0; j < parents.length; j++ ) {
aCircular = parents[ j ] === a[ i ];
bCircular = parentsB[ j ] === b[ i ];
if ( aCircular || bCircular ) {
if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
loop = true;
} else {
eq = false;
break;
}
}
}
aProperties.push( i );
if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
eq = false;
break;
}
}
parents.pop();
parentsB.pop();
// Unstack, we are done
callers.pop();
for ( i in b ) {
// Collect b's properties
bProperties.push( i );
}
// Ensures identical properties name
return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
}
};
function typeEquiv( a, b ) {
var prop = QUnit.objectType( a );
return callbacks[ prop ]( b, a );
}
// The real equiv function
function innerEquiv() {
var args = [].slice.apply( arguments );
if ( args.length < 2 ) {
// End transition
return true;
}
return ( (function( a, b ) {
if ( a === b ) {
// Catch the most you can
return true;
} else if ( a === null || b === null || typeof a === "undefined" ||
typeof b === "undefined" ||
QUnit.objectType( a ) !== QUnit.objectType( b ) ) {
// Don't lose time with error prone cases
return false;
} else {
return typeEquiv( a, b );
}
// Apply transition with (1..n) arguments
}( args[ 0 ], args[ 1 ] ) ) &&
innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) );
}
return innerEquiv;
}());
// Based on jsDump by Ariel Flesler
// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
QUnit.dump = (function() {
function quote( str ) {
return "\"" + str.toString().replace( /\\/g, "\\\\" ).replace( /"/g, "\\\"" ) + "\"";
}
function literal( o ) {
return o + "";
}
function join( pre, arr, post ) {
var s = dump.separator(),
base = dump.indent(),
inner = dump.indent( 1 );
if ( arr.join ) {
arr = arr.join( "," + s + inner );
}
if ( !arr ) {
return pre + post;
}
return [ pre, inner + arr, base + post ].join( s );
}
function array( arr, stack ) {
var i = arr.length,
ret = new Array( i );
if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
return "[object Array]";
}
this.up();
while ( i-- ) {
ret[ i ] = this.parse( arr[ i ], undefined, stack );
}
this.down();
return join( "[", ret, "]" );
}
var reName = /^function (\w+)/,
dump = {
// objType is used mostly internally, you can fix a (custom) type in advance
parse: function( obj, objType, stack ) {
stack = stack || [];
var res, parser, parserType,
inStack = inArray( obj, stack );
if ( inStack !== -1 ) {
return "recursion(" + ( inStack - stack.length ) + ")";
}
objType = objType || this.typeOf( obj );
parser = this.parsers[ objType ];
parserType = typeof parser;
if ( parserType === "function" ) {
stack.push( obj );
res = parser.call( this, obj, stack );
stack.pop();
return res;
}
return ( parserType === "string" ) ? parser : this.parsers.fatal_error;
},
typeOf: function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if ( typeof obj === "undefined" ) {
type = "undefined";
} else if ( QUnit.is( "regexp", obj ) ) {
type = "regexp";
} else if ( QUnit.is( "date", obj ) ) {
type = "date";
} else if ( QUnit.is( "function", obj ) ) {
type = "function";
} else if ( obj.setInterval !== undefined &&
obj.document !== undefined &&
obj.nodeType === undefined ) {
type = "window";
} else if ( obj.nodeType === 9 ) {
type = "document";
} else if ( obj.nodeType ) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && obj.item !== undefined &&
( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null &&
obj[ 0 ] === undefined ) ) )
) {
type = "array";
} else if ( obj.constructor === Error.prototype.constructor ) {
type = "error";
} else {
type = typeof obj;
}
return type;
},
separator: function() {
return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " ";
},
// extra can be a number, shortcut for increasing-calling-decreasing
indent: function( extra ) {
if ( !this.multiline ) {
return "";
}
var chr = this.indentChar;
if ( this.HTML ) {
chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
}
return new Array( this.depth + ( extra || 0 ) ).join( chr );
},
up: function( a ) {
this.depth += a || 1;
},
down: function( a ) {
this.depth -= a || 1;
},
setParser: function( name, parser ) {
this.parsers[ name ] = parser;
},
// The next 3 are exposed so you can use them
quote: quote,
literal: literal,
join: join,
//
depth: 1,
maxDepth: QUnit.config.maxDepth,
// This is the list of parsers, to modify them, use dump.setParser
parsers: {
window: "[Window]",
document: "[Document]",
fatal_error: function( error ) {
return "Error(\"" + error.message + "\")";
},
unknown: "[Unknown]",
"null": "null",
"undefined": "undefined",
"function": function( fn ) {
var ret = "function",
// functions never have name in IE
name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ];
if ( name ) {
ret += " " + name;
}
ret += "( ";
ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" );
return join( ret, dump.parse( fn, "functionCode" ), "}" );
},
array: array,
nodelist: array,
"arguments": array,
object: function( map, stack ) {
var keys, key, val, i, nonEnumerableProperties,
ret = [];
if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
return "[object Object]";
}
dump.up();
keys = [];
for ( key in map ) {
keys.push( key );
}
// Some properties are not always enumerable on Error objects.
nonEnumerableProperties = [ "message", "name" ];
for ( i in nonEnumerableProperties ) {
key = nonEnumerableProperties[ i ];
if ( key in map && inArray( key, keys ) < 0 ) {
keys.push( key );
}
}
keys.sort();
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
val = map[ key ];
ret.push( dump.parse( key, "key" ) + ": " +
dump.parse( val, undefined, stack ) );
}
dump.down();
return join( "{", ret, "}" );
},
node: function( node ) {
var len, i, val,
open = dump.HTML ? "<" : "<",
close = dump.HTML ? ">" : ">",
tag = node.nodeName.toLowerCase(),
ret = open + tag,
attrs = node.attributes;
if ( attrs ) {
for ( i = 0, len = attrs.length; i < len; i++ ) {
val = attrs[ i ].nodeValue;
// IE6 includes all attributes in .attributes, even ones not explicitly
// set. Those have values like undefined, null, 0, false, "" or
// "inherit".
if ( val && val !== "inherit" ) {
ret += " " + attrs[ i ].nodeName + "=" +
dump.parse( val, "attribute" );
}
}
}
ret += close;
// Show content of TextNode or CDATASection
if ( node.nodeType === 3 || node.nodeType === 4 ) {
ret += node.nodeValue;
}
return ret + open + "/" + tag + close;
},
// function calls it internally, it's the arguments part of the function
functionArgs: function( fn ) {
var args,
l = fn.length;
if ( !l ) {
return "";
}
args = new Array( l );
while ( l-- ) {
// 97 is 'a'
args[ l ] = String.fromCharCode( 97 + l );
}
return " " + args.join( ", " ) + " ";
},
// object calls it internally, the key part of an item in a map
key: quote,
// function calls it internally, it's the content of the function
functionCode: "[code]",
// node calls it internally, it's an html attribute value
attribute: quote,
string: quote,
date: quote,
regexp: literal,
number: literal,
"boolean": literal
},
// if true, entities are escaped ( <, >, \t, space and \n )
HTML: false,
// indentation unit
indentChar: " ",
// if true, items in a collection, are separated by a \n, else just a space.
multiline: true
};
return dump;
}());
// back compat
QUnit.jsDump = QUnit.dump;
// For browser, export only select globals
if ( defined.document ) {
// Deprecated
// Extend assert methods to QUnit and Global scope through Backwards compatibility
(function() {
var i,
assertions = Assert.prototype;
function applyCurrent( current ) {
return function() {
var assert = new Assert( QUnit.config.current );
current.apply( assert, arguments );
};
}
for ( i in assertions ) {
QUnit[ i ] = applyCurrent( assertions[ i ] );
}
})();
(function() {
var i, l,
keys = [
"test",
"module",
"expect",
"asyncTest",
"start",
"stop",
"ok",
"notOk",
"equal",
"notEqual",
"propEqual",
"notPropEqual",
"deepEqual",
"notDeepEqual",
"strictEqual",
"notStrictEqual",
"throws",
"raises"
];
for ( i = 0, l = keys.length; i < l; i++ ) {
window[ keys[ i ] ] = QUnit[ keys[ i ] ];
}
})();
window.QUnit = QUnit;
}
// For nodejs
if ( typeof module !== "undefined" && module && module.exports ) {
module.exports = QUnit;
// For consistency with CommonJS environments' exports
module.exports.QUnit = QUnit;
}
// For CommonJS with exports, but without module.exports, like Rhino
if ( typeof exports !== "undefined" && exports ) {
exports.QUnit = QUnit;
}
if ( typeof define === "function" && define.amd ) {
define( function() {
return QUnit;
} );
QUnit.config.autostart = false;
}
/*
* This file is a modified version of google-diff-match-patch's JavaScript implementation
* (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
* modifications are licensed as more fully set forth in LICENSE.txt.
*
* The original source of google-diff-match-patch is attributable and licensed as follows:
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* 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.
*
* More Info:
* https://code.google.com/p/google-diff-match-patch/
*
* Usage: QUnit.diff(expected, actual)
*
*/
QUnit.diff = ( function() {
function DiffMatchPatch() {
}
// DIFF FUNCTIONS
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1,
DIFF_INSERT = 1,
DIFF_EQUAL = 0;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean=} optChecklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
*/
DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines ) {
var deadline, checklines, commonlength,
commonprefix, commonsuffix, diffs;
// The diff must be complete in up to 1 second.
deadline = ( new Date() ).getTime() + 1000;
// Check for null inputs.
if ( text1 === null || text2 === null ) {
throw new Error( "Null input. (DiffMain)" );
}
// Check for equality (speedup).
if ( text1 === text2 ) {
if ( text1 ) {
return [
[ DIFF_EQUAL, text1 ]
];
}
return [];
}
if ( typeof optChecklines === "undefined" ) {
optChecklines = true;
}
checklines = optChecklines;
// Trim off common prefix (speedup).
commonlength = this.diffCommonPrefix( text1, text2 );
commonprefix = text1.substring( 0, commonlength );
text1 = text1.substring( commonlength );
text2 = text2.substring( commonlength );
// Trim off common suffix (speedup).
commonlength = this.diffCommonSuffix( text1, text2 );
commonsuffix = text1.substring( text1.length - commonlength );
text1 = text1.substring( 0, text1.length - commonlength );
text2 = text2.substring( 0, text2.length - commonlength );
// Compute the diff on the middle block.
diffs = this.diffCompute( text1, text2, checklines, deadline );
// Restore the prefix and suffix.
if ( commonprefix ) {
diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
}
if ( commonsuffix ) {
diffs.push( [ DIFF_EQUAL, commonsuffix ] );
}
this.diffCleanupMerge( diffs );
return diffs;
};
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
var changes, equalities, equalitiesLength, lastequality,
pointer, preIns, preDel, postIns, postDel;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
preIns = false;
// Is there a deletion operation before the last equality.
preDel = false;
// Is there an insertion operation after the last equality.
postIns = false;
// Is there a deletion operation after the last equality.
postDel = false;
while ( pointer < diffs.length ) {
// Equality found.
if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) {
if ( diffs[ pointer ][ 1 ].length < 4 && ( postIns || postDel ) ) {
// Candidate found.
equalities[ equalitiesLength++ ] = pointer;
preIns = postIns;
preDel = postDel;
lastequality = diffs[ pointer ][ 1 ];
} else {
// Not a candidate, and can never become one.
equalitiesLength = 0;
lastequality = null;
}
postIns = postDel = false;
// An insertion or deletion.
} else {
if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
postDel = true;
} else {
postIns = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
( ( lastequality.length < 2 ) &&
( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
// Duplicate record.
diffs.splice(
equalities[ equalitiesLength - 1 ],
0,
[ DIFF_DELETE, lastequality ]
);
// Change second copy to insert.
diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
equalitiesLength--; // Throw away the equality we just deleted;
lastequality = null;
if ( preIns && preDel ) {
// No changes made which could affect previous entry, keep going.
postIns = postDel = true;
equalitiesLength = 0;
} else {
equalitiesLength--; // Throw away the previous equality.
pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
postIns = postDel = false;
}
changes = true;
}
}
pointer++;
}
if ( changes ) {
this.diffCleanupMerge( diffs );
}
};
/**
* Convert a diff array into a pretty HTML report.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {integer} string to be beautified.
* @return {string} HTML representation.
*/
DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
var op, data, x,
html = [];
for ( x = 0; x < diffs.length; x++ ) {
op = diffs[ x ][ 0 ]; // Operation (insert, delete, equal)
data = diffs[ x ][ 1 ]; // Text of change.
switch ( op ) {
case DIFF_INSERT:
html[ x ] = "<ins>" + data + "</ins>";
break;
case DIFF_DELETE:
html[ x ] = "<del>" + data + "</del>";
break;
case DIFF_EQUAL:
html[ x ] = "<span>" + data + "</span>";
break;
}
}
return html.join( "" );
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
var pointermid, pointermax, pointermin, pointerstart;
// Quick check for common null cases.
if ( !text1 || !text2 || text1.charAt( 0 ) !== text2.charAt( 0 ) ) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min( text1.length, text2.length );
pointermid = pointermax;
pointerstart = 0;
while ( pointermin < pointermid ) {
if ( text1.substring( pointerstart, pointermid ) ===
text2.substring( pointerstart, pointermid ) ) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
var pointermid, pointermax, pointermin, pointerend;
// Quick check for common null cases.
if ( !text1 ||
!text2 ||
text1.charAt( text1.length - 1 ) !== text2.charAt( text2.length - 1 ) ) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min( text1.length, text2.length );
pointermid = pointermax;
pointerend = 0;
while ( pointermin < pointermid ) {
if ( text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
}
return pointermid;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
var diffs, longtext, shorttext, i, hm,
text1A, text2A, text1B, text2B,
midCommon, diffsA, diffsB;
if ( !text1 ) {
// Just add some text (speedup).
return [
[ DIFF_INSERT, text2 ]
];
}
if ( !text2 ) {
// Just delete some text (speedup).
return [
[ DIFF_DELETE, text1 ]
];
}
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
i = longtext.indexOf( shorttext );
if ( i !== -1 ) {
// Shorter text is inside the longer text (speedup).
diffs = [
[ DIFF_INSERT, longtext.substring( 0, i ) ],
[ DIFF_EQUAL, shorttext ],
[ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
];
// Swap insertions for deletions if diff is reversed.
if ( text1.length > text2.length ) {
diffs[ 0 ][ 0 ] = diffs[ 2 ][ 0 ] = DIFF_DELETE;
}
return diffs;
}
if ( shorttext.length === 1 ) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [
[ DIFF_DELETE, text1 ],
[ DIFF_INSERT, text2 ]
];
}
// Check to see if the problem can be split in two.
hm = this.diffHalfMatch( text1, text2 );
if ( hm ) {
// A half-match was found, sort out the return data.
text1A = hm[ 0 ];
text1B = hm[ 1 ];
text2A = hm[ 2 ];
text2B = hm[ 3 ];
midCommon = hm[ 4 ];
// Send both pairs off for separate processing.
diffsA = this.DiffMain( text1A, text2A, checklines, deadline );
diffsB = this.DiffMain( text1B, text2B, checklines, deadline );
// Merge the results.
return diffsA.concat( [
[ DIFF_EQUAL, midCommon ]
], diffsB );
}
if ( checklines && text1.length > 100 && text2.length > 100 ) {
return this.diffLineMode( text1, text2, deadline );
}
return this.diffBisect( text1, text2, deadline );
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
* @private
*/
DiffMatchPatch.prototype.diffHalfMatch = function( text1, text2 ) {
var longtext, shorttext, dmp,
text1A, text2B, text2A, text1B, midCommon,
hm1, hm2, hm;
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
if ( longtext.length < 4 || shorttext.length * 2 < longtext.length ) {
return null; // Pointless.
}
dmp = this; // 'this' becomes 'window' in a closure.
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diffHalfMatchI( longtext, shorttext, i ) {
var seed, j, bestCommon, prefixLength, suffixLength,
bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
// Start with a 1/4 length substring at position i as a seed.
seed = longtext.substring( i, i + Math.floor( longtext.length / 4 ) );
j = -1;
bestCommon = "";
while ( ( j = shorttext.indexOf( seed, j + 1 ) ) !== -1 ) {
prefixLength = dmp.diffCommonPrefix( longtext.substring( i ),
shorttext.substring( j ) );
suffixLength = dmp.diffCommonSuffix( longtext.substring( 0, i ),
shorttext.substring( 0, j ) );
if ( bestCommon.length < suffixLength + prefixLength ) {
bestCommon = shorttext.substring( j - suffixLength, j ) +
shorttext.substring( j, j + prefixLength );
bestLongtextA = longtext.substring( 0, i - suffixLength );
bestLongtextB = longtext.substring( i + prefixLength );
bestShorttextA = shorttext.substring( 0, j - suffixLength );
bestShorttextB = shorttext.substring( j + prefixLength );
}
}
if ( bestCommon.length * 2 >= longtext.length ) {
return [ bestLongtextA, bestLongtextB,
bestShorttextA, bestShorttextB, bestCommon
];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
hm1 = diffHalfMatchI( longtext, shorttext,
Math.ceil( longtext.length / 4 ) );
// Check again based on the third quarter.
hm2 = diffHalfMatchI( longtext, shorttext,
Math.ceil( longtext.length / 2 ) );
if ( !hm1 && !hm2 ) {
return null;
} else if ( !hm2 ) {
hm = hm1;
} else if ( !hm1 ) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[ 4 ].length > hm2[ 4 ].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
text1A, text1B, text2A, text2B;
if ( text1.length > text2.length ) {
text1A = hm[ 0 ];
text1B = hm[ 1 ];
text2A = hm[ 2 ];
text2B = hm[ 3 ];
} else {
text2A = hm[ 0 ];
text2B = hm[ 1 ];
text1A = hm[ 2 ];
text1B = hm[ 3 ];
}
midCommon = hm[ 4 ];
return [ text1A, text1B, text2A, text2B, midCommon ];
};
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffLineMode = function( text1, text2, deadline ) {
var a, diffs, linearray, pointer, countInsert,
countDelete, textInsert, textDelete, j;
// Scan the text on a line-by-line basis first.
a = this.diffLinesToChars( text1, text2 );
text1 = a.chars1;
text2 = a.chars2;
linearray = a.lineArray;
diffs = this.DiffMain( text1, text2, false, deadline );
// Convert the diff back to original text.
this.diffCharsToLines( diffs, linearray );
// Eliminate freak matches (e.g. blank lines)
this.diffCleanupSemantic( diffs );
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push( [ DIFF_EQUAL, "" ] );
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
while ( pointer < diffs.length ) {
switch ( diffs[ pointer ][ 0 ] ) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[ pointer ][ 1 ];
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[ pointer ][ 1 ];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if ( countDelete >= 1 && countInsert >= 1 ) {
// Delete the offending records and add the merged ones.
diffs.splice( pointer - countDelete - countInsert,
countDelete + countInsert );
pointer = pointer - countDelete - countInsert;
a = this.DiffMain( textDelete, textInsert, false, deadline );
for ( j = a.length - 1; j >= 0; j-- ) {
diffs.splice( pointer, 0, a[ j ] );
}
pointer = pointer + a.length;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
pointer++;
}
diffs.pop(); // Remove the dummy entry at the end.
return diffs;
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisect = function( text1, text2, deadline ) {
var text1Length, text2Length, maxD, vOffset, vLength,
v1, v2, x, delta, front, k1start, k1end, k2start,
k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
maxD = Math.ceil( ( text1Length + text2Length ) / 2 );
vOffset = maxD;
vLength = 2 * maxD;
v1 = new Array( vLength );
v2 = new Array( vLength );
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for ( x = 0; x < vLength; x++ ) {
v1[ x ] = -1;
v2[ x ] = -1;
}
v1[ vOffset + 1 ] = 0;
v2[ vOffset + 1 ] = 0;
delta = text1Length - text2Length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
front = ( delta % 2 !== 0 );
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
k1start = 0;
k1end = 0;
k2start = 0;
k2end = 0;
for ( d = 0; d < maxD; d++ ) {
// Bail out if deadline is reached.
if ( ( new Date() ).getTime() > deadline ) {
break;
}
// Walk the front path one step.
for ( k1 = -d + k1start; k1 <= d - k1end; k1 += 2 ) {
k1Offset = vOffset + k1;
if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
x1 = v1[ k1Offset + 1 ];
} else {
x1 = v1[ k1Offset - 1 ] + 1;
}
y1 = x1 - k1;
while ( x1 < text1Length && y1 < text2Length &&
text1.charAt( x1 ) === text2.charAt( y1 ) ) {
x1++;
y1++;
}
v1[ k1Offset ] = x1;
if ( x1 > text1Length ) {
// Ran off the right of the graph.
k1end += 2;
} else if ( y1 > text2Length ) {
// Ran off the bottom of the graph.
k1start += 2;
} else if ( front ) {
k2Offset = vOffset + delta - k1;
if ( k2Offset >= 0 && k2Offset < vLength && v2[ k2Offset ] !== -1 ) {
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - v2[ k2Offset ];
if ( x1 >= x2 ) {
// Overlap detected.
return this.diffBisectSplit( text1, text2, x1, y1, deadline );
}
}
}
}
// Walk the reverse path one step.
for ( k2 = -d + k2start; k2 <= d - k2end; k2 += 2 ) {
k2Offset = vOffset + k2;
if ( k2 === -d || ( k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
x2 = v2[ k2Offset + 1 ];
} else {
x2 = v2[ k2Offset - 1 ] + 1;
}
y2 = x2 - k2;
while ( x2 < text1Length && y2 < text2Length &&
text1.charAt( text1Length - x2 - 1 ) ===
text2.charAt( text2Length - y2 - 1 ) ) {
x2++;
y2++;
}
v2[ k2Offset ] = x2;
if ( x2 > text1Length ) {
// Ran off the left of the graph.
k2end += 2;
} else if ( y2 > text2Length ) {
// Ran off the top of the graph.
k2start += 2;
} else if ( !front ) {
k1Offset = vOffset + delta - k2;
if ( k1Offset >= 0 && k1Offset < vLength && v1[ k1Offset ] !== -1 ) {
x1 = v1[ k1Offset ];
y1 = vOffset + x1 - k1Offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - x2;
if ( x1 >= x2 ) {
// Overlap detected.
return this.diffBisectSplit( text1, text2, x1, y1, deadline );
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [
[ DIFF_DELETE, text1 ],
[ DIFF_INSERT, text2 ]
];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
var text1a, text1b, text2a, text2b, diffs, diffsb;
text1a = text1.substring( 0, x );
text2a = text2.substring( 0, y );
text1b = text1.substring( x );
text2b = text2.substring( y );
// Compute both diffs serially.
diffs = this.DiffMain( text1a, text2a, false, deadline );
diffsb = this.DiffMain( text1b, text2b, false, deadline );
return diffs.concat( diffsb );
};
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupSemantic = function( diffs ) {
var changes, equalities, equalitiesLength, lastequality,
pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
// Number of characters that changed after the equality.
lengthInsertions2 = 0;
lengthDeletions2 = 0;
while ( pointer < diffs.length ) {
if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
equalities[ equalitiesLength++ ] = pointer;
lengthInsertions1 = lengthInsertions2;
lengthDeletions1 = lengthDeletions2;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = diffs[ pointer ][ 1 ];
} else { // An insertion or deletion.
if ( diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
lengthInsertions2 += diffs[ pointer ][ 1 ].length;
} else {
lengthDeletions2 += diffs[ pointer ][ 1 ].length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if ( lastequality && ( lastequality.length <=
Math.max( lengthInsertions1, lengthDeletions1 ) ) &&
( lastequality.length <= Math.max( lengthInsertions2,
lengthDeletions2 ) ) ) {
// Duplicate record.
diffs.splice(
equalities[ equalitiesLength - 1 ],
0,
[ DIFF_DELETE, lastequality ]
);
// Change second copy to insert.
diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
// Throw away the equality we just deleted.
equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
equalitiesLength--;
pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
// Reset the counters.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = null;
changes = true;
}
}
pointer++;
}
// Normalize the diff.
if ( changes ) {
this.diffCleanupMerge( diffs );
}
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while ( pointer < diffs.length ) {
if ( diffs[ pointer - 1 ][ 0 ] === DIFF_DELETE &&
diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
deletion = diffs[ pointer - 1 ][ 1 ];
insertion = diffs[ pointer ][ 1 ];
overlapLength1 = this.diffCommonOverlap( deletion, insertion );
overlapLength2 = this.diffCommonOverlap( insertion, deletion );
if ( overlapLength1 >= overlapLength2 ) {
if ( overlapLength1 >= deletion.length / 2 ||
overlapLength1 >= insertion.length / 2 ) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.splice(
pointer,
0,
[ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ]
);
diffs[ pointer - 1 ][ 1 ] =
deletion.substring( 0, deletion.length - overlapLength1 );
diffs[ pointer + 1 ][ 1 ] = insertion.substring( overlapLength1 );
pointer++;
}
} else {
if ( overlapLength2 >= deletion.length / 2 ||
overlapLength2 >= insertion.length / 2 ) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.splice(
pointer,
0,
[ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ]
);
diffs[ pointer - 1 ][ 0 ] = DIFF_INSERT;
diffs[ pointer - 1 ][ 1 ] =
insertion.substring( 0, insertion.length - overlapLength2 );
diffs[ pointer + 1 ][ 0 ] = DIFF_DELETE;
diffs[ pointer + 1 ][ 1 ] =
deletion.substring( overlapLength2 );
pointer++;
}
}
pointer++;
}
pointer++;
}
};
/**
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
*/
DiffMatchPatch.prototype.diffCommonOverlap = function( text1, text2 ) {
var text1Length, text2Length, textLength,
best, length, pattern, found;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
// Eliminate the null case.
if ( text1Length === 0 || text2Length === 0 ) {
return 0;
}
// Truncate the longer string.
if ( text1Length > text2Length ) {
text1 = text1.substring( text1Length - text2Length );
} else if ( text1Length < text2Length ) {
text2 = text2.substring( 0, text1Length );
}
textLength = Math.min( text1Length, text2Length );
// Quick check for the worst case.
if ( text1 === text2 ) {
return textLength;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
best = 0;
length = 1;
while ( true ) {
pattern = text1.substring( textLength - length );
found = text2.indexOf( pattern );
if ( found === -1 ) {
return best;
}
length += found;
if ( found === 0 || text1.substring( textLength - length ) ===
text2.substring( 0, length ) ) {
best = length;
length++;
}
}
};
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
* An object containing the encoded text1, the encoded text2 and
* the array of unique strings.
* The zeroth element of the array of unique strings is intentionally blank.
* @private
*/
DiffMatchPatch.prototype.diffLinesToChars = function( text1, text2 ) {
var lineArray, lineHash, chars1, chars2;
lineArray = []; // e.g. lineArray[4] === 'Hello\n'
lineHash = {}; // e.g. lineHash['Hello\n'] === 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[ 0 ] = "";
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
function diffLinesToCharsMunge( text ) {
var chars, lineStart, lineEnd, lineArrayLength, line;
chars = "";
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
lineStart = 0;
lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
lineArrayLength = lineArray.length;
while ( lineEnd < text.length - 1 ) {
lineEnd = text.indexOf( "\n", lineStart );
if ( lineEnd === -1 ) {
lineEnd = text.length - 1;
}
line = text.substring( lineStart, lineEnd + 1 );
lineStart = lineEnd + 1;
if ( lineHash.hasOwnProperty ? lineHash.hasOwnProperty( line ) :
( lineHash[ line ] !== undefined ) ) {
chars += String.fromCharCode( lineHash[ line ] );
} else {
chars += String.fromCharCode( lineArrayLength );
lineHash[ line ] = lineArrayLength;
lineArray[ lineArrayLength++ ] = line;
}
}
return chars;
}
chars1 = diffLinesToCharsMunge( text1 );
chars2 = diffLinesToCharsMunge( text2 );
return {
chars1: chars1,
chars2: chars2,
lineArray: lineArray
};
};
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {!Array.<string>} lineArray Array of unique strings.
* @private
*/
DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
var x, chars, text, y;
for ( x = 0; x < diffs.length; x++ ) {
chars = diffs[ x ][ 1 ];
text = [];
for ( y = 0; y < chars.length; y++ ) {
text[ y ] = lineArray[ chars.charCodeAt( y ) ];
}
diffs[ x ][ 1 ] = text.join( "" );
}
};
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupMerge = function( diffs ) {
var pointer, countDelete, countInsert, textInsert, textDelete,
commonlength, changes, diffPointer, position;
diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
commonlength;
while ( pointer < diffs.length ) {
switch ( diffs[ pointer ][ 0 ] ) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[ pointer ][ 1 ];
pointer++;
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[ pointer ][ 1 ];
pointer++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if ( countDelete + countInsert > 1 ) {
if ( countDelete !== 0 && countInsert !== 0 ) {
// Factor out any common prefixies.
commonlength = this.diffCommonPrefix( textInsert, textDelete );
if ( commonlength !== 0 ) {
if ( ( pointer - countDelete - countInsert ) > 0 &&
diffs[ pointer - countDelete - countInsert - 1 ][ 0 ] ===
DIFF_EQUAL ) {
diffs[ pointer - countDelete - countInsert - 1 ][ 1 ] +=
textInsert.substring( 0, commonlength );
} else {
diffs.splice( 0, 0, [ DIFF_EQUAL,
textInsert.substring( 0, commonlength )
] );
pointer++;
}
textInsert = textInsert.substring( commonlength );
textDelete = textDelete.substring( commonlength );
}
// Factor out any common suffixies.
commonlength = this.diffCommonSuffix( textInsert, textDelete );
if ( commonlength !== 0 ) {
diffs[ pointer ][ 1 ] = textInsert.substring( textInsert.length -
commonlength ) + diffs[ pointer ][ 1 ];
textInsert = textInsert.substring( 0, textInsert.length -
commonlength );
textDelete = textDelete.substring( 0, textDelete.length -
commonlength );
}
}
// Delete the offending records and add the merged ones.
if ( countDelete === 0 ) {
diffs.splice( pointer - countInsert,
countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
} else if ( countInsert === 0 ) {
diffs.splice( pointer - countDelete,
countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
} else {
diffs.splice(
pointer - countDelete - countInsert,
countDelete + countInsert,
[ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ]
);
}
pointer = pointer - countDelete - countInsert +
( countDelete ? 1 : 0 ) + ( countInsert ? 1 : 0 ) + 1;
} else if ( pointer !== 0 && diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL ) {
// Merge this equality with the previous one.
diffs[ pointer - 1 ][ 1 ] += diffs[ pointer ][ 1 ];
diffs.splice( pointer, 1 );
} else {
pointer++;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
}
if ( diffs[ diffs.length - 1 ][ 1 ] === "" ) {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while ( pointer < diffs.length - 1 ) {
if ( diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL &&
diffs[ pointer + 1 ][ 0 ] === DIFF_EQUAL ) {
diffPointer = diffs[ pointer ][ 1 ];
position = diffPointer.substring(
diffPointer.length - diffs[ pointer - 1 ][ 1 ].length
);
// This is a single edit surrounded by equalities.
if ( position === diffs[ pointer - 1 ][ 1 ] ) {
// Shift the edit over the previous equality.
diffs[ pointer ][ 1 ] = diffs[ pointer - 1 ][ 1 ] +
diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer ][ 1 ].length -
diffs[ pointer - 1 ][ 1 ].length );
diffs[ pointer + 1 ][ 1 ] =
diffs[ pointer - 1 ][ 1 ] + diffs[ pointer + 1 ][ 1 ];
diffs.splice( pointer - 1, 1 );
changes = true;
} else if ( diffPointer.substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
diffs[ pointer + 1 ][ 1 ] ) {
// Shift the edit over the next equality.
diffs[ pointer - 1 ][ 1 ] += diffs[ pointer + 1 ][ 1 ];
diffs[ pointer ][ 1 ] =
diffs[ pointer ][ 1 ].substring( diffs[ pointer + 1 ][ 1 ].length ) +
diffs[ pointer + 1 ][ 1 ];
diffs.splice( pointer + 1, 1 );
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if ( changes ) {
this.diffCleanupMerge( diffs );
}
};
return function( o, n ) {
var diff, output, text;
diff = new DiffMatchPatch();
output = diff.DiffMain( o, n );
diff.diffCleanupEfficiency( output );
text = diff.diffPrettyHtml( output );
return text;
};
}() );
// Get a reference to the global object, like window in browsers
}( (function() {
return this;
})() ));
(function() {
// Don't load the HTML Reporter on non-Browser environments
if ( typeof window === "undefined" || !window.document ) {
return;
}
// Deprecated QUnit.init - Ref #530
// Re-initialize the configuration options
QUnit.init = function() {
var tests, banner, result, qunit,
config = QUnit.config;
config.stats = { all: 0, bad: 0 };
config.moduleStats = { all: 0, bad: 0 };
config.started = 0;
config.updateRate = 1000;
config.blocking = false;
config.autostart = true;
config.autorun = false;
config.filter = "";
config.queue = [];
// Return on non-browser environments
// This is necessary to not break on node tests
if ( typeof window === "undefined" ) {
return;
}
qunit = id( "qunit" );
if ( qunit ) {
qunit.innerHTML =
"<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
"<h2 id='qunit-banner'></h2>" +
"<div id='qunit-testrunner-toolbar'></div>" +
"<h2 id='qunit-userAgent'></h2>" +
"<ol id='qunit-tests'></ol>";
}
tests = id( "qunit-tests" );
banner = id( "qunit-banner" );
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = "Running...<br /> ";
}
};
var config = QUnit.config,
collapseNext = false,
hasOwn = Object.prototype.hasOwnProperty,
defined = {
document: window.document !== undefined,
sessionStorage: (function() {
var x = "qunit-test-string";
try {
sessionStorage.setItem( x, x );
sessionStorage.removeItem( x );
return true;
} catch ( e ) {
return false;
}
}())
},
modulesList = [];
/**
* Escape text for attribute or text content.
*/
function escapeText( s ) {
if ( !s ) {
return "";
}
s = s + "";
// Both single quotes and double quotes (for attributes)
return s.replace( /['"<>&]/g, function( s ) {
switch ( s ) {
case "'":
return "'";
case "\"":
return """;
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
}
});
}
/**
* @param {HTMLElement} elem
* @param {string} type
* @param {Function} fn
*/
function addEvent( elem, type, fn ) {
if ( elem.addEventListener ) {
// Standards-based browsers
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
// support: IE <9
elem.attachEvent( "on" + type, function() {
var event = window.event;
if ( !event.target ) {
event.target = event.srcElement || document;
}
fn.call( elem, event );
});
}
}
/**
* @param {Array|NodeList} elems
* @param {string} type
* @param {Function} fn
*/
function addEvents( elems, type, fn ) {
var i = elems.length;
while ( i-- ) {
addEvent( elems[ i ], type, fn );
}
}
function hasClass( elem, name ) {
return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0;
}
function addClass( elem, name ) {
if ( !hasClass( elem, name ) ) {
elem.className += ( elem.className ? " " : "" ) + name;
}
}
function toggleClass( elem, name ) {
if ( hasClass( elem, name ) ) {
removeClass( elem, name );
} else {
addClass( elem, name );
}
}
function removeClass( elem, name ) {
var set = " " + elem.className + " ";
// Class name may appear multiple times
while ( set.indexOf( " " + name + " " ) >= 0 ) {
set = set.replace( " " + name + " ", " " );
}
// trim for prettiness
elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" );
}
function id( name ) {
return defined.document && document.getElementById && document.getElementById( name );
}
function getUrlConfigHtml() {
var i, j, val,
escaped, escapedTooltip,
selection = false,
len = config.urlConfig.length,
urlConfigHtml = "";
for ( i = 0; i < len; i++ ) {
val = config.urlConfig[ i ];
if ( typeof val === "string" ) {
val = {
id: val,
label: val
};
}
escaped = escapeText( val.id );
escapedTooltip = escapeText( val.tooltip );
if ( config[ val.id ] === undefined ) {
config[ val.id ] = QUnit.urlParams[ val.id ];
}
if ( !val.value || typeof val.value === "string" ) {
urlConfigHtml += "<input id='qunit-urlconfig-" + escaped +
"' name='" + escaped + "' type='checkbox'" +
( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) +
( config[ val.id ] ? " checked='checked'" : "" ) +
" title='" + escapedTooltip + "' /><label for='qunit-urlconfig-" + escaped +
"' title='" + escapedTooltip + "'>" + val.label + "</label>";
} else {
urlConfigHtml += "<label for='qunit-urlconfig-" + escaped +
"' title='" + escapedTooltip + "'>" + val.label +
": </label><select id='qunit-urlconfig-" + escaped +
"' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
if ( QUnit.is( "array", val.value ) ) {
for ( j = 0; j < val.value.length; j++ ) {
escaped = escapeText( val.value[ j ] );
urlConfigHtml += "<option value='" + escaped + "'" +
( config[ val.id ] === val.value[ j ] ?
( selection = true ) && " selected='selected'" : "" ) +
">" + escaped + "</option>";
}
} else {
for ( j in val.value ) {
if ( hasOwn.call( val.value, j ) ) {
urlConfigHtml += "<option value='" + escapeText( j ) + "'" +
( config[ val.id ] === j ?
( selection = true ) && " selected='selected'" : "" ) +
">" + escapeText( val.value[ j ] ) + "</option>";
}
}
}
if ( config[ val.id ] && !selection ) {
escaped = escapeText( config[ val.id ] );
urlConfigHtml += "<option value='" + escaped +
"' selected='selected' disabled='disabled'>" + escaped + "</option>";
}
urlConfigHtml += "</select>";
}
}
return urlConfigHtml;
}
// Handle "click" events on toolbar checkboxes and "change" for select menus.
// Updates the URL with the new state of `config.urlConfig` values.
function toolbarChanged() {
var updatedUrl, value,
field = this,
params = {};
// Detect if field is a select menu or a checkbox
if ( "selectedIndex" in field ) {
value = field.options[ field.selectedIndex ].value || undefined;
} else {
value = field.checked ? ( field.defaultValue || true ) : undefined;
}
params[ field.name ] = value;
updatedUrl = setUrl( params );
if ( "hidepassed" === field.name && "replaceState" in window.history ) {
config[ field.name ] = value || false;
if ( value ) {
addClass( id( "qunit-tests" ), "hidepass" );
} else {
removeClass( id( "qunit-tests" ), "hidepass" );
}
// It is not necessary to refresh the whole page
window.history.replaceState( null, "", updatedUrl );
} else {
window.location = updatedUrl;
}
}
function setUrl( params ) {
var key,
querystring = "?";
params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params );
for ( key in params ) {
if ( hasOwn.call( params, key ) ) {
if ( params[ key ] === undefined ) {
continue;
}
querystring += encodeURIComponent( key );
if ( params[ key ] !== true ) {
querystring += "=" + encodeURIComponent( params[ key ] );
}
querystring += "&";
}
}
return location.protocol + "//" + location.host +
location.pathname + querystring.slice( 0, -1 );
}
function applyUrlParams() {
var selectedModule,
modulesList = id( "qunit-modulefilter" ),
filter = id( "qunit-filter-input" ).value;
selectedModule = modulesList ?
decodeURIComponent( modulesList.options[ modulesList.selectedIndex ].value ) :
undefined;
window.location = setUrl({
module: ( selectedModule === "" ) ? undefined : selectedModule,
filter: ( filter === "" ) ? undefined : filter,
// Remove testId filter
testId: undefined
});
}
function toolbarUrlConfigContainer() {
var urlConfigContainer = document.createElement( "span" );
urlConfigContainer.innerHTML = getUrlConfigHtml();
addClass( urlConfigContainer, "qunit-url-config" );
// For oldIE support:
// * Add handlers to the individual elements instead of the container
// * Use "click" instead of "change" for checkboxes
addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged );
addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged );
return urlConfigContainer;
}
function toolbarLooseFilter() {
var filter = document.createElement( "form" ),
label = document.createElement( "label" ),
input = document.createElement( "input" ),
button = document.createElement( "button" );
addClass( filter, "qunit-filter" );
label.innerHTML = "Filter: ";
input.type = "text";
input.value = config.filter || "";
input.name = "filter";
input.id = "qunit-filter-input";
button.innerHTML = "Go";
label.appendChild( input );
filter.appendChild( label );
filter.appendChild( button );
addEvent( filter, "submit", function( ev ) {
applyUrlParams();
if ( ev && ev.preventDefault ) {
ev.preventDefault();
}
return false;
});
return filter;
}
function toolbarModuleFilterHtml() {
var i,
moduleFilterHtml = "";
if ( !modulesList.length ) {
return false;
}
modulesList.sort(function( a, b ) {
return a.localeCompare( b );
});
moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" +
"<select id='qunit-modulefilter' name='modulefilter'><option value='' " +
( QUnit.urlParams.module === undefined ? "selected='selected'" : "" ) +
">< All Modules ></option>";
for ( i = 0; i < modulesList.length; i++ ) {
moduleFilterHtml += "<option value='" +
escapeText( encodeURIComponent( modulesList[ i ] ) ) + "' " +
( QUnit.urlParams.module === modulesList[ i ] ? "selected='selected'" : "" ) +
">" + escapeText( modulesList[ i ] ) + "</option>";
}
moduleFilterHtml += "</select>";
return moduleFilterHtml;
}
function toolbarModuleFilter() {
var toolbar = id( "qunit-testrunner-toolbar" ),
moduleFilter = document.createElement( "span" ),
moduleFilterHtml = toolbarModuleFilterHtml();
if ( !toolbar || !moduleFilterHtml ) {
return false;
}
moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
moduleFilter.innerHTML = moduleFilterHtml;
addEvent( moduleFilter.lastChild, "change", applyUrlParams );
toolbar.appendChild( moduleFilter );
}
function appendToolbar() {
var toolbar = id( "qunit-testrunner-toolbar" );
if ( toolbar ) {
toolbar.appendChild( toolbarUrlConfigContainer() );
toolbar.appendChild( toolbarLooseFilter() );
}
}
function appendHeader() {
var header = id( "qunit-header" );
if ( header ) {
header.innerHTML = "<a href='" +
setUrl({ filter: undefined, module: undefined, testId: undefined }) +
"'>" + header.innerHTML + "</a> ";
}
}
function appendBanner() {
var banner = id( "qunit-banner" );
if ( banner ) {
banner.className = "";
}
}
function appendTestResults() {
var tests = id( "qunit-tests" ),
result = id( "qunit-testresult" );
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
tests.innerHTML = "";
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = "Running...<br /> ";
}
}
function storeFixture() {
var fixture = id( "qunit-fixture" );
if ( fixture ) {
config.fixture = fixture.innerHTML;
}
}
function appendFilteredTest() {
var testId = QUnit.config.testId;
if ( !testId || testId.length <= 0 ) {
return "";
}
return "<div id='qunit-filteredTest'>Rerunning selected tests: " + testId.join(", ") +
" <a id='qunit-clearFilter' href='" +
setUrl({ filter: undefined, module: undefined, testId: undefined }) +
"'>" + "Run all tests" + "</a></div>";
}
function appendUserAgent() {
var userAgent = id( "qunit-userAgent" );
if ( userAgent ) {
userAgent.innerHTML = "";
userAgent.appendChild(
document.createTextNode(
"QUnit " + QUnit.version + "; " + navigator.userAgent
)
);
}
}
function appendTestsList( modules ) {
var i, l, x, z, test, moduleObj;
for ( i = 0, l = modules.length; i < l; i++ ) {
moduleObj = modules[ i ];
if ( moduleObj.name ) {
modulesList.push( moduleObj.name );
}
for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) {
test = moduleObj.tests[ x ];
appendTest( test.name, test.testId, moduleObj.name );
}
}
}
function appendTest( name, testId, moduleName ) {
var title, rerunTrigger, testBlock, assertList,
tests = id( "qunit-tests" );
if ( !tests ) {
return;
}
title = document.createElement( "strong" );
title.innerHTML = getNameHtml( name, moduleName );
rerunTrigger = document.createElement( "a" );
rerunTrigger.innerHTML = "Rerun";
rerunTrigger.href = setUrl({ testId: testId });
testBlock = document.createElement( "li" );
testBlock.appendChild( title );
testBlock.appendChild( rerunTrigger );
testBlock.id = "qunit-test-output-" + testId;
assertList = document.createElement( "ol" );
assertList.className = "qunit-assert-list";
testBlock.appendChild( assertList );
tests.appendChild( testBlock );
}
// HTML Reporter initialization and load
QUnit.begin(function( details ) {
var qunit = id( "qunit" );
// Fixture is the only one necessary to run without the #qunit element
storeFixture();
if ( qunit ) {
qunit.innerHTML =
"<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
"<h2 id='qunit-banner'></h2>" +
"<div id='qunit-testrunner-toolbar'></div>" +
appendFilteredTest() +
"<h2 id='qunit-userAgent'></h2>" +
"<ol id='qunit-tests'></ol>";
}
appendHeader();
appendBanner();
appendTestResults();
appendUserAgent();
appendToolbar();
appendTestsList( details.modules );
toolbarModuleFilter();
if ( qunit && config.hidepassed ) {
addClass( qunit.lastChild, "hidepass" );
}
});
QUnit.done(function( details ) {
var i, key,
banner = id( "qunit-banner" ),
tests = id( "qunit-tests" ),
html = [
"Tests completed in ",
details.runtime,
" milliseconds.<br />",
"<span class='passed'>",
details.passed,
"</span> assertions of <span class='total'>",
details.total,
"</span> passed, <span class='failed'>",
details.failed,
"</span> failed."
].join( "" );
if ( banner ) {
banner.className = details.failed ? "qunit-fail" : "qunit-pass";
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && defined.document && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
( details.failed ? "\u2716" : "\u2714" ),
document.title.replace( /^[\u2714\u2716] /i, "" )
].join( " " );
}
// clear own sessionStorage items if all tests passed
if ( config.reorder && defined.sessionStorage && details.failed === 0 ) {
for ( i = 0; i < sessionStorage.length; i++ ) {
key = sessionStorage.key( i++ );
if ( key.indexOf( "qunit-test-" ) === 0 ) {
sessionStorage.removeItem( key );
}
}
}
// scroll back to top to show results
if ( config.scrolltop && window.scrollTo ) {
window.scrollTo( 0, 0 );
}
});
function getNameHtml( name, module ) {
var nameHtml = "";
if ( module ) {
nameHtml = "<span class='module-name'>" + escapeText( module ) + "</span>: ";
}
nameHtml += "<span class='test-name'>" + escapeText( name ) + "</span>";
return nameHtml;
}
QUnit.testStart(function( details ) {
var running, testBlock, bad;
testBlock = id( "qunit-test-output-" + details.testId );
if ( testBlock ) {
testBlock.className = "running";
} else {
// Report later registered tests
appendTest( details.name, details.testId, details.module );
}
running = id( "qunit-testresult" );
if ( running ) {
bad = QUnit.config.reorder && defined.sessionStorage &&
+sessionStorage.getItem( "qunit-test-" + details.module + "-" + details.name );
running.innerHTML = ( bad ?
"Rerunning previously failed test: <br />" :
"Running: <br />" ) +
getNameHtml( details.name, details.module );
}
});
function stripHtml( string ) {
// strip tags, html entity and whitespaces
return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
}
QUnit.log(function( details ) {
var assertList, assertLi,
message, expected, actual, diff,
showDiff = false,
testItem = id( "qunit-test-output-" + details.testId );
if ( !testItem ) {
return;
}
message = escapeText( details.message ) || ( details.result ? "okay" : "failed" );
message = "<span class='test-message'>" + message + "</span>";
message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
// pushFailure doesn't provide details.expected
// when it calls, it's implicit to also not show expected and diff stuff
// Also, we need to check details.expected existence, as it can exist and be undefined
if ( !details.result && hasOwn.call( details, "expected" ) ) {
if ( details.negative ) {
expected = escapeText( "NOT " + QUnit.dump.parse( details.expected ) );
} else {
expected = escapeText( QUnit.dump.parse( details.expected ) );
}
actual = escapeText( QUnit.dump.parse( details.actual ) );
message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" +
expected +
"</pre></td></tr>";
if ( actual !== expected ) {
message += "<tr class='test-actual'><th>Result: </th><td><pre>" +
actual + "</pre></td></tr>";
// Don't show diff if actual or expected are booleans
if ( !( /^(true|false)$/.test( actual ) ) &&
!( /^(true|false)$/.test( expected ) ) ) {
diff = QUnit.diff( expected, actual );
showDiff = stripHtml( diff ).length !==
stripHtml( expected ).length +
stripHtml( actual ).length;
}
// Don't show diff if expected and actual are totally different
if ( showDiff ) {
message += "<tr class='test-diff'><th>Diff: </th><td><pre>" +
diff + "</pre></td></tr>";
}
} else if ( expected.indexOf( "[object Array]" ) !== -1 ||
expected.indexOf( "[object Object]" ) !== -1 ) {
message += "<tr class='test-message'><th>Message: </th><td>" +
"Diff suppressed as the depth of object is more than current max depth (" +
QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " +
" run with a higher max depth or <a href='" + setUrl({ maxDepth: -1 }) + "'>" +
"Rerun</a> without max depth.</p></td></tr>";
}
if ( details.source ) {
message += "<tr class='test-source'><th>Source: </th><td><pre>" +
escapeText( details.source ) + "</pre></td></tr>";
}
message += "</table>";
// this occours when pushFailure is set and we have an extracted stack trace
} else if ( !details.result && details.source ) {
message += "<table>" +
"<tr class='test-source'><th>Source: </th><td><pre>" +
escapeText( details.source ) + "</pre></td></tr>" +
"</table>";
}
assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
assertLi = document.createElement( "li" );
assertLi.className = details.result ? "pass" : "fail";
assertLi.innerHTML = message;
assertList.appendChild( assertLi );
});
QUnit.testDone(function( details ) {
var testTitle, time, testItem, assertList,
good, bad, testCounts, skipped, sourceName,
tests = id( "qunit-tests" );
if ( !tests ) {
return;
}
testItem = id( "qunit-test-output-" + details.testId );
assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
good = details.passed;
bad = details.failed;
// store result when possible
if ( config.reorder && defined.sessionStorage ) {
if ( bad ) {
sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad );
} else {
sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name );
}
}
if ( bad === 0 ) {
// Collapse the passing tests
addClass( assertList, "qunit-collapsed" );
} else if ( bad && config.collapse && !collapseNext ) {
// Skip collapsing the first failing test
collapseNext = true;
} else {
// Collapse remaining tests
addClass( assertList, "qunit-collapsed" );
}
// testItem.firstChild is the test name
testTitle = testItem.firstChild;
testCounts = bad ?
"<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " :
"";
testTitle.innerHTML += " <b class='counts'>(" + testCounts +
details.assertions.length + ")</b>";
if ( details.skipped ) {
testItem.className = "skipped";
skipped = document.createElement( "em" );
skipped.className = "qunit-skipped-label";
skipped.innerHTML = "skipped";
testItem.insertBefore( skipped, testTitle );
} else {
addEvent( testTitle, "click", function() {
toggleClass( assertList, "qunit-collapsed" );
});
testItem.className = bad ? "fail" : "pass";
time = document.createElement( "span" );
time.className = "runtime";
time.innerHTML = details.runtime + " ms";
testItem.insertBefore( time, assertList );
}
// Show the source of the test when showing assertions
if ( details.source ) {
sourceName = document.createElement( "p" );
sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
addClass( sourceName, "qunit-source" );
if ( bad === 0 ) {
addClass( sourceName, "qunit-collapsed" );
}
addEvent( testTitle, "click", function() {
toggleClass( sourceName, "qunit-collapsed" );
});
testItem.appendChild( sourceName );
}
});
if ( defined.document ) {
// Avoid readyState issue with phantomjs
// Ref: #818
var notPhantom = ( function( p ) {
return !( p && p.version && p.version.major > 0 );
} )( window.phantom );
if ( notPhantom && document.readyState === "complete" ) {
QUnit.load();
} else {
addEvent( window, "load", QUnit.load );
}
} else {
config.pageLoaded = true;
config.autorun = true;
}
})();
|
'use strict';
var express = require('express');
var ledstrip = require('./../lib/ledstrip');
var router = express.Router();
var config = require('./../lib/config');
router.post('/test', function (req, res) {
var len = Number(req.param('length')),
start = Number(req.param('start')) || 0,
end = Number(req.param('end')) || len,
animation = req.param('animation'),
speed = Number(req.param('speed')),
colour = req.param('colour');
if (start < 1) {
start = 0;
}
if (end > len) {
end = len - 1;
}
if (start > end) {
res.send(500);
}
ledstrip.connect(start, end);
var intervalId = ledstrip.animate({
animation: animation,
speed: speed,
colour: colour
});
setTimeout(function () {
ledstrip.disconnect();
clearInterval(intervalId);
}, 5000);
res.send();
});
router.get('/', function (req, res) {
res.json(config.get('leds'));
});
router.put('/', function (req, res) {
var payload = req.body;
config.merge('leds', payload);
config.save(function (err) {
if (err) {
res.send(500);
}
});
res.json('Configuration saved successfully.');
});
module.exports = router; |
import * as actions from './actions';
import {
chatCursor
}
from '../state';
import {
register
}
from '../dispatcher';
if (typeof io !== 'undefined') {
let socket = io();
}
export const dispatchToken = register(({
action, data
}) => {
switch (action) {
case actions.postMessage:
chatCursor(chat => {
return chat
.update('messages', (messages) => {
const msg = data;
return messages.push(msg);
});
});
break;
case actions.getMessage:
console.log('in store with getMessage');
chatCursor(chat => {
return chat.update('messages', messages => messages.push(data));
});
break;
}
});
|
// Karma configuration
// Generated on Thu May 12 2016 14:37:54 GMT-0700 (PDT)
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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'test/bundle.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};
|
import _ from 'underscore'
import MeasurementFilterModel from './MeasurementFilter'
class MeasurementListModel {
constructor () {
this._requestFilter = null
this._filter = null
this._columns = []
this._values = []
}
setRequestFilter (filter) {
if ( ! (filter instanceof MeasurementFilterModel)) {
throw new Error('Invalid measurement filter model.')
}
this._requestFilter = filter
return this
}
getRequestFilter () {
return this._requestFilter
}
setFilter (filter) {
if (typeof filter !== 'object') {
throw new Error('Invalid measurement filter object.')
}
this._filter = filter
return this
}
getFilter () {
return this._filter
}
setColumns (columns) {
if ( ! Array.isArray(columns)) {
throw new Error('Invalid columns array.')
}
this._columns = columns
return this
}
getColumns () {
return this._columns
}
setValues (values) {
var isGrouped = this.getRequestFilter().isGrouped()
if (isGrouped && ! Array.isArray(values)) {
throw new Error('Invalid values array.')
} else if ( ! isGrouped && typeof values !== 'object') {
throw new Error('Invalid values object.')
}
this._values = values
return this
}
getValues () {
return this._values
}
sortValues () {
var isGrouped = this.getRequestFilter().isGrouped()
var timestampIndex = this.getColumns().indexOf('timestamp')
var values = this.getValues()
if (isGrouped) {
this.setValues(_.sortBy(values, (value) => value[timestampIndex]))
} else {
for (var id in values) {
values[id] = _.sortBy(values[id], (value) => value[timestampIndex])
}
this.setValues(values)
}
return this
}
}
MeasurementListModel.create = (data, filter) => {
var list = new MeasurementListModel()
list.setRequestFilter(filter)
list.setFilter(data.filter)
list.setColumns(data.columns)
list.setValues(data.values)
return list
}
export default MeasurementListModel
|
(function(){
var tm = '<div class="page-bar">'+
'<ul>'+
'<li v-if="cur!=1"><a @click="btnClick(cur-1)">上一页</a></li>'+
'<li v-for="index in indexs" v-bind:class="{ active: cur == index}">'+
'<a v-on:click="btnClick(index)">{{ index }}</a>'+
'</li>'+
'<li v-if="cur!=all"><a @click="btnClick(cur+1)">下一页</a></li>'+
'<li><a>共<i>{{all}}</i>页</a></li>'+
'</ul>'+
'</div>'
var navBar = Vue.extend({
template: tm,
props: {
cur: {
type: [String, Number],
required: true
},
all: {
type: [String, Number],
required: true
},
callback: {
default() {
return function callback() {
// todo
}
}
}
},
computed: {
indexs() {
var left = 1
var right = this.all
var ar = []
if (this.all >= 11) {
if (this.cur > 5 && this.cur < this.all - 4) {
left = this.cur - 5
right = this.cur + 4
} else {
if (this.cur <= 5) {
left = 1
right = 10
} else {
right = this.all
left = this.all -9
}
}
}
while (left <= right) {
ar.push(left)
left ++
}
return ar
}
},
methods: {
btnClick(page) {
if (page != this.cur) {
this.callback(page)
}
}
}
})
window.Vnav = navBar
})() |
var WebSocket = require('ws');
var wss = new WebSocket.Server({
port: 8080
}, function() {
console.log('Listening');
var ws = new WebSocket('ws://localhost:8080');
});
wss.on('connection', function connection(ws) {
console.log("Connected");
console.log(ws.upgradeReq.url.slice(1).toLowerCase());
}); |
(function() {
'use strict';
var app;
app = angular.module('ngPostMessage', ['ng']);
app.provider('$postMessage', function() {
var $postMessageProvider = {
options: {
showConsole: false
},
$get: function() {
return angular.extend({}, $postMessageProvider.options);
}
};
return $postMessageProvider;
});
app.run([
'$window', '$rootScope', '$postMessage', 'postMessageService',
function($window, $rootScope, $postMessage, postMessageService) {
$rootScope.$on('$messageOutgoing', function(event, message, domain) {
var sender;
if (domain == null) {
domain = "*";
}
sender = $rootScope.sender || $window.parent;
return sender.postMessage(message, domain);
});
angular.element($window).bind('message', function(event) {
var response;
event = event.originalEvent || event;
if (event && event.data) {
response = null;
$rootScope.sender = event.source;
try {
response = angular.fromJson(event.data);
} catch (error) {
if ($postMessage.showConsole) {
console.error('ahem', error);
}
response = event.data;
}
$rootScope.$root.$broadcast('$messageIncoming', response);
return postMessageService.messages(response);
}
});
}
]);
app.factory('postMessageService', [
'$rootScope',
function($rootScope) {
var $messages, api;
$messages = [];
api = {
messages: function(_message_) {
if (_message_) {
$messages.push(_message_);
$rootScope.$digest();
}
return $messages;
},
lastMessage: function() {
return $messages[$messages.length - 1];
},
post: function(message, domain) {
if (!domain) {
domain = "*";
}
return $rootScope.$broadcast('$messageOutgoing', message, domain);
}
};
return api;
}
]);
}).call(this);
|
const path = require("path");
/**
* Render the app menu
* @returns {undefined}
*/
function render() {
console.log("Started: Menu rendering");
const menus = ['File', 'Edit', 'View'];
var template = [];
var menuBar = new nw.Menu({type: 'menubar'});
_.each(menus, function(menu) {
const configsBasePath = path.join('modules', 'menu'),
menuName = menu.toLowerCase(),
menuConfigPath = path.join(configsBasePath, menuName, menuName + 'MenuConfig'),
menuTemplate = rootRequire(menuConfigPath).getMenuTemplate();
var submenu = new nw.Menu();
_.each(menuTemplate.submenu, function(menuItem) {
submenu.append(new nw.MenuItem(menuItem));
});
menuBar.append(new nw.MenuItem({label: menu, submenu: submenu}));
});
nw.Window.get().menu = menuBar;
console.log("Completed: Menu rendering");
}
module.exports = {
'render' : render
} |
/**
* # QUEUE
* Copyright(c) 2015 Stefano Balietti
* MIT Licensed
*
* Handles a simple queue of operations
*/
(function(JSUS) {
"use strict";
var QUEUE = {};
QUEUE.getQueue = function() {
return new Queue();
};
/**
* ## Queue constructor
*/
function Queue() {
/**
* ### Queue.queue
*
* The list of functions waiting to be executed.
*/
this.queue = [];
/**
* ### Queue.inProgress
*
* The list of operations ids currently in progress.
*/
this.inProgress = {};
}
/**
* ### Queue.isReady
*
* Returns TRUE if no operation is in progress
*
* @return {boolean} TRUE, if no operation is in progress
*/
Queue.prototype.isReady = function() {
return JSUS.isEmpty(this.inProgress);
};
/**
* ### Queue.onReady
*
* Executes the specified callback once the queue has been cleared
*
* Multiple functions to execute can be added, and they are executed
* sequentially once the queue is cleared.
*
* If the queue is already cleared, the function is executed immediately.
*
* @param {function} cb The callback to execute
*/
Queue.prototype.onReady = function(cb) {
if ('function' !== typeof cb) {
throw new TypeError('Queue.onReady: cb must be function. Found: ' +
cb);
}
if (JSUS.isEmpty(this.inProgress)) cb();
else this.queue.push(cb);
};
/**
* ### Queue.add
*
* Adds an item to the _inProgress_ index
*
* @param {string} key A tentative key name
*
* @return {string} The unique key to be used to unregister the operation
*/
Queue.prototype.add = function(key) {
if (key && 'string' !== typeof key) {
throw new Error('Queue.add: key must be string.');
}
key = JSUS.uniqueKey(this.inProgress, key);
if ('string' !== typeof key) {
throw new Error('Queue.add: an error occurred ' +
'generating unique key.');
}
this.inProgress[key] = key;
return key;
};
/**
* ### Queue.remove
*
* Remove a specified key from the _inProgress_ index
*
* @param {string} key The key to remove from the _inProgress_ index.
*/
Queue.prototype.remove = function(key) {
if ('string' !== typeof key) {
throw new Error('Queue.remove: key must be string.');
}
delete this.inProgress[key];
if (JSUS.isEmpty(this.inProgress)) {
this.executeAndClear();
}
};
/**
* ### Queue.getRemoveCb
*
* Returns a callback to remove an item from the _inProgress_ index
*
* This method is useful when the callbacks is defined inside loops,
* so that a closure is created around the variable key.
*
* @param {string} key The key to remove from the _inProgress_ index.
*
* @see Queue.remove
*/
Queue.prototype.getRemoveCb = function(key) {
var that;
if ('string' !== typeof key) {
throw new Error('Queue.getRemoveCb: key must be string.');
}
that = this;
return function() { that.remove(key); };
};
/**
* ### Queue.executeAndClear
*
* Executes sequentially all callbacks, and removes them from the queue
*/
Queue.prototype.executeAndClear = function() {
var i, len;
i = -1;
len = this.queue.length;
for ( ; ++i < len ; ) {
this.queue[i]();
}
};
JSUS.extend(QUEUE);
})('undefined' !== typeof JSUS ? JSUS : module.parent.exports.JSUS);
|
var app = require('..');
var request = require('supertest');
describe('Home page', function () {
describe('GET /', function () {
it('should response 200 OK', function (done) {
request(app)
.get('/')
.expect(200, done);
});
});
}); |
require('ts-node/register')
global.assert = require('assert')
global.ES_SUPPORT = require('./support/es-support')
var CallLog = require('../src/value/call-log').default
var StubbingRegister = require('../src/value/stubbing-register').default
module.exports = {
beforeAll: function () {
require('./support/custom-assertions').default(assert)
},
beforeEach: function () {},
afterEach: function () {
td.reset()
td.config.reset()
CallLog.reset()
StubbingRegister.reset()
},
afterAll: function () {}
}
|
/*
* app.js: Common utility functions for working with directories
*
* (C) 2011, Nodejitsu Inc.
* MIT LICENSE
*
*/
var utile = require('utile'),
async = utile.async,
mkdirp = utile.mkdirp,
rimraf = utile.rimraf,
constants = require('../constants');
var directories = exports;
//
// ### function create (dirs, callback)
// #### @dirs {Object} Directories to create
// #### @callback {function} Continuation to respond to when complete
// Creates all of the specified `directories` in the current environment.
//
directories.create = function (dirs, callback) {
function createDir(dir, next) {
mkdirp(dir, 0755, function () {
next(null, dir);
});
}
if (!dirs) {
return callback();
}
async.mapSeries(Object.keys(dirs).map(function (key) {
return dirs[key]
}), createDir, callback);
};
//
// ### function remove (dirs, callback)
// #### @dirs {Object} Directories to remove
// #### @callback {function} Continuation to respond to when complete
// Removes all of the specified `directories` in the current environment.
//
directories.remove = function (dirs, callback) {
function removeDir (dir, next) {
rimraf(dir, function () {
next(null, dir);
});
}
if (!dirs) {
return callback();
}
async.mapSeries(Object.keys(dirs).map(function (key) {
return dirs[key]
}), removeDir, callback);
};
//
// ### function normalize (root, dirs)
// #### @root {string} Relative root of the application
// #### @dirs {Object} Set of directories to normalize.
// Normalizes the specified `dirs` against the relative
// `root` of the application.
//
directories.normalize = function (root, dirs) {
var normalized = {};
Object.keys(dirs).forEach(function (key) {
normalized[key] = dirs[key].replace(constants.ROOT, root);
});
return normalized;
}; |
(function(n,C,H,I){function D(b,a){this.element=b;t=n(b);this.options=n.extend({},E,a);this._defaults=E;this._name="WebCodeCam";this.init()&&(this.setEventListeners(),(this.options.ReadQRCode||this.options.ReadBarecode)&&this.setCallback())}var a,u,k,t,h,g,l={},e=n('<video style="position:absolute;visibility:hidden;display: none;">')[0],v=!1,F=!1,G=new Worker(WebBarCode+"assets/plugins/js/DecoderWorker.js"),m=!1,E={ReadQRCode:!0,ReadBarecode:!0,width:320,height:240,videoSource:{id:!0,maxWidth:640,maxHeight:480},flipVertical:!1,
flipHorizontal:!1,zoom:-1,beep:"js/beep.mp3",brightness:0,autoBrightnessValue:!1,grayScale:!1,contrast:0,threshold:0,sharpness:[],resultFunction:function(b,a){},getUserMediaError:function(){},cameraError:function(b){}};D.prototype={init:function(){a=this;k=a.element.getContext("2d");h=a.options.width;g=a.options.height;navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;if(navigator.getUserMedia)l[a.options.videoSource.id]&&
l[a.options.videoSource.id].active?a.cameraSuccess(l[a.options.videoSource.id]):navigator.getUserMedia({video:{mandatory:{maxWidth:a.options.videoSource.maxWidth,maxHeight:a.options.videoSource.maxHeight},optional:[{sourceId:a.options.videoSource.id}]},audio:!1},a.cameraSuccess,a.cameraError);else return a.options.getUserMediaError(),!1;return!0},cameraSuccess:function(b){l[a.options.videoSource.id]=b;var p=C.URL||C.webkitURL;e.src=p?p.createObjectURL(b):b;e.play()},cameraError:function(b){a.options.cameraError(b);
return!1},setEventListeners:function(){e.addEventListener("canplay",function(b){F||(0<e.videoWidth&&(g=e.videoHeight/(e.videoWidth/h)),t[0].setAttribute("width",h),t[0].setAttribute("height",g),a.options.flipHorizontal&&(k.scale(-1,1),k.translate(-h,0)),a.options.flipVertical&&(k.scale(1,-1),k.translate(0,-g)),F=!0,(a.options.ReadQRCode||a.options.ReadBarecode)&&a.delay())},!1);e.addEventListener("play",function(){setInterval(function(){if(!e.paused&&!e.ended){k.clearRect(0,0,h,g);var b=a.options.zoom;
0>b&&(b=a.optimalZoom());k.drawImage(e,(h*b-h)/-2,(g*b-g)/-2,h*b,g*b);b=k.getImageData(0,0,h,g);a.options.grayScale&&(b=a.grayScale(b));if(0!=a.options.brightness||0!=a.options.autoBrightnessValue)b=a.brightness(b,a.options.brightness);0!=a.options.contrast&&(b=a.contrast(b,a.options.contrast));0!=a.options.threshold&&(b=a.threshold(b,a.options.threshold));0!=a.options.sharpness.length&&(b=a.convolute(b,a.options.sharpness));k.putImageData(b,0,0)}},40)},!1)},setCallback:function(){G.onmessage=function(b){m||
e.paused||(b.data.success&&1<b.data.result[0].length&&-1==b.data.result[0].indexOf("undefined")?(a.beep(),m=!0,a.delay(),a.options.resultFunction(b.data.result[0],u)):b.data.finished&&(v=!v,setTimeout(function(){a.tryParseBarecode()},320)))};qrcode.callback=function(b){m||e.paused||(a.beep(),m=!0,a.delay(),a.options.resultFunction(b,u))}},tryParseBarecode:function(){var b=1==v?"flip":"normal";u=t[0].toDataURL();var a=k.getImageData(0,0,h,g).data;G.postMessage({ImageData:a,Width:h,Height:g,cmd:b,DecodeNr:1,
LowLight:!1})},tryParseQRCode:function(){try{u=t[0].toDataURL(),qrcode.decode()}catch(b){m||setTimeout(function(){a.tryParseQRCode()},320)}},delay:function(){a.cameraPlay(!0)},cameraStop:function(){m=!0;e.pause()},cameraStopAll:function(){k.clearRect(0,0,h,g);m=!0;e.pause();for(var b in l)l[b]&&(l[b].stop(),l[b]=null)},cameraPlay:function(b){l[a.options.videoSource.id]?b||a.cameraSuccess(l[a.options.videoSource.id]):a.init();m=!0;e.play();setTimeout(function(){m=!1;a.options.ReadBarecode&&a.tryParseBarecode();
a.options.ReadQRCode&&a.tryParseQRCode()},2E3)},getLastImageSrc:function(){return u},optimalZoom:function(b){return e.videoHeight/g},getImageLightness:function(){for(var b=k.getImageData(0,0,h,g).data,a=0,d,c,f,e=0,l=b.length;e<l;e+=4)d=b[e],c=b[e+1],f=b[e+2],d=Math.floor((d+c+f)/3),a+=d;return Math.floor(a/(h*g))},brightness:function(b,p){p=0==p&&0!=a.options.autoBrightnessValue?a.options.autoBrightnessValue-a.getImageLightness():p;for(var d=b.data,c=0;c<d.length;c+=4)d[c]+=p,d[c+1]+=p,d[c+2]+=p;
return b},grayScale:function(b){for(var a=b.data,d=0;d<a.length;d+=4)a[d]=a[d+1]=a[d+2]=.2126*a[d]+.7152*a[d+1]+.0722*a[d+2];return b},contrast:function(b,a){for(var d=b.data,c=0;c<d.length;c+=4){a=10;var f=Math.round((d[c]+d[c+1]+d[c+2])/3);127<f?(d[c]+=d[c]/f*a,d[c+1]+=d[c+1]/f*a,d[c+2]+=d[c+2]/f*a):(d[c]-=d[c]/f*a,d[c+1]-=d[c+1]/f*a,d[c+2]-=d[c+2]/f*a)}return b},threshold:function(a,e){for(var d,c=a.data,f=0,k=h*g*4;f<k;f+=4)d=c[f]+c[f+1]+c[f+2],c[f]=d<e?c[f+1]=c[f+2]=0:c[f+1]=c[f+2]=255,c[f+3]=
255;return a},convolute:function(a,e,d){var c=a.width,f=a.height,g=Math.round(Math.sqrt(e.length)),h=Math.floor(g/2);a=a.data;var k=H.createElement("canvas").getContext("2d").createImageData(c,f),l=k.data;d=d?1:0;for(var m=0;m<f;m++)for(var n=0;n<c;n++){for(var t=m,u=n,v=0,A=0,B=0,w=0,x=4*(m*c+n),y=0;y<g;y++)for(var z=0;z<g;z++){var q=t+y-h,r=u+z-h;0<=q&&q<f&&0<=r&&r<c&&(q=4*(q*c+r),r=e[y*g+z],v+=a[q]*r,A+=a[q+1]*r,B+=a[q+2]*r,w+=a[q+3]*r)}l[x]=v;l[x+1]=A;l[x+2]=B;l[x+3]=w+d*(255-w)}return k},beep:function(){if("string"==
typeof a.options.beep){var b=a.options.beep;setTimeout(function(){(new Audio(b)).play()},0)}}};n.fn.WebCodeCam=function(a){return this.each(function(){n.data(this,"plugin_WebCodeCam")||n.data(this,"plugin_WebCodeCam",new D(this,a))})}})(jQuery,window,document); |
module.exports = function (schema) {
const promise = require('bluebird');
return {
defineCreateExperimentSchema,
defineUpdateExperimentSchema,
defineCreateExperimentTaskSchema,
defineUpdateExperimentTaskSchema,
defineCreateExperimentNoteSchema,
defineUpdateExperimentNoteSchema,
defineUpdateExperimentTaskTemplatePropsSchema,
defineTemplatePropertySchema,
defineTemplateCommandSchema
};
function defineCreateExperimentSchema() {
let createExperimentSchema = schema.defineSchema('CreateExperiment', {
project_id: {
type: 'string',
nullable: false
},
name: {
type: 'string',
nullable: false
},
aim: {
type: 'string',
nullable: false
},
goal: {
type: 'string',
nullable: false
},
status: {
type: 'string',
nullable: false,
isValidExperimentStatus: true
},
description: {
type: 'string'
}
});
createExperimentSchema.setDefaults({
aim: '',
goal: '',
description: '',
status: 'active'
});
createExperimentSchema.validateAsync = promise.promisify(createExperimentSchema.validate);
return createExperimentSchema;
}
function defineUpdateExperimentSchema() {
let updateExperimentSchema = schema.defineSchema('UpdateExperiment', {
name: {
type: 'string',
nullable: true
},
description: {
type: 'string',
nullable: true
},
note: {
type: 'string',
nullable: true
},
goals: {
type: 'array',
nullable: true
},
collaborators: {
type: 'array',
nullable: true
},
funding: {
type: 'array',
nullable: true
},
citations: {
type: 'array',
nullable: true
},
papers: {
type: 'array',
nullable: true
},
publications: {
type: 'array',
nullable: true
},
status: {
type: 'string',
nullable: true
}
});
updateExperimentSchema.setDefaults({});
updateExperimentSchema.validateAsync = promise.promisify(updateExperimentSchema.validate);
return updateExperimentSchema;
}
function defineCreateExperimentTaskSchema() {
let createExperimentTaskSchema = schema.defineSchema('CreateExperimentTask', {
name: {
type: 'string',
nullable: false
},
note: {
type: 'string',
nullable: false
},
parent_id: {
type: 'string',
nullable: false
},
index: {
type: 'integer',
nullable: false,
min: 0
}
});
createExperimentTaskSchema.setDefaults({parent_id: '', note: ''});
createExperimentTaskSchema.validateAsync = promise.promisify(createExperimentTaskSchema.validate);
return createExperimentTaskSchema;
}
function defineUpdateExperimentTaskSchema() {
let updateExperimentTaskSchema = schema.defineSchema('UpdateExperimentTask', {
name: {
type: 'string',
nullable: true
},
note: {
type: 'string',
nullable: true
},
parent_id: {
type: 'string',
nullable: true
},
flags: {
nullable: true,
flagged: {
type: 'boolean',
nullable: true
},
done: {
type: 'boolean',
nullable: true
},
starred: {
type: 'boolean',
nullable: true
}
},
swap: {
nullable: true,
task_id: {
type: 'string',
nullable: true
}
}
});
updateExperimentTaskSchema.setDefaults({parent_id: ''});
updateExperimentTaskSchema.validateAsync = promise.promisify(updateExperimentTaskSchema.validate);
return updateExperimentTaskSchema;
}
function defineCreateExperimentNoteSchema() {
let createExperimentNoteSchema = schema.defineSchema('CreateExperimentNote', {
name: {
type: 'string',
nullable: false
},
note: {
type: 'string',
nullable: false
}
});
createExperimentNoteSchema.setDefaults({});
createExperimentNoteSchema.validateAsync = promise.promisify(createExperimentNoteSchema.validate);
return createExperimentNoteSchema;
}
function defineUpdateExperimentNoteSchema() {
let updateExperimentNoteSchema = schema.defineSchema('UpdateExperimentNote', {
name: {
type: 'string'
},
note: {
type: 'string'
}
});
updateExperimentNoteSchema.setDefaults({});
updateExperimentNoteSchema.validateAsync = promise.promisify(updateExperimentNoteSchema.validate);
return updateExperimentNoteSchema;
}
function defineUpdateExperimentTaskTemplatePropsSchema() {
let updateExperimentTaskTemplatePropsSchema = schema.defineSchema('updateExperimentTaskTemplatePropsSchema', {
properties: {
type: 'array',
nullable: false
},
template_id: {
type: 'string',
nullable: false
}
});
updateExperimentTaskTemplatePropsSchema.setDefaults({});
updateExperimentTaskTemplatePropsSchema.validateAsync = promise.promisify(updateExperimentTaskTemplatePropsSchema.validate);
return updateExperimentTaskTemplatePropsSchema;
}
function defineTemplatePropertySchema() {
let templatePropertySchema = schema.defineSchema('templatePropertySchema', {
id: {
type: 'string',
nullable: false
},
otype: {
type: 'string',
nullable: false
},
setup_attribute: {
type: 'string',
nullable: false
},
setup_id: {
type: 'string',
nullable: false
},
attribute: {
type: 'string',
nullable: false
},
description: {
type: 'string',
nullable: false
},
name: {
type: 'string',
nullable: false
},
unit: {
type: 'string',
nullable: true
},
value: {
nullable: false
}
});
templatePropertySchema.setDefaults({
unit: ''
});
templatePropertySchema.validateAsync = promise.promisify(templatePropertySchema.validate);
return templatePropertySchema;
}
function defineTemplateCommandSchema() {
let templateCommandSchema = schema.defineSchema('templateCommandSchema', {
id: {
type: 'string',
nullable: false
},
property_set_id: {
type: 'string',
nullable: true
},
command: {
type: 'string',
nullable: false
},
direction: {
type: 'string',
nullable: true,
},
transform: {
type: 'boolean',
nullable: true,
}
});
templateCommandSchema.setDefaults({
property_set_id: '',
direction: '',
transform: true,
});
templateCommandSchema.validateAsync = promise.promisify(templateCommandSchema.validate);
return templateCommandSchema;
}
};
|
/**
* DevExtreme (framework/navigation_devices.js)
* Version: 16.2.6
* Build date: Tue Mar 28 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
Class = require("../core/class"),
browserAdapters = require("./browser_adapters"),
SessionStorage = require("../core/utils/storage").sessionStorage,
devices = require("../core/devices");
var SESSION_KEY = "dxPhoneJSApplication";
var HistoryBasedNavigationDevice = Class.inherit({
ctor: function(options) {
options = options || {};
this._browserAdapter = options.browserAdapter || this._createBrowserAdapter(options);
this.uriChanged = $.Callbacks();
this._browserAdapter.popState.add($.proxy(this._onPopState, this))
},
init: $.noop,
getUri: function() {
return this._browserAdapter.getHash()
},
setUri: function(uri, replaceCurrent) {
if (replaceCurrent) {
return this._browserAdapter.replaceState(uri)
} else {
if (uri !== this.getUri()) {
return this._browserAdapter.pushState(uri)
} else {
return $.Deferred().resolve().promise()
}
}
},
back: function() {
return this._browserAdapter.back()
},
_onPopState: function() {
this.uriChanged.fire(this.getUri())
},
_isBuggyAndroid2: function() {
var realDevice = devices.real();
var version = realDevice.version;
return "android" === realDevice.platform && version.length > 1 && (2 === version[0] && version[1] < 4 || version[0] < 2)
},
_isBuggyAndroid4: function() {
var realDevice = devices.real();
var version = realDevice.version;
return "android" === realDevice.platform && version.length > 1 && 4 === version[0] && 0 === version[1]
},
_isWindowsPhone8: function() {
var realDevice = devices.real();
return "win" === realDevice.platform && realDevice.phone
},
_createBrowserAdapter: function(options) {
var result, sourceWindow = options.window || window,
supportPushReplace = sourceWindow.history.replaceState && sourceWindow.history.pushState;
if (this._isWindowsPhone8()) {
result = new browserAdapters.BuggyCordovaWP81BrowserAdapter(options)
} else {
if (sourceWindow !== sourceWindow.top) {
result = new browserAdapters.HistorylessBrowserAdapter(options)
} else {
if (this._isBuggyAndroid4()) {
result = new browserAdapters.BuggyAndroidBrowserAdapter(options)
} else {
if (this._isBuggyAndroid2() || !supportPushReplace) {
result = new browserAdapters.OldBrowserAdapter(options)
} else {
result = new browserAdapters.DefaultBrowserAdapter(options)
}
}
}
}
return result
}
});
var StackBasedNavigationDevice = HistoryBasedNavigationDevice.inherit({
ctor: function(options) {
this.callBase(options);
this.backInitiated = $.Callbacks();
this._rootStateHandler = null;
$(window).on("unload", this._saveBrowserState)
},
init: function() {
var that = this;
if (that._browserAdapter.canWorkInPureBrowser) {
return that._initRootPage().done(function() {
if (that._browserAdapter.isRootPage()) {
that._browserAdapter.pushState("")
}
})
} else {
return $.Deferred().resolve().promise()
}
},
setUri: function(uri) {
return this.callBase(uri, !this._browserAdapter.isRootPage())
},
_saveBrowserState: function() {
var sessionStorage = SessionStorage();
if (sessionStorage) {
sessionStorage.setItem(SESSION_KEY, true)
}
},
_initRootPage: function() {
var hash = this.getUri(),
sessionStorage = SessionStorage();
if (!sessionStorage || sessionStorage.getItem(SESSION_KEY)) {
return $.Deferred().resolve().promise()
}
sessionStorage.removeItem(SESSION_KEY);
this._browserAdapter.createRootPage();
return this._browserAdapter.pushState(hash)
},
_onPopState: function() {
if (this._browserAdapter.isRootPage()) {
if (this._rootStateHandler) {
this._rootStateHandler()
} else {
this.backInitiated.fire()
}
} else {
if (!this._rootStateHandler) {
this._createRootStateHandler()
}
this.back()
}
},
_createRootStateHandler: function() {
var uri = this.getUri();
this._rootStateHandler = function() {
this.uriChanged.fire(uri);
this._rootStateHandler = null
}
}
});
exports.HistoryBasedNavigationDevice = HistoryBasedNavigationDevice;
exports.StackBasedNavigationDevice = StackBasedNavigationDevice;
|
var express = require('express');
var router = express.Router();
var fs = require('fs');
var jsonfile = require('jsonfile');
var session = require('express-session');
var request = require('request');
var SparqlClient = require('sparql-client');
var shell = require('shelljs');
var endpointPortNumber = process.argv.slice(2)[1] || 3030;
var endpoint = 'http:\//localhost:' + endpointPortNumber.toString() +
'/dataset/sparql';
var client = new SparqlClient(endpoint);
var escapeHtml = require('escape-html');
const ejs = require('ejs');
// GET home page.
router.get('/', function(req, res) {
if (!req.session.isAuthenticated && req.app.locals.authRequired)
res.render('login', {
title: 'login'
});
else {
var acceptHeader = req.headers['accept'];
// return all turtle code inside fuseki endpoint if content-type is turtle
if (acceptHeader === 'text/turtle' ||
acceptHeader === 'text/ntriples' ||
acceptHeader === 'application/rdf+xml' ||
acceptHeader === 'application/ld+json') {
var queryObject = 'CONSTRUCT{?s ?p ?o .}WHERE {?s ?p ?o .}';
var endpoint = "http:\/\/localhost:" + process.argv.slice(2)[1] ||
3030 + "/dataset/sparql?query="
request({
url: endpoint + queryObject,
headers: {
'accept': acceptHeader
},
}, function(error, response, body) {
if (error) {
console.log('error:', error); // Print the error if one occurred
} else if (response && body) {
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
if (body) {
res.write("RDF code in " + acceptHeader + ":\n");
res.write(
"========================================================\n"
);
res.write(body);
res.end();
} else {
res.send("No data is found ");
}
}
})
} else {
var metaData = "";
var statistics = "";
var query_r = {};
var qe = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
PREFIX owl: <http://www.w3.org/2002/07/owl#> \
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\
SELECT \
(count(?cls) as ?Classes)\
(count(?rdfProperty) as ?RDF_Property)\
(count(?objProp) as ?OWL_ObjectProperty) \
(count(?dtProp) as ?OWL_DatatypeProperty) \
(count(?annot) as ?OWL_AnnotationProperty)\
(count(?indiv) as ?Individuals)\
WHERE {{?objProp a owl:ObjectProperty.} \
UNION {?dtProp a owl:DatatypeProperty.}\
UNION {?indiv a owl:NamedIndividual.} \
UNION {?annot a owl:AnnotationProperty.} \
UNION {?cls a rdfs:Class. FILTER(!isBlank(?cls))} \
UNION {?cls a owl:Class. FILTER(!isBlank(?cls))} \
UNION {?rdfProperty a rdf:Property.} \
}";
var qOnt = "PREFIX owl: <http://www.w3.org/2002/07/owl#> \
SELECT ?p ?o\
WHERE {\
?s a owl:Ontology.\
OPTIONAL { ?s ?p ?o.}}";
// check if fuseki endpoint is running
var output = shell.exec('fuser -v -n tcp ' + endpointPortNumber.toString(), {
silent: false
}).stdout;
if (output) {
client.query(qOnt, function(error, data) { // query on dataset.
if (error) {
console.log(error);
}
var result = data.results.bindings;
if (result[0] != null) {
// json values of the query result
metaData = result;
}
client.query(qe, function(error, data) { // query on dataset.
if (error) {
console.log(error);
}
if (data) {
// string to hold table content
statistics = "";
for (key in data['results']['bindings'][0]) {
var obj = data['results']['bindings'][0][key][
'value'
];
if (key == "RDF_Property")
key = "RDF Properties";
if (key == "OWL_ObjectProperty")
key = "OWL ObjectProperties";
if (key == "OWL_DatatypeProperty")
key = "OWL DatatypeProperties";
if (key == "OWL_AnnotationProperty")
key = "OWL AnnotationProperties";
statistics += '<tr><td class="td_content">' +
key +
'</td><td class="right aligned">' + obj +
'</td></tr>';
}
}
// check if the userConfigurations file is exist
// for the first time of app running
var path = "jsonDataFiles/userConfigurations.json";
fs.exists(path, function(exists) {
var data = fs.readFileSync(path);
if (exists && data.includes('vocabularyName')) {
jsonfile.readFile(path, function(err, obj) {
if (err)
console.log(err);
if (obj.hasOwnProperty(
'vocabularyName')) {
// string to hold table content
var repoInfo = "";
repoInfo += '<tr><td class="td_content"> Instance Name</td><td class="right aligned">' +
obj.vocabularyName + '</td></tr>';
repoInfo += '<tr><td class="td_content"> Repository Owner </td><td class="right aligned">' +
obj.repositoryOwner +
'</td></tr>';
repoInfo += '<tr><td class="td_content"> Repository Service </td><td class="right aligned">' +
obj.repositoryService +
'</td></tr>';
repoInfo += '<tr><td class="td_content"> Repository Branch </td><td class="right aligned">' +
obj.branchName + '</td></tr>';
res.render('index', {
title: 'Home',
metaData: metaData,
statistics: statistics,
repoInfo: repoInfo,
homePage: obj.text
});
}
});
}
});
});
});
} else {
// check if the userConfigurations file is exist
// for the first time of app running
var path = "jsonDataFiles/userConfigurations.json";
fs.exists(path, function(exists) {
var data = fs.readFileSync(path);
if (exists && data.includes('vocabularyName')) {
jsonfile.readFile(path, function(err, obj) {
if (err)
console.log(err);
if (obj.hasOwnProperty('text'))
res.render('index', {
title: 'Home',
metaData: "",
statistics: "",
repoInfo: "",
homePage: obj.text
});
});
}
});
}
}
}
});
module.exports = router;
|
const GelatoView = require('./view');
/**
* @class GelatoComponent
* @extends {GelatoView}
*/
const GelatoComponent = GelatoView.extend({
/**
* Instance variable to represent whether the component has fully loaded
* @type {Boolean}
*/
loaded: false,
/**
* Renders a component's template with a supplied context
* @method renderTemplate
* @param {Object} [context]
* @returns {GelatoPage}
*/
renderTemplate: function (context) {
return GelatoView.prototype.renderTemplate.call(this, context);
},
/**
* Removes a component and any listeners
* @method remove
* @returns {GelatoPage}
*/
remove: function () {
return GelatoView.prototype.remove.call(this);
},
});
module.exports = GelatoComponent;
|
'use strict';
if (!MODULE) { var MODULE = {}; }
MODULE.Modal = (function() {
var MODAL_HIDE_TIME = 300;
var Modal = function() {
this.background = document.getElementById('modal');
this.modal = this.background.getElementsByClassName('modal')[0];
this.content = this.modal.getElementsByClassName('content')[0];
this.buttons = this.modal.getElementsByClassName('buttons')[0];
this.visible = false;
};
Modal.prototype.show = function(content, buttons, small) {
var self = this;
buttons = buttons || [{
text: 'Ok',
highlight: true
}];
this.empty();
this.content.innerHTML = content;
buttons.forEach(function(data) {
var button = document.createElement('button');
var text = document.createTextNode(data.text);
button.appendChild(text);
if (data.highlight) {
button.classList.add('cycle');
}
button.onclick = function() {
self.fadeOut(data.callback);
};
self.buttons.appendChild(button);
});
this.modal.classList.toggle('small', !!small);
this.background.classList.add('visible');
this.visible = true;
};
Modal.prototype.fadeOut = function(callback) {
this.background.classList.remove('visible');
this.visible = false;
setTimeout(function() {
this.empty();
if (callback) callback();
}.bind(this), MODAL_HIDE_TIME);
};
Modal.prototype.hide = function() {
this.background.classList.remove('visible');
this.visible = false;
this.empty();
};
Modal.prototype.empty = function() {
this.content.innerHTML = '';
this.buttons.innerHTML = '';
};
return Modal;
}());
|
var struct_tempest_1_1_graphics_subsystem_1_1_event =
[
[ "Type", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#aee9c81a4df7bf24670fbec79fc13054d", [
[ "NoEvent", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#aee9c81a4df7bf24670fbec79fc13054daaeebaee15a70b7270c8ad9a377a4a968", null ],
[ "DeleteObject", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#aee9c81a4df7bf24670fbec79fc13054da32fef920f5141c583a0192f3d7d04e5d", null ],
[ "Count", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#aee9c81a4df7bf24670fbec79fc13054da385304d774f635be40209d8afda2386a", null ]
] ],
[ "Event", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#ab45be1c9feb60b9660d597704296b300", null ],
[ "type", "struct_tempest_1_1_graphics_subsystem_1_1_event.html#a6f95f8855a6d2008b6988aa941ecee20", null ]
]; |
(function UMDish(name, context, definition) { context[name] = definition.call(context); if (typeof module !== "undefined" && module.exports) { module.exports = context[name]; } else if (typeof define == "function" && define.amd) { define(function reference() { return context[name]; }); }})("Primus", this, function Primus() {/*globals require, define */
'use strict';
/**
* Representation of a single EventEmitter function.
*
* @param {Function} fn Event handler to be called.
* @param {Mixed} context Context for function execution.
* @param {Boolean} once Only emit once
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal EventEmitter interface that is molded against the Node.js
* EventEmitter interface.
*
* @constructor
* @api public
*/
function EventEmitter() { /* Nothing to set */ }
/**
* Holds the assigned EventEmitters by name.
*
* @type {Object}
* @private
*/
EventEmitter.prototype._events = undefined;
/**
* Return a list of assigned event listeners.
*
* @param {String} event The events that should be listed.
* @returns {Array}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event) {
if (!this._events || !this._events[event]) return [];
if (this._events[event].fn) return [this._events[event].fn];
for (var i = 0, l = this._events[event].length, ee = new Array(l); i < l; i++) {
ee[i] = this._events[event][i].fn;
}
return ee;
};
/**
* Emit an event to all registered event listeners.
*
* @param {String} event The name of the event.
* @returns {Boolean} Indication if we've emitted an event.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
if (!this._events || !this._events[event]) return false;
var listeners = this._events[event]
, len = arguments.length
, args
, i;
if ('function' === typeof listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Register a new EventListener for the given event.
*
* @param {String} event Name of the event.
* @param {Functon} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Add an EventListener that's only called once.
*
* @param {String} event Name of the event.
* @param {Function} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Remove event listeners.
*
* @param {String} event The event we want to remove.
* @param {Function} fn The listener that we need to find.
* @param {Boolean} once Only remove once listeners.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, once) {
if (!this._events || !this._events[event]) return this;
var listeners = this._events[event]
, events = [];
if (fn) {
if (listeners.fn && (listeners.fn !== fn || (once && !listeners.once))) {
events.push(listeners);
}
if (!listeners.fn) for (var i = 0, length = listeners.length; i < length; i++) {
if (listeners[i].fn !== fn || (once && !listeners[i].once)) {
events.push(listeners[i]);
}
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) {
this._events[event] = events.length === 1 ? events[0] : events;
} else {
delete this._events[event];
}
return this;
};
/**
* Remove all listeners or only the listeners for the specified event.
*
* @param {String} event The event want to remove all listeners for.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
if (!this._events) return this;
if (event) delete this._events[event];
else this._events = {};
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
/**
* Context assertion, ensure that some of our public Primus methods are called
* with the correct context to ensure that
*
* @param {Primus} self The context of the function.
* @param {String} method The method name.
* @api private
*/
function context(self, method) {
if (self instanceof Primus) return;
var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance');
if ('function' !== typeof self.listeners || !self.listeners('error').length) {
throw failure;
}
self.emit('error', failure);
}
//
// Sets the default connection URL, it uses the default origin of the browser
// when supported but degrades for older browsers. In Node.js, we cannot guess
// where the user wants to connect to, so we just default to localhost.
//
var defaultUrl;
try {
if (location.origin) {
defaultUrl = location.origin;
} else {
defaultUrl = location.protocol +'//'+ location.hostname + (location.port ? ':'+ location.port : '');
}
} catch (e) {
defaultUrl = 'http://127.0.0.1';
}
/**
* Primus in a real-time library agnostic framework for establishing real-time
* connections with servers.
*
* Options:
* - reconnect, configuration for the reconnect process.
* - manual, don't automatically call `.open` to start the connection.
* - websockets, force the use of WebSockets, even when you should avoid them.
* - timeout, connect timeout, server didn't respond in a timely manner.
* - ping, The heartbeat interval for sending a ping packet to the server.
* - pong, The heartbeat timeout for receiving a response to the ping.
* - network, Use network events as leading method for network connection drops.
* - strategy, Reconnection strategies.
* - transport, Transport options.
* - url, uri, The URL to use connect with the server.
*
* @constructor
* @param {String} url The URL of your server.
* @param {Object} options The configuration.
* @api public
*/
function Primus(url, options) {
if (!(this instanceof Primus)) return new Primus(url, options);
if ('function' !== typeof this.client) {
var message = 'The client library has not been compiled correctly, ' +
'see https://github.com/primus/primus#client-library for more details';
return this.critical(new Error(message));
}
if ('object' === typeof url) {
options = url;
url = options.url || options.uri || defaultUrl;
} else {
options = options || {};
}
var primus = this;
// The maximum number of messages that can be placed in queue.
options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
// Connection timeout duration.
options.timeout = 'timeout' in options ? options.timeout : 10e3;
// Stores the back off configuration.
options.reconnect = 'reconnect' in options ? options.reconnect : {};
// Heartbeat ping interval.
options.ping = 'ping' in options ? options.ping : 25000;
// Heartbeat pong response timeout.
options.pong = 'pong' in options ? options.pong : 10e3;
// Reconnect strategies.
options.strategy = 'strategy' in options ? options.strategy : [];
// Custom transport options.
options.transport = 'transport' in options ? options.transport : {};
primus.buffer = []; // Stores premature send data.
primus.writable = true; // Silly stream compatibility.
primus.readable = true; // Silly stream compatibility.
primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
primus.readyState = Primus.CLOSED; // The readyState of the connection.
primus.options = options; // Reference to the supplied options.
primus.timers = {}; // Contains all our timers.
primus.attempt = null; // Current back off attempt.
primus.socket = null; // Reference to the internal connection.
primus.latency = 0; // Latency between messages.
primus.stamps = 0; // Counter to make timestamps unqiue.
primus.disconnect = false; // Did we receive a disconnect packet?
primus.transport = options.transport; // Transport options.
primus.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
//
// Parse the reconnection strategy. It can have the following strategies:
//
// - timeout: Reconnect when we have a network timeout.
// - disconnect: Reconnect when we have an unexpected disconnect.
// - online: Reconnect when we're back online.
//
if ('string' === typeof options.strategy) {
options.strategy = options.strategy.split(/\s?\,\s?/g);
}
if (false === options.strategy) {
//
// Strategies are disabled, but we still need an empty array to join it in
// to nothing.
//
options.strategy = [];
} else if (!options.strategy.length) {
options.strategy.push('disconnect', 'online');
//
// Timeout based reconnection should only be enabled conditionally. When
// authorization is enabled it could trigger.
//
if (!this.authorization) options.strategy.push('timeout');
}
options.strategy = options.strategy.join(',').toLowerCase();
//
// Only initialise the EventEmitter interface if we're running in a plain
// browser environment. The Stream interface is inherited differently when it
// runs on browserify and on Node.js.
//
if (!Stream) EventEmitter.call(primus);
//
// Force the use of WebSockets, even when we've detected some potential
// broken WebSocket implementation.
//
if ('websockets' in options) {
primus.AVOID_WEBSOCKETS = !options.websockets;
}
//
// Force or disable the use of NETWORK events as leading client side
// disconnection detection.
//
if ('network' in options) {
primus.NETWORK_EVENTS = options.network;
}
//
// Check if the user wants to manually initialise a connection. If they don't,
// we want to do it after a really small timeout so we give the users enough
// time to listen for `error` events etc.
//
if (!options.manual) primus.timers.open = setTimeout(function open() {
primus.clearTimeout('open').open();
}, 0);
primus.initialise(options);
}
/**
* Simple require wrapper to make browserify, node and require.js play nice.
*
* @param {String} name The module to require.
* @returns {Object|Undefined} The module that we required.
* @api private
*/
Primus.require = function requires(name) {
if ('function' !== typeof require) return undefined;
return !('function' === typeof define && define.amd)
? require(name)
: undefined;
};
//
// It's possible that we're running in Node.js or in a Node.js compatible
// environment such as browserify. In these cases we want to use some build in
// libraries to minimize our dependence on the DOM.
//
var Stream, parse;
try {
Primus.Stream = Stream = Primus.require('stream');
parse = Primus.require('url').parse;
//
// Normally inheritance is done in the same way as we do in our catch
// statement. But due to changes to the EventEmitter interface in Node 0.10
// this will trigger annoying memory leak warnings and other potential issues
// outlined in the issue linked below.
//
// @see https://github.com/joyent/node/issues/4971
//
Primus.require('util').inherits(Primus, Stream);
} catch (e) {
Primus.Stream = EventEmitter;
Primus.prototype = new EventEmitter();
//
// In the browsers we can leverage the DOM to parse the URL for us. It will
// automatically default to host of the current server when we supply it path
// etc.
//
parse = function parse(url) {
var a = document.createElement('a')
, data = {}
, key;
a.href = url;
//
// Transform it from a readOnly object to a read/writable object so we can
// change some parsed values. This is required if we ever want to override
// a port number etc. (as browsers remove port 443 and 80 from the URL's).
//
for (key in a) {
if ('string' === typeof a[key] || 'number' === typeof a[key]) {
data[key] = a[key];
}
}
//
// We need to make sure that the URL is properly encoded because IE doesn't
// do this automatically.
//
data.href = encodeURI(decodeURI(data.href));
//
// If we don't obtain a port number (e.g. when using zombie) then try
// and guess at a value from the 'href' value.
//
if (!data.port) {
var splits = (data.href || '').split('/');
if (splits.length > 2) {
var host = splits[2]
, atSignIndex = host.lastIndexOf('@');
if (~atSignIndex) host = host.slice(atSignIndex + 1);
splits = host.split(':');
if (splits.length === 2) data.port = splits[1];
}
}
//
// IE quirk: The `protocol` is parsed as ":" or "" when a protocol agnostic
// URL is used. In this case we extract the value from the `href` value.
//
if (!data.protocol || ':' === data.protocol) {
data.protocol = data.href.substr(0, data.href.indexOf(':') + 1);
}
//
// Safari 5.1.7 (windows) quirk: When parsing a URL without a port number
// the `port` in the data object will default to "0" instead of the expected
// "". We're going to do an explicit check on "0" and force it to "".
//
if ('0' === data.port) data.port = '';
//
// Browsers do not parse authorization information, so we need to extract
// that from the URL.
//
if (~data.href.indexOf('@') && !data.auth) {
var start = data.protocol.length + 2;
data.auth = data.href.slice(start, data.href.indexOf(data.pathname, start)).split('@')[0];
}
return data;
};
}
/**
* Primus readyStates, used internally to set the correct ready state.
*
* @type {Number}
* @private
*/
Primus.OPENING = 1; // We're opening the connection.
Primus.CLOSED = 2; // No active connection.
Primus.OPEN = 3; // The connection is open.
/**
* Are we working with a potentially broken WebSockets implementation? This
* boolean can be used by transformers to remove `WebSockets` from their
* supported transports.
*
* @type {Boolean}
* @private
*/
Primus.prototype.AVOID_WEBSOCKETS = false;
/**
* Some browsers support registering emitting `online` and `offline` events when
* the connection has been dropped on the client. We're going to detect it in
* a simple `try {} catch (e) {}` statement so we don't have to do complicated
* feature detection.
*
* @type {Boolean}
* @private
*/
Primus.prototype.NETWORK_EVENTS = false;
Primus.prototype.online = true;
try {
if (
Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator
&& (window.addEventListener || document.body.attachEvent)
) {
if (!navigator.onLine) {
Primus.prototype.online = false;
}
}
} catch (e) { }
/**
* The Ark contains all our plugins definitions. It's namespaced by
* name => plugin.
*
* @type {Object}
* @private
*/
Primus.prototype.ark = {};
/**
* Return the given plugin.
*
* @param {String} name The name of the plugin.
* @returns {Object|undefined} The plugin or undefined.
* @api public
*/
Primus.prototype.plugin = function plugin(name) {
context(this, 'plugin');
if (name) return this.ark[name];
var plugins = {};
for (name in this.ark) {
plugins[name] = this.ark[name];
}
return plugins;
};
/**
* Checks if the given event is an emitted event by Primus.
*
* @param {String} evt The event name.
* @returns {Boolean} Indication of the event is reserved for internal use.
* @api public
*/
Primus.prototype.reserved = function reserved(evt) {
return (/^(incoming|outgoing)::/).test(evt)
|| evt in this.reserved.events;
};
/**
* The actual events that are used by the client.
*
* @type {Object}
* @public
*/
Primus.prototype.reserved.events = {
readyStateChange: 1,
reconnecting: 1,
reconnected: 1,
reconnect: 1,
offline: 1,
timeout: 1,
online: 1,
error: 1,
close: 1,
open: 1,
data: 1,
end: 1
};
/**
* Initialise the Primus and setup all parsers and internal listeners.
*
* @param {Object} options The original options object.
* @returns {Primus}
* @api private
*/
Primus.prototype.initialise = function initialise(options) {
var primus = this
, start;
primus.on('outgoing::open', function opening() {
var readyState = primus.readyState;
primus.readyState = Primus.OPENING;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'opening');
}
start = +new Date();
});
primus.on('incoming::open', function opened() {
var readyState = primus.readyState
, reconnect = primus.attempt;
if (primus.attempt) primus.attempt = null;
//
// The connection has been openend so we should set our state to
// (writ|read)able so our stream compatibility works as intended.
//
primus.writable = true;
primus.readable = true;
//
// Make sure we are flagged as `online` as we've successfully opened the
// connection.
//
if (!primus.online) {
primus.online = true;
primus.emit('online');
}
primus.readyState = Primus.OPEN;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'open');
}
primus.latency = +new Date() - start;
primus.emit('open');
if (reconnect) primus.emit('reconnected');
primus.clearTimeout('ping', 'pong').heartbeat();
if (primus.buffer.length) {
var data = primus.buffer.slice()
, length = data.length
, i = 0;
primus.buffer.length = 0;
for (; i < length; i++) {
primus._write(data[i]);
}
}
});
primus.on('incoming::pong', function pong(time) {
primus.online = true;
primus.clearTimeout('pong').heartbeat();
primus.latency = (+new Date()) - time;
});
primus.on('incoming::error', function error(e) {
var connect = primus.timers.connect
, err = e;
//
// We're still doing a reconnect attempt, it could be that we failed to
// connect because the server was down. Failing connect attempts should
// always emit an `error` event instead of a `open` event.
//
if (primus.attempt) return primus.reconnect();
//
// When the error is not an Error instance we try to normalize it.
//
if ('string' === typeof e) {
err = new Error(e);
} else if (!(e instanceof Error) && 'object' === typeof e) {
//
// BrowserChannel and SockJS returns an object which contains some
// details of the error. In order to have a proper error we "copy" the
// details in an Error instance.
//
err = new Error(e.message || e.reason);
for (var key in e) {
if (e.hasOwnProperty(key)) err[key] = e[key];
}
}
if (primus.listeners('error').length) primus.emit('error', err);
//
// We received an error while connecting, this most likely the result of an
// unauthorized access to the server.
//
if (connect) {
if (~primus.options.strategy.indexOf('timeout')) primus.reconnect();
else primus.end();
}
});
primus.on('incoming::data', function message(raw) {
primus.decoder(raw, function decoding(err, data) {
//
// Do a "save" emit('error') when we fail to parse a message. We don't
// want to throw here as listening to errors should be optional.
//
if (err) return primus.listeners('error').length && primus.emit('error', err);
//
// Handle all "primus::" prefixed protocol messages.
//
if (primus.protocol(data)) return;
primus.transforms(primus, primus, 'incoming', data, raw);
});
});
primus.on('incoming::end', function end() {
var readyState = primus.readyState;
//
// This `end` started with the receiving of a primus::server::close packet
// which indicated that the user/developer on the server closed the
// connection and it was not a result of a network disruption. So we should
// kill the connection without doing a reconnect.
//
if (primus.disconnect) {
primus.disconnect = false;
return primus.end();
}
//
// Always set the readyState to closed, and if we're still connecting, close
// the connection so we're sure that everything after this if statement block
// is only executed because our readyState is set to `open`.
//
primus.readyState = Primus.CLOSED;
if (readyState !== primus.readyState) {
primus.emit('readyStateChange', 'end');
}
if (primus.timers.connect) primus.end();
if (readyState !== Primus.OPEN) {
return primus.attempt ? primus.reconnect() : false;
}
this.writable = false;
this.readable = false;
//
// Clear all timers in case we're not going to reconnect.
//
for (var timeout in this.timers) {
this.clearTimeout(timeout);
}
//
// Fire the `close` event as an indication of connection disruption.
// This is also fired by `primus#end` so it is emitted in all cases.
//
primus.emit('close');
//
// The disconnect was unintentional, probably because the server has
// shutdown, so if the reconnection is enabled start a reconnect procedure.
//
if (~primus.options.strategy.indexOf('disconnect')) {
return primus.reconnect();
}
primus.emit('outgoing::end');
primus.emit('end');
});
//
// Setup the real-time client.
//
primus.client();
//
// Process the potential plugins.
//
for (var plugin in primus.ark) {
primus.ark[plugin].call(primus, primus, options);
}
//
// NOTE: The following code is only required if we're supporting network
// events as it requires access to browser globals.
//
if (!primus.NETWORK_EVENTS) return primus;
/**
* Handler for offline notifications.
*
* @api private
*/
function offline() {
if (!primus.online) return; // Already or still offline, bailout.
primus.online = false;
primus.emit('offline');
primus.end();
//
// It is certainly possible that we're in a reconnection loop and that the
// user goes offline. In this case we want to kill the existing attempt so
// when the user goes online, it will attempt to reconnect freshly again.
//
primus.clearTimeout('reconnect');
primus.attempt = null;
}
/**
* Handler for online notifications.
*
* @api private
*/
function online() {
if (primus.online) return; // Already or still online, bailout
primus.online = true;
primus.emit('online');
if (~primus.options.strategy.indexOf('online')) primus.reconnect();
}
if (window.addEventListener) {
window.addEventListener('offline', offline, false);
window.addEventListener('online', online, false);
} else if (document.body.attachEvent){
document.body.attachEvent('onoffline', offline);
document.body.attachEvent('ononline', online);
}
return primus;
};
/**
* Really dead simple protocol parser. We simply assume that every message that
* is prefixed with `primus::` could be used as some sort of protocol definition
* for Primus.
*
* @param {String} msg The data.
* @returns {Boolean} Is a protocol message.
* @api private
*/
Primus.prototype.protocol = function protocol(msg) {
if (
'string' !== typeof msg
|| msg.indexOf('primus::') !== 0
) return false;
var last = msg.indexOf(':', 8)
, value = msg.slice(last + 2);
switch (msg.slice(8, last)) {
case 'pong':
this.emit('incoming::pong', value);
break;
case 'server':
//
// The server is closing the connection, forcefully disconnect so we don't
// reconnect again.
//
if ('close' === value) {
this.disconnect = true;
}
break;
case 'id':
this.emit('incoming::id', value);
break;
//
// Unknown protocol, somebody is probably sending `primus::` prefixed
// messages.
//
default:
return false;
}
return true;
};
/**
* Execute the set of message transformers from Primus on the incoming or
* outgoing message.
* This function and it's content should be in sync with Spark#transforms in
* spark.js.
*
* @param {Primus} primus Reference to the Primus instance with message transformers.
* @param {Spark|Primus} connection Connection that receives or sends data.
* @param {String} type The type of message, 'incoming' or 'outgoing'.
* @param {Mixed} data The data to send or that has been received.
* @param {String} raw The raw encoded data.
* @returns {Primus}
* @api public
*/
Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) {
var packet = { data: data }
, fns = primus.transformers[type];
//
// Iterate in series over the message transformers so we can allow optional
// asynchronous execution of message transformers which could for example
// retrieve additional data from the server, do extra decoding or even
// message validation.
//
(function transform(index, done) {
var transformer = fns[index++];
if (!transformer) return done();
if (1 === transformer.length) {
if (false === transformer.call(connection, packet)) {
//
// When false is returned by an incoming transformer it means that's
// being handled by the transformer and we should not emit the `data`
// event.
//
return;
}
return transform(index, done);
}
transformer.call(connection, packet, function finished(err, arg) {
if (err) return connection.emit('error', err);
if (false === arg) return;
transform(index, done);
});
}(0, function done() {
//
// We always emit 2 arguments for the data event, the first argument is the
// parsed data and the second argument is the raw string that we received.
// This allows you, for example, to do some validation on the parsed data
// and then save the raw string in your database without the stringify
// overhead.
//
if ('incoming' === type) return connection.emit('data', packet.data, raw);
connection._write(packet.data);
}));
return this;
};
/**
* Retrieve the current id from the server.
*
* @param {Function} fn Callback function.
* @returns {Primus}
* @api public
*/
Primus.prototype.id = function id(fn) {
if (this.socket && this.socket.id) return fn(this.socket.id);
this._write('primus::id::');
return this.once('incoming::id', fn);
};
/**
* Establish a connection with the server. When this function is called we
* assume that we don't have any open connections. If you do call it when you
* have a connection open, it could cause duplicate connections.
*
* @returns {Primus}
* @api public
*/
Primus.prototype.open = function open() {
context(this, 'open');
//
// Only start a `connection timeout` procedure if we're not reconnecting as
// that shouldn't count as an initial connection. This should be started
// before the connection is opened to capture failing connections and kill the
// timeout.
//
if (!this.attempt && this.options.timeout) this.timeout();
this.emit('outgoing::open');
return this;
};
/**
* Send a new message.
*
* @param {Mixed} data The data that needs to be written.
* @returns {Boolean} Always returns true as we don't support back pressure.
* @api public
*/
Primus.prototype.write = function write(data) {
context(this, 'write');
this.transforms(this, this, 'outgoing', data);
return true;
};
/**
* The actual message writer.
*
* @param {Mixed} data The message that needs to be written.
* @returns {Boolean} Successful write to the underlaying transport.
* @api private
*/
Primus.prototype._write = function write(data) {
var primus = this;
//
// The connection is closed, normally this would already be done in the
// `spark.write` method, but as `_write` is used internally, we should also
// add the same check here to prevent potential crashes by writing to a dead
// socket.
//
if (Primus.OPEN !== primus.readyState) {
//
// If the buffer is at capacity, remove the first item.
//
if (this.buffer.length === this.options.queueSize) {
this.buffer.splice(0, 1);
}
this.buffer.push(data);
return false;
}
primus.encoder(data, function encoded(err, packet) {
//
// Do a "save" emit('error') when we fail to parse a message. We don't
// want to throw here as listening to errors should be optional.
//
if (err) return primus.listeners('error').length && primus.emit('error', err);
primus.emit('outgoing::data', packet);
});
return true;
};
/**
* Send a new heartbeat over the connection to ensure that we're still
* connected and our internet connection didn't drop. We cannot use server side
* heartbeats for this unfortunately.
*
* @returns {Primus}
* @api private
*/
Primus.prototype.heartbeat = function heartbeat() {
var primus = this;
if (!primus.options.ping) return primus;
/**
* Exterminate the connection as we've timed out.
*
* @api private
*/
function pong() {
primus.clearTimeout('pong');
//
// The network events already captured the offline event.
//
if (!primus.online) return;
primus.online = false;
primus.emit('offline');
primus.emit('incoming::end');
}
/**
* We should send a ping message to the server.
*
* @api private
*/
function ping() {
var value = +new Date();
primus.clearTimeout('ping')._write('primus::ping::'+ value);
primus.emit('outgoing::ping', value);
primus.timers.pong = setTimeout(pong, primus.options.pong);
}
primus.timers.ping = setTimeout(ping, primus.options.ping);
return this;
};
/**
* Start a connection timeout.
*
* @returns {Primus}
* @api private
*/
Primus.prototype.timeout = function timeout() {
var primus = this;
/**
* Remove all references to the timeout listener as we've received an event
* that can be used to determine state.
*
* @api private
*/
function remove() {
primus.removeListener('error', remove)
.removeListener('open', remove)
.removeListener('end', remove)
.clearTimeout('connect');
}
primus.timers.connect = setTimeout(function expired() {
remove(); // Clean up old references.
if (primus.readyState === Primus.OPEN || primus.attempt) return;
primus.emit('timeout');
//
// We failed to connect to the server.
//
if (~primus.options.strategy.indexOf('timeout')) primus.reconnect();
else primus.end();
}, primus.options.timeout);
return primus.on('error', remove)
.on('open', remove)
.on('end', remove);
};
/**
* Properly clean up all `setTimeout` references.
*
* @param {String} ..args.. The names of the timeout's we need clear.
* @returns {Primus}
* @api private
*/
Primus.prototype.clearTimeout = function clear() {
for (var args = arguments, i = 0, l = args.length; i < l; i++) {
if (this.timers[args[i]]) clearTimeout(this.timers[args[i]]);
delete this.timers[args[i]];
}
return this;
};
/**
* Exponential back off algorithm for retry operations. It uses an randomized
* retry so we don't DDOS our server when it goes down under pressure.
*
* @param {Function} callback Callback to be called after the timeout.
* @param {Object} opts Options for configuring the timeout.
* @returns {Primus}
* @api private
*/
Primus.prototype.backoff = function backoff(callback, opts) {
opts = opts || {};
var primus = this;
//
// Bailout when we already have a backoff process running. We shouldn't call
// the callback then as it might cause an unexpected `end` event as another
// reconnect process is already running.
//
if (opts.backoff) return primus;
opts.maxDelay = 'maxDelay' in opts ? opts.maxDelay : Infinity; // Maximum delay.
opts.minDelay = 'minDelay' in opts ? opts.minDelay : 500; // Minimum delay.
opts.retries = 'retries' in opts ? opts.retries : 10; // Allowed retries.
opts.attempt = (+opts.attempt || 0) + 1; // Current attempt.
opts.factor = 'factor' in opts ? opts.factor : 2; // Back off factor.
//
// Bailout if we are about to make to much attempts. Please note that we use
// `>` because we already incremented the value above.
//
if (opts.attempt > opts.retries) {
callback(new Error('Unable to retry'), opts);
return primus;
}
//
// Prevent duplicate back off attempts using the same options object.
//
opts.backoff = true;
//
// Calculate the timeout, but make it randomly so we don't retry connections
// at the same interval and defeat the purpose. This exponential back off is
// based on the work of:
//
// http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html
//
opts.timeout = opts.attempt !== 1
? Math.min(Math.round(
(Math.random() + 1) * opts.minDelay * Math.pow(opts.factor, opts.attempt)
), opts.maxDelay)
: opts.minDelay;
primus.timers.reconnect = setTimeout(function delay() {
opts.backoff = false;
primus.clearTimeout('reconnect');
callback(undefined, opts);
}, opts.timeout);
//
// Emit a `reconnecting` event with current reconnect options. This allows
// them to update the UI and provide their users with feedback.
//
primus.emit('reconnecting', opts);
return primus;
};
/**
* Start a new reconnect procedure.
*
* @returns {Primus}
* @api private
*/
Primus.prototype.reconnect = function reconnect() {
var primus = this;
//
// Try to re-use the existing attempt.
//
primus.attempt = primus.attempt || primus.clone(primus.options.reconnect);
primus.backoff(function attempt(fail, backoff) {
if (fail) {
primus.attempt = null;
return primus.emit('end');
}
//
// Try to re-open the connection again.
//
primus.emit('reconnect', backoff);
primus.emit('outgoing::reconnect');
}, primus.attempt);
return primus;
};
/**
* Close the connection completely.
*
* @param {Mixed} data last packet of data.
* @returns {Primus}
* @api public
*/
Primus.prototype.end = function end(data) {
context(this, 'end');
if (this.readyState === Primus.CLOSED && !this.timers.connect) {
//
// If we are reconnecting stop the reconnection procedure.
//
if (this.timers.reconnect) {
this.clearTimeout('reconnect');
this.attempt = null;
this.emit('end');
}
return this;
}
if (data !== undefined) this.write(data);
this.writable = false;
this.readable = false;
var readyState = this.readyState;
this.readyState = Primus.CLOSED;
if (readyState !== this.readyState) {
this.emit('readyStateChange', 'end');
}
for (var timeout in this.timers) {
this.clearTimeout(timeout);
}
this.emit('outgoing::end');
this.emit('close');
this.emit('end');
return this;
};
/**
* Create a shallow clone of a given object.
*
* @param {Object} obj The object that needs to be cloned.
* @returns {Object} Copy.
* @api private
*/
Primus.prototype.clone = function clone(obj) {
return this.merge({}, obj);
};
/**
* Merge different objects in to one target object.
*
* @param {Object} target The object where everything should be merged in.
* @returns {Object} Original target with all merged objects.
* @api private
*/
Primus.prototype.merge = function merge(target) {
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = args.length, key, obj; i < l; i++) {
obj = args[i];
for (key in obj) {
if (obj.hasOwnProperty(key)) target[key] = obj[key];
}
}
return target;
};
/**
* Parse the connection string.
*
* @type {Function}
* @param {String} url Connection URL.
* @returns {Object} Parsed connection.
* @api private
*/
Primus.prototype.parse = parse;
/**
* Parse a query string.
*
* @param {String} query The query string that needs to be parsed.
* @returns {Object} Parsed query string.
* @api private
*/
Primus.prototype.querystring = function querystring(query) {
var parser = /([^=?&]+)=([^&]*)/g
, result = {}
, part;
//
// Little nifty parsing hack, leverage the fact that RegExp.exec increments
// the lastIndex property so we can continue executing this loop until we've
// parsed all results.
//
for (;
part = parser.exec(query);
result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
);
return result;
};
/**
* Transform a query string object back in to string equiv.
*
* @param {Object} obj The query string object.
* @returns {String}
* @api private
*/
Primus.prototype.querystringify = function querystringify(obj) {
var pairs = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
};
/**
* Generates a connection URI.
*
* @param {String} protocol The protocol that should used to crate the URI.
* @returns {String|options} The URL.
* @api private
*/
Primus.prototype.uri = function uri(options) {
var url = this.url
, server = []
, qsa = false;
//
// Query strings are only allowed when we've received clearance for it.
//
if (options.query) qsa = true;
options = options || {};
options.protocol = 'protocol' in options ? options.protocol : 'http';
options.query = url.search && 'query' in options ? (url.search.charAt(0) === '?' ? url.search.slice(1) : url.search) : false;
options.secure = 'secure' in options ? options.secure : (url.protocol === 'https:' || url.protocol === 'wss:');
options.auth = 'auth' in options ? options.auth : url.auth;
options.pathname = 'pathname' in options ? options.pathname : this.pathname.slice(1);
options.port = 'port' in options ? +options.port : +url.port || (options.secure ? 443 : 80);
options.host = 'host' in options ? options.host : url.hostname || url.host.replace(':'+ url.port, '');
//
// Allow transformation of the options before we construct a full URL from it.
//
this.emit('outgoing::url', options);
//
// `url.host` might be undefined (e.g. when using zombie) so we use the
// hostname and port defined above.
//
var host = (443 !== options.port && 80 !== options.port)
? options.host +':'+ options.port
: options.host;
//
// We need to make sure that we create a unique connection URL every time to
// prevent bfcache back forward cache of becoming an issue. We're doing this
// by forcing an cache busting query string in to the URL.
//
var querystring = this.querystring(options.query || '');
querystring._primuscb = +new Date() +'-'+ this.stamps++;
options.query = this.querystringify(querystring);
//
// Automatically suffix the protocol so we can supply `ws` and `http` and it gets
// transformed correctly.
//
server.push(options.secure ? options.protocol +'s:' : options.protocol +':', '');
if (options.auth) server.push(options.auth +'@'+ host);
else server.push(host);
//
// Pathnames are optional as some Transformers would just use the pathname
// directly.
//
if (options.pathname) server.push(options.pathname);
//
// Optionally add a search query, again, not supported by all Transformers.
// SockJS is known to throw errors when a query string is included.
//
if (qsa) server.push('?'+ options.query);
else delete options.query;
if (options.object) return options;
return server.join('/');
};
/**
* Simple emit wrapper that returns a function that emits an event once it's
* called. This makes it easier for transports to emit specific events. The
* scope of this function is limited as it will only emit one single argument.
*
* @param {String} event Name of the event that we should emit.
* @param {Function} parser Argument parser.
* @returns {Function} The wrapped function that will emit events when called.
* @api public
*/
Primus.prototype.emits = function emits(event, parser) {
var primus = this;
return function emit(arg) {
var data = parser ? parser.apply(primus, arguments) : arg;
//
// Timeout is required to prevent crashes on WebSockets connections on
// mobile devices. We need to handle these edge cases in our own library
// as we cannot be certain that all frameworks fix these issues.
//
setTimeout(function timeout() {
primus.emit('incoming::'+ event, data);
}, 0);
};
};
/**
* Register a new message transformer. This allows you to easily manipulate incoming
* and outgoing data which is particularity handy for plugins that want to send
* meta data together with the messages.
*
* @param {String} type Incoming or outgoing
* @param {Function} fn A new message transformer.
* @returns {Primus}
* @api public
*/
Primus.prototype.transform = function transform(type, fn) {
context(this, 'transform');
if (!(type in this.transformers)) {
return this.critical(new Error('Invalid transformer type'));
}
this.transformers[type].push(fn);
return this;
};
/**
* A critical error has occurred, if we have an `error` listener, emit it there.
* If not, throw it, so we get a stack trace + proper error message.
*
* @param {Error} err The critical error.
* @returns {Primus}
* @api private
*/
Primus.prototype.critical = function critical(err) {
if (this.listeners('error').length) {
this.emit('error', err);
return this;
}
throw err;
};
/**
* Syntax sugar, adopt a Socket.IO like API.
*
* @param {String} url The URL we want to connect to.
* @param {Object} options Connection options.
* @returns {Primus}
* @api public
*/
Primus.connect = function connect(url, options) {
return new Primus(url, options);
};
//
// Expose the EventEmitter so it can be re-used by wrapping libraries we're also
// exposing the Stream interface.
//
Primus.EventEmitter = EventEmitter;
//
// These libraries are automatically are automatically inserted at the
// server-side using the Primus#library method.
//
Primus.prototype.client = function client() {
var primus = this
, socket;
//
// Select an available WebSocket factory.
//
var Factory = (function factory() {
if ('undefined' !== typeof WebSocket) return WebSocket;
if ('undefined' !== typeof MozWebSocket) return MozWebSocket;
try { return Primus.require('ws'); }
catch (e) {}
return undefined;
})();
if (!Factory) return primus.critical(new Error(
'Missing required `ws` module. Please run `npm install --save ws`'
));
//
// Connect to the given URL.
//
primus.on('outgoing::open', function opening() {
primus.emit('outgoing::end');
//
// FireFox will throw an error when we try to establish a connection from
// a secure page to an unsecured WebSocket connection. This is inconsistent
// behaviour between different browsers. This should ideally be solved in
// Primus when we connect.
//
try {
var prot = primus.url.protocol === 'ws+unix:' ? 'ws+unix' : 'ws'
, qsa = prot === 'ws';
//
// Only allow primus.transport object in Node.js, it will throw in
// browsers with a TypeError if we supply to much arguments.
//
if (Factory.length === 3) {
primus.socket = socket = new Factory(
primus.uri({ protocol: prot, query: qsa }), // URL
[], // Sub protocols
primus.transport // options.
);
} else {
primus.socket = socket = new Factory(primus.uri({
protocol: prot,
query: qsa
}));
}
} catch (e) { return primus.emit('error', e); }
//
// Setup the Event handlers.
//
socket.binaryType = 'arraybuffer';
socket.onopen = primus.emits('open');
socket.onerror = primus.emits('error');
socket.onclose = primus.emits('end');
socket.onmessage = primus.emits('data', function parse(evt) {
return evt.data;
});
});
//
// We need to write a new message to the socket.
//
primus.on('outgoing::data', function write(message) {
if (!socket || socket.readyState !== Factory.OPEN) return;
try { socket.send(message); }
catch (e) { primus.emit('incoming::error', e); }
});
//
// Attempt to reconnect the socket.
//
primus.on('outgoing::reconnect', function reconnect() {
primus.emit('outgoing::open');
});
//
// We need to close the socket.
//
primus.on('outgoing::end', function close() {
if (!socket) return;
socket.onerror = socket.onopen = socket.onclose = socket.onmessage = function () {};
socket.close();
socket = null;
});
};
Primus.prototype.authorization = false;
Primus.prototype.pathname = "/primus";
Primus.prototype.encoder = function encoder(data, fn) {
var err;
try { data = JSON.stringify(data); }
catch (e) { err = e; }
fn(err, data);
};
Primus.prototype.decoder = function decoder(data, fn) {
var err;
if ('string' !== typeof data) return fn(err, data);
try { data = JSON.parse(data); }
catch (e) { err = e; }
fn(err, data);
};
Primus.prototype.version = "2.4.12";
//
// Hack 1: \u2028 and \u2029 are allowed inside string in JSON. But JavaScript
// defines them as newline separators. Because no literal newlines are allowed
// in a string this causes a ParseError. We work around this issue by replacing
// these characters with a properly escaped version for those chars. This can
// cause errors with JSONP requests or if the string is just evaluated.
//
// This could have been solved by replacing the data during the "outgoing::data"
// event. But as it affects the JSON encoding in general I've opted for a global
// patch instead so all JSON.stringify operations are save.
//
if (
'object' === typeof JSON
&& 'function' === typeof JSON.stringify
&& JSON.stringify(['\u2028\u2029']) === '["\u2028\u2029"]'
) {
JSON.stringify = function replace(stringify) {
var u2028 = /\u2028/g
, u2029 = /\u2029/g;
return function patched(value, replacer, spaces) {
var result = stringify.call(this, value, replacer, spaces);
//
// Replace the bad chars.
//
if (result) {
if (~result.indexOf('\u2028')) result = result.replace(u2028, '\\u2028');
if (~result.indexOf('\u2029')) result = result.replace(u2029, '\\u2029');
}
return result;
};
}(JSON.stringify);
}
if (
'undefined' !== typeof document
&& 'undefined' !== typeof navigator
) {
//
// Hack 2: If you press ESC in FireFox it will close all active connections.
// Normally this makes sense, when your page is still loading. But versions
// before FireFox 22 will close all connections including WebSocket connections
// after page load. One way to prevent this is to do a `preventDefault()` and
// cancel the operation before it bubbles up to the browsers default handler.
// It needs to be added as `keydown` event, if it's added keyup it will not be
// able to prevent the connection from being closed.
//
if (document.addEventListener) {
document.addEventListener('keydown', function keydown(e) {
if (e.keyCode !== 27 || !e.preventDefault) return;
e.preventDefault();
}, false);
}
//
// Hack 3: This is a Mac/Apple bug only, when you're behind a reverse proxy or
// have you network settings set to `automatic proxy discovery` the safari
// browser will crash when the WebSocket constructor is initialised. There is
// no way to detect the usage of these proxies available in JavaScript so we
// need to do some nasty browser sniffing. This only affects Safari versions
// lower then 5.1.4
//
var ua = (navigator.userAgent || '').toLowerCase()
, parsed = ua.match(/.+(?:rv|it|ra|ie)[\/: ](\d+)\.(\d+)(?:\.(\d+))?/) || []
, version = +[parsed[1], parsed[2]].join('.');
if (
!~ua.indexOf('chrome')
&& ~ua.indexOf('safari')
&& version < 534.54
) {
Primus.prototype.AVOID_WEBSOCKETS = true;
}
}
return Primus; });
;;;
(function(exports){
var ActionheroClient = function(options, client){
var self = this;
self.callbacks = {};
self.id = null;
self.events = {};
self.rooms = [];
self.state = 'disconnected';
self.options = self.defaults();
for(var i in options){
self.options[i] = options[i];
}
if(client){
self.client = client;
}
}
if(typeof Primus === 'undefined'){
var util = require('util');
var EventEmitter = require('events').EventEmitter;
util.inherits(ActionheroClient, EventEmitter);
}else{
ActionheroClient.prototype = new Primus.EventEmitter();
}
ActionheroClient.prototype.defaults = function(){
return { apiPath: '/api', url: window.location.origin }
}
////////////////
// CONNECTION //
////////////////
ActionheroClient.prototype.connect = function(callback){
var self = this;
self.messageCount = 0;
if(!self.client){
self.client = Primus.connect(self.options.url, self.options);
}else{
self.client.end();
self.client.open();
}
self.client.on('open', function(){
self.configure(function(details){
self.emit('connected');
if(self.state === 'connected'){
//
}else{
self.state = 'connected';
if(typeof callback === 'function'){ callback(null, details); }
}
});
})
self.client.on('error', function(err){
self.emit('error', err);
});
self.client.on('reconnect', function(){
self.messageCount = 0;
self.emit('reconnect');
});
self.client.on('reconnecting', function(){
self.emit('reconnecting');
self.state = 'reconnecting';
self.emit('disconnected');
});
self.client.on('end', function(){
self.messageCount = 0;
if(self.state !== 'disconnected'){
self.state = 'disconnected';
self.emit('disconnected');
}
});
self.client.on('data', function(data){
self.handleMessage(data);
});
}
ActionheroClient.prototype.configure = function(callback){
var self = this;
self.rooms.forEach(function(room){
self.send({event: 'roomAdd', room: room});
});
self.detailsView(function(details){
self.id = details.data.id;
self.fingerprint = details.data.fingerprint;
self.rooms = details.data.rooms;
callback(details);
});
}
///////////////
// MESSAGING //
///////////////
ActionheroClient.prototype.send = function(args, callback){
// primus will buffer messages when not connected
var self = this;
self.messageCount++;
if(typeof callback === 'function'){
self.callbacks[self.messageCount] = callback;
}
self.client.write(args);
}
ActionheroClient.prototype.handleMessage = function(message){
var self = this;
self.emit('message', message);
if(message.context === 'response'){
if(typeof self.callbacks[message.messageCount] === 'function'){
self.callbacks[message.messageCount](message);
}
delete self.callbacks[message.messageCount];
} else if(message.context === 'user'){
self.emit('say', message);
} else if(message.context === 'alert'){
self.emit('alert', message);
} else if(message.welcome && message.context === 'api'){
self.welcomeMessage = message.welcome;
self.emit('welcome', message);
} else if(message.context === 'api'){
self.emit('api', message);
}
}
/////////////
// ACTIONS //
/////////////
ActionheroClient.prototype.action = function(action, params, callback){
if(!callback && typeof params === 'function'){
callback = params;
params = null;
}
if(!params){ params = {}; }
params.action = action;
if(this.state !== 'connected'){
this.actionWeb(params, callback);
}else{
this.actionWebSocket(params, callback);
}
}
ActionheroClient.prototype.actionWeb = function(params, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4){
if(xmlhttp.status === 200){
var response = JSON.parse(xmlhttp.responseText);
callback(null, response);
}else{
callback(xmlhttp.statusText, xmlhttp.responseText);
}
}
}
var qs = '?';
for(var i in params){
qs += i + '=' + params[i] + '&';
}
var method = 'GET';
if(params.httpMethod){
method = params.httpMethod;
}
var url = this.options.url + this.options.apiPath + qs;
xmlhttp.open(method, url, true);
xmlhttp.send();
}
ActionheroClient.prototype.actionWebSocket = function(params, callback){
this.send({event: 'action',params: params}, callback);
}
//////////////
// COMMANDS //
//////////////
ActionheroClient.prototype.say = function(room, message, callback){
this.send({event: 'say', room: room, message: message}, callback);
}
ActionheroClient.prototype.file = function(file, callback){
this.send({event: 'file', file: file}, callback);
}
ActionheroClient.prototype.detailsView = function(callback){
this.send({event: 'detailsView'}, callback);
}
ActionheroClient.prototype.roomView = function(room, callback){
this.send({event: 'roomView', room: room}, callback);
}
ActionheroClient.prototype.roomAdd = function(room, callback){
var self = this;
self.send({event: 'roomAdd', room: room}, function(data){
self.configure(function(details){
if(typeof callback === 'function'){ callback(data); }
});
});
}
ActionheroClient.prototype.roomLeave = function(room, callback){
var self = this;
var index = self.rooms.indexOf(room);
if(index > -1){ self.rooms.splice(index, 1); }
this.send({event: 'roomLeave', room: room}, function(data){
self.configure(function(details){
if(typeof callback === 'function'){ callback(data); }
});
});
}
ActionheroClient.prototype.documentation = function(callback){
this.send({event: 'documentation'}, callback);
}
ActionheroClient.prototype.disconnect = function(){
this.state = 'disconnected';
this.client.end();
this.emit('disconnected');
}
// depricated lowercase name
var actionheroClient = ActionheroClient;
exports.ActionheroClient = ActionheroClient;
exports.actionheroClient = actionheroClient;
})(typeof exports === 'undefined' ? window : exports);
|
"format register";
System.register("github:aurelia/metadata@0.3.1/system/origin", [], function(_export) {
"use strict";
var _prototypeProperties,
originStorage,
Origin;
function ensureType(value) {
if (value instanceof Origin) {
return value;
}
return new Origin(value);
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
originStorage = new Map();
Origin = (function() {
function Origin(moduleId, moduleMember) {
this.moduleId = moduleId;
this.moduleMember = moduleMember;
}
_prototypeProperties(Origin, {
get: {
value: function get(fn) {
var origin = originStorage.get(fn);
if (origin !== undefined) {
return origin;
}
if (typeof fn.origin === "function") {
originStorage.set(fn, origin = ensureType(fn.origin()));
} else if (fn.origin !== undefined) {
originStorage.set(fn, origin = ensureType(fn.origin));
}
return origin;
},
writable: true,
enumerable: true,
configurable: true
},
set: {
value: function set(fn, origin) {
if (Origin.get(fn) === undefined) {
originStorage.set(fn, origin);
}
},
writable: true,
enumerable: true,
configurable: true
}
});
return Origin;
})();
_export("Origin", Origin);
}
};
});
System.register("github:aurelia/metadata@0.3.1/system/resource-type", [], function(_export) {
"use strict";
var _prototypeProperties,
ResourceType;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ResourceType = (function() {
function ResourceType() {}
_prototypeProperties(ResourceType, null, {
load: {
value: function load(container, target) {
return this;
},
writable: true,
enumerable: true,
configurable: true
},
register: {
value: function register(registry, name) {
throw new Error("All descendents of \"ResourceType\" must implement the \"register\" method.");
},
writable: true,
enumerable: true,
configurable: true
}
});
return ResourceType;
})();
_export("ResourceType", ResourceType);
}
};
});
System.register("github:aurelia/metadata@0.3.1/system/metadata", [], function(_export) {
"use strict";
var _prototypeProperties,
functionMetadataStorage,
emptyArray,
locateFunctionMetadataElsewhere,
MetadataStorage,
Metadata;
function normalize(metadata, fn, replace) {
if (metadata instanceof MetadataStorage) {
if (replace) {
fn.metadata = function() {
return metadata;
};
}
metadata.owner = fn;
return metadata;
}
if (Array.isArray(metadata)) {
return new MetadataStorage(metadata, fn);
}
throw new Error("Incorrect metadata format for " + metadata + ".");
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
functionMetadataStorage = new Map();
emptyArray = Object.freeze([]);
MetadataStorage = (function() {
function MetadataStorage(metadata, owner) {
this.metadata = metadata;
this.owner = owner;
}
_prototypeProperties(MetadataStorage, null, {
first: {
value: function first(type, searchPrototype) {
var metadata = this.metadata,
i,
ii,
potential;
if (metadata === undefined || metadata.length === 0) {
if (searchPrototype && this.owner !== undefined) {
return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
}
return null;
}
for (i = 0, ii = metadata.length; i < ii; ++i) {
potential = metadata[i];
if (potential instanceof type) {
return potential;
}
}
if (searchPrototype && this.owner !== undefined) {
return Metadata.on(Object.getPrototypeOf(this.owner)).first(type, searchPrototype);
}
return null;
},
writable: true,
enumerable: true,
configurable: true
},
has: {
value: function has(type, searchPrototype) {
return this.first(type, searchPrototype) !== null;
},
writable: true,
enumerable: true,
configurable: true
},
all: {
value: function all(type, searchPrototype) {
var metadata = this.metadata,
i,
ii,
found,
potential;
if (metadata === undefined || metadata.length === 0) {
if (searchPrototype && this.owner !== undefined) {
return Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype);
}
return emptyArray;
}
found = [];
for (i = 0, ii = metadata.length; i < ii; ++i) {
potential = metadata[i];
if (potential instanceof type) {
found.push(potential);
}
}
if (searchPrototype && this.owner !== undefined) {
found = found.concat(Metadata.on(Object.getPrototypeOf(this.owner)).all(type, searchPrototype));
}
return found;
},
writable: true,
enumerable: true,
configurable: true
},
add: {
value: function add(instance) {
if (this.metadata === undefined) {
this.metadata = [];
}
this.last = instance;
this.metadata.push(instance);
return this;
},
writable: true,
enumerable: true,
configurable: true
},
and: {
value: function and(func) {
func(this.last);
return this;
},
writable: true,
enumerable: true,
configurable: true
}
});
return MetadataStorage;
})();
MetadataStorage.empty = Object.freeze(new MetadataStorage());
Metadata = _export("Metadata", {
on: function on(owner) {
var metadata;
if (!owner) {
return MetadataStorage.empty;
}
metadata = functionMetadataStorage.get(owner);
if (metadata === undefined) {
if ("metadata" in owner) {
if (typeof owner.metadata === "function") {
functionMetadataStorage.set(owner, metadata = normalize(owner.metadata(), owner, true));
} else {
functionMetadataStorage.set(owner, metadata = normalize(owner.metadata, owner));
}
} else if (locateFunctionMetadataElsewhere !== undefined) {
metadata = locateFunctionMetadataElsewhere(owner);
if (metadata === undefined) {
functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
} else {
functionMetadataStorage.set(owner, metadata = normalize(metadata, owner));
}
} else {
functionMetadataStorage.set(owner, metadata = new MetadataStorage(undefined, owner));
}
}
return metadata;
},
configure: {
location: function location(staticPropertyName) {
this.locator(function(fn) {
return fn[staticPropertyName];
});
},
locator: function locator(loc) {
if (locateFunctionMetadataElsewhere === undefined) {
locateFunctionMetadataElsewhere = loc;
return;
}
var original = locateFunctionMetadataElsewhere;
locateFunctionMetadataElsewhere = function(fn) {
return original(fn) || loc(fn);
};
},
classHelper: function classHelper(name, fn) {
MetadataStorage.prototype[name] = function() {
var context = Object.create(fn.prototype);
var metadata = fn.apply(context, arguments) || context;
this.add(metadata);
return this;
};
Metadata[name] = function() {
var storage = new MetadataStorage([]);
return storage[name].apply(storage, arguments);
};
},
functionHelper: function functionHelper(name, fn) {
MetadataStorage.prototype[name] = function() {
fn.apply(this, arguments);
return this;
};
Metadata[name] = function() {
var storage = new MetadataStorage([]);
return storage[name].apply(storage, arguments);
};
}
}
});
}
};
});
System.register("github:aurelia/loader@0.3.3/system/index", [], function(_export) {
"use strict";
var _prototypeProperties,
hasTemplateElement,
Loader;
function importElements(frag, link, callback) {
document.head.appendChild(frag);
if (window.Polymer && Polymer.whenReady) {
Polymer.whenReady(callback);
} else {
link.addEventListener("load", callback);
}
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
hasTemplateElement = "content" in document.createElement("template");
Loader = (function() {
function Loader() {}
_prototypeProperties(Loader, {createDefaultLoader: {
value: function createDefaultLoader() {
throw new Error("No default loader module imported.");
},
writable: true,
enumerable: true,
configurable: true
}}, {
loadModule: {
value: function loadModule(id) {
throw new Error("Loaders must implement loadModule(id).");
},
writable: true,
enumerable: true,
configurable: true
},
loadAllModules: {
value: function loadAllModules(ids) {
throw new Error("Loader must implement loadAllModules(ids).");
},
writable: true,
enumerable: true,
configurable: true
},
loadTemplate: {
value: function loadTemplate(url) {
throw new Error("Loader must implement loadTemplate(url).");
},
writable: true,
enumerable: true,
configurable: true
},
importDocument: {
value: function importDocument(url) {
return new Promise(function(resolve, reject) {
var frag = document.createDocumentFragment();
var link = document.createElement("link");
link.rel = "import";
link.href = url;
frag.appendChild(link);
importElements(frag, link, function() {
return resolve(link["import"]);
});
});
},
writable: true,
enumerable: true,
configurable: true
},
importTemplate: {
value: function importTemplate(url) {
var _this = this;
return this.importDocument(url).then(function(doc) {
return _this.findTemplate(doc, url);
});
},
writable: true,
enumerable: true,
configurable: true
},
findTemplate: {
value: function findTemplate(doc, url) {
if (!hasTemplateElement) {
HTMLTemplateElement.bootstrap(doc);
}
var template = doc.querySelector("template");
if (!template) {
throw new Error("There was no template element found in '" + url + "'.");
}
return template;
},
writable: true,
enumerable: true,
configurable: true
}
});
return Loader;
})();
_export("Loader", Loader);
}
};
});
System.register("github:aurelia/path@0.4.2/system/index", [], function(_export) {
"use strict";
_export("relativeToFile", relativeToFile);
_export("join", join);
function trimDots(ary) {
var i,
part;
for (i = 0; i < ary.length; ++i) {
part = ary[i];
if (part === ".") {
ary.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 0 || i == 1 && ary[2] === ".." || ary[i - 1] === "..") {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function relativeToFile(name, file) {
var lastIndex,
normalizedBaseParts,
fileParts = file && file.split("/");
name = name.trim();
name = name.split("/");
if (name[0].charAt(0) === "." && fileParts) {
normalizedBaseParts = fileParts.slice(0, fileParts.length - 1);
name = normalizedBaseParts.concat(name);
}
trimDots(name);
return name.join("/");
}
function join(path1, path2) {
var url1,
url2,
url3,
i,
ii,
urlPrefix;
if (!path1) {
return path2;
}
if (!path2) {
return path1;
}
urlPrefix = path1.indexOf("/") === 0 ? "/" : "";
url1 = path1.split("/");
url2 = path2.split("/");
url3 = [];
for (i = 0, ii = url1.length; i < ii; ++i) {
if (url1[i] == "..") {
url3.pop();
} else if (url1[i] == "." || url1[i] == "") {
continue;
} else {
url3.push(url1[i]);
}
}
for (i = 0, ii = url2.length; i < ii; ++i) {
if (url2[i] == "..") {
url3.pop();
} else if (url2[i] == "." || url2[i] == "") {
continue;
} else {
url3.push(url2[i]);
}
}
return urlPrefix + url3.join("/").replace(/\:\//g, "://");
;
}
return {
setters: [],
execute: function() {}
};
});
System.register("github:aurelia/logging@0.2.2/system/index", [], function(_export) {
"use strict";
var _prototypeProperties,
levels,
loggers,
logLevel,
appenders,
slice,
loggerConstructionKey,
Logger;
_export("getLogger", getLogger);
_export("addAppender", addAppender);
_export("setLevel", setLevel);
function log(logger, level, args) {
var i = appenders.length,
current;
args = slice.call(args);
args.unshift(logger);
while (i--) {
current = appenders[i];
current[level].apply(current, args);
}
}
function debug() {
if (logLevel < 4) {
return;
}
log(this, "debug", arguments);
}
function info() {
if (logLevel < 3) {
return;
}
log(this, "info", arguments);
}
function warn() {
if (logLevel < 2) {
return;
}
log(this, "warn", arguments);
}
function error() {
if (logLevel < 1) {
return;
}
log(this, "error", arguments);
}
function connectLogger(logger) {
logger.debug = debug;
logger.info = info;
logger.warn = warn;
logger.error = error;
}
function createLogger(id) {
var logger = new Logger(id, loggerConstructionKey);
if (appenders.length) {
connectLogger(logger);
}
return logger;
}
function getLogger(id) {
return loggers[id] || (loggers[id] = createLogger(id));
}
function addAppender(appender) {
appenders.push(appender);
if (appenders.length === 1) {
for (var key in loggers) {
connectLogger(loggers[key]);
}
}
}
function setLevel(level) {
logLevel = level;
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
levels = _export("levels", {
none: 0,
error: 1,
warn: 2,
info: 3,
debug: 4
});
loggers = {};
logLevel = levels.none;
appenders = [];
slice = Array.prototype.slice;
loggerConstructionKey = {};
Logger = (function() {
function Logger(id, key) {
if (key !== loggerConstructionKey) {
throw new Error("You cannot instantiate \"Logger\". Use the \"getLogger\" API instead.");
}
this.id = id;
}
_prototypeProperties(Logger, null, {
debug: {
value: function debug() {},
writable: true,
enumerable: true,
configurable: true
},
info: {
value: function info() {},
writable: true,
enumerable: true,
configurable: true
},
warn: {
value: function warn() {},
writable: true,
enumerable: true,
configurable: true
},
error: {
value: function error() {},
writable: true,
enumerable: true,
configurable: true
}
});
return Logger;
})();
_export("Logger", Logger);
}
};
});
System.register("github:aurelia/dependency-injection@0.4.2/system/metadata", [], function(_export) {
"use strict";
var _inherits,
_prototypeProperties,
Registration,
Transient,
Singleton,
Resolver,
Lazy,
All,
Optional,
Parent;
return {
setters: [],
execute: function() {
_inherits = function(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)
subClass.__proto__ = superClass;
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Registration = _export("Registration", (function() {
function Registration() {}
_prototypeProperties(Registration, null, {register: {
value: function register(container, key, fn) {
throw new Error("A custom Registration must implement register(container, key, fn).");
},
writable: true,
configurable: true
}});
return Registration;
})());
Transient = _export("Transient", (function(Registration) {
function Transient(key) {
this.key = key;
}
_inherits(Transient, Registration);
_prototypeProperties(Transient, null, {register: {
value: function register(container, key, fn) {
container.registerTransient(this.key || key, fn);
},
writable: true,
configurable: true
}});
return Transient;
})(Registration));
Singleton = _export("Singleton", (function(Registration) {
function Singleton(key) {
this.key = key;
}
_inherits(Singleton, Registration);
_prototypeProperties(Singleton, null, {register: {
value: function register(container, key, fn) {
container.registerSingleton(this.key || key, fn);
},
writable: true,
configurable: true
}});
return Singleton;
})(Registration));
Resolver = _export("Resolver", (function() {
function Resolver() {}
_prototypeProperties(Resolver, null, {get: {
value: function get(container) {
throw new Error("A custom Resolver must implement get(container) and return the resolved instance(s).");
},
writable: true,
configurable: true
}});
return Resolver;
})());
Lazy = _export("Lazy", (function(Resolver) {
function Lazy(key) {
this.key = key;
}
_inherits(Lazy, Resolver);
_prototypeProperties(Lazy, {of: {
value: function of(key) {
return new Lazy(key);
},
writable: true,
configurable: true
}}, {get: {
value: function get(container) {
var _this = this;
return function() {
return container.get(_this.key);
};
},
writable: true,
configurable: true
}});
return Lazy;
})(Resolver));
All = _export("All", (function(Resolver) {
function All(key) {
this.key = key;
}
_inherits(All, Resolver);
_prototypeProperties(All, {of: {
value: function of(key) {
return new All(key);
},
writable: true,
configurable: true
}}, {get: {
value: function get(container) {
return container.getAll(this.key);
},
writable: true,
configurable: true
}});
return All;
})(Resolver));
Optional = _export("Optional", (function(Resolver) {
function Optional(key) {
var checkParent = arguments[1] === undefined ? false : arguments[1];
this.key = key;
this.checkParent = checkParent;
}
_inherits(Optional, Resolver);
_prototypeProperties(Optional, {of: {
value: function of(key) {
var checkParent = arguments[1] === undefined ? false : arguments[1];
return new Optional(key, checkParent);
},
writable: true,
configurable: true
}}, {get: {
value: function get(container) {
if (container.hasHandler(this.key, this.checkParent)) {
return container.get(this.key);
}
return null;
},
writable: true,
configurable: true
}});
return Optional;
})(Resolver));
Parent = _export("Parent", (function(Resolver) {
function Parent(key) {
this.key = key;
}
_inherits(Parent, Resolver);
_prototypeProperties(Parent, {of: {
value: function of(key) {
return new Parent(key);
},
writable: true,
configurable: true
}}, {get: {
value: function get(container) {
return container.parent ? container.parent.get(this.key) : null;
},
writable: true,
configurable: true
}});
return Parent;
})(Resolver));
}
};
});
System.register("github:aurelia/dependency-injection@0.4.2/system/util", [], function(_export) {
"use strict";
_export("isClass", isClass);
function test() {}
function isUpperCase(char) {
return char.toUpperCase() === char;
}
function isClass(clsOrFunction) {
if (clsOrFunction.name) {
return isUpperCase(clsOrFunction.name.charAt(0));
}
return Object.keys(clsOrFunction.prototype).length > 0;
}
return {
setters: [],
execute: function() {
if (!test.name) {
Object.defineProperty(Function.prototype, "name", {get: function() {
var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];
Object.defineProperty(this, "name", {value: name});
return name;
}});
}
}
};
});
System.register("github:aurelia/templating@0.8.8/system/util", [], function(_export) {
"use strict";
var capitalMatcher;
_export("hyphenate", hyphenate);
function addHyphenAndLower(char) {
return "-" + char.toLowerCase();
}
function hyphenate(name) {
return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower);
}
return {
setters: [],
execute: function() {
capitalMatcher = /([A-Z])/g;
}
};
});
System.register("github:aurelia/binding@0.3.3/system/value-converter", ["aurelia-metadata"], function(_export) {
"use strict";
var ResourceType,
_prototypeProperties,
_inherits,
capitalMatcher,
ValueConverter;
function addHyphenAndLower(char) {
return "-" + char.toLowerCase();
}
function hyphenate(name) {
return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower);
}
return {
setters: [function(_aureliaMetadata) {
ResourceType = _aureliaMetadata.ResourceType;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
capitalMatcher = /([A-Z])/g;
ValueConverter = _export("ValueConverter", (function(ResourceType) {
function ValueConverter(name) {
this.name = name;
}
_inherits(ValueConverter, ResourceType);
_prototypeProperties(ValueConverter, {convention: {
value: function convention(name) {
if (name.endsWith("ValueConverter")) {
return new ValueConverter(hyphenate(name.substring(0, name.length - 14)));
}
},
writable: true,
configurable: true
}}, {
load: {
value: function load(container, target) {
this.instance = container.get(target);
return Promise.resolve(this);
},
writable: true,
configurable: true
},
register: {
value: function register(registry, name) {
registry.registerValueConverter(name || this.name, this.instance);
},
writable: true,
configurable: true
}
});
return ValueConverter;
})(ResourceType));
}
};
});
System.register("github:aurelia/binding@0.3.3/system/event-manager", [], function(_export) {
"use strict";
var _prototypeProperties,
DefaultEventStrategy,
EventManager;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
DefaultEventStrategy = (function() {
function DefaultEventStrategy() {
this.delegatedEvents = {};
}
_prototypeProperties(DefaultEventStrategy, null, {
ensureDelegatedEvent: {
value: function ensureDelegatedEvent(eventName) {
if (this.delegatedEvents[eventName]) {
return;
}
this.delegatedEvents[eventName] = true;
document.addEventListener(eventName, this.handleDelegatedEvent.bind(this), false);
},
writable: true,
configurable: true
},
handleCallbackResult: {
value: function handleCallbackResult(result) {},
writable: true,
configurable: true
},
handleDelegatedEvent: {
value: function handleDelegatedEvent(event) {
event = event || window.event;
var target = event.target || event.srcElement,
callback;
while (target && !callback) {
if (target.delegatedEvents) {
callback = target.delegatedEvents[event.type];
}
if (!callback) {
target = target.parentNode;
}
}
if (callback) {
this.handleCallbackResult(callback(event));
}
},
writable: true,
configurable: true
},
createDirectEventCallback: {
value: function createDirectEventCallback(callback) {
var _this = this;
return function(event) {
_this.handleCallbackResult(callback(event));
};
},
writable: true,
configurable: true
},
subscribeToDelegatedEvent: {
value: function subscribeToDelegatedEvent(target, targetEvent, callback) {
var lookup = target.delegatedEvents || (target.delegatedEvents = {});
this.ensureDelegatedEvent(targetEvent);
lookup[targetEvent] = callback;
return function() {
lookup[targetEvent] = null;
};
},
writable: true,
configurable: true
},
subscribeToDirectEvent: {
value: function subscribeToDirectEvent(target, targetEvent, callback) {
var directEventCallback = this.createDirectEventCallback(callback);
target.addEventListener(targetEvent, directEventCallback, false);
return function() {
target.removeEventListener(targetEvent, directEventCallback);
};
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(target, targetEvent, callback, delegate) {
if (delegate) {
return this.subscribeToDirectEvent(target, targetEvent, callback);
} else {
return this.subscribeToDelegatedEvent(target, targetEvent, callback);
}
},
writable: true,
configurable: true
}
});
return DefaultEventStrategy;
})();
EventManager = _export("EventManager", (function() {
function EventManager() {
this.elementHandlerLookup = {};
this.eventStrategyLookup = {};
this.registerElementConfig({
tagName: "input",
properties: {
value: ["change", "input"],
checked: ["change", "input"]
}
});
this.registerElementConfig({
tagName: "textarea",
properties: {value: ["change", "input"]}
});
this.registerElementConfig({
tagName: "select",
properties: {value: ["change"]}
});
this.defaultEventStrategy = new DefaultEventStrategy();
}
_prototypeProperties(EventManager, null, {
registerElementConfig: {
value: function registerElementConfig(config) {
this.elementHandlerLookup[config.tagName.toLowerCase()] = {subscribe: function subscribe(target, property, callback) {
var events = config.properties[property];
if (events) {
events.forEach(function(changeEvent) {
target.addEventListener(changeEvent, callback, false);
});
return function() {
events.forEach(function(changeEvent) {
target.removeEventListener(changeEvent, callback);
});
};
} else {
throw new Error("Cannot observe property " + property + " of " + config.tagName + ". No events found.");
}
}};
},
writable: true,
configurable: true
},
registerElementHandler: {
value: function registerElementHandler(tagName, handler) {
this.elementHandlerLookup[tagName.toLowerCase()] = handler;
},
writable: true,
configurable: true
},
registerEventStrategy: {
value: function registerEventStrategy(eventName, strategy) {
this.eventStrategyLookup[eventName] = strategy;
},
writable: true,
configurable: true
},
getElementHandler: {
value: function getElementHandler(target) {
if (target.tagName) {
var handler = this.elementHandlerLookup[target.tagName.toLowerCase()];
if (handler) {
return handler;
}
}
return null;
},
writable: true,
configurable: true
},
addEventListener: {
value: function addEventListener(target, targetEvent, callback, delegate) {
return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callback, delegate);
},
writable: true,
configurable: true
}
});
return EventManager;
})());
}
};
});
System.register("github:aurelia/task-queue@0.2.3/system/index", [], function(_export) {
"use strict";
var _prototypeProperties,
BrowserMutationObserver,
hasSetImmediate,
TaskQueue;
function makeRequestFlushFromMutationObserver(flush) {
var toggle = 1;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode("");
observer.observe(node, {characterData: true});
return function requestFlush() {
toggle = -toggle;
node.data = toggle;
};
}
function makeRequestFlushFromTimer(flush) {
return function requestFlush() {
var timeoutHandle = setTimeout(handleFlushTimer, 0);
var intervalHandle = setInterval(handleFlushTimer, 50);
function handleFlushTimer() {
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
flush();
}
};
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BrowserMutationObserver = window.MutationObserver || window.WebKitMutationObserver;
hasSetImmediate = typeof setImmediate === "function";
TaskQueue = _export("TaskQueue", (function() {
function TaskQueue() {
var _this = this;
this.microTaskQueue = [];
this.microTaskQueueCapacity = 1024;
this.taskQueue = [];
if (typeof BrowserMutationObserver === "function") {
this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(function() {
return _this.flushMicroTaskQueue();
});
} else {
this.requestFlushMicroTaskQueue = makeRequestFlushFromTimer(function() {
return _this.flushMicroTaskQueue();
});
}
this.requestFlushTaskQueue = makeRequestFlushFromTimer(function() {
return _this.flushTaskQueue();
});
}
_prototypeProperties(TaskQueue, null, {
queueMicroTask: {
value: function queueMicroTask(task) {
if (this.microTaskQueue.length < 1) {
this.requestFlushMicroTaskQueue();
}
this.microTaskQueue.push(task);
},
writable: true,
configurable: true
},
queueTask: {
value: function queueTask(task) {
if (this.taskQueue.length < 1) {
this.requestFlushTaskQueue();
}
this.taskQueue.push(task);
},
writable: true,
configurable: true
},
flushTaskQueue: {
value: function flushTaskQueue() {
var queue = this.taskQueue,
index = 0,
task;
this.taskQueue = [];
while (index < queue.length) {
task = queue[index];
try {
task.call();
} catch (error) {
this.onError(error, task);
}
index++;
}
},
writable: true,
configurable: true
},
flushMicroTaskQueue: {
value: function flushMicroTaskQueue() {
var queue = this.microTaskQueue,
capacity = this.microTaskQueueCapacity,
index = 0,
task;
while (index < queue.length) {
task = queue[index];
try {
task.call();
} catch (error) {
this.onError(error, task);
}
index++;
if (index > capacity) {
for (var scan = 0; scan < index; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
},
writable: true,
configurable: true
},
onError: {
value: function onError(error, task) {
if ("onError" in task) {
task.onError(error);
} else if (hasSetImmediate) {
setImmediate(function() {
throw error;
});
} else {
setTimeout(function() {
throw error;
}, 0);
}
},
writable: true,
configurable: true
}
});
return TaskQueue;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/array-change-records", [], function(_export) {
"use strict";
var EDIT_LEAVE,
EDIT_UPDATE,
EDIT_ADD,
EDIT_DELETE,
arraySplice;
_export("calcSplices", calcSplices);
_export("projectArraySplices", projectArraySplices);
function isIndex(s) {
return +s === s >>> 0;
}
function toNumber(s) {
return +s;
}
function newSplice(index, removed, addedCount) {
return {
index: index,
removed: removed,
addedCount: addedCount
};
}
function ArraySplice() {}
function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) {
return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd);
}
function intersect(start1, end1, start2, end2) {
if (end1 < start2 || end2 < start1)
return -1;
if (end1 == start2 || end2 == start1)
return 0;
if (start1 < start2) {
if (end1 < end2)
return end1 - start2;
else
return end2 - start2;
} else {
if (end2 < end1)
return end2 - start1;
else
return end1 - start1;
}
}
function mergeSplice(splices, index, removed, addedCount) {
var splice = newSplice(index, removed, addedCount);
var inserted = false;
var insertionOffset = 0;
for (var i = 0; i < splices.length; i++) {
var current = splices[i];
current.index += insertionOffset;
if (inserted)
continue;
var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount);
if (intersectCount >= 0) {
splices.splice(i, 1);
i--;
insertionOffset -= current.addedCount - current.removed.length;
splice.addedCount += current.addedCount - intersectCount;
var deleteCount = splice.removed.length + current.removed.length - intersectCount;
if (!splice.addedCount && !deleteCount) {
inserted = true;
} else {
var removed = current.removed;
if (splice.index < current.index) {
var prepend = splice.removed.slice(0, current.index - splice.index);
Array.prototype.push.apply(prepend, removed);
removed = prepend;
}
if (splice.index + splice.removed.length > current.index + current.addedCount) {
var append = splice.removed.slice(current.index + current.addedCount - splice.index);
Array.prototype.push.apply(removed, append);
}
splice.removed = removed;
if (current.index < splice.index) {
splice.index = current.index;
}
}
} else if (splice.index < current.index) {
inserted = true;
splices.splice(i, 0, splice);
i++;
var offset = splice.addedCount - splice.removed.length;
current.index += offset;
insertionOffset += offset;
}
}
if (!inserted)
splices.push(splice);
}
function createInitialSplices(array, changeRecords) {
var splices = [];
for (var i = 0; i < changeRecords.length; i++) {
var record = changeRecords[i];
switch (record.type) {
case "splice":
mergeSplice(splices, record.index, record.removed.slice(), record.addedCount);
break;
case "add":
case "update":
case "delete":
if (!isIndex(record.name))
continue;
var index = toNumber(record.name);
if (index < 0)
continue;
mergeSplice(splices, index, [record.oldValue], 1);
break;
default:
console.error("Unexpected record type: " + JSON.stringify(record));
break;
}
}
return splices;
}
function projectArraySplices(array, changeRecords) {
var splices = [];
createInitialSplices(array, changeRecords).forEach(function(splice) {
if (splice.addedCount == 1 && splice.removed.length == 1) {
if (splice.removed[0] !== array[splice.index])
splices.push(splice);
return;
}
;
splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length));
});
return splices;
}
return {
setters: [],
execute: function() {
EDIT_LEAVE = 0;
EDIT_UPDATE = 1;
EDIT_ADD = 2;
EDIT_DELETE = 3;
ArraySplice.prototype = {
calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var rowCount = oldEnd - oldStart + 1;
var columnCount = currentEnd - currentStart + 1;
var distances = new Array(rowCount);
var i,
j,
north,
west;
for (i = 0; i < rowCount; ++i) {
distances[i] = new Array(columnCount);
distances[i][0] = i;
}
for (j = 0; j < columnCount; ++j) {
distances[0][j] = j;
}
for (i = 1; i < rowCount; ++i) {
for (j = 1; j < columnCount; ++j) {
if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1]))
distances[i][j] = distances[i - 1][j - 1];
else {
north = distances[i - 1][j] + 1;
west = distances[i][j - 1] + 1;
distances[i][j] = north < west ? north : west;
}
}
}
return distances;
},
spliceOperationsFromEditDistances: function(distances) {
var i = distances.length - 1;
var j = distances[0].length - 1;
var current = distances[i][j];
var edits = [];
while (i > 0 || j > 0) {
if (i == 0) {
edits.push(EDIT_ADD);
j--;
continue;
}
if (j == 0) {
edits.push(EDIT_DELETE);
i--;
continue;
}
var northWest = distances[i - 1][j - 1];
var west = distances[i - 1][j];
var north = distances[i][j - 1];
var min;
if (west < north)
min = west < northWest ? west : northWest;
else
min = north < northWest ? north : northWest;
if (min == northWest) {
if (northWest == current) {
edits.push(EDIT_LEAVE);
} else {
edits.push(EDIT_UPDATE);
current = northWest;
}
i--;
j--;
} else if (min == west) {
edits.push(EDIT_DELETE);
i--;
current = west;
} else {
edits.push(EDIT_ADD);
j--;
current = north;
}
}
edits.reverse();
return edits;
},
calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var prefixCount = 0;
var suffixCount = 0;
var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);
if (currentStart == 0 && oldStart == 0)
prefixCount = this.sharedPrefix(current, old, minLength);
if (currentEnd == current.length && oldEnd == old.length)
suffixCount = this.sharedSuffix(current, old, minLength - prefixCount);
currentStart += prefixCount;
oldStart += prefixCount;
currentEnd -= suffixCount;
oldEnd -= suffixCount;
if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0)
return [];
if (currentStart == currentEnd) {
var splice = newSplice(currentStart, [], 0);
while (oldStart < oldEnd)
splice.removed.push(old[oldStart++]);
return [splice];
} else if (oldStart == oldEnd)
return [newSplice(currentStart, [], currentEnd - currentStart)];
var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd));
var splice = undefined;
var splices = [];
var index = currentStart;
var oldIndex = oldStart;
for (var i = 0; i < ops.length; ++i) {
switch (ops[i]) {
case EDIT_LEAVE:
if (splice) {
splices.push(splice);
splice = undefined;
}
index++;
oldIndex++;
break;
case EDIT_UPDATE:
if (!splice)
splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
case EDIT_ADD:
if (!splice)
splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
break;
case EDIT_DELETE:
if (!splice)
splice = newSplice(index, [], 0);
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
}
}
if (splice) {
splices.push(splice);
}
return splices;
},
sharedPrefix: function(current, old, searchLength) {
for (var i = 0; i < searchLength; ++i)
if (!this.equals(current[i], old[i]))
return i;
return searchLength;
},
sharedSuffix: function(current, old, searchLength) {
var index1 = current.length;
var index2 = old.length;
var count = 0;
while (count < searchLength && this.equals(current[--index1], old[--index2]))
count++;
return count;
},
calculateSplices: function(current, previous) {
return this.calcSplices(current, 0, current.length, previous, 0, previous.length);
},
equals: function(currentValue, previousValue) {
return currentValue === previousValue;
}
};
arraySplice = new ArraySplice();
}
};
});
System.register("github:aurelia/binding@0.3.3/system/dirty-checking", [], function(_export) {
"use strict";
var _prototypeProperties,
DirtyChecker,
DirtyCheckProperty;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
DirtyChecker = _export("DirtyChecker", (function() {
function DirtyChecker() {
this.tracked = [];
this.checkDelay = 120;
}
_prototypeProperties(DirtyChecker, null, {
addProperty: {
value: function addProperty(property) {
var tracked = this.tracked;
tracked.push(property);
if (tracked.length === 1) {
this.scheduleDirtyCheck();
}
},
writable: true,
configurable: true
},
removeProperty: {
value: function removeProperty(property) {
var tracked = this.tracked;
tracked.splice(tracked.indexOf(property), 1);
},
writable: true,
configurable: true
},
scheduleDirtyCheck: {
value: function scheduleDirtyCheck() {
var _this = this;
setTimeout(function() {
return _this.check();
}, this.checkDelay);
},
writable: true,
configurable: true
},
check: {
value: function check() {
var tracked = this.tracked,
i = tracked.length;
while (i--) {
var current = tracked[i];
if (current.isDirty()) {
current.call();
}
}
if (tracked.length) {
this.scheduleDirtyCheck();
}
},
writable: true,
configurable: true
}
});
return DirtyChecker;
})());
DirtyCheckProperty = _export("DirtyCheckProperty", (function() {
function DirtyCheckProperty(dirtyChecker, obj, propertyName) {
this.dirtyChecker = dirtyChecker;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.isSVG = obj instanceof SVGElement;
}
_prototypeProperties(DirtyCheckProperty, null, {
getValue: {
value: function getValue() {
return this.obj[this.propertyName];
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
if (this.isSVG) {
this.obj.setAttributeNS(null, this.propertyName, newValue);
} else {
this.obj[this.propertyName] = newValue;
}
},
writable: true,
configurable: true
},
call: {
value: function call() {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.getValue();
while (i--) {
callbacks[i](newValue, oldValue);
}
this.oldValue = newValue;
},
writable: true,
configurable: true
},
isDirty: {
value: function isDirty() {
return this.oldValue !== this.getValue();
},
writable: true,
configurable: true
},
beginTracking: {
value: function beginTracking() {
this.tracking = true;
this.oldValue = this.newValue = this.getValue();
this.dirtyChecker.addProperty(this);
},
writable: true,
configurable: true
},
endTracking: {
value: function endTracking() {
this.tracking = false;
this.dirtyChecker.removeProperty(this);
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var callbacks = this.callbacks,
that = this;
callbacks.push(callback);
if (!this.tracking) {
this.beginTracking();
}
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
if (callbacks.length === 0) {
that.endTracking();
}
};
},
writable: true,
configurable: true
}
});
return DirtyCheckProperty;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/property-observation", [], function(_export) {
"use strict";
var _prototypeProperties,
SetterObserver,
OoObjectObserver,
OoPropertyObserver,
ElementObserver;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
SetterObserver = _export("SetterObserver", (function() {
function SetterObserver(taskQueue, obj, propertyName) {
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.queued = false;
this.observing = false;
this.isSVG = obj instanceof SVGElement;
}
_prototypeProperties(SetterObserver, null, {
getValue: {
value: function getValue() {
return this.obj[this.propertyName];
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
if (this.isSVG) {
this.obj.setAttributeNS(null, this.propertyName, newValue);
} else {
this.obj[this.propertyName] = newValue;
}
},
writable: true,
configurable: true
},
getterValue: {
value: function getterValue() {
return this.currentValue;
},
writable: true,
configurable: true
},
setterValue: {
value: function setterValue(newValue) {
var oldValue = this.currentValue;
if (oldValue != newValue) {
if (!this.queued) {
this.oldValue = oldValue;
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
this.currentValue = newValue;
}
},
writable: true,
configurable: true
},
call: {
value: function call() {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.currentValue;
this.queued = false;
while (i--) {
callbacks[i](newValue, oldValue);
}
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var callbacks = this.callbacks;
callbacks.push(callback);
if (!this.observing) {
this.convertProperty();
}
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
},
convertProperty: {
value: function convertProperty() {
this.observing = true;
this.currentValue = this.obj[this.propertyName];
this.setValue = this.setterValue;
this.getValue = this.getterValue;
Object.defineProperty(this.obj, this.propertyName, {
configurable: true,
enumerable: true,
get: this.getValue.bind(this),
set: this.setValue.bind(this)
});
},
writable: true,
configurable: true
}
});
return SetterObserver;
})());
OoObjectObserver = _export("OoObjectObserver", (function() {
function OoObjectObserver(obj) {
this.obj = obj;
this.observers = {};
}
_prototypeProperties(OoObjectObserver, null, {
subscribe: {
value: function subscribe(propertyObserver, callback) {
var _this = this;
var callbacks = propertyObserver.callbacks;
callbacks.push(callback);
if (!this.observing) {
this.observing = true;
Object.observe(this.obj, function(changes) {
return _this.handleChanges(changes);
}, ["update", "add"]);
}
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
},
getObserver: {
value: function getObserver(propertyName) {
var propertyObserver = this.observers[propertyName] || (this.observers[propertyName] = new OoPropertyObserver(this, this.obj, propertyName));
return propertyObserver;
},
writable: true,
configurable: true
},
handleChanges: {
value: function handleChanges(changeRecords) {
var updates = {},
observers = this.observers,
i = changeRecords.length;
while (i--) {
var change = changeRecords[i],
name = change.name;
if (!(name in updates)) {
var observer = observers[name];
updates[name] = true;
if (observer) {
observer.trigger(change.object[name], change.oldValue);
}
}
}
},
writable: true,
configurable: true
}
});
return OoObjectObserver;
})());
OoPropertyObserver = _export("OoPropertyObserver", (function() {
function OoPropertyObserver(owner, obj, propertyName) {
this.owner = owner;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.isSVG = obj instanceof SVGElement;
}
_prototypeProperties(OoPropertyObserver, null, {
getValue: {
value: function getValue() {
return this.obj[this.propertyName];
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
if (this.isSVG) {
this.obj.setAttributeNS(null, this.propertyName, newValue);
} else {
this.obj[this.propertyName] = newValue;
}
},
writable: true,
configurable: true
},
trigger: {
value: function trigger(newValue, oldValue) {
var callbacks = this.callbacks,
i = callbacks.length;
while (i--) {
callbacks[i](newValue, oldValue);
}
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
return this.owner.subscribe(this, callback);
},
writable: true,
configurable: true
}
});
return OoPropertyObserver;
})());
ElementObserver = _export("ElementObserver", (function() {
function ElementObserver(handler, element, propertyName) {
this.element = element;
this.propertyName = propertyName;
this.callbacks = [];
this.oldValue = element[propertyName];
this.handler = handler;
}
_prototypeProperties(ElementObserver, null, {
getValue: {
value: function getValue() {
return this.element[this.propertyName];
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
this.element[this.propertyName] = newValue;
this.call();
},
writable: true,
configurable: true
},
call: {
value: function call() {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.getValue();
while (i--) {
callbacks[i](newValue, oldValue);
}
this.oldValue = newValue;
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var that = this;
if (!this.disposeHandler) {
this.disposeHandler = this.handler.subscribe(this.element, this.propertyName, this.call.bind(this));
}
var callbacks = this.callbacks;
callbacks.push(callback);
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
if (callback.length === 0) {
that.disposeHandler();
that.disposeHandler = null;
}
};
},
writable: true,
configurable: true
}
});
return ElementObserver;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/binding-modes", [], function(_export) {
"use strict";
var ONE_WAY,
TWO_WAY,
ONE_TIME;
return {
setters: [],
execute: function() {
ONE_WAY = _export("ONE_WAY", 1);
TWO_WAY = _export("TWO_WAY", 2);
ONE_TIME = _export("ONE_TIME", 3);
}
};
});
System.register("github:aurelia/binding@0.3.3/system/lexer", [], function(_export) {
"use strict";
var _prototypeProperties,
Token,
Lexer,
Scanner,
OPERATORS,
$EOF,
$TAB,
$LF,
$VTAB,
$FF,
$CR,
$SPACE,
$BANG,
$DQ,
$$,
$PERCENT,
$AMPERSAND,
$SQ,
$LPAREN,
$RPAREN,
$STAR,
$PLUS,
$COMMA,
$MINUS,
$PERIOD,
$SLASH,
$COLON,
$SEMICOLON,
$LT,
$EQ,
$GT,
$QUESTION,
$0,
$9,
$A,
$E,
$Z,
$LBRACKET,
$BACKSLASH,
$RBRACKET,
$CARET,
$_,
$a,
$e,
$f,
$n,
$r,
$t,
$u,
$v,
$z,
$LBRACE,
$BAR,
$RBRACE,
$NBSP;
function isWhitespace(code) {
return code >= $TAB && code <= $SPACE || code === $NBSP;
}
function isIdentifierStart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || code === $_ || code === $$;
}
function isIdentifierPart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || $0 <= code && code <= $9 || code === $_ || code === $$;
}
function isDigit(code) {
return $0 <= code && code <= $9;
}
function isExponentStart(code) {
return code === $e || code === $E;
}
function isExponentSign(code) {
return code === $MINUS || code === $PLUS;
}
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Token = _export("Token", (function() {
function Token(index, text) {
this.index = index;
this.text = text;
}
_prototypeProperties(Token, null, {
withOp: {
value: function withOp(op) {
this.opKey = op;
return this;
},
writable: true,
configurable: true
},
withGetterSetter: {
value: function withGetterSetter(key) {
this.key = key;
return this;
},
writable: true,
configurable: true
},
withValue: {
value: function withValue(value) {
this.value = value;
return this;
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
return "Token(" + this.text + ")";
},
writable: true,
configurable: true
}
});
return Token;
})());
Lexer = _export("Lexer", (function() {
function Lexer() {}
_prototypeProperties(Lexer, null, {lex: {
value: function lex(text) {
var scanner = new Scanner(text);
var tokens = [];
var token = scanner.scanToken();
while (token) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
},
writable: true,
configurable: true
}});
return Lexer;
})());
Scanner = _export("Scanner", (function() {
function Scanner(input) {
this.input = input;
this.length = input.length;
this.peek = 0;
this.index = -1;
this.advance();
}
_prototypeProperties(Scanner, null, {
scanToken: {
value: function scanToken() {
while (this.peek <= $SPACE) {
if (++this.index >= this.length) {
this.peek = $EOF;
return null;
} else {
this.peek = this.input.charCodeAt(this.index);
}
}
if (isIdentifierStart(this.peek)) {
return this.scanIdentifier();
}
if (isDigit(this.peek)) {
return this.scanNumber(this.index);
}
var start = this.index;
switch (this.peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) : new Token(start, ".");
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, String.fromCharCode(this.peek));
case $SQ:
case $DQ:
return this.scanString();
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
case $QUESTION:
return this.scanOperator(start, String.fromCharCode(this.peek));
case $LT:
case $GT:
case $BANG:
case $EQ:
return this.scanComplexOperator(start, $EQ, String.fromCharCode(this.peek), "=");
case $AMPERSAND:
return this.scanComplexOperator(start, $AMPERSAND, "&", "&");
case $BAR:
return this.scanComplexOperator(start, $BAR, "|", "|");
case $NBSP:
while (isWhitespace(this.peek)) {
this.advance();
}
return this.scanToken();
}
var character = String.fromCharCode(this.peek);
this.error("Unexpected character [" + character + "]");
return null;
},
writable: true,
configurable: true
},
scanCharacter: {
value: function scanCharacter(start, text) {
assert(this.peek === text.charCodeAt(0));
this.advance();
return new Token(start, text);
},
writable: true,
configurable: true
},
scanOperator: {
value: function scanOperator(start, text) {
assert(this.peek === text.charCodeAt(0));
assert(OPERATORS.indexOf(text) !== -1);
this.advance();
return new Token(start, text).withOp(text);
},
writable: true,
configurable: true
},
scanComplexOperator: {
value: function scanComplexOperator(start, code, one, two) {
assert(this.peek === one.charCodeAt(0));
this.advance();
var text = one;
if (this.peek === code) {
this.advance();
text += two;
}
if (this.peek === code) {
this.advance();
text += two;
}
assert(OPERATORS.indexOf(text) != -1);
return new Token(start, text).withOp(text);
},
writable: true,
configurable: true
},
scanIdentifier: {
value: function scanIdentifier() {
assert(isIdentifierStart(this.peek));
var start = this.index;
this.advance();
while (isIdentifierPart(this.peek)) {
this.advance();
}
var text = this.input.substring(start, this.index);
var result = new Token(start, text);
if (OPERATORS.indexOf(text) !== -1) {
result.withOp(text);
} else {
result.withGetterSetter(text);
}
return result;
},
writable: true,
configurable: true
},
scanNumber: {
value: function scanNumber(start) {
assert(isDigit(this.peek));
var simple = this.index === start;
this.advance();
while (true) {
if (isDigit(this.peek)) {} else if (this.peek === $PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek)) {
this.advance();
}
if (!isDigit(this.peek)) {
this.error("Invalid exponent", -1);
}
simple = false;
} else {
break;
}
this.advance();
}
var text = this.input.substring(start, this.index);
var value = simple ? parseInt(text) : parseFloat(text);
return new Token(start, text).withValue(value);
},
writable: true,
configurable: true
},
scanString: {
value: function scanString() {
assert(this.peek === $SQ || this.peek === $DQ);
var start = this.index;
var quote = this.peek;
this.advance();
var buffer;
var marker = this.index;
while (this.peek !== quote) {
if (this.peek === $BACKSLASH) {
if (buffer === null) {
buffer = [];
}
buffer.push(this.input.substring(marker, this.index));
this.advance();
var unescaped;
if (this.peek === $u) {
var hex = this.input.substring(this.index + 1, this.index + 5);
if (!/[A-Z0-9]{4}/.test(hex)) {
this.error("Invalid unicode escape [\\u" + hex + "]");
}
unescaped = parseInt(hex, 16);
for (var i = 0; i < 5; ++i) {
this.advance();
}
} else {
unescaped = decodeURIComponent(this.peek);
this.advance();
}
buffer.push(String.fromCharCode(unescaped));
marker = this.index;
} else if (this.peek === $EOF) {
this.error("Unterminated quote");
} else {
this.advance();
}
}
var last = this.input.substring(marker, this.index);
this.advance();
var text = this.input.substring(start, this.index);
var unescaped = last;
if (buffer != null) {
buffer.push(last);
unescaped = buffer.join("");
}
return new Token(start, text).withValue(unescaped);
},
writable: true,
configurable: true
},
advance: {
value: function advance() {
if (++this.index >= this.length) {
this.peek = $EOF;
} else {
this.peek = this.input.charCodeAt(this.index);
}
},
writable: true,
configurable: true
},
error: {
value: function error(message) {
var offset = arguments[1] === undefined ? 0 : arguments[1];
var position = this.index + offset;
throw new Error("Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
},
writable: true,
configurable: true
}
});
return Scanner;
})());
OPERATORS = ["undefined", "null", "true", "false", "+", "-", "*", "/", "%", "^", "=", "==", "===", "!=", "!==", "<", ">", "<=", ">=", "&&", "||", "&", "|", "!", "?"];
$EOF = 0;
$TAB = 9;
$LF = 10;
$VTAB = 11;
$FF = 12;
$CR = 13;
$SPACE = 32;
$BANG = 33;
$DQ = 34;
$$ = 36;
$PERCENT = 37;
$AMPERSAND = 38;
$SQ = 39;
$LPAREN = 40;
$RPAREN = 41;
$STAR = 42;
$PLUS = 43;
$COMMA = 44;
$MINUS = 45;
$PERIOD = 46;
$SLASH = 47;
$COLON = 58;
$SEMICOLON = 59;
$LT = 60;
$EQ = 61;
$GT = 62;
$QUESTION = 63;
$0 = 48;
$9 = 57;
$A = 65;
$E = 69;
$Z = 90;
$LBRACKET = 91;
$BACKSLASH = 92;
$RBRACKET = 93;
$CARET = 94;
$_ = 95;
$a = 97;
$e = 101;
$f = 102;
$n = 110;
$r = 114;
$t = 116;
$u = 117;
$v = 118;
$z = 122;
$LBRACE = 123;
$BAR = 124;
$RBRACE = 125;
$NBSP = 160;
}
};
});
System.register("github:aurelia/binding@0.3.3/system/path-observer", [], function(_export) {
"use strict";
var _prototypeProperties,
PathObserver;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
PathObserver = _export("PathObserver", (function() {
function PathObserver(leftObserver, getRightObserver, value) {
var _this = this;
this.leftObserver = leftObserver;
this.disposeLeft = leftObserver.subscribe(function(newValue) {
var newRightValue = _this.updateRight(getRightObserver(newValue));
_this.notify(newRightValue);
});
this.updateRight(getRightObserver(value));
}
_prototypeProperties(PathObserver, null, {
updateRight: {
value: function updateRight(observer) {
var _this = this;
this.rightObserver = observer;
if (this.disposeRight) {
this.disposeRight();
}
if (!observer) {
return null;
}
this.disposeRight = observer.subscribe(function(newValue) {
return _this.notify(newValue);
});
return observer.getValue();
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var that = this;
that.callback = callback;
return function() {
that.callback = null;
};
},
writable: true,
configurable: true
},
notify: {
value: function notify(newValue) {
var callback = this.callback;
if (callback) {
callback(newValue);
}
},
writable: true,
configurable: true
},
dispose: {
value: function dispose() {
if (this.disposeLeft) {
this.disposeLeft();
}
if (this.disposeRight) {
this.disposeRight();
}
},
writable: true,
configurable: true
}
});
return PathObserver;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/composite-observer", [], function(_export) {
"use strict";
var _prototypeProperties,
CompositeObserver;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
CompositeObserver = _export("CompositeObserver", (function() {
function CompositeObserver(observers, evaluate) {
var _this = this;
this.subscriptions = new Array(observers.length);
this.evaluate = evaluate;
for (var i = 0,
ii = observers.length; i < ii; i++) {
this.subscriptions[i] = observers[i].subscribe(function(newValue) {
_this.notify(_this.evaluate());
});
}
}
_prototypeProperties(CompositeObserver, null, {
subscribe: {
value: function subscribe(callback) {
var that = this;
that.callback = callback;
return function() {
that.callback = null;
};
},
writable: true,
configurable: true
},
notify: {
value: function notify(newValue) {
var callback = this.callback;
if (callback) {
callback(newValue);
}
},
writable: true,
configurable: true
},
dispose: {
value: function dispose() {
var subscriptions = this.subscriptions;
while (i--) {
subscriptions[i]();
}
},
writable: true,
configurable: true
}
});
return CompositeObserver;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/binding-expression", ["./binding-modes"], function(_export) {
"use strict";
var ONE_WAY,
TWO_WAY,
_prototypeProperties,
BindingExpression,
Binding;
return {
setters: [function(_bindingModes) {
ONE_WAY = _bindingModes.ONE_WAY;
TWO_WAY = _bindingModes.TWO_WAY;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BindingExpression = _export("BindingExpression", (function() {
function BindingExpression(observerLocator, targetProperty, sourceExpression, mode, valueConverterLookupFunction, attribute) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.mode = mode;
this.valueConverterLookupFunction = valueConverterLookupFunction;
this.attribute = attribute;
this.discrete = false;
}
_prototypeProperties(BindingExpression, null, {createBinding: {
value: function createBinding(target) {
return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.valueConverterLookupFunction);
},
writable: true,
configurable: true
}});
return BindingExpression;
})());
Binding = (function() {
function Binding(observerLocator, sourceExpression, target, targetProperty, mode, valueConverterLookupFunction) {
this.observerLocator = observerLocator;
this.sourceExpression = sourceExpression;
this.targetProperty = observerLocator.getObserver(target, targetProperty);
this.mode = mode;
this.valueConverterLookupFunction = valueConverterLookupFunction;
}
_prototypeProperties(Binding, null, {
getObserver: {
value: function getObserver(obj, propertyName) {
return this.observerLocator.getObserver(obj, propertyName);
},
writable: true,
configurable: true
},
bind: {
value: function bind(source) {
var _this = this;
var targetProperty = this.targetProperty,
info;
if (this.mode == ONE_WAY || this.mode == TWO_WAY) {
if (this._disposeObserver) {
if (this.source === source) {
return;
}
this.unbind();
}
info = this.sourceExpression.connect(this, source);
if (info.observer) {
this._disposeObserver = info.observer.subscribe(function(newValue) {
var existing = targetProperty.getValue();
if (newValue !== existing) {
targetProperty.setValue(newValue);
}
});
}
if (info.value !== undefined) {
targetProperty.setValue(info.value);
}
if (this.mode == TWO_WAY) {
this._disposeListener = targetProperty.subscribe(function(newValue) {
_this.sourceExpression.assign(source, newValue, _this.valueConverterLookupFunction);
});
}
this.source = source;
} else {
var value = this.sourceExpression.evaluate(source, this.valueConverterLookupFunction);
if (value !== undefined) {
targetProperty.setValue(value);
}
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
if (this._disposeObserver) {
this._disposeObserver();
this._disposeObserver = null;
}
if (this._disposeListener) {
this._disposeListener();
this._disposeListener = null;
}
},
writable: true,
configurable: true
}
});
return Binding;
})();
}
};
});
System.register("github:aurelia/binding@0.3.3/system/listener-expression", [], function(_export) {
"use strict";
var _prototypeProperties,
ListenerExpression,
Listener;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ListenerExpression = _export("ListenerExpression", (function() {
function ListenerExpression(eventManager, targetEvent, sourceExpression, delegate, preventDefault) {
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.sourceExpression = sourceExpression;
this.delegate = delegate;
this.discrete = true;
this.preventDefault = preventDefault;
}
_prototypeProperties(ListenerExpression, null, {createBinding: {
value: function createBinding(target) {
return new Listener(this.eventManager, this.targetEvent, this.delegate, this.sourceExpression, target, this.preventDefault);
},
writable: true,
configurable: true
}});
return ListenerExpression;
})());
Listener = (function() {
function Listener(eventManager, targetEvent, delegate, sourceExpression, target, preventDefault) {
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.delegate = delegate;
this.sourceExpression = sourceExpression;
this.target = target;
this.preventDefault = preventDefault;
}
_prototypeProperties(Listener, null, {
bind: {
value: function bind(source) {
var _this = this;
if (this._disposeListener) {
if (this.source === source) {
return;
}
this.unbind();
}
this.source = source;
this._disposeListener = this.eventManager.addEventListener(this.target, this.targetEvent, function(event) {
var prevEvent = source.$event;
source.$event = event;
var result = _this.sourceExpression.evaluate(source);
source.$event = prevEvent;
if (_this.preventDefault) {
event.preventDefault();
}
return result;
}, this.delegate);
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
if (this._disposeListener) {
this._disposeListener();
this._disposeListener = null;
}
},
writable: true,
configurable: true
}
});
return Listener;
})();
}
};
});
System.register("github:aurelia/binding@0.3.3/system/name-expression", [], function(_export) {
"use strict";
var _prototypeProperties,
NameExpression,
NameBinder;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
NameExpression = _export("NameExpression", (function() {
function NameExpression(name, mode) {
this.property = name;
this.discrete = true;
this.mode = (mode || "view-model").toLowerCase();
}
_prototypeProperties(NameExpression, null, {createBinding: {
value: function createBinding(target) {
return new NameBinder(this.property, target, this.mode);
},
writable: true,
configurable: true
}});
return NameExpression;
})());
NameBinder = (function() {
function NameBinder(property, target, mode) {
this.property = property;
switch (mode) {
case "element":
this.target = target;
break;
case "view-model":
this.target = target.primaryBehavior ? target.primaryBehavior.executionContext : target;
break;
default:
throw new Error("Name expressions do not support mode: " + mode);
}
}
_prototypeProperties(NameBinder, null, {
bind: {
value: function bind(source) {
if (this.source) {
if (this.source === source) {
return;
}
this.unbind();
}
this.source = source;
source[this.property] = this.target;
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
this.source[this.property] = null;
},
writable: true,
configurable: true
}
});
return NameBinder;
})();
}
};
});
System.register("github:aurelia/binding@0.3.3/system/call-expression", [], function(_export) {
"use strict";
var _prototypeProperties,
CallExpression,
Call;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
CallExpression = _export("CallExpression", (function() {
function CallExpression(observerLocator, targetProperty, sourceExpression, valueConverterLookupFunction) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.valueConverterLookupFunction = valueConverterLookupFunction;
}
_prototypeProperties(CallExpression, null, {createBinding: {
value: function createBinding(target) {
return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.valueConverterLookupFunction);
},
writable: true,
configurable: true
}});
return CallExpression;
})());
Call = (function() {
function Call(observerLocator, sourceExpression, target, targetProperty, valueConverterLookupFunction) {
this.sourceExpression = sourceExpression;
this.target = target;
this.targetProperty = observerLocator.getObserver(target, targetProperty);
this.valueConverterLookupFunction = valueConverterLookupFunction;
}
_prototypeProperties(Call, null, {
bind: {
value: function bind(source) {
var _this = this;
if (this.source === source) {
return;
}
if (this.source) {
this.unbind();
}
this.source = source;
this.targetProperty.setValue(function() {
for (var _len = arguments.length,
rest = Array(_len),
_key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return _this.sourceExpression.evaluate(source, _this.valueConverterLookupFunction, rest);
});
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
this.targetProperty.setValue(null);
},
writable: true,
configurable: true
}
});
return Call;
})();
}
};
});
System.register("github:aurelia/templating@0.8.8/system/behavior-instance", [], function(_export) {
"use strict";
var _prototypeProperties,
BehaviorInstance;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BehaviorInstance = _export("BehaviorInstance", (function() {
function BehaviorInstance(behavior, executionContext, instruction) {
this.behavior = behavior;
this.executionContext = executionContext;
var observerLookup = behavior.observerLocator.getObserversLookup(executionContext),
handlesBind = behavior.handlesBind,
attributes = instruction.attributes,
boundProperties = this.boundProperties = [],
properties = behavior.properties,
i,
ii;
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i].initialize(executionContext, observerLookup, attributes, handlesBind, boundProperties);
}
}
_prototypeProperties(BehaviorInstance, null, {
created: {
value: function created(context) {
if (this.behavior.handlesCreated) {
this.executionContext.created(context);
}
},
writable: true,
configurable: true
},
bind: {
value: function bind(context) {
var skipSelfSubscriber = this.behavior.handlesBind,
boundProperties = this.boundProperties,
i,
ii,
x,
observer,
selfSubscriber;
for (i = 0, ii = boundProperties.length; i < ii; ++i) {
x = boundProperties[i];
observer = x.observer;
selfSubscriber = observer.selfSubscriber;
observer.publishing = false;
if (skipSelfSubscriber) {
observer.selfSubscriber = null;
}
x.binding.bind(context);
observer.call();
observer.publishing = true;
observer.selfSubscriber = selfSubscriber;
}
if (skipSelfSubscriber) {
this.executionContext.bind(context);
}
if (this.view) {
this.view.bind(this.executionContext);
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
var boundProperties = this.boundProperties,
i,
ii;
if (this.view) {
this.view.unbind();
}
if (this.behavior.handlesUnbind) {
this.executionContext.unbind();
}
for (i = 0, ii = boundProperties.length; i < ii; ++i) {
boundProperties[i].binding.unbind();
}
},
writable: true,
configurable: true
},
attached: {
value: function attached() {
if (this.behavior.handlesAttached) {
this.executionContext.attached();
}
},
writable: true,
configurable: true
},
detached: {
value: function detached() {
if (this.behavior.handlesDetached) {
this.executionContext.detached();
}
},
writable: true,
configurable: true
}
});
return BehaviorInstance;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/children", [], function(_export) {
"use strict";
var _prototypeProperties,
noMutations,
ChildObserver,
ChildObserverBinder;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
noMutations = [];
ChildObserver = _export("ChildObserver", (function() {
function ChildObserver(property, changeHandler, selector) {
this.selector = selector;
this.changeHandler = changeHandler;
this.property = property;
}
_prototypeProperties(ChildObserver, null, {createBinding: {
value: function createBinding(target, behavior) {
return new ChildObserverBinder(this.selector, target, this.property, behavior, this.changeHandler);
},
writable: true,
configurable: true
}});
return ChildObserver;
})());
ChildObserverBinder = _export("ChildObserverBinder", (function() {
function ChildObserverBinder(selector, target, property, behavior, changeHandler) {
this.selector = selector;
this.target = target;
this.property = property;
this.target = target;
this.behavior = behavior;
this.changeHandler = changeHandler;
this.observer = new MutationObserver(this.onChange.bind(this));
}
_prototypeProperties(ChildObserverBinder, null, {
bind: {
value: function bind(source) {
var items,
results,
i,
ii,
node,
behavior = this.behavior;
this.observer.observe(this.target, {
childList: true,
subtree: true
});
items = behavior[this.property];
if (!items) {
items = behavior[this.property] = [];
} else {
items.length = 0;
}
results = this.target.querySelectorAll(this.selector);
for (i = 0, ii = results.length; i < ii; ++i) {
node = results[i];
items.push(node.primaryBehavior ? node.primaryBehavior.executionContext : node);
}
if (this.changeHandler) {
this.behavior[this.changeHandler](noMutations);
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
this.observer.disconnect();
},
writable: true,
configurable: true
},
onChange: {
value: function onChange(mutations) {
var items = this.behavior[this.property],
selector = this.selector;
mutations.forEach(function(record) {
var added = record.addedNodes,
removed = record.removedNodes,
prev = record.previousSibling,
i,
ii,
primary,
index,
node;
for (i = 0, ii = removed.length; i < ii; ++i) {
node = removed[i];
if (node.nodeType === 1 && node.matches(selector)) {
primary = node.primaryBehavior ? node.primaryBehavior.executionContext : node;
index = items.indexOf(primary);
if (index != -1) {
items.splice(index, 1);
}
}
}
for (i = 0, ii = added.length; i < ii; ++i) {
node = added[i];
if (node.nodeType === 1 && node.matches(selector)) {
primary = node.primaryBehavior ? node.primaryBehavior.executionContext : node;
index = 0;
while (prev) {
if (prev.nodeType === 1 && prev.matches(selector)) {
index++;
}
prev = prev.previousSibling;
}
items.splice(index, 0, primary);
}
}
});
if (this.changeHandler) {
this.behavior[this.changeHandler](mutations);
}
},
writable: true,
configurable: true
}
});
return ChildObserverBinder;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/content-selector", [], function(_export) {
"use strict";
var _prototypeProperties,
proto,
placeholder,
ContentSelector;
function findInsertionPoint(groups, index) {
var insertionPoint;
while (!insertionPoint && index >= 0) {
insertionPoint = groups[index][0];
index--;
}
return insertionPoint || anchor;
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
if (Element && !Element.prototype.matches) {
proto = Element.prototype;
proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector;
}
placeholder = [];
ContentSelector = _export("ContentSelector", (function() {
function ContentSelector(anchor, selector) {
this.anchor = anchor;
this.selector = selector;
this.all = !this.selector;
this.groups = [];
}
_prototypeProperties(ContentSelector, {applySelectors: {
value: function applySelectors(view, contentSelectors, callback) {
var currentChild = view.fragment.firstChild,
contentMap = new Map(),
nextSibling,
i,
ii,
contentSelector;
while (currentChild) {
nextSibling = currentChild.nextSibling;
if (currentChild.viewSlot) {
var viewSlotSelectors = contentSelectors.map(function(x) {
return x.copyForViewSlot();
});
currentChild.viewSlot.installContentSelectors(viewSlotSelectors);
} else {
for (i = 0, ii = contentSelectors.length; i < ii; i++) {
contentSelector = contentSelectors[i];
if (contentSelector.matches(currentChild)) {
var elements = contentMap.get(contentSelector);
if (!elements) {
elements = [];
contentMap.set(contentSelector, elements);
}
elements.push(currentChild);
break;
}
}
}
currentChild = nextSibling;
}
for (i = 0, ii = contentSelectors.length; i < ii; ++i) {
contentSelector = contentSelectors[i];
callback(contentSelector, contentMap.get(contentSelector) || placeholder);
}
},
writable: true,
configurable: true
}}, {
copyForViewSlot: {
value: function copyForViewSlot() {
return new ContentSelector(this.anchor, this.selector);
},
writable: true,
configurable: true
},
matches: {
value: function matches(node) {
return this.all || node.nodeType === 1 && node.matches(this.selector);
},
writable: true,
configurable: true
},
add: {
value: function add(group) {
var anchor = this.anchor,
parent = anchor.parentNode,
i,
ii;
for (i = 0, ii = group.length; i < ii; ++i) {
parent.insertBefore(group[i], anchor);
}
this.groups.push(group);
},
writable: true,
configurable: true
},
insert: {
value: function insert(index, group) {
if (group.length) {
var anchor = findInsertionPoint(this.groups, index) || this.anchor,
parent = anchor.parentNode,
i,
ii;
for (i = 0, ii = group.length; i < ii; ++i) {
parent.insertBefore(group[i], anchor);
}
}
this.groups.splice(index, 0, group);
},
writable: true,
configurable: true
},
removeAt: {
value: function removeAt(index, fragment) {
var group = this.groups[index],
i,
ii;
for (i = 0, ii = group.length; i < ii; ++i) {
fragment.appendChild(group[i]);
}
this.groups.splice(index, 1);
},
writable: true,
configurable: true
}
});
return ContentSelector;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/resource-registry", ["aurelia-path"], function(_export) {
"use strict";
var relativeToFile,
_get,
_inherits,
_prototypeProperties,
ResourceRegistry,
ViewResources;
function register(lookup, name, resource, type) {
if (!name) {
return;
}
var existing = lookup[name];
if (existing) {
if (existing != resource) {
throw new Error("Attempted to register " + type + " when one with the same name already exists. Name: " + name + ".");
}
return;
}
lookup[name] = resource;
}
return {
setters: [function(_aureliaPath) {
relativeToFile = _aureliaPath.relativeToFile;
}],
execute: function() {
_get = function get(object, property, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc && desc.writable) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ResourceRegistry = _export("ResourceRegistry", (function() {
function ResourceRegistry() {
this.attributes = {};
this.elements = {};
this.valueConverters = {};
this.attributeMap = {};
this.baseResourceUrl = "";
}
_prototypeProperties(ResourceRegistry, null, {
registerElement: {
value: function registerElement(tagName, behavior) {
register(this.elements, tagName, behavior, "an Element");
},
writable: true,
configurable: true
},
getElement: {
value: function getElement(tagName) {
return this.elements[tagName];
},
writable: true,
configurable: true
},
registerAttribute: {
value: function registerAttribute(attribute, behavior, knownAttribute) {
this.attributeMap[attribute] = knownAttribute;
register(this.attributes, attribute, behavior, "an Attribute");
},
writable: true,
configurable: true
},
getAttribute: {
value: function getAttribute(attribute) {
return this.attributes[attribute];
},
writable: true,
configurable: true
},
registerValueConverter: {
value: function registerValueConverter(name, valueConverter) {
register(this.valueConverters, name, valueConverter, "a ValueConverter");
},
writable: true,
configurable: true
},
getValueConverter: {
value: function getValueConverter(name) {
return this.valueConverters[name];
},
writable: true,
configurable: true
}
});
return ResourceRegistry;
})());
ViewResources = _export("ViewResources", (function(ResourceRegistry) {
function ViewResources(parent, viewUrl) {
_get(Object.getPrototypeOf(ViewResources.prototype), "constructor", this).call(this);
this.parent = parent;
this.viewUrl = viewUrl;
this.valueConverterLookupFunction = this.getValueConverter.bind(this);
}
_inherits(ViewResources, ResourceRegistry);
_prototypeProperties(ViewResources, null, {
relativeToView: {
value: function relativeToView(path) {
return relativeToFile(path, this.viewUrl);
},
writable: true,
configurable: true
},
getElement: {
value: function getElement(tagName) {
return this.elements[tagName] || this.parent.getElement(tagName);
},
writable: true,
configurable: true
},
mapAttribute: {
value: function mapAttribute(attribute) {
return this.attributeMap[attribute] || this.parent.attributeMap[attribute];
},
writable: true,
configurable: true
},
getAttribute: {
value: function getAttribute(attribute) {
return this.attributes[attribute] || this.parent.getAttribute(attribute);
},
writable: true,
configurable: true
},
getValueConverter: {
value: function getValueConverter(name) {
return this.valueConverters[name] || this.parent.getValueConverter(name);
},
writable: true,
configurable: true
}
});
return ViewResources;
})(ResourceRegistry));
}
};
});
System.register("github:aurelia/templating@0.8.8/system/view", [], function(_export) {
"use strict";
var _prototypeProperties,
View;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
View = _export("View", (function() {
function View(fragment, behaviors, bindings, children, systemControlled, contentSelectors) {
this.fragment = fragment;
this.behaviors = behaviors;
this.bindings = bindings;
this.children = children;
this.systemControlled = systemControlled;
this.contentSelectors = contentSelectors;
this.firstChild = fragment.firstChild;
this.lastChild = fragment.lastChild;
this.isBound = false;
this.isAttached = false;
}
_prototypeProperties(View, null, {
created: {
value: function created(executionContext) {
var i,
ii,
behaviors = this.behaviors;
for (i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].created(executionContext);
}
},
writable: true,
configurable: true
},
bind: {
value: function bind(executionContext, systemUpdate) {
var context,
behaviors,
bindings,
children,
i,
ii;
if (systemUpdate && !this.systemControlled) {
context = this.executionContext || executionContext;
} else {
context = executionContext || this.executionContext;
}
if (this.isBound) {
if (this.executionContext === context) {
return;
}
this.unbind();
}
this.isBound = true;
this.executionContext = context;
if (this.owner) {
this.owner.bind(context);
}
bindings = this.bindings;
for (i = 0, ii = bindings.length; i < ii; ++i) {
bindings[i].bind(context);
}
behaviors = this.behaviors;
for (i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].bind(context);
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].bind(context, true);
}
},
writable: true,
configurable: true
},
addBinding: {
value: function addBinding(binding) {
this.bindings.push(binding);
if (this.isBound) {
binding.bind(this.executionContext);
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
var behaviors,
bindings,
children,
i,
ii;
if (this.isBound) {
this.isBound = false;
if (this.owner) {
this.owner.unbind();
}
bindings = this.bindings;
for (i = 0, ii = bindings.length; i < ii; ++i) {
bindings[i].unbind();
}
behaviors = this.behaviors;
for (i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].unbind();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].unbind();
}
}
},
writable: true,
configurable: true
},
insertNodesBefore: {
value: function insertNodesBefore(refNode) {
var parent = refNode.parentNode;
parent.insertBefore(this.fragment, refNode);
},
writable: true,
configurable: true
},
appendNodesTo: {
value: function appendNodesTo(parent) {
parent.appendChild(this.fragment);
},
writable: true,
configurable: true
},
removeNodes: {
value: function removeNodes() {
var start = this.firstChild,
end = this.lastChild,
fragment = this.fragment,
next;
var current = start,
loop = true,
nodes = [];
while (loop) {
if (current === end) {
loop = false;
}
next = current.nextSibling;
this.fragment.appendChild(current);
current = next;
}
},
writable: true,
configurable: true
},
attached: {
value: function attached() {
var behaviors,
children,
i,
ii;
if (this.isAttached) {
return;
}
this.isAttached = true;
if (this.owner) {
this.owner.attached();
}
behaviors = this.behaviors;
for (i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].attached();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].attached();
}
},
writable: true,
configurable: true
},
detached: {
value: function detached() {
var behaviors,
children,
i,
ii;
if (this.isAttached) {
this.isAttached = false;
if (this.owner) {
this.owner.detached();
}
behaviors = this.behaviors;
for (i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].detached();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].detached();
}
}
},
writable: true,
configurable: true
}
});
return View;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/view-slot", ["./content-selector"], function(_export) {
"use strict";
var ContentSelector,
_prototypeProperties,
ViewSlot;
return {
setters: [function(_contentSelector) {
ContentSelector = _contentSelector.ContentSelector;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ViewSlot = _export("ViewSlot", (function() {
function ViewSlot(anchor, anchorIsContainer, executionContext) {
this.anchor = anchor;
this.viewAddMethod = anchorIsContainer ? "appendNodesTo" : "insertNodesBefore";
this.executionContext = executionContext;
this.children = [];
this.isBound = false;
this.isAttached = false;
anchor.viewSlot = this;
}
_prototypeProperties(ViewSlot, null, {
transformChildNodesIntoView: {
value: function transformChildNodesIntoView() {
var parent = this.anchor;
this.children.push({
removeNodes: function removeNodes() {
var last;
while (last = parent.lastChild) {
parent.removeChild(last);
}
},
created: function created() {},
bind: function bind() {},
unbind: function unbind() {},
attached: function attached() {},
detached: function detached() {}
});
},
writable: true,
configurable: true
},
bind: {
value: function bind(executionContext) {
var i,
ii,
children;
if (this.isBound) {
if (this.executionContext === executionContext) {
return;
}
this.unbind();
}
this.isBound = true;
this.executionContext = executionContext = executionContext || this.executionContext;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].bind(executionContext, true);
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
var i,
ii,
children = this.children;
this.isBound = false;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].unbind();
}
},
writable: true,
configurable: true
},
add: {
value: function add(view) {
view[this.viewAddMethod](this.anchor);
this.children.push(view);
if (this.isAttached) {
view.attached();
}
},
writable: true,
configurable: true
},
insert: {
value: function insert(index, view) {
if (index === 0 && !this.children.length || index >= this.children.length) {
this.add(view);
} else {
view.insertNodesBefore(this.children[index].firstChild);
this.children.splice(index, 0, view);
if (this.isAttached) {
view.attached();
}
}
},
writable: true,
configurable: true
},
remove: {
value: function remove(view) {
view.removeNodes();
this.children.splice(this.children.indexOf(view), 1);
if (this.isAttached) {
view.detached();
}
},
writable: true,
configurable: true
},
removeAt: {
value: function removeAt(index) {
var view = this.children[index];
view.removeNodes();
this.children.splice(index, 1);
if (this.isAttached) {
view.detached();
}
return view;
},
writable: true,
configurable: true
},
removeAll: {
value: function removeAll() {
var children = this.children,
ii = children.length,
i;
for (i = 0; i < ii; ++i) {
children[i].removeNodes();
}
if (this.isAttached) {
for (i = 0; i < ii; ++i) {
children[i].detached();
}
}
this.children = [];
},
writable: true,
configurable: true
},
swap: {
value: function swap(view) {
this.removeAll();
this.add(view);
},
writable: true,
configurable: true
},
attached: {
value: function attached() {
var i,
ii,
children;
if (this.isAttached) {
return;
}
this.isAttached = true;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].attached();
}
},
writable: true,
configurable: true
},
detached: {
value: function detached() {
var i,
ii,
children;
if (this.isAttached) {
this.isAttached = false;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].detached();
}
}
},
writable: true,
configurable: true
},
installContentSelectors: {
value: function installContentSelectors(contentSelectors) {
this.contentSelectors = contentSelectors;
this.add = this.contentSelectorAdd;
this.insert = this.contentSelectorInsert;
this.remove = this.contentSelectorRemove;
this.removeAt = this.contentSelectorRemoveAt;
this.removeAll = this.contentSelectorRemoveAll;
},
writable: true,
configurable: true
},
contentSelectorAdd: {
value: function contentSelectorAdd(view) {
ContentSelector.applySelectors(view, this.contentSelectors, function(contentSelector, group) {
return contentSelector.add(group);
});
this.children.push(view);
if (this.isAttached) {
view.attached();
}
},
writable: true,
configurable: true
},
contentSelectorInsert: {
value: function contentSelectorInsert(index, view) {
if (index === 0 && !this.children.length || index >= this.children.length) {
this.add(view);
} else {
ContentSelector.applySelectors(view, this.contentSelectors, function(contentSelector, group) {
return contentSelector.insert(index, group);
});
this.children.splice(index, 0, view);
if (this.isAttached) {
view.attached();
}
}
},
writable: true,
configurable: true
},
contentSelectorRemove: {
value: function contentSelectorRemove(view) {
var index = this.children.indexOf(view),
contentSelectors = this.contentSelectors,
i,
ii;
for (i = 0, ii = contentSelectors.length; i < ii; ++i) {
contentSelectors[i].removeAt(index, view.fragment);
}
this.children.splice(index, 1);
if (this.isAttached) {
view.detached();
}
},
writable: true,
configurable: true
},
contentSelectorRemoveAt: {
value: function contentSelectorRemoveAt(index) {
var view = this.children[index],
contentSelectors = this.contentSelectors,
i,
ii;
for (i = 0, ii = contentSelectors.length; i < ii; ++i) {
contentSelectors[i].removeAt(index, view.fragment);
}
this.children.splice(index, 1);
if (this.isAttached) {
view.detached();
}
return view;
},
writable: true,
configurable: true
},
contentSelectorRemoveAll: {
value: function contentSelectorRemoveAll() {
var children = this.children,
contentSelectors = this.contentSelectors,
ii = children.length,
jj = contentSelectors.length,
i,
j,
view;
for (i = 0; i < ii; ++i) {
view = children[i];
for (j = 0; j < jj; ++j) {
contentSelectors[j].removeAt(i, view.fragment);
}
}
if (this.isAttached) {
for (i = 0; i < ii; ++i) {
children[i].detached();
}
}
this.children = [];
},
writable: true,
configurable: true
}
});
return ViewSlot;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/binding-language", [], function(_export) {
"use strict";
var _prototypeProperties,
BindingLanguage;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BindingLanguage = _export("BindingLanguage", (function() {
function BindingLanguage() {}
_prototypeProperties(BindingLanguage, null, {
inspectAttribute: {
value: function inspectAttribute(resources, attrName, attrValue) {
throw new Error("A BindingLanguage must implement inspectAttribute(...)");
},
writable: true,
configurable: true
},
createAttributeInstruction: {
value: function createAttributeInstruction(resources, element, info, existingInstruction) {
throw new Error("A BindingLanguage must implement createAttributeInstruction(...)");
},
writable: true,
configurable: true
},
parseText: {
value: function parseText(resources, value) {
throw new Error("A BindingLanguage must implement parseText(...)");
},
writable: true,
configurable: true
}
});
return BindingLanguage;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/view-strategy", ["aurelia-metadata", "aurelia-path"], function(_export) {
"use strict";
var Metadata,
Origin,
relativeToFile,
_inherits,
_prototypeProperties,
ViewStrategy,
UseView,
ConventionalView,
NoView;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
Origin = _aureliaMetadata.Origin;
}, function(_aureliaPath) {
relativeToFile = _aureliaPath.relativeToFile;
}],
execute: function() {
_inherits = function(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)
subClass.__proto__ = superClass;
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ViewStrategy = _export("ViewStrategy", (function() {
function ViewStrategy() {}
_prototypeProperties(ViewStrategy, {
normalize: {
value: function normalize(value) {
if (typeof value === "string") {
value = new UseView(value);
}
if (value && !(value instanceof ViewStrategy)) {
throw new Error("The view must be a string or an instance of ViewStrategy.");
}
return value;
},
writable: true,
configurable: true
},
getDefault: {
value: function getDefault(target) {
var strategy,
annotation;
if (typeof target !== "function") {
target = target.constructor;
}
annotation = Origin.get(target);
strategy = Metadata.on(target).first(ViewStrategy);
if (!strategy) {
if (!annotation) {
throw new Error("Cannot determinte default view strategy for object.", target);
}
strategy = new ConventionalView(annotation.moduleId);
} else if (annotation) {
strategy.moduleId = annotation.moduleId;
}
return strategy;
},
writable: true,
configurable: true
}
}, {
makeRelativeTo: {
value: function makeRelativeTo(baseUrl) {},
writable: true,
configurable: true
},
loadViewFactory: {
value: function loadViewFactory(viewEngine, options) {
throw new Error("A ViewStrategy must implement loadViewFactory(viewEngine, options).");
},
writable: true,
configurable: true
}
});
return ViewStrategy;
})());
UseView = _export("UseView", (function(ViewStrategy) {
function UseView(path) {
this.path = path;
}
_inherits(UseView, ViewStrategy);
_prototypeProperties(UseView, null, {
loadViewFactory: {
value: function loadViewFactory(viewEngine, options) {
if (!this.absolutePath && this.moduleId) {
this.absolutePath = relativeToFile(this.path, this.moduleId);
}
return viewEngine.loadViewFactory(this.absolutePath || this.path, options, this.moduleId);
},
writable: true,
configurable: true
},
makeRelativeTo: {
value: function makeRelativeTo(file) {
this.absolutePath = relativeToFile(this.path, file);
},
writable: true,
configurable: true
}
});
return UseView;
})(ViewStrategy));
ConventionalView = _export("ConventionalView", (function(ViewStrategy) {
function ConventionalView(moduleId) {
this.moduleId = moduleId;
this.viewUrl = ConventionalView.convertModuleIdToViewUrl(moduleId);
}
_inherits(ConventionalView, ViewStrategy);
_prototypeProperties(ConventionalView, {convertModuleIdToViewUrl: {
value: function convertModuleIdToViewUrl(moduleId) {
return moduleId + ".html";
},
writable: true,
configurable: true
}}, {loadViewFactory: {
value: function loadViewFactory(viewEngine, options) {
return viewEngine.loadViewFactory(this.viewUrl, options, this.moduleId);
},
writable: true,
configurable: true
}});
return ConventionalView;
})(ViewStrategy));
NoView = _export("NoView", (function(ViewStrategy) {
function NoView() {
if (Object.getPrototypeOf(NoView) !== null) {
Object.getPrototypeOf(NoView).apply(this, arguments);
}
}
_inherits(NoView, ViewStrategy);
_prototypeProperties(NoView, null, {loadViewFactory: {
value: function loadViewFactory() {
return Promise.resolve(null);
},
writable: true,
configurable: true
}});
return NoView;
})(ViewStrategy));
}
};
});
System.register("github:aurelia/templating@0.8.8/system/element-config", ["aurelia-metadata", "aurelia-binding"], function(_export) {
"use strict";
var ResourceType,
EventManager,
_prototypeProperties,
_inherits,
ElementConfig;
return {
setters: [function(_aureliaMetadata) {
ResourceType = _aureliaMetadata.ResourceType;
}, function(_aureliaBinding) {
EventManager = _aureliaBinding.EventManager;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
ElementConfig = _export("ElementConfig", (function(ResourceType) {
function ElementConfig() {
if (Object.getPrototypeOf(ElementConfig) !== null) {
Object.getPrototypeOf(ElementConfig).apply(this, arguments);
}
}
_inherits(ElementConfig, ResourceType);
_prototypeProperties(ElementConfig, null, {
load: {
value: function load(container, target) {
var config = new target(),
eventManager = container.get(EventManager);
eventManager.registerElementConfig(config);
},
writable: true,
configurable: true
},
register: {
value: function register() {},
writable: true,
configurable: true
}
});
return ElementConfig;
})(ResourceType));
}
};
});
System.register("github:aurelia/templating@0.8.8/system/template-controller", ["aurelia-metadata", "./behavior-instance", "./behaviors", "./util"], function(_export) {
"use strict";
var ResourceType,
BehaviorInstance,
configureBehavior,
hyphenate,
_prototypeProperties,
_inherits,
TemplateController;
return {
setters: [function(_aureliaMetadata) {
ResourceType = _aureliaMetadata.ResourceType;
}, function(_behaviorInstance) {
BehaviorInstance = _behaviorInstance.BehaviorInstance;
}, function(_behaviors) {
configureBehavior = _behaviors.configureBehavior;
}, function(_util) {
hyphenate = _util.hyphenate;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
TemplateController = _export("TemplateController", (function(ResourceType) {
function TemplateController(attribute) {
this.name = attribute;
this.properties = [];
this.attributes = {};
this.liftsContent = true;
}
_inherits(TemplateController, ResourceType);
_prototypeProperties(TemplateController, {convention: {
value: function convention(name) {
if (name.endsWith("TemplateController")) {
return new TemplateController(hyphenate(name.substring(0, name.length - 18)));
}
},
writable: true,
configurable: true
}}, {
analyze: {
value: function analyze(container, target) {
configureBehavior(container, this, target);
},
writable: true,
configurable: true
},
load: {
value: function load(container, target) {
return Promise.resolve(this);
},
writable: true,
configurable: true
},
register: {
value: function register(registry, name) {
registry.registerAttribute(name || this.name, this, this.name);
},
writable: true,
configurable: true
},
compile: {
value: function compile(compiler, resources, node, instruction, parentNode) {
if (!instruction.viewFactory) {
var template = document.createElement("template"),
fragment = document.createDocumentFragment();
node.removeAttribute(instruction.originalAttrName);
if (node.parentNode) {
node.parentNode.replaceChild(template, node);
} else if (window.ShadowDOMPolyfill) {
ShadowDOMPolyfill.unwrap(parentNode).replaceChild(ShadowDOMPolyfill.unwrap(template), ShadowDOMPolyfill.unwrap(node));
} else {
parentNode.replaceChild(template, node);
}
fragment.appendChild(node);
instruction.viewFactory = compiler.compile(fragment, resources);
node = template;
}
instruction.suppressBind = true;
return node;
},
writable: true,
configurable: true
},
create: {
value: function create(container, instruction, element) {
var executionContext = instruction.executionContext || container.get(this.target),
behaviorInstance = new BehaviorInstance(this, executionContext, instruction);
element.primaryBehavior = behaviorInstance;
return behaviorInstance;
},
writable: true,
configurable: true
}
});
return TemplateController;
})(ResourceType));
}
};
});
System.register("github:aurelia/templating@0.8.8/system/resource-coordinator", ["aurelia-loader", "aurelia-path", "aurelia-dependency-injection", "aurelia-metadata", "aurelia-binding", "./custom-element", "./attached-behavior", "./template-controller", "./view-engine", "./resource-registry"], function(_export) {
"use strict";
var Loader,
relativeToFile,
join,
Container,
Metadata,
ResourceType,
Origin,
ValueConverter,
CustomElement,
AttachedBehavior,
TemplateController,
ViewEngine,
ResourceRegistry,
_prototypeProperties,
id,
ResourceCoordinator,
ResourceModule;
function nextId() {
return ++id;
}
function analyzeModule(moduleInstance, viewModelMember) {
var viewModelType,
fallback,
annotation,
key,
meta,
exportedValue,
resources = [],
name,
conventional;
if (typeof moduleInstance === "function") {
moduleInstance = {"default": moduleInstance};
}
if (viewModelMember) {
viewModelType = moduleInstance[viewModelMember];
}
for (key in moduleInstance) {
exportedValue = moduleInstance[key];
if (key === viewModelMember || typeof exportedValue !== "function") {
continue;
}
meta = Metadata.on(exportedValue);
annotation = meta.first(ResourceType);
if (annotation) {
if (!viewModelType && annotation instanceof CustomElement) {
viewModelType = exportedValue;
} else {
resources.push({
type: annotation,
value: exportedValue
});
}
} else {
name = exportedValue.name;
if (conventional = CustomElement.convention(name)) {
if (!viewModelType) {
meta.add(conventional);
viewModelType = exportedValue;
} else {
resources.push({
type: conventional,
value: exportedValue
});
}
} else if (conventional = AttachedBehavior.convention(name)) {
resources.push({
type: conventional,
value: exportedValue
});
} else if (conventional = TemplateController.convention(name)) {
resources.push({
type: conventional,
value: exportedValue
});
} else if (conventional = ValueConverter.convention(name)) {
resources.push({
type: conventional,
value: exportedValue
});
} else if (!fallback) {
fallback = exportedValue;
}
}
}
viewModelType = viewModelType || fallback;
return new ResourceModule(moduleInstance, viewModelType ? {
value: viewModelType,
type: Metadata.on(viewModelType).first(CustomElement) || new CustomElement()
} : null, resources);
}
return {
setters: [function(_aureliaLoader) {
Loader = _aureliaLoader.Loader;
}, function(_aureliaPath) {
relativeToFile = _aureliaPath.relativeToFile;
join = _aureliaPath.join;
}, function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
ResourceType = _aureliaMetadata.ResourceType;
Origin = _aureliaMetadata.Origin;
}, function(_aureliaBinding) {
ValueConverter = _aureliaBinding.ValueConverter;
}, function(_customElement) {
CustomElement = _customElement.CustomElement;
}, function(_attachedBehavior) {
AttachedBehavior = _attachedBehavior.AttachedBehavior;
}, function(_templateController) {
TemplateController = _templateController.TemplateController;
}, function(_viewEngine) {
ViewEngine = _viewEngine.ViewEngine;
}, function(_resourceRegistry) {
ResourceRegistry = _resourceRegistry.ResourceRegistry;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
id = 0;
ResourceCoordinator = _export("ResourceCoordinator", (function() {
function ResourceCoordinator(loader, container, viewEngine, appResources) {
this.loader = loader;
this.container = container;
this.viewEngine = viewEngine;
this.importedModules = {};
this.importedAnonymous = {};
this.appResources = appResources;
viewEngine.resourceCoordinator = this;
}
_prototypeProperties(ResourceCoordinator, {inject: {
value: function inject() {
return [Loader, Container, ViewEngine, ResourceRegistry];
},
writable: true,
configurable: true
}}, {
getExistingModuleAnalysis: {
value: function getExistingModuleAnalysis(id) {
return this.importedModules[id] || this.importedAnonymous[id];
},
writable: true,
configurable: true
},
loadViewModelInfo: {
value: function loadViewModelInfo(moduleImport, moduleMember) {
return this._loadAndAnalyzeModuleForElement(moduleImport, moduleMember, this.importedAnonymous);
},
writable: true,
configurable: true
},
loadElement: {
value: function loadElement(moduleImport, moduleMember, viewStategy) {
var _this = this;
return this._loadAndAnalyzeModuleForElement(moduleImport, moduleMember, this.importedModules).then(function(info) {
var type = info.type;
if (type.isLoaded) {
return type;
}
type.isLoaded = true;
return type.load(_this.container, info.value, viewStategy);
});
},
writable: true,
configurable: true
},
_loadAndAnalyzeModuleForElement: {
value: function _loadAndAnalyzeModuleForElement(moduleImport, moduleMember, cache) {
var _this = this;
var existing = cache[moduleImport];
if (existing) {
return Promise.resolve(existing.element);
}
return this.loader.loadModule(moduleImport).then(function(elementModule) {
var analysis = analyzeModule(elementModule, moduleMember),
resources = analysis.resources,
container = _this.container,
loads = [],
type,
current,
i,
ii;
if (!analysis.element) {
throw new Error("No element found in module \"" + moduleImport + "\".");
}
analysis.analyze(container);
for (i = 0, ii = resources.length; i < ii; ++i) {
current = resources[i];
type = current.type;
if (!type.isLoaded) {
type.isLoaded = true;
loads.push(type.load(container, current.value));
}
}
cache[analysis.id] = analysis;
return Promise.all(loads).then(function() {
return analysis.element;
});
});
},
writable: true,
configurable: true
},
importResources: {
value: function importResources(imports, resourceManifestUrl) {
var i,
ii,
current,
annotation,
existing,
lookup = {},
finalModules = [],
importIds = [],
analysis,
type;
var container = this.container;
for (i = 0, ii = imports.length; i < ii; ++i) {
current = imports[i];
annotation = Origin.get(current);
if (!annotation) {
analysis = analyzeModule({"default": current});
analysis.analyze(container);
type = (analysis.element || analysis.resources[0]).type;
if (resourceManifestUrl) {
annotation = new Origin(relativeToFile("./" + type.name, resourceManifestUrl));
} else {
annotation = new Origin(join(this.appResources.baseResourceUrl, type.name));
}
Origin.set(current, annotation);
}
existing = lookup[annotation.moduleId];
if (!existing) {
existing = {};
importIds.push(annotation.moduleId);
finalModules.push(existing);
lookup[annotation.moduleId] = existing;
}
existing[nextId()] = current;
}
return this.importResourcesFromModules(finalModules, importIds);
},
writable: true,
configurable: true
},
importResourcesFromModuleIds: {
value: function importResourcesFromModuleIds(importIds) {
var _this = this;
return this.loader.loadAllModules(importIds).then(function(imports) {
return _this.importResourcesFromModules(imports, importIds);
});
},
writable: true,
configurable: true
},
importResourcesFromModules: {
value: function importResourcesFromModules(imports, importIds) {
var loads = [],
i,
ii,
analysis,
type,
key,
annotation,
j,
jj,
resources,
current,
existing = this.importedModules,
container = this.container,
allAnalysis = new Array(imports.length);
if (!importIds) {
importIds = new Array(imports.length);
for (i = 0, ii = imports.length; i < ii; ++i) {
current = imports[i];
for (key in current) {
type = current[key];
annotation = Origin.get(type);
if (annotation) {
importIds[i] = annotation.moduleId;
break;
}
}
}
}
for (i = 0, ii = imports.length; i < ii; ++i) {
analysis = existing[importIds[i]];
if (analysis) {
allAnalysis[i] = analysis;
continue;
}
analysis = analyzeModule(imports[i]);
analysis.analyze(container);
existing[analysis.id] = analysis;
allAnalysis[i] = analysis;
resources = analysis.resources;
for (j = 0, jj = resources.length; j < jj; ++j) {
current = resources[j];
type = current.type;
if (!type.isLoaded) {
type.isLoaded = true;
loads.push(type.load(container, current.value));
}
}
if (analysis.element) {
type = analysis.element.type;
if (!type.isLoaded) {
type.isLoaded = true;
loads.push(type.load(container, analysis.element.value));
}
}
}
return Promise.all(loads).then(function() {
return allAnalysis;
});
},
writable: true,
configurable: true
}
});
return ResourceCoordinator;
})());
ResourceModule = (function() {
function ResourceModule(source, element, resources) {
var i,
ii,
org;
this.source = source;
this.element = element;
this.resources = resources;
if (element) {
org = Origin.get(element.value);
} else if (resources.length) {
org = Origin.get(resources[0].value);
} else {
org = Origin.get(source);
}
if (org) {
this.id = org.moduleId;
}
}
_prototypeProperties(ResourceModule, null, {
analyze: {
value: function analyze(container) {
var current = this.element,
resources = this.resources,
i,
ii;
if (current) {
if (!current.type.isAnalyzed) {
current.type.isAnalyzed = true;
current.type.analyze(container, current.value);
}
}
for (i = 0, ii = resources.length; i < ii; ++i) {
current = resources[i];
if ("analyze" in current.type && !current.type.isAnalyzed) {
current.type.isAnalyzed = true;
current.type.analyze(container, current.value);
}
}
},
writable: true,
configurable: true
},
register: {
value: function register(registry, name) {
var i,
ii,
resources = this.resources;
if (this.element) {
this.element.type.register(registry, name);
name = null;
}
for (i = 0, ii = resources.length; i < ii; ++i) {
resources[i].type.register(registry, name);
name = null;
}
},
writable: true,
configurable: true
}
});
return ResourceModule;
})();
}
};
});
System.register("github:aurelia/templating@0.8.8/system/composition-engine", ["aurelia-metadata", "./view-strategy", "./resource-coordinator", "./view-engine", "./custom-element"], function(_export) {
"use strict";
var Origin,
ViewStrategy,
UseView,
ResourceCoordinator,
ViewEngine,
CustomElement,
_prototypeProperties,
CompositionEngine;
return {
setters: [function(_aureliaMetadata) {
Origin = _aureliaMetadata.Origin;
}, function(_viewStrategy) {
ViewStrategy = _viewStrategy.ViewStrategy;
UseView = _viewStrategy.UseView;
}, function(_resourceCoordinator) {
ResourceCoordinator = _resourceCoordinator.ResourceCoordinator;
}, function(_viewEngine) {
ViewEngine = _viewEngine.ViewEngine;
}, function(_customElement) {
CustomElement = _customElement.CustomElement;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
CompositionEngine = _export("CompositionEngine", (function() {
function CompositionEngine(resourceCoordinator, viewEngine) {
this.resourceCoordinator = resourceCoordinator;
this.viewEngine = viewEngine;
}
_prototypeProperties(CompositionEngine, {inject: {
value: function inject() {
return [ResourceCoordinator, ViewEngine];
},
writable: true,
configurable: true
}}, {
activate: {
value: function activate(instruction) {
if (instruction.skipActivation || typeof instruction.viewModel.activate !== "function") {
return Promise.resolve();
}
return instruction.viewModel.activate(instruction.model) || Promise.resolve();
},
writable: true,
configurable: true
},
createBehaviorAndSwap: {
value: function createBehaviorAndSwap(instruction) {
return this.createBehavior(instruction).then(function(behavior) {
behavior.view.bind(behavior.executionContext);
instruction.viewSlot.swap(behavior.view);
if (instruction.currentBehavior) {
instruction.currentBehavior.unbind();
}
return behavior;
});
},
writable: true,
configurable: true
},
createBehavior: {
value: function createBehavior(instruction) {
var childContainer = instruction.childContainer,
viewModelInfo = instruction.viewModelInfo,
viewModel = instruction.viewModel;
return this.activate(instruction).then(function() {
var doneLoading,
viewStrategyFromViewModel,
origin;
if ("getViewStrategy" in viewModel && !instruction.view) {
viewStrategyFromViewModel = true;
instruction.view = ViewStrategy.normalize(viewModel.getViewStrategy());
}
if (instruction.view) {
if (viewStrategyFromViewModel) {
origin = Origin.get(viewModel.constructor);
if (origin) {
instruction.view.makeRelativeTo(origin.moduleId);
}
} else if (instruction.viewResources) {
instruction.view.makeRelativeTo(instruction.viewResources.viewUrl);
}
}
if (viewModelInfo) {
doneLoading = viewModelInfo.type.load(childContainer, viewModelInfo.value, instruction.view);
} else {
doneLoading = new CustomElement().load(childContainer, viewModel.constructor, instruction.view);
}
return doneLoading.then(function(behaviorType) {
return behaviorType.create(childContainer, {
executionContext: viewModel,
suppressBind: true
});
});
});
},
writable: true,
configurable: true
},
createViewModel: {
value: function createViewModel(instruction) {
var childContainer = instruction.childContainer || instruction.container.createChild();
instruction.viewModel = instruction.viewResources ? instruction.viewResources.relativeToView(instruction.viewModel) : instruction.viewModel;
return this.resourceCoordinator.loadViewModelInfo(instruction.viewModel).then(function(viewModelInfo) {
childContainer.autoRegister(viewModelInfo.value);
instruction.viewModel = childContainer.viewModel = childContainer.get(viewModelInfo.value);
instruction.viewModelInfo = viewModelInfo;
return instruction;
});
},
writable: true,
configurable: true
},
compose: {
value: function compose(instruction) {
var _this = this;
instruction.childContainer = instruction.childContainer || instruction.container.createChild();
instruction.view = ViewStrategy.normalize(instruction.view);
if (instruction.viewModel) {
if (typeof instruction.viewModel === "string") {
return this.createViewModel(instruction).then(function(instruction) {
return _this.createBehaviorAndSwap(instruction);
});
} else {
return this.createBehaviorAndSwap(instruction);
}
} else if (instruction.view) {
if (instruction.viewResources) {
instruction.view.makeRelativeTo(instruction.viewResources.viewUrl);
}
return instruction.view.loadViewFactory(this.viewEngine).then(function(viewFactory) {
var result = viewFactory.create(instruction.childContainer, instruction.executionContext);
instruction.viewSlot.swap(result);
return result;
});
} else if (instruction.viewSlot) {
instruction.viewSlot.removeAll();
return Promise.resolve(null);
}
},
writable: true,
configurable: true
}
});
return CompositionEngine;
})());
}
};
});
System.register("github:aurelia/framework@0.8.6/system/plugins", ["aurelia-logging", "aurelia-metadata"], function(_export) {
"use strict";
var LogManager,
Metadata,
_prototypeProperties,
logger,
Plugins;
function loadPlugin(aurelia, loader, info) {
logger.debug("Loading plugin " + info.moduleId + ".");
aurelia.currentPluginId = info.moduleId;
var baseUrl = info.moduleId.startsWith("./") ? undefined : "";
return loader.loadModule(info.moduleId, baseUrl).then(function(exportedValue) {
if ("install" in exportedValue) {
var result = exportedValue.install(aurelia, info.config || {});
if (result) {
return result.then(function() {
aurelia.currentPluginId = null;
logger.debug("Installed plugin " + info.moduleId + ".");
});
} else {
logger.debug("Installed plugin " + info.moduleId + ".");
}
} else {
logger.debug("Loaded plugin " + info.moduleId + ".");
}
aurelia.currentPluginId = null;
});
}
return {
setters: [function(_aureliaLogging) {
LogManager = _aureliaLogging;
}, function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
logger = LogManager.getLogger("aurelia");
Plugins = _export("Plugins", (function() {
function Plugins(aurelia) {
this.aurelia = aurelia;
this.info = [];
this.processed = false;
}
_prototypeProperties(Plugins, null, {
plugin: {
value: function plugin(moduleId, config) {
var plugin = {
moduleId: moduleId,
config: config || {}
};
if (this.processed) {
loadPlugin(this.aurelia, this.aurelia.loader, plugin);
} else {
this.info.push(plugin);
}
return this;
},
writable: true,
configurable: true
},
es5: {
value: function es5() {
Function.prototype.computed = function(computedProperties) {
for (var key in computedProperties) {
if (computedProperties.hasOwnProperty(key)) {
Object.defineProperty(this.prototype, key, {
get: computedProperties[key],
enumerable: true
});
}
}
};
return this;
},
writable: true,
configurable: true
},
atscript: {
value: function atscript() {
this.aurelia.container.supportAtScript();
Metadata.configure.locator(function(fn) {
return fn.annotate || fn.annotations;
});
return this;
},
writable: true,
configurable: true
},
_process: {
value: function _process() {
var _this = this;
var aurelia = this.aurelia,
loader = aurelia.loader,
info = this.info,
current;
if (this.processed) {
return;
}
var next = function() {
if (current = info.shift()) {
return loadPlugin(aurelia, loader, current).then(next);
}
_this.processed = true;
return Promise.resolve();
};
return next();
},
writable: true,
configurable: true
}
});
return Plugins;
})());
}
};
});
System.register("github:aurelia/logging-console@0.2.2/system/index", [], function(_export) {
"use strict";
var _toArray,
_prototypeProperties,
ConsoleAppender;
return {
setters: [],
execute: function() {
_toArray = function(arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ConsoleAppender = (function() {
function ConsoleAppender() {}
_prototypeProperties(ConsoleAppender, null, {
debug: {
value: function debug(logger, message) {
for (var _len = arguments.length,
rest = Array(_len > 2 ? _len - 2 : 0),
_key = 2; _key < _len; _key++) {
rest[_key - 2] = arguments[_key];
}
console.debug.apply(console, ["DEBUG [" + logger.id + "] " + message].concat(_toArray(rest)));
},
writable: true,
enumerable: true,
configurable: true
},
info: {
value: function info(logger, message) {
for (var _len2 = arguments.length,
rest = Array(_len2 > 2 ? _len2 - 2 : 0),
_key2 = 2; _key2 < _len2; _key2++) {
rest[_key2 - 2] = arguments[_key2];
}
console.info.apply(console, ["INFO [" + logger.id + "] " + message].concat(_toArray(rest)));
},
writable: true,
enumerable: true,
configurable: true
},
warn: {
value: function warn(logger, message) {
for (var _len3 = arguments.length,
rest = Array(_len3 > 2 ? _len3 - 2 : 0),
_key3 = 2; _key3 < _len3; _key3++) {
rest[_key3 - 2] = arguments[_key3];
}
console.warn.apply(console, ["WARN [" + logger.id + "] " + message].concat(_toArray(rest)));
},
writable: true,
enumerable: true,
configurable: true
},
error: {
value: function error(logger, message) {
for (var _len4 = arguments.length,
rest = Array(_len4 > 2 ? _len4 - 2 : 0),
_key4 = 2; _key4 < _len4; _key4++) {
rest[_key4 - 2] = arguments[_key4];
}
console.error.apply(console, ["ERROR [" + logger.id + "] " + message].concat(_toArray(rest)));
},
writable: true,
enumerable: true,
configurable: true
}
});
return ConsoleAppender;
})();
_export("ConsoleAppender", ConsoleAppender);
}
};
});
System.register("github:aurelia/templating-binding@0.8.4/system/syntax-interpreter", ["aurelia-binding"], function(_export) {
"use strict";
var Parser,
ObserverLocator,
EventManager,
ListenerExpression,
BindingExpression,
NameExpression,
CallExpression,
ONE_WAY,
TWO_WAY,
ONE_TIME,
_prototypeProperties,
SyntaxInterpreter;
return {
setters: [function(_aureliaBinding) {
Parser = _aureliaBinding.Parser;
ObserverLocator = _aureliaBinding.ObserverLocator;
EventManager = _aureliaBinding.EventManager;
ListenerExpression = _aureliaBinding.ListenerExpression;
BindingExpression = _aureliaBinding.BindingExpression;
NameExpression = _aureliaBinding.NameExpression;
CallExpression = _aureliaBinding.CallExpression;
ONE_WAY = _aureliaBinding.ONE_WAY;
TWO_WAY = _aureliaBinding.TWO_WAY;
ONE_TIME = _aureliaBinding.ONE_TIME;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
SyntaxInterpreter = (function() {
function SyntaxInterpreter(parser, observerLocator, eventManager) {
this.parser = parser;
this.observerLocator = observerLocator;
this.eventManager = eventManager;
}
_prototypeProperties(SyntaxInterpreter, {inject: {
value: function inject() {
return [Parser, ObserverLocator, EventManager];
},
writable: true,
enumerable: true,
configurable: true
}}, {
interpret: {
value: function interpret(resources, element, info, existingInstruction) {
if (info.command in this) {
return this[info.command](resources, element, info, existingInstruction);
}
return this.handleUnknownCommand(resources, element, info, existingInstruction);
},
writable: true,
enumerable: true,
configurable: true
},
handleUnknownCommand: {
value: function handleUnknownCommand(resources, element, info, existingInstruction) {
var attrName = info.attrName,
command = info.command;
var instruction = this.options(resources, element, info, existingInstruction);
instruction.alteredAttr = true;
instruction.attrName = "global-behavior";
instruction.attributes.aureliaAttrName = attrName;
instruction.attributes.aureliaCommand = command;
return instruction;
},
writable: true,
enumerable: true,
configurable: true
},
determineDefaultBindingMode: {
value: function determineDefaultBindingMode(element, attrName) {
var tagName = element.tagName.toLowerCase();
if (tagName === "input") {
return attrName === "value" || attrName === "checked" ? TWO_WAY : ONE_WAY;
} else if (tagName == "textarea" || tagName == "select") {
return attrName == "value" ? TWO_WAY : ONE_WAY;
}
return ONE_WAY;
},
writable: true,
enumerable: true,
configurable: true
},
bind: {
value: function bind(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), info.defaultBindingMode || this.determineDefaultBindingMode(element, info.attrName), resources.valueConverterLookupFunction);
return instruction;
},
writable: true,
enumerable: true,
configurable: true
},
trigger: {
value: function trigger(resources, element, info) {
return new ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), false, true);
},
writable: true,
enumerable: true,
configurable: true
},
delegate: {
value: function delegate(resources, element, info) {
return new ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), true, true);
},
writable: true,
enumerable: true,
configurable: true
},
call: {
value: function call(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = new CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.valueConverterLookupFunction);
return instruction;
},
writable: true,
enumerable: true,
configurable: true
},
options: {
value: function options(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
},
attrValue = info.attrValue,
language = this.language,
name = null,
target = "",
current,
i,
ii;
for (i = 0, ii = attrValue.length; i < ii; ++i) {
current = attrValue[i];
if (current === ";") {
info = language.inspectAttribute(resources, name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction);
if (!instruction.attributes[info.attrName]) {
instruction.attributes[info.attrName] = info.attrValue;
}
target = "";
name = null;
} else if (current === ":" && name === null) {
name = target.trim();
target = "";
} else {
target += current;
}
}
if (name !== null) {
info = language.inspectAttribute(resources, name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction);
if (!instruction.attributes[info.attrName]) {
instruction.attributes[info.attrName] = info.attrValue;
}
}
return instruction;
},
writable: true,
enumerable: true,
configurable: true
}
});
return SyntaxInterpreter;
})();
_export("SyntaxInterpreter", SyntaxInterpreter);
SyntaxInterpreter.prototype["for"] = function(resources, element, info, existingInstruction) {
var parts = info.attrValue.split(" of ");
if (parts.length !== 2) {
throw new Error("Incorrect syntax for \"for\". The form is: \"$local of $items\".");
}
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes.local = parts[0];
instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, info.attrName, this.parser.parse(parts[1]), ONE_WAY, resources.valueConverterLookupFunction);
return instruction;
};
SyntaxInterpreter.prototype["two-way"] = function(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), TWO_WAY, resources.valueConverterLookupFunction);
return instruction;
};
SyntaxInterpreter.prototype["one-way"] = function(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), ONE_WAY, resources.valueConverterLookupFunction);
return instruction;
};
SyntaxInterpreter.prototype["one-time"] = function(resources, element, info, existingInstruction) {
var instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap[info.attrName] || info.attrName, this.parser.parse(info.attrValue), ONE_TIME, resources.valueConverterLookupFunction);
return instruction;
};
SyntaxInterpreter.prototype["view-model"] = function(resources, element, info) {
return new NameExpression(info.attrValue, "view-model");
};
}
};
});
System.register("github:aurelia/route-recognizer@0.2.2/system/dsl", [], function(_export) {
"use strict";
_export("map", map);
function Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
}
function Matcher(target) {
this.routes = {};
this.children = {};
this.target = target;
}
function generateMatch(startingPath, matcher, delegate) {
return function(path, nestedCallback) {
var fullPath = startingPath + path;
if (nestedCallback) {
nestedCallback(generateMatch(fullPath, matcher, delegate));
} else {
return new Target(startingPath + path, matcher, delegate);
}
};
}
function addRoute(routeArray, path, handler) {
var len = 0;
for (var i = 0,
l = routeArray.length; i < l; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = {
path: path,
handler: handler
};
routeArray.push(route);
}
function eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
for (var path in routes) {
if (routes.hasOwnProperty(path)) {
var routeArray = baseRoute.slice();
addRoute(routeArray, path, routes[path]);
if (matcher.children[path]) {
eachRoute(routeArray, matcher.children[path], callback, binding);
} else {
callback.call(binding, routeArray);
}
}
}
}
function map(callback, addRouteCallback) {
var matcher = new Matcher();
callback(generateMatch("", matcher, this.delegate));
eachRoute([], matcher, function(route) {
if (addRouteCallback) {
addRouteCallback(this, route);
} else {
this.add(route);
}
}, this);
}
return {
setters: [],
execute: function() {
Target.prototype = {to: function(target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) {
throw new Error("You must have an argument in the function passed to `to`");
}
this.matcher.addChild(this.path, target, callback, this.delegate);
}
return this;
}};
Matcher.prototype = {
add: function(path, handler) {
this.routes[path] = handler;
},
addChild: function(path, target, callback, delegate) {
var matcher = new Matcher(target);
this.children[path] = matcher;
var match = generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
}
};
}
};
});
System.register("github:aurelia/router@0.5.4/system/navigation-plan", [], function(_export) {
"use strict";
var _toArray,
_prototypeProperties,
NO_CHANGE,
INVOKE_LIFECYCLE,
REPLACE,
BuildNavigationPlanStep;
_export("buildNavigationPlan", buildNavigationPlan);
function buildNavigationPlan(navigationContext, forceLifecycleMinimum) {
var prev = navigationContext.prevInstruction;
var next = navigationContext.nextInstruction;
var plan = {},
viewPortName;
if (prev) {
var newParams = hasDifferentParameterValues(prev, next);
var pending = [];
for (viewPortName in prev.viewPortInstructions) {
var prevViewPortInstruction = prev.viewPortInstructions[viewPortName];
var nextViewPortConfig = next.config.viewPorts[viewPortName];
var viewPortPlan = plan[viewPortName] = {
name: viewPortName,
config: nextViewPortConfig,
prevComponent: prevViewPortInstruction.component,
prevModuleId: prevViewPortInstruction.moduleId
};
if (prevViewPortInstruction.moduleId != nextViewPortConfig.moduleId) {
viewPortPlan.strategy = REPLACE;
} else if ("determineActivationStrategy" in prevViewPortInstruction.component.executionContext) {
var _prevViewPortInstruction$component$executionContext;
viewPortPlan.strategy = (_prevViewPortInstruction$component$executionContext = prevViewPortInstruction.component.executionContext).determineActivationStrategy.apply(_prevViewPortInstruction$component$executionContext, _toArray(next.lifecycleArgs));
} else if (newParams || forceLifecycleMinimum) {
viewPortPlan.strategy = INVOKE_LIFECYCLE;
} else {
viewPortPlan.strategy = NO_CHANGE;
}
if (viewPortPlan.strategy !== REPLACE && prevViewPortInstruction.childRouter) {
var path = next.getWildcardPath();
var task = prevViewPortInstruction.childRouter.createNavigationInstruction(path, next).then(function(childInstruction) {
viewPortPlan.childNavigationContext = prevViewPortInstruction.childRouter.createNavigationContext(childInstruction);
return buildNavigationPlan(viewPortPlan.childNavigationContext, viewPortPlan.strategy == INVOKE_LIFECYCLE).then(function(childPlan) {
viewPortPlan.childNavigationContext.plan = childPlan;
});
});
pending.push(task);
}
}
return Promise.all(pending).then(function() {
return plan;
});
} else {
for (viewPortName in next.config.viewPorts) {
plan[viewPortName] = {
name: viewPortName,
strategy: REPLACE,
config: next.config.viewPorts[viewPortName]
};
}
return Promise.resolve(plan);
}
}
function hasDifferentParameterValues(prev, next) {
var prevParams = prev.params,
nextParams = next.params,
nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null;
for (var key in nextParams) {
if (key == nextWildCardName) {
continue;
}
if (prevParams[key] != nextParams[key]) {
return true;
}
}
return false;
}
return {
setters: [],
execute: function() {
_toArray = function(arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
NO_CHANGE = _export("NO_CHANGE", "no-change");
INVOKE_LIFECYCLE = _export("INVOKE_LIFECYCLE", "invoke-lifecycle");
REPLACE = _export("REPLACE", "replace");
BuildNavigationPlanStep = _export("BuildNavigationPlanStep", (function() {
function BuildNavigationPlanStep() {}
_prototypeProperties(BuildNavigationPlanStep, null, {run: {
value: function run(navigationContext, next) {
return buildNavigationPlan(navigationContext).then(function(plan) {
navigationContext.plan = plan;
return next();
})["catch"](next.cancel);
},
writable: true,
configurable: true
}});
return BuildNavigationPlanStep;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/navigation-instruction", [], function(_export) {
"use strict";
var _prototypeProperties,
NavigationInstruction;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
NavigationInstruction = _export("NavigationInstruction", (function() {
function NavigationInstruction(fragment, queryString, params, queryParams, config, parentInstruction) {
this.fragment = fragment;
this.queryString = queryString;
this.params = params || {};
this.queryParams = queryParams;
this.config = config;
this.lifecycleArgs = [params, queryParams, config];
this.viewPortInstructions = {};
if (parentInstruction) {
this.params.$parent = parentInstruction.params;
}
}
_prototypeProperties(NavigationInstruction, null, {
addViewPortInstruction: {
value: function addViewPortInstruction(viewPortName, strategy, moduleId, component) {
return this.viewPortInstructions[viewPortName] = {
name: viewPortName,
strategy: strategy,
moduleId: moduleId,
component: component,
childRouter: component.executionContext.router,
lifecycleArgs: this.lifecycleArgs.slice()
};
},
writable: true,
configurable: true
},
getWildCardName: {
value: function getWildCardName() {
var wildcardIndex = this.config.route.lastIndexOf("*");
return this.config.route.substr(wildcardIndex + 1);
},
writable: true,
configurable: true
},
getWildcardPath: {
value: function getWildcardPath() {
var wildcardName = this.getWildCardName(),
path = this.params[wildcardName];
if (this.queryString) {
path += "?" + this.queryString;
}
return path;
},
writable: true,
configurable: true
},
getBaseUrl: {
value: function getBaseUrl() {
if (!this.params) {
return this.fragment;
}
var wildcardName = this.getWildCardName(),
path = this.params[wildcardName];
if (!path) {
return this.fragment;
}
return this.fragment.substr(0, this.fragment.lastIndexOf(path));
},
writable: true,
configurable: true
}
});
return NavigationInstruction;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/router-configuration", [], function(_export) {
"use strict";
var _prototypeProperties,
RouterConfiguration;
function ensureConfigValue(config, property, getter) {
var value = config[property];
if (value || value === "") {
return value;
}
return getter(config);
}
function stripParametersFromRoute(route) {
var colonIndex = route.indexOf(":");
var length = colonIndex > 0 ? colonIndex - 1 : route.length;
return route.substr(0, length);
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
RouterConfiguration = _export("RouterConfiguration", (function() {
function RouterConfiguration() {
this.instructions = [];
this.options = {};
}
_prototypeProperties(RouterConfiguration, null, {
map: {
value: function map(route, config) {
if (Array.isArray(route)) {
for (var i = 0; i < route.length; i++) {
this.map(route[i]);
}
return this;
}
if (typeof route == "string") {
if (!config) {
config = {};
} else if (typeof config == "string") {
config = {moduleId: config};
}
config.route = route;
} else {
config = route;
}
return this.mapRoute(config);
},
writable: true,
configurable: true
},
mapRoute: {
value: function mapRoute(config) {
var _this = this;
this.instructions.push(function(router) {
if (Array.isArray(config.route)) {
var navModel = {},
i,
ii,
current;
for (i = 0, ii = config.route.length; i < ii; ++i) {
current = Object.assign({}, config);
current.route = config.route[i];
_this.configureRoute(router, current, navModel);
}
} else {
_this.configureRoute(router, Object.assign({}, config));
}
});
return this;
},
writable: true,
configurable: true
},
mapUnknownRoutes: {
value: function mapUnknownRoutes(config) {
this.unknownRouteConfig = config;
return this;
},
writable: true,
configurable: true
},
exportToRouter: {
value: function exportToRouter(router) {
var instructions = this.instructions,
i,
ii;
for (i = 0, ii = instructions.length; i < ii; ++i) {
instructions[i](router);
}
if (this.title) {
router.title = this.title;
}
if (this.unknownRouteConfig) {
router.handleUnknownRoutes(this.unknownRouteConfig);
}
router.options = this.options;
},
writable: true,
configurable: true
},
configureRoute: {
value: function configureRoute(router, config, navModel) {
this.ensureDefaultsForRouteConfig(config);
router.addRoute(config, navModel);
},
writable: true,
configurable: true
},
ensureDefaultsForRouteConfig: {
value: function ensureDefaultsForRouteConfig(config) {
config.name = ensureConfigValue(config, "name", this.deriveName);
config.route = ensureConfigValue(config, "route", this.deriveRoute);
config.title = ensureConfigValue(config, "title", this.deriveTitle);
config.moduleId = ensureConfigValue(config, "moduleId", this.deriveModuleId);
},
writable: true,
configurable: true
},
deriveName: {
value: function deriveName(config) {
return config.title || (config.route ? stripParametersFromRoute(config.route) : config.moduleId);
},
writable: true,
configurable: true
},
deriveRoute: {
value: function deriveRoute(config) {
return config.moduleId || config.name;
},
writable: true,
configurable: true
},
deriveTitle: {
value: function deriveTitle(config) {
var value = config.name;
return value.substr(0, 1).toUpperCase() + value.substr(1);
},
writable: true,
configurable: true
},
deriveModuleId: {
value: function deriveModuleId(config) {
return stripParametersFromRoute(config.route);
},
writable: true,
configurable: true
}
});
return RouterConfiguration;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/util", [], function(_export) {
"use strict";
_export("processPotential", processPotential);
function processPotential(obj, resolve, reject) {
if (obj && typeof obj.then === "function") {
var dfd = obj.then(resolve);
if (typeof dfd["catch"] === "function") {
return dfd["catch"](reject);
} else if (typeof dfd.fail === "function") {
return dfd.fail(reject);
}
return dfd;
} else {
try {
return resolve(obj);
} catch (error) {
return reject(error);
}
}
}
return {
setters: [],
execute: function() {}
};
});
System.register("github:aurelia/history@0.2.2/system/index", [], function(_export) {
"use strict";
var _prototypeProperties,
History;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
History = (function() {
function History() {}
_prototypeProperties(History, null, {
activate: {
value: function activate() {
throw new Error("History must implement activate().");
},
writable: true,
enumerable: true,
configurable: true
},
deactivate: {
value: function deactivate() {
throw new Error("History must implement deactivate().");
},
writable: true,
enumerable: true,
configurable: true
},
navigate: {
value: function navigate() {
throw new Error("History must implement navigate().");
},
writable: true,
enumerable: true,
configurable: true
},
navigateBack: {
value: function navigateBack() {
throw new Error("History must implement navigateBack().");
},
writable: true,
enumerable: true,
configurable: true
}
});
return History;
})();
_export("History", History);
}
};
});
System.register("github:aurelia/router@0.5.4/system/pipeline", [], function(_export) {
"use strict";
var _prototypeProperties,
COMPLETED,
CANCELLED,
REJECTED,
RUNNING,
Pipeline;
function createResult(ctx, next) {
return {
status: next.status,
context: ctx,
output: next.output,
completed: next.status == COMPLETED
};
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
COMPLETED = _export("COMPLETED", "completed");
CANCELLED = _export("CANCELLED", "cancelled");
REJECTED = _export("REJECTED", "rejected");
RUNNING = _export("RUNNING", "running");
Pipeline = _export("Pipeline", (function() {
function Pipeline() {
this.steps = [];
}
_prototypeProperties(Pipeline, null, {
withStep: {
value: function withStep(step) {
var run;
if (typeof step == "function") {
run = step;
} else {
run = step.run.bind(step);
}
this.steps.push(run);
return this;
},
writable: true,
configurable: true
},
run: {
value: function run(ctx) {
var index = -1,
steps = this.steps,
next,
currentStep;
next = function() {
index++;
if (index < steps.length) {
currentStep = steps[index];
try {
return currentStep(ctx, next);
} catch (e) {
return next.reject(e);
}
} else {
return next.complete();
}
};
next.complete = function(output) {
next.status = COMPLETED;
next.output = output;
return Promise.resolve(createResult(ctx, next));
};
next.cancel = function(reason) {
next.status = CANCELLED;
next.output = reason;
return Promise.resolve(createResult(ctx, next));
};
next.reject = function(error) {
next.status = REJECTED;
next.output = error;
return Promise.reject(createResult(ctx, next));
};
next.status = RUNNING;
return next();
},
writable: true,
configurable: true
}
});
return Pipeline;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/model-binding", [], function(_export) {
"use strict";
var _prototypeProperties,
ApplyModelBindersStep;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
ApplyModelBindersStep = _export("ApplyModelBindersStep", (function() {
function ApplyModelBindersStep() {}
_prototypeProperties(ApplyModelBindersStep, null, {run: {
value: function run(navigationContext, next) {
return next();
},
writable: true,
configurable: true
}});
return ApplyModelBindersStep;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/route-loading", ["./navigation-plan"], function(_export) {
"use strict";
var REPLACE,
buildNavigationPlan,
_prototypeProperties,
RouteLoader,
LoadRouteStep;
_export("loadNewRoute", loadNewRoute);
function loadNewRoute(routers, routeLoader, navigationContext) {
var toLoad = determineWhatToLoad(navigationContext);
var loadPromises = toLoad.map(function(current) {
return loadRoute(routers, routeLoader, current.navigationContext, current.viewPortPlan);
});
return Promise.all(loadPromises);
}
function determineWhatToLoad(navigationContext, toLoad) {
var plan = navigationContext.plan;
var next = navigationContext.nextInstruction;
toLoad = toLoad || [];
for (var viewPortName in plan) {
var viewPortPlan = plan[viewPortName];
if (viewPortPlan.strategy == REPLACE) {
toLoad.push({
viewPortPlan: viewPortPlan,
navigationContext: navigationContext
});
if (viewPortPlan.childNavigationContext) {
determineWhatToLoad(viewPortPlan.childNavigationContext, toLoad);
}
} else {
var viewPortInstruction = next.addViewPortInstruction(viewPortName, viewPortPlan.strategy, viewPortPlan.prevModuleId, viewPortPlan.prevComponent);
if (viewPortPlan.childNavigationContext) {
viewPortInstruction.childNavigationContext = viewPortPlan.childNavigationContext;
determineWhatToLoad(viewPortPlan.childNavigationContext, toLoad);
}
}
}
return toLoad;
}
function loadRoute(routers, routeLoader, navigationContext, viewPortPlan) {
var moduleId = viewPortPlan.config.moduleId;
var next = navigationContext.nextInstruction;
routers.push(navigationContext.router);
return loadComponent(routeLoader, navigationContext.router, viewPortPlan.config).then(function(component) {
var viewPortInstruction = next.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component);
var controller = component.executionContext;
if (controller.router && routers.indexOf(controller.router) === -1) {
var path = next.getWildcardPath();
return controller.router.createNavigationInstruction(path, next).then(function(childInstruction) {
viewPortPlan.childNavigationContext = controller.router.createNavigationContext(childInstruction);
return buildNavigationPlan(viewPortPlan.childNavigationContext).then(function(childPlan) {
viewPortPlan.childNavigationContext.plan = childPlan;
viewPortInstruction.childNavigationContext = viewPortPlan.childNavigationContext;
return loadNewRoute(routers, routeLoader, viewPortPlan.childNavigationContext);
});
});
}
});
}
function loadComponent(routeLoader, router, config) {
return routeLoader.loadRoute(router, config).then(function(component) {
if ("configureRouter" in component.executionContext) {
var result = component.executionContext.configureRouter() || Promise.resolve();
return result.then(function() {
return component;
});
}
component.router = router;
component.config = config;
return component;
});
}
return {
setters: [function(_navigationPlan) {
REPLACE = _navigationPlan.REPLACE;
buildNavigationPlan = _navigationPlan.buildNavigationPlan;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
RouteLoader = _export("RouteLoader", (function() {
function RouteLoader() {}
_prototypeProperties(RouteLoader, null, {loadRoute: {
value: function loadRoute(router, config) {
throw Error("Route loaders must implment \"loadRoute(router, config)\".");
},
writable: true,
configurable: true
}});
return RouteLoader;
})());
LoadRouteStep = _export("LoadRouteStep", (function() {
function LoadRouteStep(routeLoader) {
this.routeLoader = routeLoader;
}
_prototypeProperties(LoadRouteStep, {inject: {
value: function inject() {
return [RouteLoader];
},
writable: true,
configurable: true
}}, {run: {
value: function run(navigationContext, next) {
return loadNewRoute([], this.routeLoader, navigationContext).then(next)["catch"](next.cancel);
},
writable: true,
configurable: true
}});
return LoadRouteStep;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/navigation-commands", [], function(_export) {
"use strict";
var _prototypeProperties,
Redirect;
_export("isNavigationCommand", isNavigationCommand);
function isNavigationCommand(obj) {
return obj && typeof obj.navigate === "function";
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Redirect = _export("Redirect", (function() {
function Redirect(url) {
this.url = url;
this.shouldContinueProcessing = false;
}
_prototypeProperties(Redirect, null, {navigate: {
value: function navigate(appRouter) {
(this.router || appRouter).navigate(this.url, {
trigger: true,
replace: true
});
},
writable: true,
configurable: true
}});
return Redirect;
})());
}
};
});
System.register("github:aurelia/templating-router@0.9.2/system/route-loader", ["aurelia-templating", "aurelia-router", "aurelia-path", "aurelia-metadata"], function(_export) {
"use strict";
var CompositionEngine,
RouteLoader,
Router,
relativeToFile,
Origin,
_prototypeProperties,
_inherits,
TemplatingRouteLoader;
return {
setters: [function(_aureliaTemplating) {
CompositionEngine = _aureliaTemplating.CompositionEngine;
}, function(_aureliaRouter) {
RouteLoader = _aureliaRouter.RouteLoader;
Router = _aureliaRouter.Router;
}, function(_aureliaPath) {
relativeToFile = _aureliaPath.relativeToFile;
}, function(_aureliaMetadata) {
Origin = _aureliaMetadata.Origin;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
TemplatingRouteLoader = (function(RouteLoader) {
function TemplatingRouteLoader(compositionEngine) {
this.compositionEngine = compositionEngine;
}
_inherits(TemplatingRouteLoader, RouteLoader);
_prototypeProperties(TemplatingRouteLoader, {inject: {
value: function inject() {
return [CompositionEngine];
},
writable: true,
enumerable: true,
configurable: true
}}, {loadRoute: {
value: function loadRoute(router, config) {
var childContainer = router.container.createChild(),
instruction = {
viewModel: relativeToFile(config.moduleId, Origin.get(router.container.viewModel.constructor).moduleId),
childContainer: childContainer,
view: config.view
},
childRouter;
childContainer.registerHandler(Router, function(c) {
return childRouter || (childRouter = router.createChild(childContainer));
});
return this.compositionEngine.createViewModel(instruction).then(function(instruction) {
instruction.executionContext = instruction.viewModel;
instruction.router = router;
return instruction;
});
},
writable: true,
enumerable: true,
configurable: true
}});
return TemplatingRouteLoader;
})(RouteLoader);
_export("TemplatingRouteLoader", TemplatingRouteLoader);
}
};
});
System.register("github:aurelia/templating-router@0.9.2/system/router-view", ["aurelia-dependency-injection", "aurelia-templating", "aurelia-router", "aurelia-metadata"], function(_export) {
"use strict";
var Container,
ViewSlot,
ViewStrategy,
Router,
Metadata,
Origin,
_prototypeProperties,
RouterView;
return {
setters: [function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_aureliaTemplating) {
ViewSlot = _aureliaTemplating.ViewSlot;
ViewStrategy = _aureliaTemplating.ViewStrategy;
}, function(_aureliaRouter) {
Router = _aureliaRouter.Router;
}, function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
Origin = _aureliaMetadata.Origin;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
RouterView = (function() {
function RouterView(element, container, viewSlot, router) {
this.element = element;
this.container = container;
this.viewSlot = viewSlot;
this.router = router;
router.registerViewPort(this, element.getAttribute("name"));
}
_prototypeProperties(RouterView, {
metadata: {
value: function metadata() {
return Metadata.customElement("router-view").noView();
},
writable: true,
enumerable: true,
configurable: true
},
inject: {
value: function inject() {
return [Element, Container, ViewSlot, Router];
},
writable: true,
enumerable: true,
configurable: true
}
}, {
process: {
value: function process(viewPortInstruction, waitToSwap) {
var _this = this;
var component = viewPortInstruction.component,
viewStrategy = component.view,
viewModelInfo = component.viewModelInfo,
childContainer = component.childContainer,
viewModel = component.executionContext;
if (!viewStrategy && "getViewStrategy" in viewModel) {
viewStrategy = viewModel.getViewStrategy();
}
if (viewStrategy) {
viewStrategy = ViewStrategy.normalize(viewStrategy);
viewStrategy.makeRelativeTo(Origin.get(component.router.container.viewModel.constructor).moduleId);
}
return viewModelInfo.type.load(childContainer, viewModelInfo.value, viewStrategy).then(function(behaviorType) {
viewPortInstruction.behavior = behaviorType.create(childContainer, {
executionContext: viewModel,
suppressBind: true
});
if (waitToSwap) {
return;
}
_this.swap(viewPortInstruction);
});
},
writable: true,
enumerable: true,
configurable: true
},
swap: {
value: function swap(viewPortInstruction) {
viewPortInstruction.behavior.view.bind(viewPortInstruction.behavior.executionContext);
this.viewSlot.swap(viewPortInstruction.behavior.view);
if (this.view) {
this.view.unbind();
}
this.view = viewPortInstruction.behavior.view;
},
writable: true,
enumerable: true,
configurable: true
}
});
return RouterView;
})();
_export("RouterView", RouterView);
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/compose", ["aurelia-dependency-injection", "aurelia-templating"], function(_export) {
"use strict";
var Container,
Behavior,
CompositionEngine,
ViewSlot,
ViewResources,
_prototypeProperties,
Compose;
function processInstruction(composer, instruction) {
composer.compositionEngine.compose(Object.assign(instruction, {
executionContext: composer.executionContext,
container: composer.container,
viewSlot: composer.viewSlot,
viewResources: composer.viewResources,
currentBehavior: composer.current
})).then(function(next) {
composer.current = next;
});
}
return {
setters: [function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
CompositionEngine = _aureliaTemplating.CompositionEngine;
ViewSlot = _aureliaTemplating.ViewSlot;
ViewResources = _aureliaTemplating.ViewResources;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Compose = _export("Compose", (function() {
function Compose(container, compositionEngine, viewSlot, viewResources) {
this.container = container;
this.compositionEngine = compositionEngine;
this.viewSlot = viewSlot;
this.viewResources = viewResources;
}
_prototypeProperties(Compose, {
metadata: {
value: function metadata() {
return Behavior.customElement("compose").withProperty("model").withProperty("view").withProperty("viewModel").noView();
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [Container, CompositionEngine, ViewSlot, ViewResources];
},
writable: true,
configurable: true
}
}, {
bind: {
value: function bind(executionContext) {
this.executionContext = executionContext;
processInstruction(this, {
view: this.view,
viewModel: this.viewModel,
model: this.model
});
},
writable: true,
configurable: true
},
modelChanged: {
value: function modelChanged(newValue, oldValue) {
if (this.viewModel && typeof this.viewModel.activate === "function") {
this.viewModel.activate(newValue);
}
},
writable: true,
configurable: true
},
viewChanged: {
value: function viewChanged(newValue, oldValue) {
processInstruction(this, {view: newValue});
},
writable: true,
configurable: true
},
viewModelChanged: {
value: function viewModelChanged(newValue, oldValue) {
processInstruction(this, {viewModel: newValue});
},
writable: true,
configurable: true
}
});
return Compose;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/if", ["aurelia-templating"], function(_export) {
"use strict";
var Behavior,
BoundViewFactory,
ViewSlot,
_prototypeProperties,
If;
return {
setters: [function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
BoundViewFactory = _aureliaTemplating.BoundViewFactory;
ViewSlot = _aureliaTemplating.ViewSlot;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
If = _export("If", (function() {
function If(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.showing = false;
}
_prototypeProperties(If, {
metadata: {
value: function metadata() {
return Behavior.templateController("if").withProperty("value", "valueChanged", "if");
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [BoundViewFactory, ViewSlot];
},
writable: true,
configurable: true
}
}, {valueChanged: {
value: function valueChanged(newValue) {
if (!newValue) {
if (this.view) {
this.viewSlot.remove(this.view);
this.view.unbind();
}
this.showing = false;
return;
}
if (!this.view) {
this.view = this.viewFactory.create();
}
if (!this.showing) {
this.showing = true;
if (!this.view.bound) {
this.view.bind();
}
this.viewSlot.add(this.view);
}
},
writable: true,
configurable: true
}});
return If;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/repeat", ["aurelia-binding", "aurelia-templating"], function(_export) {
"use strict";
var ObserverLocator,
calcSplices,
Behavior,
BoundViewFactory,
ViewSlot,
_prototypeProperties,
Repeat;
return {
setters: [function(_aureliaBinding) {
ObserverLocator = _aureliaBinding.ObserverLocator;
calcSplices = _aureliaBinding.calcSplices;
}, function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
BoundViewFactory = _aureliaTemplating.BoundViewFactory;
ViewSlot = _aureliaTemplating.ViewSlot;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Repeat = _export("Repeat", (function() {
function Repeat(viewFactory, viewSlot, observerLocator) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.observerLocator = observerLocator;
this.local = "item";
}
_prototypeProperties(Repeat, {
metadata: {
value: function metadata() {
return Behavior.templateController("repeat").withProperty("items", "itemsChanged", "repeat").withProperty("local");
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [BoundViewFactory, ViewSlot, ObserverLocator];
},
writable: true,
configurable: true
}
}, {
bind: {
value: function bind(executionContext) {
var _this = this;
var items = this.items;
this.executionContext = executionContext;
if (this.oldItems === items) {
var splices = calcSplices(items, 0, items.length, this.lastBoundItems, 0, this.lastBoundItems.length);
var observer = this.observerLocator.getArrayObserver(items);
this.handleSplices(items, splices);
this.lastBoundItems = this.oldItems = null;
this.disposeArraySubscription = observer.subscribe(function(splices) {
_this.handleSplices(items, splices);
});
} else {
this.processItems();
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
this.oldItems = this.items;
this.lastBoundItems = this.items.slice(0);
if (this.disposeArraySubscription) {
this.disposeArraySubscription();
this.disposeArraySubscription = null;
}
},
writable: true,
configurable: true
},
itemsChanged: {
value: function itemsChanged() {
this.processItems();
},
writable: true,
configurable: true
},
processItems: {
value: function processItems() {
var _this = this;
var items = this.items,
observer = this.observerLocator.getArrayObserver(items),
viewSlot = this.viewSlot,
viewFactory = this.viewFactory,
i,
ii,
row,
view;
if (this.disposeArraySubscription) {
this.disposeArraySubscription();
viewSlot.removeAll();
}
for (i = 0, ii = items.length; i < ii; ++i) {
row = this.createFullExecutionContext(items[i], i, ii);
view = viewFactory.create(row);
viewSlot.add(view);
}
this.disposeArraySubscription = observer.subscribe(function(splices) {
_this.handleSplices(items, splices);
});
},
writable: true,
configurable: true
},
createBaseExecutionContext: {
value: function createBaseExecutionContext(data) {
var context = {};
context[this.local] = data;
return context;
},
writable: true,
configurable: true
},
createFullExecutionContext: {
value: function createFullExecutionContext(data, index, length) {
var context = this.createBaseExecutionContext(data);
return this.updateExecutionContext(context, index, length);
},
writable: true,
configurable: true
},
updateExecutionContext: {
value: function updateExecutionContext(context, index, length) {
var first = index === 0,
last = index === length - 1,
even = index % 2 === 0;
context.$parent = this.executionContext;
context.$index = index;
context.$first = first;
context.$last = last;
context.$middle = !(first || last);
context.$odd = !even;
context.$even = even;
return context;
},
writable: true,
configurable: true
},
handleSplices: {
value: function handleSplices(array, splices) {
var viewLookup = new Map(),
removeDelta = 0,
arrayLength = array.length,
viewSlot = this.viewSlot,
viewFactory = this.viewFactory,
i,
ii,
j,
jj,
splice,
removed,
addIndex,
end,
model,
view,
children,
length,
row;
for (i = 0, ii = splices.length; i < ii; ++i) {
splice = splices[i];
removed = splice.removed;
for (j = 0, jj = removed.length; j < jj; ++j) {
model = removed[j];
view = viewSlot.removeAt(splice.index + removeDelta);
if (view) {
viewLookup.set(model, view);
}
}
removeDelta -= splice.addedCount;
}
for (i = 0, ii = splices.length; i < ii; ++i) {
splice = splices[i];
addIndex = splice.index;
end = splice.index + splice.addedCount;
for (; addIndex < end; ++addIndex) {
model = array[addIndex];
view = viewLookup.get(model);
if (view) {
viewLookup["delete"](model);
viewSlot.insert(addIndex, view);
} else {
row = this.createBaseExecutionContext(model);
view = this.viewFactory.create(row);
viewSlot.insert(addIndex, view);
}
}
}
children = viewSlot.children;
length = children.length;
for (i = 0; i < length; i++) {
this.updateExecutionContext(children[i].executionContext, i, length);
}
viewLookup.forEach(function(x) {
return x.unbind();
});
},
writable: true,
configurable: true
}
});
return Repeat;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/show", ["aurelia-templating"], function(_export) {
"use strict";
var Behavior,
_prototypeProperties,
Show;
function addStyleString(str) {
var node = document.createElement("style");
node.innerHTML = str;
node.type = "text/css";
document.head.appendChild(node);
}
return {
setters: [function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
addStyleString(".aurelia-hide { display:none !important; }");
Show = _export("Show", (function() {
function Show(element) {
this.element = element;
}
_prototypeProperties(Show, {
metadata: {
value: function metadata() {
return Behavior.attachedBehavior("show").withProperty("value", "valueChanged", "show");
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [Element];
},
writable: true,
configurable: true
}
}, {valueChanged: {
value: function valueChanged(newValue) {
if (newValue) {
this.element.classList.remove("aurelia-hide");
} else {
this.element.classList.add("aurelia-hide");
}
},
writable: true,
configurable: true
}});
return Show;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/selected-item", ["aurelia-templating"], function(_export) {
"use strict";
var Behavior,
_prototypeProperties,
SelectedItem;
return {
setters: [function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
SelectedItem = _export("SelectedItem", (function() {
function SelectedItem(element) {
this.element = element;
this.options = [];
this.callback = this.selectedIndexChanged.bind(this);
}
_prototypeProperties(SelectedItem, {
metadata: {
value: function metadata() {
return Behavior.attachedBehavior("selected-item").withProperty("value", "valueChanged", "selected-item").and(function(x) {
return x.bindingIsTwoWay();
}).syncChildren("options", "optionsChanged", "option");
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [Element];
},
writable: true,
configurable: true
}
}, {
bind: {
value: function bind() {
this.element.addEventListener("change", this.callback, false);
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
this.element.removeEventListener("change", this.callback);
},
writable: true,
configurable: true
},
valueChanged: {
value: function valueChanged(newValue) {
this.optionsChanged();
},
writable: true,
configurable: true
},
selectedIndexChanged: {
value: function selectedIndexChanged() {
var index = this.element.selectedIndex,
option = this.options[index];
this.value = option ? option.model : null;
},
writable: true,
configurable: true
},
optionsChanged: {
value: function optionsChanged(mutations) {
var value = this.value,
options = this.options,
option,
i,
ii;
for (i = 0, ii = options.length; i < ii; ++i) {
option = options[i];
if (option.model === value) {
if (this.element.selectedIndex !== i) {
this.element.selectedIndex = i;
}
return;
}
}
this.element.selectedIndex = 0;
},
writable: true,
configurable: true
}
});
return SelectedItem;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/global-behavior", ["aurelia-templating"], function(_export) {
"use strict";
var Behavior,
_prototypeProperties,
GlobalBehavior;
return {
setters: [function(_aureliaTemplating) {
Behavior = _aureliaTemplating.Behavior;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
GlobalBehavior = _export("GlobalBehavior", (function() {
function GlobalBehavior(element) {
this.element = element;
}
_prototypeProperties(GlobalBehavior, {
metadata: {
value: function metadata() {
return Behavior.attachedBehavior("global-behavior").withOptions().and(function(x) {
return x.dynamic();
});
},
writable: true,
configurable: true
},
inject: {
value: function inject() {
return [Element];
},
writable: true,
configurable: true
}
}, {
bind: {
value: function bind() {
var handler = GlobalBehavior.handlers[this.aureliaAttrName];
if (!handler) {
throw new Error("Conventional binding handler not found for " + this.aureliaAttrName + ".");
}
try {
this.handler = handler.bind(this, this.element, this.aureliaCommand) || handler;
} catch (error) {
throw new Error("Conventional binding handler failed.", error);
}
},
writable: true,
configurable: true
},
attached: {
value: function attached() {
if (this.handler && "attached" in this.handler) {
this.handler.attached(this, this.element);
}
},
writable: true,
configurable: true
},
detached: {
value: function detached() {
if (this.handler && "detached" in this.handler) {
this.handler.detached(this, this.element);
}
},
writable: true,
configurable: true
},
unbind: {
value: function unbind() {
if (this.handler && "unbind" in this.handler) {
this.handler.unbind(this, this.element);
}
this.handler = null;
},
writable: true,
configurable: true
}
});
return GlobalBehavior;
})());
GlobalBehavior.createSettingsFromBehavior = function(behavior) {
var settings = {};
for (var key in behavior) {
if (key === "aureliaAttrName" || key === "aureliaCommand" || !behavior.hasOwnProperty(key)) {
continue;
}
settings[key] = behavior[key];
}
return settings;
};
GlobalBehavior.jQueryPlugins = {};
GlobalBehavior.handlers = {jquery: {
bind: function bind(behavior, element, command) {
var settings = GlobalBehavior.createSettingsFromBehavior(behavior);
var pluginName = GlobalBehavior.jQueryPlugins[command] || command;
behavior.plugin = window.jQuery(element)[pluginName](settings);
},
unbind: function unbind(behavior, element) {
if (typeof behavior.plugin.destroy === "function") {
behavior.plugin.destroy();
behavior.plugin = null;
}
}
}};
}
};
});
System.register("github:aurelia/event-aggregator@0.2.2/system/index", [], function(_export) {
"use strict";
var _prototypeProperties,
Handler,
EventAggregator;
_export("includeEventsIn", includeEventsIn);
_export("install", install);
function includeEventsIn(obj) {
var ea = new EventAggregator();
obj.subscribe = function(event, callback) {
return ea.subscribe(event, callback);
};
obj.publish = function(event, data) {
ea.publish(event, data);
};
return ea;
}
function install(aurelia) {
aurelia.withInstance(EventAggregator, includeEventsIn(aurelia));
}
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Handler = (function() {
function Handler(messageType, callback) {
this.messageType = messageType;
this.callback = callback;
}
_prototypeProperties(Handler, null, {handle: {
value: function handle(message) {
if (message instanceof this.messageType) {
this.callback.call(null, message);
}
},
writable: true,
enumerable: true,
configurable: true
}});
return Handler;
})();
EventAggregator = (function() {
function EventAggregator() {
this.eventLookup = {};
this.messageHandlers = [];
}
_prototypeProperties(EventAggregator, null, {
publish: {
value: function publish(event, data) {
var subscribers,
i,
handler;
if (typeof event === "string") {
subscribers = this.eventLookup[event];
if (subscribers) {
subscribers = subscribers.slice();
i = subscribers.length;
while (i--) {
subscribers[i](data, event);
}
}
} else {
subscribers = this.messageHandlers.slice();
i = subscribers.length;
while (i--) {
subscribers[i].handle(event);
}
}
},
writable: true,
enumerable: true,
configurable: true
},
subscribe: {
value: function subscribe(event, callback) {
var subscribers,
handler;
if (typeof event === "string") {
subscribers = this.eventLookup[event] || (this.eventLookup[event] = []);
subscribers.push(callback);
return function() {
subscribers.splice(subscribers.indexOf(callback), 1);
};
} else {
handler = new Handler(event, callback);
subscribers = this.messageHandlers;
subscribers.push(handler);
return function() {
subscribers.splice(subscribers.indexOf(handler), 1);
};
}
},
writable: true,
enumerable: true,
configurable: true
}
});
return EventAggregator;
})();
_export("EventAggregator", EventAggregator);
}
};
});
System.register("github:aurelia/history-browser@0.2.3/system/index", ["aurelia-history"], function(_export) {
"use strict";
var History,
_prototypeProperties,
_inherits,
routeStripper,
rootStripper,
isExplorer,
trailingSlash,
BrowserHistory;
function updateHash(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, "");
location.replace(href + "#" + fragment);
} else {
location.hash = "#" + fragment;
}
}
function install(aurelia) {
aurelia.withSingleton(History, BrowserHistory);
}
return {
setters: [function(_aureliaHistory) {
History = _aureliaHistory.History;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
routeStripper = /^[#\/]|\s+$/g;
rootStripper = /^\/+|\/+$/g;
isExplorer = /msie [\w.]+/;
trailingSlash = /\/$/;
BrowserHistory = (function(History) {
function BrowserHistory() {
this.interval = 50;
this.active = false;
this.previousFragment = "";
this._checkUrlCallback = this.checkUrl.bind(this);
if (typeof window !== "undefined") {
this.location = window.location;
this.history = window.history;
}
}
_inherits(BrowserHistory, History);
_prototypeProperties(BrowserHistory, null, {
getHash: {
value: function getHash(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : "";
},
writable: true,
enumerable: true,
configurable: true
},
getFragment: {
value: function getFragment(fragment, forcePushState) {
var root;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, "");
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, "");
},
writable: true,
enumerable: true,
configurable: true
},
activate: {
value: function activate(options) {
if (this.active) {
throw new Error("History has already been activated.");
}
this.active = true;
this.options = Object.assign({}, {root: "/"}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
this.root = ("/" + this.root + "/").replace(rootStripper, "/");
if (this._hasPushState) {
window.onpopstate = this._checkUrlCallback;
} else if (this._wantsHashChange && "onhashchange" in window) {
window.addEventListener("hashchange", this._checkUrlCallback);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this._checkUrlCallback, this.interval);
}
this.fragment = fragment;
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, "$&/") === this.root;
if (this._wantsHashChange && this._wantsPushState) {
if (!this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + this.location.search + "#" + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, "");
this["this"].replaceState({}, document.title, this.root + this.fragment + loc.search);
}
}
if (!this.options.silent) {
return this.loadUrl();
}
},
writable: true,
enumerable: true,
configurable: true
},
deactivate: {
value: function deactivate() {
window.onpopstate = null;
window.removeEventListener("hashchange", this._checkUrlCallback);
clearInterval(this._checkUrlInterval);
this.active = false;
},
writable: true,
enumerable: true,
configurable: true
},
checkUrl: {
value: function checkUrl() {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) {
return false;
}
if (this.iframe) {
this.navigate(current, false);
}
this.loadUrl();
},
writable: true,
enumerable: true,
configurable: true
},
loadUrl: {
value: function loadUrl(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
},
writable: true,
enumerable: true,
configurable: true
},
navigate: {
value: function navigate(fragment, options) {
if (fragment && fragment.indexOf("://") != -1) {
window.location.href = fragment;
return true;
}
if (!this.active) {
return false;
}
if (options === undefined) {
options = {trigger: true};
} else if (typeof options === "boolean") {
options = {trigger: options};
}
fragment = this.getFragment(fragment || "");
if (this.fragment === fragment) {
return;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === "" && url !== "/") {
url = url.slice(0, -1);
}
if (this._hasPushState) {
this.history[options.replace ? "replaceState" : "pushState"]({}, document.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, options.replace);
if (this.iframe && fragment !== this.getFragment(this.getHash(this.iframe))) {
if (!options.replace) {
this.iframe.document.open().close();
}
updateHash(this.iframe.location, fragment, options.replace);
}
} else {
return this.location.assign(url);
}
if (options.trigger) {
return this.loadUrl(fragment);
} else {
this.previousFragment = fragment;
}
},
writable: true,
enumerable: true,
configurable: true
},
navigateBack: {
value: function navigateBack() {
this.history.back();
},
writable: true,
enumerable: true,
configurable: true
}
});
return BrowserHistory;
})(History);
_export("BrowserHistory", BrowserHistory);
_export("install", install);
}
};
});
System.register("dist/nav-bar", ["aurelia-framework"], function(_export) {
"use strict";
var Behavior,
_prototypeProperties,
_classCallCheck,
NavBar;
return {
setters: [function(_aureliaFramework) {
Behavior = _aureliaFramework.Behavior;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
NavBar = _export("NavBar", (function() {
function NavBar() {
_classCallCheck(this, NavBar);
}
_prototypeProperties(NavBar, {metadata: {
value: function metadata() {
return Behavior.withProperty("router");
},
writable: true,
configurable: true
}});
return NavBar;
})());
}
};
});
System.register("dist/app", ["aurelia-router"], function(_export) {
"use strict";
var Router,
_prototypeProperties,
_classCallCheck,
App;
return {
setters: [function(_aureliaRouter) {
Router = _aureliaRouter.Router;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
App = _export("App", (function() {
function App(router) {
_classCallCheck(this, App);
this.router = router;
this.router.configure(function(config) {
config.title = "Aurelia";
config.map([{
route: ["", "welcome"],
moduleId: "welcome",
nav: true,
title: "Welcome"
}, {
route: "flickr",
moduleId: "flickr",
nav: true
}, {
route: "child-router",
moduleId: "child-router",
nav: true,
title: "Child Router"
}]);
});
}
_prototypeProperties(App, {inject: {
value: function inject() {
return [Router];
},
writable: true,
configurable: true
}});
return App;
})());
}
};
});
System.register("dist/child-router", ["aurelia-router"], function(_export) {
"use strict";
var Router,
_prototypeProperties,
_classCallCheck,
Welcome;
return {
setters: [function(_aureliaRouter) {
Router = _aureliaRouter.Router;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
Welcome = _export("Welcome", (function() {
function Welcome(router) {
_classCallCheck(this, Welcome);
this.heading = "Child Router";
this.router = router;
router.configure(function(config) {
config.map([{
route: ["", "welcome"],
moduleId: "welcome",
nav: true,
title: "Welcome"
}, {
route: "flickr",
moduleId: "flickr",
nav: true
}, {
route: "child-router",
moduleId: "child-router",
nav: true,
title: "Child Router"
}]);
});
}
_prototypeProperties(Welcome, {inject: {
value: function inject() {
return [Router];
},
writable: true,
configurable: true
}});
return Welcome;
})());
}
};
});
System.register("github:aurelia/http-client@0.4.4/system/headers", [], function(_export) {
"use strict";
var _prototypeProperties,
Headers;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Headers = _export("Headers", (function() {
function Headers() {
var headers = arguments[0] === undefined ? {} : arguments[0];
this.headers = headers;
}
_prototypeProperties(Headers, null, {
add: {
value: function add(key, value) {
this.headers[key] = value;
},
writable: true,
configurable: true
},
get: {
value: function get(key) {
return this.headers[key];
},
writable: true,
configurable: true
},
clear: {
value: function clear() {
this.headers = {};
},
writable: true,
configurable: true
},
configureXHR: {
value: function configureXHR(xhr) {
var headers = this.headers,
key;
for (key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
},
writable: true,
configurable: true
}
});
return Headers;
})());
}
};
});
System.register("github:aurelia/http-client@0.4.4/system/http-response-message", ["./headers"], function(_export) {
"use strict";
var Headers,
_prototypeProperties,
HttpResponseMessage;
function parseResponseHeaders(headerStr) {
var headers = {};
if (!headerStr) {
return headers;
}
var headerPairs = headerStr.split("\r\n");
for (var i = 0; i < headerPairs.length; i++) {
var headerPair = headerPairs[i];
var index = headerPair.indexOf(": ");
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
}
return {
setters: [function(_headers) {
Headers = _headers.Headers;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
HttpResponseMessage = _export("HttpResponseMessage", (function() {
function HttpResponseMessage(requestMessage, xhr, responseType, reviver) {
this.requestMessage = requestMessage;
this.statusCode = xhr.status;
this.response = xhr.response;
this.isSuccess = xhr.status >= 200 && xhr.status < 300;
this.statusText = xhr.statusText;
this.responseType = responseType;
this.reviver = reviver;
if (xhr.getAllResponseHeaders) {
this.headers = new Headers(parseResponseHeaders(xhr.getAllResponseHeaders()));
} else {
this.headers = new Headers();
}
}
_prototypeProperties(HttpResponseMessage, null, {content: {
get: function() {
if (this._content !== undefined) {
return this._content;
}
if (this.responseType === "json") {
return this._content = JSON.parse(this.response, this.reviver);
}
if (this.reviver) {
return this._content = this.reviver(this.response);
}
return this._content = this.response;
},
configurable: true
}});
return HttpResponseMessage;
})());
}
};
});
System.register("github:aurelia/http-client@0.4.4/system/jsonp-request-message", ["./http-response-message"], function(_export) {
"use strict";
var HttpResponseMessage,
_prototypeProperties,
JSONPRequestMessage;
return {
setters: [function(_httpResponseMessage) {
HttpResponseMessage = _httpResponseMessage.HttpResponseMessage;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
JSONPRequestMessage = _export("JSONPRequestMessage", (function() {
function JSONPRequestMessage(uri, callbackParameterName) {
this.uri = uri;
this.callbackParameterName = callbackParameterName;
}
_prototypeProperties(JSONPRequestMessage, null, {send: {
value: function send(client) {
var _this = this;
return new Promise(function(resolve, reject) {
var callbackName = "jsonp_callback_" + Math.round(100000 * Math.random());
var uri = _this.uri + (_this.uri.indexOf("?") >= 0 ? "&" : "?") + _this.callbackParameterName + "=" + callbackName;
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
resolve(new HttpResponseMessage(_this, {
response: data,
status: 200,
statusText: "OK"
}, "jsonp"));
};
var script = document.createElement("script");
script.src = uri;
document.body.appendChild(script);
});
},
writable: true,
configurable: true
}});
return JSONPRequestMessage;
})());
}
};
});
System.register("dist/welcome", [], function(_export) {
"use strict";
var _prototypeProperties,
_classCallCheck,
Welcome,
UpperValueConverter;
return {
setters: [],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
Welcome = _export("Welcome", (function() {
function Welcome() {
_classCallCheck(this, Welcome);
this.heading = "Welcome to the Aurelia Navigation App!";
this.firstName = "John";
this.lastName = "Doe";
}
_prototypeProperties(Welcome, null, {
fullName: {
get: function() {
return "" + this.firstName + " " + this.lastName;
},
configurable: true
},
welcome: {
value: function welcome() {
alert("Welcome, " + this.fullName + "!");
},
writable: true,
configurable: true
}
});
return Welcome;
})());
UpperValueConverter = _export("UpperValueConverter", (function() {
function UpperValueConverter() {
_classCallCheck(this, UpperValueConverter);
}
_prototypeProperties(UpperValueConverter, null, {toView: {
value: function toView(value) {
return value && value.toUpperCase();
},
writable: true,
configurable: true
}});
return UpperValueConverter;
})());
}
};
});
System.register("github:aurelia/metadata@0.3.1/system/index", ["./origin", "./resource-type", "./metadata"], function(_export) {
"use strict";
return {
setters: [function(_origin) {
_export("Origin", _origin.Origin);
}, function(_resourceType) {
_export("ResourceType", _resourceType.ResourceType);
}, function(_metadata) {
_export("Metadata", _metadata.Metadata);
}],
execute: function() {}
};
});
System.register("github:aurelia/loader@0.3.3", ["github:aurelia/loader@0.3.3/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/path@0.4.2", ["github:aurelia/path@0.4.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/logging@0.2.2", ["github:aurelia/logging@0.2.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/dependency-injection@0.4.2/system/container", ["aurelia-metadata", "./metadata", "./util"], function(_export) {
"use strict";
var Metadata,
Resolver,
Registration,
isClass,
_prototypeProperties,
emptyParameters,
Container;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}, function(_metadata) {
Resolver = _metadata.Resolver;
Registration = _metadata.Registration;
}, function(_util) {
isClass = _util.isClass;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
emptyParameters = Object.freeze([]);
Container = _export("Container", (function() {
function Container(constructionInfo) {
this.constructionInfo = constructionInfo || new Map();
this.entries = new Map();
}
_prototypeProperties(Container, null, {
supportAtScript: {
value: function supportAtScript() {
this.addParameterInfoLocator(function(fn) {
var parameters = fn.parameters,
keys,
i,
ii;
if (parameters) {
keys = new Array(parameters.length);
for (i = 0, ii = parameters.length; i < ii; ++i) {
keys[i] = parameters[i].is || parameters[i][0];
}
}
return keys;
});
},
writable: true,
configurable: true
},
addParameterInfoLocator: {
value: function addParameterInfoLocator(locator) {
if (this.locateParameterInfoElsewhere === undefined) {
this.locateParameterInfoElsewhere = locator;
return;
}
var original = this.locateParameterInfoElsewhere;
this.locateParameterInfoElsewhere = function(fn) {
return original(fn) || locator(fn);
};
},
writable: true,
configurable: true
},
registerInstance: {
value: function registerInstance(key, instance) {
this.registerHandler(key, function(x) {
return instance;
});
},
writable: true,
configurable: true
},
registerTransient: {
value: function registerTransient(key, fn) {
fn = fn || key;
this.registerHandler(key, function(x) {
return x.invoke(fn);
});
},
writable: true,
configurable: true
},
registerSingleton: {
value: function registerSingleton(key, fn) {
var singleton = null;
fn = fn || key;
this.registerHandler(key, function(x) {
return singleton || (singleton = x.invoke(fn));
});
},
writable: true,
configurable: true
},
autoRegister: {
value: function autoRegister(fn, key) {
var registration = Metadata.on(fn).first(Registration, true);
if (registration) {
registration.register(this, key || fn, fn);
} else {
this.registerSingleton(key || fn, fn);
}
},
writable: true,
configurable: true
},
autoRegisterAll: {
value: function autoRegisterAll(fns) {
var i = fns.length;
while (i--) {
this.autoRegister(fns[i]);
}
},
writable: true,
configurable: true
},
registerHandler: {
value: function registerHandler(key, handler) {
this.getOrCreateEntry(key).push(handler);
},
writable: true,
configurable: true
},
get: {
value: function get(key) {
var entry;
if (key instanceof Resolver) {
return key.get(this);
}
if (key === Container) {
return this;
}
entry = this.entries.get(key);
if (entry !== undefined) {
return entry[0](this);
}
if (this.parent) {
return this.parent.get(key);
}
this.autoRegister(key);
entry = this.entries.get(key);
return entry[0](this);
},
writable: true,
configurable: true
},
getAll: {
value: function getAll(key) {
var _this = this;
var entry = this.entries.get(key);
if (entry !== undefined) {
return entry.map(function(x) {
return x(_this);
});
}
if (this.parent) {
return this.parent.getAll(key);
}
return [];
},
writable: true,
configurable: true
},
hasHandler: {
value: function hasHandler(key) {
var checkParent = arguments[1] === undefined ? false : arguments[1];
return this.entries.has(key) || checkParent && this.parent && this.parent.hasHandler(key, checkParent);
},
writable: true,
configurable: true
},
createChild: {
value: function createChild() {
var childContainer = new Container(this.constructionInfo);
childContainer.parent = this;
childContainer.locateParameterInfoElsewhere = this.locateParameterInfoElsewhere;
return childContainer;
},
writable: true,
configurable: true
},
invoke: {
value: function invoke(fn) {
var info = this.getOrCreateConstructionInfo(fn),
keys = info.keys,
args = new Array(keys.length),
context,
i,
ii;
for (i = 0, ii = keys.length; i < ii; ++i) {
args[i] = this.get(keys[i]);
}
if (info.isClass) {
context = Object.create(fn.prototype);
if ("initialize" in fn) {
fn.initialize(context);
}
return fn.apply(context, args) || context;
} else {
return fn.apply(undefined, args);
}
},
writable: true,
configurable: true
},
getOrCreateEntry: {
value: function getOrCreateEntry(key) {
var entry = this.entries.get(key);
if (entry === undefined) {
entry = [];
this.entries.set(key, entry);
}
return entry;
},
writable: true,
configurable: true
},
getOrCreateConstructionInfo: {
value: function getOrCreateConstructionInfo(fn) {
var info = this.constructionInfo.get(fn);
if (info === undefined) {
info = this.createConstructionInfo(fn);
this.constructionInfo.set(fn, info);
}
return info;
},
writable: true,
configurable: true
},
createConstructionInfo: {
value: function createConstructionInfo(fn) {
var info = {isClass: isClass(fn)};
if (fn.inject !== undefined) {
if (typeof fn.inject === "function") {
info.keys = fn.inject();
} else {
info.keys = fn.inject;
}
return info;
}
if (this.locateParameterInfoElsewhere !== undefined) {
info.keys = this.locateParameterInfoElsewhere(fn) || emptyParameters;
} else {
info.keys = emptyParameters;
}
return info;
},
writable: true,
configurable: true
}
});
return Container;
})());
}
};
});
System.register("github:aurelia/task-queue@0.2.3", ["github:aurelia/task-queue@0.2.3/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/binding@0.3.3/system/array-observation", ["./array-change-records"], function(_export) {
"use strict";
var calcSplices,
projectArraySplices,
_prototypeProperties,
arrayProto,
hasArrayObserve,
ModifyArrayObserver,
ArrayObserveObserver,
ArrayLengthObserver;
_export("getArrayObserver", getArrayObserver);
function getArrayObserver(taskQueue, array) {
if (hasArrayObserve) {
return new ArrayObserveObserver(array);
} else {
return ModifyArrayObserver.create(taskQueue, array);
}
}
return {
setters: [function(_arrayChangeRecords) {
calcSplices = _arrayChangeRecords.calcSplices;
projectArraySplices = _arrayChangeRecords.projectArraySplices;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
arrayProto = Array.prototype;
hasArrayObserve = (function detectArrayObserve() {
if (typeof Array.observe !== "function") {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var arr = [];
Array.observe(arr, callback);
arr.push(1, 2);
arr.length = 0;
Object.deliverChangeRecords(callback);
if (records.length !== 2)
return false;
if (records[0].type != "splice" || records[1].type != "splice") {
return false;
}
Array.unobserve(arr, callback);
return true;
})();
ModifyArrayObserver = (function() {
function ModifyArrayObserver(taskQueue, array) {
this.taskQueue = taskQueue;
this.callbacks = [];
this.changeRecords = [];
this.queued = false;
this.array = array;
this.oldArray = null;
}
_prototypeProperties(ModifyArrayObserver, {create: {
value: function create(taskQueue, array) {
var observer = new ModifyArrayObserver(taskQueue, array);
array.pop = function() {
var methodCallResult = arrayProto.pop.apply(array, arguments);
observer.addChangeRecord({
type: "delete",
object: array,
name: array.length,
oldValue: methodCallResult
});
return methodCallResult;
};
array.push = function() {
var methodCallResult = arrayProto.push.apply(array, arguments);
observer.addChangeRecord({
type: "splice",
object: array,
index: array.length - arguments.length,
removed: [],
addedCount: arguments.length
});
return methodCallResult;
};
array.reverse = function() {
var oldArray = array.slice();
var methodCallResult = arrayProto.reverse.apply(array, arguments);
observer.reset(oldArray);
return methodCallResult;
};
array.shift = function() {
var methodCallResult = arrayProto.shift.apply(array, arguments);
observer.addChangeRecord({
type: "delete",
object: array,
name: 0,
oldValue: methodCallResult
});
return methodCallResult;
};
array.sort = function() {
var oldArray = array.slice();
var methodCallResult = arrayProto.sort.apply(array, arguments);
observer.reset(oldArray);
return methodCallResult;
};
array.splice = function() {
var methodCallResult = arrayProto.splice.apply(array, arguments);
observer.addChangeRecord({
type: "splice",
object: array,
index: arguments[0],
removed: methodCallResult,
addedCount: arguments.length > 2 ? arguments.length - 2 : 0
});
return methodCallResult;
};
array.unshift = function() {
var methodCallResult = arrayProto.unshift.apply(array, arguments);
observer.addChangeRecord({
type: "splice",
object: array,
index: 0,
removed: [],
addedCount: arguments.length
});
return methodCallResult;
};
return observer;
},
writable: true,
configurable: true
}}, {
subscribe: {
value: function subscribe(callback) {
var callbacks = this.callbacks;
callbacks.push(callback);
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
},
addChangeRecord: {
value: function addChangeRecord(changeRecord) {
if (!this.callbacks.length) {
return;
}
this.changeRecords.push(changeRecord);
if (!this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
},
writable: true,
configurable: true
},
reset: {
value: function reset(oldArray) {
if (!this.callbacks.length) {
return;
}
this.oldArray = oldArray;
if (!this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
},
writable: true,
configurable: true
},
getObserver: {
value: function getObserver(propertyName) {
if (propertyName == "length") {
return this.lengthObserver || (this.lengthObserver = new ArrayLengthObserver(this.array));
} else {
throw new Error("You cannot observe the " + propertyName + " property of an array.");
}
},
writable: true,
configurable: true
},
call: {
value: function call() {
var callbacks = this.callbacks,
i = callbacks.length,
changeRecords = this.changeRecords,
oldArray = this.oldArray,
splices;
this.queued = false;
this.changeRecords = [];
this.oldArray = null;
if (i) {
if (oldArray) {
splices = calcSplices(this.array, 0, this.array.length, oldArray, 0, oldArray.length);
} else {
splices = projectArraySplices(this.array, changeRecords);
}
while (i--) {
callbacks[i](splices);
}
}
if (this.lengthObserver) {
this.lengthObserver(this.array.length);
}
},
writable: true,
configurable: true
}
});
return ModifyArrayObserver;
})();
ArrayObserveObserver = (function() {
function ArrayObserveObserver(array) {
this.array = array;
this.callbacks = [];
this.observing = false;
}
_prototypeProperties(ArrayObserveObserver, null, {
subscribe: {
value: function subscribe(callback) {
var _this = this;
var callbacks = this.callbacks;
callbacks.push(callback);
if (!this.observing) {
this.observing = true;
Array.observe(this.array, function(changes) {
return _this.handleChanges(changes);
});
}
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
},
getObserver: {
value: function getObserver(propertyName) {
if (propertyName == "length") {
return this.lengthObserver || (this.lengthObserver = new ArrayLengthObserver(this.array));
} else {
throw new Error("You cannot observe the " + propertyName + " property of an array.");
}
},
writable: true,
configurable: true
},
handleChanges: {
value: function handleChanges(changeRecords) {
var callbacks = this.callbacks,
i = callbacks.length,
splices;
if (!i) {
return;
}
var splices = projectArraySplices(this.array, changeRecords);
while (i--) {
callbacks[i](splices);
}
if (this.lengthObserver) {
this.lengthObserver.call(this.array.length);
}
},
writable: true,
configurable: true
}
});
return ArrayObserveObserver;
})();
ArrayLengthObserver = (function() {
function ArrayLengthObserver(array) {
this.array = array;
this.callbacks = [];
this.currentValue = array.length;
}
_prototypeProperties(ArrayLengthObserver, null, {
getValue: {
value: function getValue() {
return this.array.length;
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
this.array.length = newValue;
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var callbacks = this.callbacks;
callbacks.push(callback);
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
},
call: {
value: function call(newValue) {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.currentValue;
while (i--) {
callbacks[i](newValue, oldValue);
}
this.currentValue = newValue;
},
writable: true,
configurable: true
}
});
return ArrayLengthObserver;
})();
}
};
});
System.register("github:aurelia/binding@0.3.3/system/ast", ["./path-observer", "./composite-observer"], function(_export) {
"use strict";
var PathObserver,
CompositeObserver,
_get,
_inherits,
_prototypeProperties,
Expression,
Chain,
ValueConverter,
Assign,
Conditional,
AccessScope,
AccessMember,
AccessKeyed,
CallScope,
CallMember,
CallFunction,
Binary,
PrefixNot,
LiteralPrimitive,
LiteralString,
LiteralArray,
LiteralObject,
Unparser,
evalListCache;
function evalList(scope, list, valueConverters) {
var length = list.length,
cacheLength,
i;
for (cacheLength = evalListCache.length; cacheLength <= length; ++cacheLength) {
_evalListCache.push([]);
}
var result = evalListCache[length];
for (i = 0; i < length; ++i) {
result[i] = list[i].evaluate(scope, valueConverters);
}
return result;
}
function autoConvertAdd(a, b) {
if (a != null && b != null) {
if (typeof a == "string" && typeof b != "string") {
return a + b.toString();
}
if (typeof a != "string" && typeof b == "string") {
return a.toString() + b;
}
return a + b;
}
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return 0;
}
function ensureFunctionFromMap(obj, name) {
var func = obj[name];
if (typeof func === "function") {
return func;
}
if (func === null) {
throw new Error("Undefined function " + name);
} else {
throw new Error("" + name + " is not a function");
}
}
function getKeyed(obj, key) {
if (Array.isArray(obj)) {
return obj[parseInt(key)];
} else if (obj) {
return obj[key];
} else if (obj === null) {
throw new Error("Accessing null object");
} else {
return obj[key];
}
}
function setKeyed(obj, key, value) {
if (Array.isArray(obj)) {
var index = parseInt(key);
if (obj.length <= index) {
obj.length = index + 1;
}
obj[index] = value;
} else {
obj[key] = value;
}
return value;
}
return {
setters: [function(_pathObserver) {
PathObserver = _pathObserver.PathObserver;
}, function(_compositeObserver) {
CompositeObserver = _compositeObserver.CompositeObserver;
}],
execute: function() {
_get = function get(object, property, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc && desc.writable) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Expression = _export("Expression", (function() {
function Expression() {
this.isChain = false;
this.isAssignable = false;
}
_prototypeProperties(Expression, null, {
evaluate: {
value: function evaluate() {
throw new Error("Cannot evaluate " + this);
},
writable: true,
configurable: true
},
assign: {
value: function assign() {
throw new Error("Cannot assign to " + this);
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
return Unparser.unparse(this);
},
writable: true,
configurable: true
}
});
return Expression;
})());
Chain = _export("Chain", (function(Expression) {
function Chain(expressions) {
_get(Object.getPrototypeOf(Chain.prototype), "constructor", this).call(this);
this.expressions = expressions;
this.isChain = true;
}
_inherits(Chain, Expression);
_prototypeProperties(Chain, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var result,
expressions = this.expressions,
length = expressions.length,
i,
last;
for (i = 0; i < length; ++i) {
last = expressions[i].evaluate(scope, valueConverters);
if (last !== null) {
result = last;
}
}
return result;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitChain(this);
},
writable: true,
configurable: true
}
});
return Chain;
})(Expression));
ValueConverter = _export("ValueConverter", (function(Expression) {
function ValueConverter(expression, name, args, allArgs) {
_get(Object.getPrototypeOf(ValueConverter.prototype), "constructor", this).call(this);
this.expression = expression;
this.name = name;
this.args = args;
this.allArgs = allArgs;
}
_inherits(ValueConverter, Expression);
_prototypeProperties(ValueConverter, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var converter = valueConverters(this.name);
if (!converter) {
throw new Error("No ValueConverter named \"" + this.name + "\" was found!");
}
if ("toView" in converter) {
return converter.toView.apply(converter, evalList(scope, this.allArgs, valueConverters));
}
return this.allArgs[0].evaluate(scope, valueConverters);
},
writable: true,
configurable: true
},
assign: {
value: function assign(scope, value, valueConverters) {
var converter = valueConverters(this.name);
if (!converter) {
throw new Error("No ValueConverter named \"" + this.name + "\" was found!");
}
if ("fromView" in converter) {
value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, valueConverters)));
}
return this.allArgs[0].assign(scope, value, valueConverters);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitValueConverter(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
childObservers = [],
i,
ii,
exp,
expInfo;
for (i = 0, ii = this.allArgs.length; i < ii; ++i) {
exp = this.allArgs[i];
expInfo = exp.connect(binding, scope);
if (expInfo.observer) {
childObservers.push(expInfo.observer);
}
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return ValueConverter;
})(Expression));
Assign = _export("Assign", (function(Expression) {
function Assign(target, value) {
_get(Object.getPrototypeOf(Assign.prototype), "constructor", this).call(this);
this.target = target;
this.value = value;
}
_inherits(Assign, Expression);
_prototypeProperties(Assign, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return this.target.assign(scope, this.value.evaluate(scope, valueConverters));
},
writable: true,
configurable: true
},
accept: {
value: function accept(vistor) {
vistor.visitAssign(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
return {value: this.evaluate(scope, binding.valueConverterLookupFunction)};
},
writable: true,
configurable: true
}
});
return Assign;
})(Expression));
Conditional = _export("Conditional", (function(Expression) {
function Conditional(condition, yes, no) {
_get(Object.getPrototypeOf(Conditional.prototype), "constructor", this).call(this);
this.condition = condition;
this.yes = yes;
this.no = no;
}
_inherits(Conditional, Expression);
_prototypeProperties(Conditional, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return !!this.condition.evaluate(scope) ? this.yes.evaluate(scope) : this.no.evaluate(scope);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitConditional(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var conditionInfo = this.condition.connect(binding, scope),
yesInfo = this.yes.connect(binding, scope),
noInfo = this.no.connect(binding, scope),
childObservers = [],
observer;
if (conditionInfo.observer) {
childObservers.push(conditionInfo.observer);
}
if (yesInfo.observer) {
childObservers.push(yesInfo.observer);
}
if (noInfo.observer) {
childObservers.push(noInfo.observer);
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: !!conditionInfo.value ? yesInfo.value : noInfo.value,
observer: observer
};
},
writable: true,
configurable: true
}
});
return Conditional;
})(Expression));
AccessScope = _export("AccessScope", (function(Expression) {
function AccessScope(name) {
_get(Object.getPrototypeOf(AccessScope.prototype), "constructor", this).call(this);
this.name = name;
this.isAssignable = true;
}
_inherits(AccessScope, Expression);
_prototypeProperties(AccessScope, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return scope[this.name];
},
writable: true,
configurable: true
},
assign: {
value: function assign(scope, value) {
return scope[this.name] = value;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitAccessScope(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var observer = binding.getObserver(scope, this.name);
return {
value: observer.getValue(),
observer: observer
};
},
writable: true,
configurable: true
}
});
return AccessScope;
})(Expression));
AccessMember = _export("AccessMember", (function(Expression) {
function AccessMember(object, name) {
_get(Object.getPrototypeOf(AccessMember.prototype), "constructor", this).call(this);
this.object = object;
this.name = name;
this.isAssignable = true;
}
_inherits(AccessMember, Expression);
_prototypeProperties(AccessMember, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var instance = this.object.evaluate(scope, valueConverters);
return instance === null || instance === undefined ? instance : instance[this.name];
},
writable: true,
configurable: true
},
assign: {
value: function assign(scope, value) {
var instance = this.object.evaluate(scope);
if (instance === null || instance === undefined) {
instance = {};
this.object.assign(scope, instance);
}
return instance[this.name] = value;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitAccessMember(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var info = this.object.connect(binding, scope),
objectInstance = info.value,
objectObserver = info.observer,
observer;
if (objectObserver) {
observer = new PathObserver(objectObserver, function(value) {
if (value == null || value == undefined) {
return value;
}
return binding.getObserver(value, _this.name);
}, objectInstance);
} else {
observer = binding.getObserver(objectInstance, this.name);
}
return {
value: objectInstance == null ? null : objectInstance[this.name],
observer: observer
};
},
writable: true,
configurable: true
}
});
return AccessMember;
})(Expression));
AccessKeyed = _export("AccessKeyed", (function(Expression) {
function AccessKeyed(object, key) {
_get(Object.getPrototypeOf(AccessKeyed.prototype), "constructor", this).call(this);
this.object = object;
this.key = key;
this.isAssignable = true;
}
_inherits(AccessKeyed, Expression);
_prototypeProperties(AccessKeyed, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var instance = this.object.evaluate(scope, valueConverters);
var lookup = this.key.evaluate(scope, valueConverters);
return getKeyed(instance, lookup);
},
writable: true,
configurable: true
},
assign: {
value: function assign(scope, value) {
var instance = this.object.evaluate(scope);
var lookup = this.key.evaluate(scope);
return setKeyed(instance, lookup, value);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitAccessKeyed(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var objectInfo = this.object.connect(binding, scope),
keyInfo = this.key.connect(binding, scope),
childObservers = [],
observer;
if (objectInfo.observer) {
childObservers.push(objectInfo.observer);
}
if (keyInfo.observer) {
childObservers.push(keyInfo.observer);
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return AccessKeyed;
})(Expression));
CallScope = _export("CallScope", (function(Expression) {
function CallScope(name, args) {
_get(Object.getPrototypeOf(CallScope.prototype), "constructor", this).call(this);
this.name = name;
this.args = args;
}
_inherits(CallScope, Expression);
_prototypeProperties(CallScope, null, {
evaluate: {
value: function evaluate(scope, valueConverters, args) {
args = args || evalList(scope, this.args, valueConverters);
return ensureFunctionFromMap(scope, this.name).apply(scope, args);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitCallScope(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
childObservers = [],
i,
ii,
exp,
expInfo;
for (i = 0, ii = this.args.length; i < ii; ++i) {
exp = this.args[i];
expInfo = exp.connect(binding, scope);
if (expInfo.observer) {
childObservers.push(expInfo.observer);
}
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return CallScope;
})(Expression));
CallMember = _export("CallMember", (function(Expression) {
function CallMember(object, name, args) {
_get(Object.getPrototypeOf(CallMember.prototype), "constructor", this).call(this);
this.object = object;
this.name = name;
this.args = args;
}
_inherits(CallMember, Expression);
_prototypeProperties(CallMember, null, {
evaluate: {
value: function evaluate(scope, valueConverters, args) {
var instance = this.object.evaluate(scope, valueConverters);
args = args || evalList(scope, this.args, valueConverters);
return ensureFunctionFromMap(instance, this.name).apply(instance, args);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitCallMember(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
objectInfo = this.object.connect(binding, scope),
childObservers = [],
i,
ii,
exp,
expInfo;
if (objectInfo.observer) {
childObservers.push(objectInfo.observer);
}
for (i = 0, ii = this.args.length; i < ii; ++i) {
exp = this.args[i];
expInfo = exp.connect(binding, scope);
if (expInfo.observer) {
childObservers.push(expInfo.observer);
}
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return CallMember;
})(Expression));
CallFunction = _export("CallFunction", (function(Expression) {
function CallFunction(func, args) {
_get(Object.getPrototypeOf(CallFunction.prototype), "constructor", this).call(this);
this.func = func;
this.args = args;
}
_inherits(CallFunction, Expression);
_prototypeProperties(CallFunction, null, {
evaluate: {
value: function evaluate(scope, valueConverters, args) {
var func = this.func.evaluate(scope, valueConverters);
if (typeof func !== "function") {
throw new Error("" + this.func + " is not a function");
} else {
return func.apply(null, args || evalList(scope, this.args, valueConverters));
}
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitCallFunction(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
funcInfo = this.func.connect(binding, scope),
childObservers = [],
i,
ii,
exp,
expInfo;
if (funcInfo.observer) {
childObservers.push(funcInfo.observer);
}
for (i = 0, ii = this.args.length; i < ii; ++i) {
exp = this.args[i];
expInfo = exp.connect(binding, scope);
if (expInfo.observer) {
childObservers.push(expInfo.observer);
}
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return CallFunction;
})(Expression));
Binary = _export("Binary", (function(Expression) {
function Binary(operation, left, right) {
_get(Object.getPrototypeOf(Binary.prototype), "constructor", this).call(this);
this.operation = operation;
this.left = left;
this.right = right;
}
_inherits(Binary, Expression);
_prototypeProperties(Binary, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var left = this.left.evaluate(scope);
switch (this.operation) {
case "&&":
return !!left && !!this.right.evaluate(scope);
case "||":
return !!left || !!this.right.evaluate(scope);
}
var right = this.right.evaluate(scope);
switch (this.operation) {
case "==":
return left == right;
case "===":
return left === right;
case "!=":
return left != right;
case "!==":
return left !== right;
}
if (left === null || right === null) {
switch (this.operation) {
case "+":
if (left != null)
return left;
if (right != null)
return right;
return 0;
case "-":
if (left != null)
return left;
if (right != null)
return 0 - right;
return 0;
}
return null;
}
switch (this.operation) {
case "+":
return autoConvertAdd(left, right);
case "-":
return left - right;
case "*":
return left * right;
case "/":
return left / right;
case "%":
return left % right;
case "<":
return left < right;
case ">":
return left > right;
case "<=":
return left <= right;
case ">=":
return left >= right;
case "^":
return left ^ right;
case "&":
return left & right;
}
throw new Error("Internal error [" + this.operation + "] not handled");
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitBinary(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var leftInfo = this.left.connect(binding, scope),
rightInfo = this.right.connect(binding, scope),
childObservers = [],
observer;
if (leftInfo.observer) {
childObservers.push(leftInfo.observer);
}
if (rightInfo.observer) {
childObservers.push(rightInfo.observer);
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: this.evaluate(scope, binding.valueConverterLookupFunction),
observer: observer
};
},
writable: true,
configurable: true
}
});
return Binary;
})(Expression));
PrefixNot = _export("PrefixNot", (function(Expression) {
function PrefixNot(operation, expression) {
_get(Object.getPrototypeOf(PrefixNot.prototype), "constructor", this).call(this);
this.operation = operation;
this.expression = expression;
}
_inherits(PrefixNot, Expression);
_prototypeProperties(PrefixNot, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return !this.expression.evaluate(scope);
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitPrefix(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var info = this.expression.connect(binding, scope),
observer;
if (info.observer) {
observer = new CompositeObserver([info.observer], function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: !info.value,
observer: observer
};
},
writable: true,
configurable: true
}
});
return PrefixNot;
})(Expression));
LiteralPrimitive = _export("LiteralPrimitive", (function(Expression) {
function LiteralPrimitive(value) {
_get(Object.getPrototypeOf(LiteralPrimitive.prototype), "constructor", this).call(this);
this.value = value;
}
_inherits(LiteralPrimitive, Expression);
_prototypeProperties(LiteralPrimitive, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return this.value;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitLiteralPrimitive(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
return {value: this.value};
},
writable: true,
configurable: true
}
});
return LiteralPrimitive;
})(Expression));
LiteralString = _export("LiteralString", (function(Expression) {
function LiteralString(value) {
_get(Object.getPrototypeOf(LiteralString.prototype), "constructor", this).call(this);
this.value = value;
}
_inherits(LiteralString, Expression);
_prototypeProperties(LiteralString, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
return this.value;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitLiteralString(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
return {value: this.value};
},
writable: true,
configurable: true
}
});
return LiteralString;
})(Expression));
LiteralArray = _export("LiteralArray", (function(Expression) {
function LiteralArray(elements) {
_get(Object.getPrototypeOf(LiteralArray.prototype), "constructor", this).call(this);
this.elements = elements;
}
_inherits(LiteralArray, Expression);
_prototypeProperties(LiteralArray, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var elements = this.elements,
length = elements.length,
result = [],
i;
for (i = 0; i < length; ++i) {
result[i] = elements[i].evaluate(scope, valueConverters);
}
return result;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitLiteralArray(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
childObservers = [],
results = [],
i,
ii,
exp,
expInfo;
for (i = 0, ii = this.elements.length; i < ii; ++i) {
exp = this.elements[i];
expInfo = exp.connect(binding, scope);
if (expInfo.observer) {
childObservers.push(expInfo.observer);
}
results[i] = expInfo.value;
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: results,
observer: observer
};
},
writable: true,
configurable: true
}
});
return LiteralArray;
})(Expression));
LiteralObject = _export("LiteralObject", (function(Expression) {
function LiteralObject(keys, values) {
_get(Object.getPrototypeOf(LiteralObject.prototype), "constructor", this).call(this);
this.keys = keys;
this.values = values;
}
_inherits(LiteralObject, Expression);
_prototypeProperties(LiteralObject, null, {
evaluate: {
value: function evaluate(scope, valueConverters) {
var instance = {},
keys = this.keys,
values = this.values,
length = keys.length,
i;
for (i = 0; i < length; ++i) {
instance[keys[i]] = values[i].evaluate(scope, valueConverters);
}
return instance;
},
writable: true,
configurable: true
},
accept: {
value: function accept(visitor) {
visitor.visitLiteralObject(this);
},
writable: true,
configurable: true
},
connect: {
value: function connect(binding, scope) {
var _this = this;
var observer,
childObservers = [],
instance = {},
keys = this.keys,
values = this.values,
length = keys.length,
i,
valueInfo;
for (i = 0; i < length; ++i) {
valueInfo = values[i].connect(binding, scope);
if (valueInfo.observer) {
childObservers.push(valueInfo.observer);
}
instance[keys[i]] = valueInfo.value;
}
if (childObservers.length) {
observer = new CompositeObserver(childObservers, function() {
return _this.evaluate(scope, binding.valueConverterLookupFunction);
});
}
return {
value: instance,
observer: observer
};
},
writable: true,
configurable: true
}
});
return LiteralObject;
})(Expression));
Unparser = _export("Unparser", (function() {
function Unparser(buffer) {
this.buffer = buffer;
}
_prototypeProperties(Unparser, {unparse: {
value: function unparse(expression) {
var buffer = [],
visitor = new Unparser(buffer);
expression.accept(visitor);
return buffer.join("");
},
writable: true,
configurable: true
}}, {
write: {
value: function write(text) {
this.buffer.push(text);
},
writable: true,
configurable: true
},
writeArgs: {
value: function writeArgs(args) {
var i,
length;
this.write("(");
for (i = 0, length = args.length; i < length; ++i) {
if (i !== 0) {
this.write(",");
}
args[i].accept(this);
}
this.write(")");
},
writable: true,
configurable: true
},
visitChain: {
value: function visitChain(chain) {
var expressions = chain.expressions,
length = expressions.length,
i;
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(";");
}
expressions[i].accept(this);
}
},
writable: true,
configurable: true
},
visitValueConverter: {
value: function visitValueConverter(converter) {
var args = converter.args,
length = args.length,
i;
this.write("(");
converter.expression.accept(this);
this.write("|" + converter.name);
for (i = 0; i < length; ++i) {
this.write(" :");
args[i].accept(this);
}
this.write(")");
},
writable: true,
configurable: true
},
visitAssign: {
value: function visitAssign(assign) {
assign.target.accept(this);
this.write("=");
assign.value.accept(this);
},
writable: true,
configurable: true
},
visitConditional: {
value: function visitConditional(conditional) {
conditional.condition.accept(this);
this.write("?");
conditional.yes.accept(this);
this.write(":");
conditional.no.accept(this);
},
writable: true,
configurable: true
},
visitAccessScope: {
value: function visitAccessScope(access) {
this.write(access.name);
},
writable: true,
configurable: true
},
visitAccessMember: {
value: function visitAccessMember(access) {
access.object.accept(this);
this.write("." + access.name);
},
writable: true,
configurable: true
},
visitAccessKeyed: {
value: function visitAccessKeyed(access) {
access.object.accept(this);
this.write("[");
access.key.accept(this);
this.write("]");
},
writable: true,
configurable: true
},
visitCallScope: {
value: function visitCallScope(call) {
this.write(call.name);
this.writeArgs(call.args);
},
writable: true,
configurable: true
},
visitCallFunction: {
value: function visitCallFunction(call) {
call.func.accept(this);
this.writeArgs(call.args);
},
writable: true,
configurable: true
},
visitCallMember: {
value: function visitCallMember(call) {
call.object.accept(this);
this.write("." + call.name);
this.writeArgs(call.args);
},
writable: true,
configurable: true
},
visitPrefix: {
value: function visitPrefix(prefix) {
this.write("(" + prefix.operation);
prefix.expression.accept(this);
this.write(")");
},
writable: true,
configurable: true
},
visitBinary: {
value: function visitBinary(binary) {
this.write("(");
binary.left.accept(this);
this.write(binary.operation);
binary.right.accept(this);
this.write(")");
},
writable: true,
configurable: true
},
visitLiteralPrimitive: {
value: function visitLiteralPrimitive(literal) {
this.write("" + literal.value);
},
writable: true,
configurable: true
},
visitLiteralArray: {
value: function visitLiteralArray(literal) {
var elements = literal.elements,
length = elements.length,
i;
this.write("[");
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(",");
}
elements[i].accept(this);
}
this.write("]");
},
writable: true,
configurable: true
},
visitLiteralObject: {
value: function visitLiteralObject(literal) {
var keys = literal.keys,
values = literal.values,
length = keys.length,
i;
this.write("{");
for (i = 0; i < length; ++i) {
if (i !== 0) {
this.write(",");
}
this.write("'" + keys[i] + "':");
values[i].accept(this);
}
this.write("}");
},
writable: true,
configurable: true
},
visitLiteralString: {
value: function visitLiteralString(literal) {
var escaped = literal.value.replace(/'/g, "'");
this.write("'" + escaped + "'");
},
writable: true,
configurable: true
}
});
return Unparser;
})());
evalListCache = [[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]];
}
};
});
System.register("github:aurelia/templating@0.8.8/system/behaviors", ["aurelia-metadata", "aurelia-task-queue", "aurelia-binding", "./children", "./property", "./util"], function(_export) {
"use strict";
var Metadata,
TaskQueue,
ObserverLocator,
ChildObserver,
BehaviorProperty,
hyphenate;
_export("configureBehavior", configureBehavior);
function configureBehavior(container, behavior, target, valuePropertyName) {
var proto = target.prototype,
taskQueue = container.get(TaskQueue),
meta = Metadata.on(target),
observerLocator = container.get(ObserverLocator),
i,
ii,
properties;
if (!behavior.name) {
behavior.name = hyphenate(target.name);
}
behavior.target = target;
behavior.observerLocator = observerLocator;
behavior.handlesCreated = "created" in proto;
behavior.handlesBind = "bind" in proto;
behavior.handlesUnbind = "unbind" in proto;
behavior.handlesAttached = "attached" in proto;
behavior.handlesDetached = "detached" in proto;
properties = meta.all(BehaviorProperty);
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i].define(taskQueue, behavior);
}
properties = behavior.properties;
if (properties.length === 0 && "valueChanged" in target.prototype) {
new BehaviorProperty("value", "valueChanged", valuePropertyName || behavior.name).define(taskQueue, behavior);
}
if (properties.length !== 0) {
target.initialize = function(executionContext) {
var observerLookup = observerLocator.getObserversLookup(executionContext),
i,
ii,
observer;
for (i = 0, ii = properties.length; i < ii; ++i) {
observer = properties[i].createObserver(executionContext);
if (observer !== undefined) {
observerLookup[observer.propertyName] = observer;
}
}
};
}
behavior.childExpression = meta.first(ChildObserver);
}
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}, function(_aureliaTaskQueue) {
TaskQueue = _aureliaTaskQueue.TaskQueue;
}, function(_aureliaBinding) {
ObserverLocator = _aureliaBinding.ObserverLocator;
}, function(_children) {
ChildObserver = _children.ChildObserver;
}, function(_property) {
BehaviorProperty = _property.BehaviorProperty;
}, function(_util) {
hyphenate = _util.hyphenate;
}],
execute: function() {}
};
});
System.register("github:aurelia/templating@0.8.8/system/view-factory", ["aurelia-dependency-injection", "./view", "./view-slot", "./content-selector", "./resource-registry"], function(_export) {
"use strict";
var Container,
View,
ViewSlot,
ContentSelector,
ViewResources,
_prototypeProperties,
BoundViewFactory,
defaultFactoryOptions,
ViewFactory;
function elementContainerGet(key) {
if (key === Element) {
return this.element;
}
if (key === BoundViewFactory) {
return this.boundViewFactory || (this.boundViewFactory = new BoundViewFactory(this, this.instruction.viewFactory, this.executionContext));
}
if (key === ViewSlot) {
if (this.viewSlot === undefined) {
this.viewSlot = new ViewSlot(this.element, this.instruction.anchorIsContainer, this.executionContext);
this.children.push(this.viewSlot);
}
return this.viewSlot;
}
if (key === ViewResources) {
return this.viewResources;
}
return this.superGet(key);
}
function createElementContainer(parent, element, instruction, executionContext, children, resources) {
var container = parent.createChild(),
providers,
i;
container.element = element;
container.instruction = instruction;
container.executionContext = executionContext;
container.children = children;
container.viewResources = resources;
providers = instruction.providers;
i = providers.length;
while (i--) {
container.registerSingleton(providers[i]);
}
container.superGet = container.get;
container.get = elementContainerGet;
return container;
}
function applyInstructions(containers, executionContext, element, instruction, behaviors, bindings, children, contentSelectors, resources) {
var behaviorInstructions = instruction.behaviorInstructions,
expressions = instruction.expressions,
elementContainer,
i,
ii,
current,
instance;
if (instruction.contentExpression) {
bindings.push(instruction.contentExpression.createBinding(element.nextSibling));
element.parentNode.removeChild(element);
return;
}
if (instruction.contentSelector) {
contentSelectors.push(new ContentSelector(element, instruction.selector));
return;
}
if (behaviorInstructions.length) {
containers[instruction.injectorId] = elementContainer = createElementContainer(containers[instruction.parentInjectorId], element, instruction, executionContext, children, resources);
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
current = behaviorInstructions[i];
instance = current.type.create(elementContainer, current, element, bindings);
if (instance.contentView) {
children.push(instance.contentView);
}
behaviors.push(instance);
}
}
for (i = 0, ii = expressions.length; i < ii; ++i) {
bindings.push(expressions[i].createBinding(element));
}
}
return {
setters: [function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_view) {
View = _view.View;
}, function(_viewSlot) {
ViewSlot = _viewSlot.ViewSlot;
}, function(_contentSelector) {
ContentSelector = _contentSelector.ContentSelector;
}, function(_resourceRegistry) {
ViewResources = _resourceRegistry.ViewResources;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BoundViewFactory = _export("BoundViewFactory", (function() {
function BoundViewFactory(parentContainer, viewFactory, executionContext) {
this.parentContainer = parentContainer;
this.viewFactory = viewFactory;
this.executionContext = executionContext;
this.factoryOptions = {behaviorInstance: false};
}
_prototypeProperties(BoundViewFactory, null, {create: {
value: function create(executionContext) {
var childContainer = this.parentContainer.createChild(),
context = executionContext || this.executionContext;
this.factoryOptions.systemControlled = !executionContext;
return this.viewFactory.create(childContainer, context, this.factoryOptions);
},
writable: true,
configurable: true
}});
return BoundViewFactory;
})());
defaultFactoryOptions = {
systemControlled: false,
suppressBind: false
};
ViewFactory = _export("ViewFactory", (function() {
function ViewFactory(template, instructions, resources) {
this.template = template;
this.instructions = instructions;
this.resources = resources;
}
_prototypeProperties(ViewFactory, null, {create: {
value: function create(container, executionContext) {
var options = arguments[2] === undefined ? defaultFactoryOptions : arguments[2];
var fragment = this.template.cloneNode(true),
instructables = fragment.querySelectorAll(".au-target"),
instructions = this.instructions,
resources = this.resources,
behaviors = [],
bindings = [],
children = [],
contentSelectors = [],
containers = {root: container},
i,
ii,
view;
for (i = 0, ii = instructables.length; i < ii; ++i) {
applyInstructions(containers, executionContext, instructables[i], instructions[i], behaviors, bindings, children, contentSelectors, resources);
}
view = new View(fragment, behaviors, bindings, children, options.systemControlled, contentSelectors);
view.created(executionContext);
if (!options.suppressBind) {
view.bind(executionContext);
}
return view;
},
writable: true,
configurable: true
}});
return ViewFactory;
})());
}
};
});
System.register("github:aurelia/logging-console@0.2.2", ["github:aurelia/logging-console@0.2.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/templating-binding@0.8.4/system/binding-language", ["aurelia-templating", "aurelia-binding", "./syntax-interpreter"], function(_export) {
"use strict";
var BindingLanguage,
Parser,
ObserverLocator,
BindingExpression,
NameExpression,
ONE_WAY,
SyntaxInterpreter,
_prototypeProperties,
_inherits,
info,
TemplatingBindingLanguage,
InterpolationBindingExpression,
InterpolationBinding;
return {
setters: [function(_aureliaTemplating) {
BindingLanguage = _aureliaTemplating.BindingLanguage;
}, function(_aureliaBinding) {
Parser = _aureliaBinding.Parser;
ObserverLocator = _aureliaBinding.ObserverLocator;
BindingExpression = _aureliaBinding.BindingExpression;
NameExpression = _aureliaBinding.NameExpression;
ONE_WAY = _aureliaBinding.ONE_WAY;
}, function(_syntaxInterpreter) {
SyntaxInterpreter = _syntaxInterpreter.SyntaxInterpreter;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
info = {};
TemplatingBindingLanguage = (function(BindingLanguage) {
function TemplatingBindingLanguage(parser, observerLocator, syntaxInterpreter) {
this.parser = parser;
this.observerLocator = observerLocator;
this.syntaxInterpreter = syntaxInterpreter;
this.interpolationRegex = /\${(.*?)}/g;
syntaxInterpreter.language = this;
this.attributeMap = syntaxInterpreter.attributeMap = {
"class": "className",
"for": "htmlFor"
};
}
_inherits(TemplatingBindingLanguage, BindingLanguage);
_prototypeProperties(TemplatingBindingLanguage, {inject: {
value: function inject() {
return [Parser, ObserverLocator, SyntaxInterpreter];
},
writable: true,
enumerable: true,
configurable: true
}}, {
inspectAttribute: {
value: function inspectAttribute(resources, attrName, attrValue) {
var parts = attrName.split(".");
info.defaultBindingMode = null;
if (parts.length == 2) {
info.attrName = parts[0].trim();
info.attrValue = attrValue;
info.command = parts[1].trim();
info.expression = null;
} else if (attrName == "ref") {
info.attrName = attrName;
info.attrValue = attrValue;
info.command = null;
info.expression = new NameExpression(attrValue, "element");
} else {
info.attrName = attrName;
info.attrValue = attrValue;
info.command = null;
info.expression = this.parseContent(resources, attrName, attrValue);
}
return info;
},
writable: true,
enumerable: true,
configurable: true
},
createAttributeInstruction: {
value: function createAttributeInstruction(resources, element, info, existingInstruction) {
var instruction;
if (info.expression) {
if (info.attrName === "ref") {
return info.expression;
}
instruction = existingInstruction || {
attrName: info.attrName,
attributes: {}
};
instruction.attributes[info.attrName] = info.expression;
} else if (info.command) {
instruction = this.syntaxInterpreter.interpret(resources, element, info, existingInstruction);
}
return instruction;
},
writable: true,
enumerable: true,
configurable: true
},
parseText: {
value: function parseText(resources, value) {
return this.parseContent(resources, "textContent", value);
},
writable: true,
enumerable: true,
configurable: true
},
parseContent: {
value: function parseContent(resources, attrName, attrValue) {
var parts = attrValue.split(this.interpolationRegex),
i,
ii;
if (parts.length <= 1) {
return null;
}
for (i = 0, ii = parts.length; i < ii; ++i) {
if (i % 2 === 0) {} else {
parts[i] = this.parser.parse(parts[i]);
}
}
return new InterpolationBindingExpression(this.observerLocator, this.attributeMap[attrName] || attrName, parts, ONE_WAY, resources.valueConverterLookupFunction, attrName);
},
writable: true,
enumerable: true,
configurable: true
}
});
return TemplatingBindingLanguage;
})(BindingLanguage);
_export("TemplatingBindingLanguage", TemplatingBindingLanguage);
InterpolationBindingExpression = (function() {
function InterpolationBindingExpression(observerLocator, targetProperty, parts, mode, valueConverterLookupFunction, attribute) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.parts = parts;
this.mode = mode;
this.valueConverterLookupFunction = valueConverterLookupFunction;
this.attribute = attribute;
this.discrete = false;
}
_prototypeProperties(InterpolationBindingExpression, null, {createBinding: {
value: function createBinding(target) {
return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.valueConverterLookupFunction);
},
writable: true,
enumerable: true,
configurable: true
}});
return InterpolationBindingExpression;
})();
_export("InterpolationBindingExpression", InterpolationBindingExpression);
InterpolationBinding = (function() {
function InterpolationBinding(observerLocator, parts, target, targetProperty, mode, valueConverterLookupFunction) {
this.observerLocator = observerLocator;
this.parts = parts;
this.targetProperty = observerLocator.getObserver(target, targetProperty);
this.mode = mode;
this.valueConverterLookupFunction = valueConverterLookupFunction;
this.toDispose = [];
}
_prototypeProperties(InterpolationBinding, null, {
getObserver: {
value: function getObserver(obj, propertyName) {
return this.observerLocator.getObserver(obj, propertyName);
},
writable: true,
enumerable: true,
configurable: true
},
bind: {
value: function bind(source) {
this.source = source;
if (this.mode == ONE_WAY) {
this.unbind();
this.connect();
this.setValue();
} else {
this.setValue();
}
},
writable: true,
enumerable: true,
configurable: true
},
setValue: {
value: function setValue() {
var value = this.interpolate();
this.targetProperty.setValue(value);
},
writable: true,
enumerable: true,
configurable: true
},
connect: {
value: function connect() {
var _this = this;
var info,
parts = this.parts,
source = this.source,
toDispose = this.toDispose = [],
i,
ii;
for (i = 0, ii = parts.length; i < ii; ++i) {
if (i % 2 === 0) {} else {
info = parts[i].connect(this, source);
if (info.observer) {
toDispose.push(info.observer.subscribe(function(newValue) {
_this.setValue();
}));
}
}
}
},
writable: true,
enumerable: true,
configurable: true
},
interpolate: {
value: function interpolate() {
var value = "",
parts = this.parts,
source = this.source,
valueConverterLookupFunction = this.valueConverterLookupFunction,
i,
ii,
temp;
for (i = 0, ii = parts.length; i < ii; ++i) {
if (i % 2 === 0) {
value += parts[i];
} else {
temp = parts[i].evaluate(source, valueConverterLookupFunction);
value += typeof temp !== "undefined" && temp !== null ? temp.toString() : "";
}
}
return value;
},
writable: true,
enumerable: true,
configurable: true
},
unbind: {
value: function unbind() {
var i,
ii,
toDispose = this.toDispose;
if (toDispose) {
for (i = 0, ii = toDispose.length; i < ii; ++i) {
toDispose[i]();
}
}
this.toDispose = null;
},
writable: true,
enumerable: true,
configurable: true
}
});
return InterpolationBinding;
})();
}
};
});
System.register("github:aurelia/route-recognizer@0.2.2/system/index", ["./dsl"], function(_export) {
"use strict";
var map,
specials,
escapeRegex,
oCreate,
RouteRecognizer;
function isArray(test) {
return Object.prototype.toString.call(test) === "[object Array]";
}
function StaticSegment(string) {
this.string = string;
}
function DynamicSegment(name) {
this.name = name;
}
function StarSegment(name) {
this.name = name;
}
function EpsilonSegment() {}
function parse(route, names, types) {
if (route.charAt(0) === "/") {
route = route.substr(1);
}
var segments = route.split("/"),
results = [];
for (var i = 0,
l = segments.length; i < l; i++) {
var segment = segments[i],
match;
if (match = segment.match(/^:([^\/]+)$/)) {
results.push(new DynamicSegment(match[1]));
names.push(match[1]);
types.dynamics++;
} else if (match = segment.match(/^\*([^\/]+)$/)) {
results.push(new StarSegment(match[1]));
names.push(match[1]);
types.stars++;
} else if (segment === "") {
results.push(new EpsilonSegment());
} else {
results.push(new StaticSegment(segment));
types.statics++;
}
}
return results;
}
function State(charSpec) {
this.charSpec = charSpec;
this.nextStates = [];
}
function sortSolutions(states) {
return states.sort(function(a, b) {
if (a.types.stars !== b.types.stars) {
return a.types.stars - b.types.stars;
}
if (a.types.stars) {
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
if (a.types.dynamics !== b.types.dynamics) {
return b.types.dynamics - a.types.dynamics;
}
}
if (a.types.dynamics !== b.types.dynamics) {
return a.types.dynamics - b.types.dynamics;
}
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0,
l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
function RecognizeResults(queryParams) {
this.queryParams = queryParams || {};
}
function findHandler(state, path, queryParams) {
var handlers = state.handlers,
regex = state.regex;
var captures = path.match(regex),
currentCapture = 1;
var result = new RecognizeResults(queryParams);
for (var i = 0,
l = handlers.length; i < l; i++) {
var handler = handlers[i],
names = handler.names,
params = {};
for (var j = 0,
m = names.length; j < m; j++) {
params[names[j]] = captures[currentCapture++];
}
result.push({
handler: handler.handler,
params: params,
isDynamic: !!names.length
});
}
return result;
}
function addSegment(currentState, segment) {
segment.eachChar(function(ch) {
var state;
currentState = currentState.put(ch);
});
return currentState;
}
return {
setters: [function(_dsl) {
map = _dsl.map;
}],
execute: function() {
specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\"];
escapeRegex = new RegExp("(\\" + specials.join("|\\") + ")", "g");
StaticSegment.prototype = {
eachChar: function(callback) {
var string = this.string,
ch;
for (var i = 0,
l = string.length; i < l; i++) {
ch = string.charAt(i);
callback({validChars: ch});
}
},
regex: function() {
return this.string.replace(escapeRegex, "\\$1");
},
generate: function() {
return this.string;
}
};
DynamicSegment.prototype = {
eachChar: function(callback) {
callback({
invalidChars: "/",
repeat: true
});
},
regex: function() {
return "([^/]+)";
},
generate: function(params) {
return params[this.name];
}
};
StarSegment.prototype = {
eachChar: function(callback) {
callback({
invalidChars: "",
repeat: true
});
},
regex: function() {
return "(.+)";
},
generate: function(params) {
return params[this.name];
}
};
EpsilonSegment.prototype = {
eachChar: function() {},
regex: function() {
return "";
},
generate: function() {
return "";
}
};
State.prototype = {
get: function(charSpec) {
var nextStates = this.nextStates;
for (var i = 0,
l = nextStates.length; i < l; i++) {
var child = nextStates[i];
var isEqual = child.charSpec.validChars === charSpec.validChars;
isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars;
if (isEqual) {
return child;
}
}
},
put: function(charSpec) {
var state;
if (state = this.get(charSpec)) {
return state;
}
state = new State(charSpec);
this.nextStates.push(state);
if (charSpec.repeat) {
state.nextStates.push(state);
}
return state;
},
match: function(ch) {
var nextStates = this.nextStates,
child,
charSpec,
chars;
var returned = [];
for (var i = 0,
l = nextStates.length; i < l; i++) {
child = nextStates[i];
charSpec = child.charSpec;
if (typeof(chars = charSpec.validChars) !== "undefined") {
if (chars.indexOf(ch) !== -1) {
returned.push(child);
}
} else if (typeof(chars = charSpec.invalidChars) !== "undefined") {
if (chars.indexOf(ch) === -1) {
returned.push(child);
}
}
}
return returned;
}
};
oCreate = Object.create || function(proto) {
var F = function() {};
F.prototype = proto;
return new F();
};
RecognizeResults.prototype = oCreate({
splice: Array.prototype.splice,
slice: Array.prototype.slice,
push: Array.prototype.push,
length: 0,
queryParams: null
});
RouteRecognizer = _export("RouteRecognizer", function() {
this.rootState = new State();
this.names = {};
});
RouteRecognizer.prototype = {
add: function(routes, options) {
var currentState = this.rootState,
regex = "^",
types = {
statics: 0,
dynamics: 0,
stars: 0
},
handlers = [],
allSegments = [],
name;
var isEmpty = true;
for (var i = 0,
l = routes.length; i < l; i++) {
var route = routes[i],
names = [];
var segments = parse(route.path, names, types);
allSegments = allSegments.concat(segments);
for (var j = 0,
m = segments.length; j < m; j++) {
var segment = segments[j];
if (segment instanceof EpsilonSegment) {
continue;
}
isEmpty = false;
currentState = currentState.put({validChars: "/"});
regex += "/";
currentState = addSegment(currentState, segment);
regex += segment.regex();
}
var handler = {
handler: route.handler,
names: names
};
handlers.push(handler);
}
if (isEmpty) {
currentState = currentState.put({validChars: "/"});
regex += "/";
}
currentState.handlers = handlers;
currentState.regex = new RegExp(regex + "$");
currentState.types = types;
if (name = options && options.as) {
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
},
handlersFor: function(name) {
var route = this.names[name],
result = [];
if (!route) {
throw new Error("There is no route named " + name);
}
for (var i = 0,
l = route.handlers.length; i < l; i++) {
result.push(route.handlers[i]);
}
return result;
},
hasRoute: function(name) {
return !!this.names[name];
},
generate: function(name, params) {
var route = this.names[name],
output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0,
l = segments.length; i < l; i++) {
var segment = segments[i];
if (segment instanceof EpsilonSegment) {
continue;
}
output += "/";
output += segment.generate(params);
}
if (output.charAt(0) !== "/") {
output = "/" + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams, route.handlers);
}
return output;
},
generateQueryString: function(params, handlers) {
var pairs = [];
var keys = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.sort();
for (var i = 0,
len = keys.length; i < len; i++) {
key = keys[i];
var value = params[key];
if (value === null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0,
l = value.length; j < l; j++) {
var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return "";
}
return "?" + pairs.join("&");
},
parseQueryString: function(queryString) {
var pairs = queryString.split("&"),
queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("="),
key = decodeURIComponent(pair[0]),
keyLength = key.length,
isArray = false,
value;
if (pair.length === 1) {
value = "true";
} else {
if (keyLength > 2 && key.slice(keyLength - 2) === "[]") {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeURIComponent(pair[1]) : "";
}
if (isArray) {
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}
return queryParams;
},
recognize: function(path) {
var states = [this.rootState],
pathLen,
i,
l,
queryStart,
queryParams = {},
isSlashDropped = false;
queryStart = path.indexOf("?");
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
path = decodeURI(path);
if (path.charAt(0) !== "/") {
path = "/" + path;
}
pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
isSlashDropped = true;
}
for (i = 0, l = path.length; i < l; i++) {
states = recognizeChar(states, path.charAt(i));
if (!states.length) {
break;
}
}
var solutions = [];
for (i = 0, l = states.length; i < l; i++) {
if (states[i].handlers) {
solutions.push(states[i]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") {
path = path + "/";
}
return findHandler(state, path, queryParams);
}
}
};
RouteRecognizer.prototype.map = map;
}
};
});
System.register("github:aurelia/router@0.5.4/system/navigation-context", ["./navigation-plan"], function(_export) {
"use strict";
var REPLACE,
_prototypeProperties,
NavigationContext,
CommitChangesStep;
return {
setters: [function(_navigationPlan) {
REPLACE = _navigationPlan.REPLACE;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
NavigationContext = _export("NavigationContext", (function() {
function NavigationContext(router, nextInstruction) {
this.router = router;
this.nextInstruction = nextInstruction;
this.currentInstruction = router.currentInstruction;
this.prevInstruction = router.currentInstruction;
}
_prototypeProperties(NavigationContext, null, {
commitChanges: {
value: function commitChanges(waitToSwap) {
var next = this.nextInstruction,
prev = this.prevInstruction,
viewPortInstructions = next.viewPortInstructions,
router = this.router,
loads = [],
delaySwaps = [];
router.currentInstruction = next;
if (prev) {
prev.config.navModel.isActive = false;
}
next.config.navModel.isActive = true;
router.refreshBaseUrl();
router.refreshNavigation();
for (var viewPortName in viewPortInstructions) {
var viewPortInstruction = viewPortInstructions[viewPortName];
var viewPort = router.viewPorts[viewPortName];
if (!viewPort) {
throw new Error("There was no router-view found in the view for " + viewPortInstruction.moduleId + ".");
}
if (viewPortInstruction.strategy === REPLACE) {
if (waitToSwap) {
delaySwaps.push({
viewPort: viewPort,
viewPortInstruction: viewPortInstruction
});
}
loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function(x) {
if ("childNavigationContext" in viewPortInstruction) {
return viewPortInstruction.childNavigationContext.commitChanges();
}
}));
} else {
if ("childNavigationContext" in viewPortInstruction) {
loads.push(viewPortInstruction.childNavigationContext.commitChanges(waitToSwap));
}
}
}
return Promise.all(loads).then(function() {
delaySwaps.forEach(function(x) {
return x.viewPort.swap(x.viewPortInstruction);
});
});
},
writable: true,
configurable: true
},
buildTitle: {
value: function buildTitle() {
var separator = arguments[0] === undefined ? " | " : arguments[0];
var next = this.nextInstruction,
title = next.config.navModel.title || "",
viewPortInstructions = next.viewPortInstructions,
childTitles = [];
for (var viewPortName in viewPortInstructions) {
var viewPortInstruction = viewPortInstructions[viewPortName];
if ("childNavigationContext" in viewPortInstruction) {
var childTitle = viewPortInstruction.childNavigationContext.buildTitle(separator);
if (childTitle) {
childTitles.push(childTitle);
}
}
}
if (childTitles.length) {
title = childTitles.join(separator) + (title ? separator : "") + title;
}
if (this.router.title) {
title += (title ? separator : "") + this.router.title;
}
return title;
},
writable: true,
configurable: true
}
});
return NavigationContext;
})());
CommitChangesStep = _export("CommitChangesStep", (function() {
function CommitChangesStep() {}
_prototypeProperties(CommitChangesStep, null, {run: {
value: function run(navigationContext, next) {
navigationContext.commitChanges(true);
var title = navigationContext.buildTitle();
if (title) {
document.title = title;
}
return next();
},
writable: true,
configurable: true
}});
return CommitChangesStep;
})());
}
};
});
System.register("github:aurelia/history@0.2.2", ["github:aurelia/history@0.2.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/router@0.5.4/system/activation", ["./navigation-plan", "./navigation-commands", "./util"], function(_export) {
"use strict";
var INVOKE_LIFECYCLE,
REPLACE,
isNavigationCommand,
processPotential,
_toArray,
_prototypeProperties,
affirmations,
CanDeactivatePreviousStep,
CanActivateNextStep,
DeactivatePreviousStep,
ActivateNextStep;
function processDeactivatable(plan, callbackName, next, ignoreResult) {
var infos = findDeactivatable(plan, callbackName),
i = infos.length;
function inspect(val) {
if (ignoreResult || shouldContinue(val)) {
return iterate();
} else {
return next.cancel(val);
}
}
function iterate() {
if (i--) {
try {
var controller = infos[i];
var result = controller[callbackName]();
return processPotential(result, inspect, next.cancel);
} catch (error) {
return next.cancel(error);
}
} else {
return next();
}
}
return iterate();
}
function findDeactivatable(plan, callbackName, list) {
list = list || [];
for (var viewPortName in plan) {
var viewPortPlan = plan[viewPortName];
var prevComponent = viewPortPlan.prevComponent;
if ((viewPortPlan.strategy == INVOKE_LIFECYCLE || viewPortPlan.strategy == REPLACE) && prevComponent) {
var controller = prevComponent.executionContext;
if (callbackName in controller) {
list.push(controller);
}
}
if (viewPortPlan.childNavigationContext) {
findDeactivatable(viewPortPlan.childNavigationContext.plan, callbackName, list);
} else if (prevComponent) {
addPreviousDeactivatable(prevComponent, callbackName, list);
}
}
return list;
}
function addPreviousDeactivatable(component, callbackName, list) {
var controller = component.executionContext;
if (controller.router && controller.router.currentInstruction) {
var viewPortInstructions = controller.router.currentInstruction.viewPortInstructions;
for (var viewPortName in viewPortInstructions) {
var viewPortInstruction = viewPortInstructions[viewPortName];
var prevComponent = viewPortInstruction.component;
var prevController = prevComponent.executionContext;
if (callbackName in prevController) {
list.push(prevController);
}
addPreviousDeactivatable(prevComponent, callbackName, list);
}
}
}
function processActivatable(navigationContext, callbackName, next, ignoreResult) {
var infos = findActivatable(navigationContext, callbackName),
length = infos.length,
i = -1;
function inspect(val, router) {
if (ignoreResult || shouldContinue(val, router)) {
return iterate();
} else {
return next.cancel(val);
}
}
function iterate() {
i++;
if (i < length) {
try {
var _current$controller;
var current = infos[i];
var result = (_current$controller = current.controller)[callbackName].apply(_current$controller, _toArray(current.lifecycleArgs));
return processPotential(result, function(val) {
return inspect(val, current.router);
}, next.cancel);
} catch (error) {
return next.cancel(error);
}
} else {
return next();
}
}
return iterate();
}
function findActivatable(navigationContext, callbackName, list, router) {
var plan = navigationContext.plan;
var next = navigationContext.nextInstruction;
list = list || [];
Object.keys(plan).filter(function(viewPortName) {
var viewPortPlan = plan[viewPortName];
var viewPortInstruction = next.viewPortInstructions[viewPortName];
var controller = viewPortInstruction.component.executionContext;
if ((viewPortPlan.strategy === INVOKE_LIFECYCLE || viewPortPlan.strategy === REPLACE) && callbackName in controller) {
list.push({
controller: controller,
lifecycleArgs: viewPortInstruction.lifecycleArgs,
router: router
});
}
if (viewPortPlan.childNavigationContext) {
findActivatable(viewPortPlan.childNavigationContext, callbackName, list, controller.router || router);
}
});
return list;
}
function shouldContinue(output, router) {
if (output instanceof Error) {
return false;
}
if (isNavigationCommand(output)) {
output.router = router;
return !!output.shouldContinueProcessing;
}
if (typeof output == "string") {
return affirmations.indexOf(value.toLowerCase()) !== -1;
}
if (typeof output == "undefined") {
return true;
}
return output;
}
return {
setters: [function(_navigationPlan) {
INVOKE_LIFECYCLE = _navigationPlan.INVOKE_LIFECYCLE;
REPLACE = _navigationPlan.REPLACE;
}, function(_navigationCommands) {
isNavigationCommand = _navigationCommands.isNavigationCommand;
}, function(_util) {
processPotential = _util.processPotential;
}],
execute: function() {
_toArray = function(arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
affirmations = _export("affirmations", ["yes", "ok", "true"]);
CanDeactivatePreviousStep = _export("CanDeactivatePreviousStep", (function() {
function CanDeactivatePreviousStep() {}
_prototypeProperties(CanDeactivatePreviousStep, null, {run: {
value: function run(navigationContext, next) {
return processDeactivatable(navigationContext.plan, "canDeactivate", next);
},
writable: true,
configurable: true
}});
return CanDeactivatePreviousStep;
})());
CanActivateNextStep = _export("CanActivateNextStep", (function() {
function CanActivateNextStep() {}
_prototypeProperties(CanActivateNextStep, null, {run: {
value: function run(navigationContext, next) {
return processActivatable(navigationContext, "canActivate", next);
},
writable: true,
configurable: true
}});
return CanActivateNextStep;
})());
DeactivatePreviousStep = _export("DeactivatePreviousStep", (function() {
function DeactivatePreviousStep() {}
_prototypeProperties(DeactivatePreviousStep, null, {run: {
value: function run(navigationContext, next) {
return processDeactivatable(navigationContext.plan, "deactivate", next, true);
},
writable: true,
configurable: true
}});
return DeactivatePreviousStep;
})());
ActivateNextStep = _export("ActivateNextStep", (function() {
function ActivateNextStep() {}
_prototypeProperties(ActivateNextStep, null, {run: {
value: function run(navigationContext, next) {
return processActivatable(navigationContext, "activate", next, true);
},
writable: true,
configurable: true
}});
return ActivateNextStep;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5/system/index", ["./compose", "./if", "./repeat", "./show", "./selected-item", "./global-behavior"], function(_export) {
"use strict";
var Compose,
If,
Repeat,
Show,
SelectedItem,
GlobalBehavior;
function install(aurelia) {
aurelia.withResources([Show, If, Repeat, Compose, SelectedItem, GlobalBehavior]);
}
return {
setters: [function(_compose) {
Compose = _compose.Compose;
}, function(_if) {
If = _if.If;
}, function(_repeat) {
Repeat = _repeat.Repeat;
}, function(_show) {
Show = _show.Show;
}, function(_selectedItem) {
SelectedItem = _selectedItem.SelectedItem;
}, function(_globalBehavior) {
GlobalBehavior = _globalBehavior.GlobalBehavior;
}],
execute: function() {
_export("Compose", Compose);
_export("If", If);
_export("Repeat", Repeat);
_export("Show", Show);
_export("SelectedItem", SelectedItem);
_export("GlobalBehavior", GlobalBehavior);
_export("install", install);
}
};
});
System.register("github:aurelia/event-aggregator@0.2.2", ["github:aurelia/event-aggregator@0.2.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/history-browser@0.2.3", ["github:aurelia/history-browser@0.2.3/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/http-client@0.4.4/system/http-request-message", ["./headers", "./http-response-message"], function(_export) {
"use strict";
var Headers,
HttpResponseMessage,
_prototypeProperties,
HttpRequestMessage;
return {
setters: [function(_headers) {
Headers = _headers.Headers;
}, function(_httpResponseMessage) {
HttpResponseMessage = _httpResponseMessage.HttpResponseMessage;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
HttpRequestMessage = _export("HttpRequestMessage", (function() {
function HttpRequestMessage(method, uri, content, replacer) {
this.method = method;
this.uri = uri;
this.content = content;
this.headers = new Headers();
this.responseType = "json";
this.replacer = replacer;
}
_prototypeProperties(HttpRequestMessage, null, {
withHeaders: {
value: function withHeaders(headers) {
this.headers = headers;
return this;
},
writable: true,
configurable: true
},
configureXHR: {
value: function configureXHR(xhr) {
xhr.open(this.method, this.uri, true);
xhr.responseType = this.responseType;
this.headers.configureXHR(xhr);
},
writable: true,
configurable: true
},
formatContent: {
value: function formatContent() {
var content = this.content;
if (window.FormData && content instanceof FormData) {
return content;
}
if (window.Blob && content instanceof Blob) {
return content;
}
if (window.ArrayBufferView && content instanceof ArrayBufferView) {
return content;
}
if (content instanceof Document) {
return content;
}
if (typeof content === "string") {
return content;
}
return JSON.stringify(content, this.replacer);
},
writable: true,
configurable: true
},
send: {
value: function send(client, progressCallback) {
var _this = this;
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest(),
responseType = _this.responseType;
if (responseType === "json") {
_this.responseType = "text";
}
if (client.timeout !== undefined) {
xhr.timeout = client.timeout;
}
_this.configureXHR(xhr);
xhr.onload = function(e) {
resolve(new HttpResponseMessage(_this, xhr, responseType, client.reviver));
};
xhr.ontimeout = function(e) {
reject(new HttpResponseMessage(_this, {
response: e,
status: xhr.status,
statusText: xhr.statusText
}, "timeout"));
};
xhr.onerror = function(e) {
reject(new HttpResponseMessage(_this, {
response: e,
status: xhr.status,
statusText: xhr.statusText
}, "error"));
};
if (progressCallback) {
xhr.upload.onprogress = progressCallback;
}
xhr.send(_this.formatContent());
});
},
writable: true,
configurable: true
}
});
return HttpRequestMessage;
})());
}
};
});
System.register("github:aurelia/metadata@0.3.1", ["github:aurelia/metadata@0.3.1/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/dependency-injection@0.4.2/system/index", ["aurelia-metadata", "./metadata", "./container"], function(_export) {
"use strict";
var Metadata,
Transient,
Singleton;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}, function(_metadata) {
Transient = _metadata.Transient;
Singleton = _metadata.Singleton;
_export("Registration", _metadata.Registration);
_export("Transient", _metadata.Transient);
_export("Singleton", _metadata.Singleton);
_export("Resolver", _metadata.Resolver);
_export("Lazy", _metadata.Lazy);
_export("All", _metadata.All);
_export("Optional", _metadata.Optional);
_export("Parent", _metadata.Parent);
}, function(_container) {
_export("Container", _container.Container);
}],
execute: function() {
Metadata.configure.classHelper("transient", Transient);
Metadata.configure.classHelper("singleton", Singleton);
}
};
});
System.register("github:aurelia/binding@0.3.3/system/observer-locator", ["aurelia-task-queue", "./array-observation", "./event-manager", "./dirty-checking", "./property-observation", "aurelia-dependency-injection"], function(_export) {
"use strict";
var TaskQueue,
getArrayObserver,
EventManager,
DirtyChecker,
DirtyCheckProperty,
SetterObserver,
OoObjectObserver,
OoPropertyObserver,
ElementObserver,
All,
_prototypeProperties,
hasObjectObserve,
ObserverLocator,
ObjectObservationAdapter;
function createObserversLookup(obj) {
var value = {};
Object.defineProperty(obj, "__observers__", {
enumerable: false,
configurable: false,
writable: false,
value: value
});
return value;
}
function createObserverLookup(obj) {
var value = new OoObjectObserver(obj);
Object.defineProperty(obj, "__observer__", {
enumerable: false,
configurable: false,
writable: false,
value: value
});
return value;
}
return {
setters: [function(_aureliaTaskQueue) {
TaskQueue = _aureliaTaskQueue.TaskQueue;
}, function(_arrayObservation) {
getArrayObserver = _arrayObservation.getArrayObserver;
}, function(_eventManager) {
EventManager = _eventManager.EventManager;
}, function(_dirtyChecking) {
DirtyChecker = _dirtyChecking.DirtyChecker;
DirtyCheckProperty = _dirtyChecking.DirtyCheckProperty;
}, function(_propertyObservation) {
SetterObserver = _propertyObservation.SetterObserver;
OoObjectObserver = _propertyObservation.OoObjectObserver;
OoPropertyObserver = _propertyObservation.OoPropertyObserver;
ElementObserver = _propertyObservation.ElementObserver;
}, function(_aureliaDependencyInjection) {
All = _aureliaDependencyInjection.All;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
if (typeof Object.getPropertyDescriptor !== "function") {
Object.getPropertyDescriptor = function(subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (typeof pd === "undefined" && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
};
}
hasObjectObserve = (function detectObjectObserve() {
if (typeof Object.observe !== "function") {
return false;
}
var records = [];
function callback(recs) {
records = recs;
}
var test = {};
Object.observe(test, callback);
test.id = 1;
test.id = 2;
delete test.id;
Object.deliverChangeRecords(callback);
if (records.length !== 3)
return false;
if (records[0].type != "add" || records[1].type != "update" || records[2].type != "delete") {
return false;
}
Object.unobserve(test, callback);
return true;
})();
ObserverLocator = _export("ObserverLocator", (function() {
function ObserverLocator(taskQueue, eventManager, dirtyChecker, observationAdapters) {
this.taskQueue = taskQueue;
this.eventManager = eventManager;
this.dirtyChecker = dirtyChecker;
this.observationAdapters = observationAdapters;
}
_prototypeProperties(ObserverLocator, {inject: {
value: function inject() {
return [TaskQueue, EventManager, DirtyChecker, All.of(ObjectObservationAdapter)];
},
writable: true,
configurable: true
}}, {
getObserversLookup: {
value: function getObserversLookup(obj) {
return obj.__observers__ || createObserversLookup(obj);
},
writable: true,
configurable: true
},
getObserver: {
value: function getObserver(obj, propertyName) {
var observersLookup = this.getObserversLookup(obj);
if (propertyName in observersLookup) {
return observersLookup[propertyName];
}
return observersLookup[propertyName] = this.createPropertyObserver(obj, propertyName);
},
writable: true,
configurable: true
},
getObservationAdapter: {
value: function getObservationAdapter(obj, propertyName) {
var i,
ii,
observationAdapter;
for (i = 0, ii = this.observationAdapters.length; i < ii; i++) {
observationAdapter = this.observationAdapters[i];
if (observationAdapter.handlesProperty(obj, propertyName))
return observationAdapter;
}
return null;
},
writable: true,
configurable: true
},
createPropertyObserver: {
value: function createPropertyObserver(obj, propertyName) {
var observerLookup,
descriptor,
handler,
observationAdapter;
if (obj instanceof Element) {
handler = this.eventManager.getElementHandler(obj);
if (handler) {
return new ElementObserver(handler, obj, propertyName);
}
}
descriptor = Object.getPropertyDescriptor(obj, propertyName);
if (descriptor && (descriptor.get || descriptor.set)) {
observationAdapter = this.getObservationAdapter(obj, propertyName);
if (observationAdapter)
return observationAdapter.getObserver(obj, propertyName);
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
if (hasObjectObserve) {
observerLookup = obj.__observer__ || createObserverLookup(obj);
return observerLookup.getObserver(propertyName);
}
if (obj instanceof Array) {
observerLookup = this.getArrayObserver(obj);
return observerLookup.getObserver(propertyName);
}
return new SetterObserver(this.taskQueue, obj, propertyName);
},
writable: true,
configurable: true
},
getArrayObserver: {
value: (function(_getArrayObserver) {
var _getArrayObserverWrapper = function getArrayObserver() {
return _getArrayObserver.apply(this, arguments);
};
_getArrayObserverWrapper.toString = function() {
return _getArrayObserver.toString();
};
return _getArrayObserverWrapper;
})(function(array) {
if ("__array_observer__" in array) {
return array.__array_observer__;
}
return array.__array_observer__ = getArrayObserver(this.taskQueue, array);
}),
writable: true,
configurable: true
}
});
return ObserverLocator;
})());
ObjectObservationAdapter = _export("ObjectObservationAdapter", (function() {
function ObjectObservationAdapter() {}
_prototypeProperties(ObjectObservationAdapter, null, {
handlesProperty: {
value: function handlesProperty(object, propertyName) {
throw new Error("BindingAdapters must implement handlesProperty(object, propertyName).");
},
writable: true,
configurable: true
},
getObserver: {
value: function getObserver(object, propertyName) {
throw new Error("BindingAdapters must implement createObserver(object, propertyName).");
},
writable: true,
configurable: true
}
});
return ObjectObservationAdapter;
})());
}
};
});
System.register("github:aurelia/binding@0.3.3/system/parser", ["./lexer", "./ast"], function(_export) {
"use strict";
var Lexer,
Token,
Expression,
ArrayOfExpression,
Chain,
ValueConverter,
Assign,
Conditional,
AccessScope,
AccessMember,
AccessKeyed,
CallScope,
CallFunction,
CallMember,
PrefixNot,
Binary,
LiteralPrimitive,
LiteralArray,
LiteralObject,
LiteralString,
_prototypeProperties,
EOF,
Parser,
ParserImplementation;
return {
setters: [function(_lexer) {
Lexer = _lexer.Lexer;
Token = _lexer.Token;
}, function(_ast) {
Expression = _ast.Expression;
ArrayOfExpression = _ast.ArrayOfExpression;
Chain = _ast.Chain;
ValueConverter = _ast.ValueConverter;
Assign = _ast.Assign;
Conditional = _ast.Conditional;
AccessScope = _ast.AccessScope;
AccessMember = _ast.AccessMember;
AccessKeyed = _ast.AccessKeyed;
CallScope = _ast.CallScope;
CallFunction = _ast.CallFunction;
CallMember = _ast.CallMember;
PrefixNot = _ast.PrefixNot;
Binary = _ast.Binary;
LiteralPrimitive = _ast.LiteralPrimitive;
LiteralArray = _ast.LiteralArray;
LiteralObject = _ast.LiteralObject;
LiteralString = _ast.LiteralString;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
EOF = new Token(-1, null);
Parser = _export("Parser", (function() {
function Parser() {
this.cache = {};
this.lexer = new Lexer();
}
_prototypeProperties(Parser, null, {parse: {
value: function parse(input) {
input = input || "";
return this.cache[input] || (this.cache[input] = new ParserImplementation(this.lexer, input).parseChain());
},
writable: true,
configurable: true
}});
return Parser;
})());
ParserImplementation = _export("ParserImplementation", (function() {
function ParserImplementation(lexer, input) {
this.index = 0;
this.input = input;
this.tokens = lexer.lex(input);
}
_prototypeProperties(ParserImplementation, null, {
peek: {
get: function() {
return this.index < this.tokens.length ? this.tokens[this.index] : EOF;
},
configurable: true
},
parseChain: {
value: function parseChain() {
var isChain = false,
expressions = [];
while (this.optional(";")) {
isChain = true;
}
while (this.index < this.tokens.length) {
if (this.peek.text === ")" || this.peek.text === "}" || this.peek.text === "]") {
this.error("Unconsumed token " + this.peek.text);
}
var expr = this.parseValueConverter();
expressions.push(expr);
while (this.optional(";")) {
isChain = true;
}
if (isChain && expr instanceof ValueConverter) {
this.error("cannot have a value converter in a chain");
}
}
return expressions.length === 1 ? expressions[0] : new Chain(expressions);
},
writable: true,
configurable: true
},
parseValueConverter: {
value: function parseValueConverter() {
var result = this.parseExpression();
while (this.optional("|")) {
var name = this.peek.text,
args = [];
this.advance();
while (this.optional(":")) {
args.push(this.parseExpression());
}
result = new ValueConverter(result, name, args, [result].concat(args));
}
return result;
},
writable: true,
configurable: true
},
parseExpression: {
value: function parseExpression() {
var start = this.peek.index,
result = this.parseConditional();
while (this.peek.text === "=") {
if (!result.isAssignable) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var expression = this.input.substring(start, end);
this.error("Expression " + expression + " is not assignable");
}
this.expect("=");
result = new Assign(result, this.parseConditional());
}
return result;
},
writable: true,
configurable: true
},
parseConditional: {
value: function parseConditional() {
var start = this.peek.index,
result = this.parseLogicalOr();
if (this.optional("?")) {
var yes = this.parseExpression();
if (!this.optional(":")) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var expression = this.input.substring(start, end);
this.error("Conditional expression " + expression + " requires all 3 expressions");
}
var no = this.parseExpression();
result = new Conditional(result, yes, no);
}
return result;
},
writable: true,
configurable: true
},
parseLogicalOr: {
value: function parseLogicalOr() {
var result = this.parseLogicalAnd();
while (this.optional("||")) {
result = new Binary("||", result, this.parseLogicalAnd());
}
return result;
},
writable: true,
configurable: true
},
parseLogicalAnd: {
value: function parseLogicalAnd() {
var result = this.parseEquality();
while (this.optional("&&")) {
result = new Binary("&&", result, this.parseEquality());
}
return result;
},
writable: true,
configurable: true
},
parseEquality: {
value: function parseEquality() {
var result = this.parseRelational();
while (true) {
if (this.optional("==")) {
result = new Binary("==", result, this.parseRelational());
} else if (this.optional("!=")) {
result = new Binary("!=", result, this.parseRelational());
} else if (this.optional("===")) {
result = new Binary("===", result, this.parseRelational());
} else if (this.optional("!==")) {
result = new Binary("!==", result, this.parseRelational());
} else {
return result;
}
}
},
writable: true,
configurable: true
},
parseRelational: {
value: function parseRelational() {
var result = this.parseAdditive();
while (true) {
if (this.optional("<")) {
result = new Binary("<", result, this.parseAdditive());
} else if (this.optional(">")) {
result = new Binary(">", result, this.parseAdditive());
} else if (this.optional("<=")) {
result = new Binary("<=", result, this.parseAdditive());
} else if (this.optional(">=")) {
result = new Binary(">=", result, this.parseAdditive());
} else {
return result;
}
}
},
writable: true,
configurable: true
},
parseAdditive: {
value: function parseAdditive() {
var result = this.parseMultiplicative();
while (true) {
if (this.optional("+")) {
result = new Binary("+", result, this.parseMultiplicative());
} else if (this.optional("-")) {
result = new Binary("-", result, this.parseMultiplicative());
} else {
return result;
}
}
},
writable: true,
configurable: true
},
parseMultiplicative: {
value: function parseMultiplicative() {
var result = this.parsePrefix();
while (true) {
if (this.optional("*")) {
result = new Binary("*", result, this.parsePrefix());
} else if (this.optional("%")) {
result = new Binary("%", result, this.parsePrefix());
} else if (this.optional("/")) {
result = new Binary("/", result, this.parsePrefix());
} else {
return result;
}
}
},
writable: true,
configurable: true
},
parsePrefix: {
value: function parsePrefix() {
if (this.optional("+")) {
return this.parsePrefix();
} else if (this.optional("-")) {
return new Binary("-", new LiteralPrimitive(0), this.parsePrefix());
} else if (this.optional("!")) {
return new PrefixNot("!", this.parsePrefix());
} else {
return this.parseAccessOrCallMember();
}
},
writable: true,
configurable: true
},
parseAccessOrCallMember: {
value: function parseAccessOrCallMember() {
var result = this.parsePrimary();
while (true) {
if (this.optional(".")) {
var name = this.peek.text;
this.advance();
if (this.optional("(")) {
var args = this.parseExpressionList(")");
this.expect(")");
result = new CallMember(result, name, args);
} else {
result = new AccessMember(result, name);
}
} else if (this.optional("[")) {
var key = this.parseExpression();
this.expect("]");
result = new AccessKeyed(result, key);
} else if (this.optional("(")) {
var args = this.parseExpressionList(")");
this.expect(")");
result = new CallFunction(result, args);
} else {
return result;
}
}
},
writable: true,
configurable: true
},
parsePrimary: {
value: function parsePrimary() {
if (this.optional("(")) {
var result = this.parseExpression();
this.expect(")");
return result;
} else if (this.optional("null") || this.optional("undefined")) {
return new LiteralPrimitive(null);
} else if (this.optional("true")) {
return new LiteralPrimitive(true);
} else if (this.optional("false")) {
return new LiteralPrimitive(false);
} else if (this.optional("[")) {
var elements = this.parseExpressionList("]");
this.expect("]");
return new LiteralArray(elements);
} else if (this.peek.text == "{") {
return this.parseObject();
} else if (this.peek.key != null) {
return this.parseAccessOrCallScope();
} else if (this.peek.value != null) {
var value = this.peek.value;
this.advance();
return isNaN(value) ? new LiteralString(value) : new LiteralPrimitive(value);
} else if (this.index >= this.tokens.length) {
throw new Error("Unexpected end of expression: " + this.input);
} else {
this.error("Unexpected token " + this.peek.text);
}
},
writable: true,
configurable: true
},
parseAccessOrCallScope: {
value: function parseAccessOrCallScope() {
var name = this.peek.key;
this.advance();
if (!this.optional("(")) {
return new AccessScope(name);
}
var args = this.parseExpressionList(")");
this.expect(")");
return new CallScope(name, args);
},
writable: true,
configurable: true
},
parseObject: {
value: function parseObject() {
var keys = [],
values = [];
this.expect("{");
if (this.peek.text !== "}") {
do {
var value = this.peek.value;
keys.push(typeof value === "string" ? value : this.peek.text);
this.advance();
this.expect(":");
values.push(this.parseExpression());
} while (this.optional(","));
}
this.expect("}");
return new LiteralObject(keys, values);
},
writable: true,
configurable: true
},
parseExpressionList: {
value: function parseExpressionList(terminator) {
var result = [];
if (this.peek.text != terminator) {
do {
result.push(this.parseExpression());
} while (this.optional(","));
}
return result;
},
writable: true,
configurable: true
},
optional: {
value: function optional(text) {
if (this.peek.text === text) {
this.advance();
return true;
}
return false;
},
writable: true,
configurable: true
},
expect: {
value: function expect(text) {
if (this.peek.text === text) {
this.advance();
} else {
this.error("Missing expected " + text);
}
},
writable: true,
configurable: true
},
advance: {
value: function advance() {
this.index++;
},
writable: true,
configurable: true
},
error: {
value: function error(message) {
var location = this.index < this.tokens.length ? "at column " + (this.tokens[this.index].index + 1) + " in" : "at the end of the expression";
throw new Error("Parser Error: " + message + " " + location + " [" + this.input + "]");
},
writable: true,
configurable: true
}
});
return ParserImplementation;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/attached-behavior", ["aurelia-metadata", "./behavior-instance", "./behaviors", "./util"], function(_export) {
"use strict";
var ResourceType,
BehaviorInstance,
configureBehavior,
hyphenate,
_prototypeProperties,
_inherits,
AttachedBehavior;
return {
setters: [function(_aureliaMetadata) {
ResourceType = _aureliaMetadata.ResourceType;
}, function(_behaviorInstance) {
BehaviorInstance = _behaviorInstance.BehaviorInstance;
}, function(_behaviors) {
configureBehavior = _behaviors.configureBehavior;
}, function(_util) {
hyphenate = _util.hyphenate;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
AttachedBehavior = _export("AttachedBehavior", (function(ResourceType) {
function AttachedBehavior(attribute) {
this.name = attribute;
this.properties = [];
this.attributes = {};
}
_inherits(AttachedBehavior, ResourceType);
_prototypeProperties(AttachedBehavior, {convention: {
value: function convention(name) {
if (name.endsWith("AttachedBehavior")) {
return new AttachedBehavior(hyphenate(name.substring(0, name.length - 16)));
}
},
writable: true,
configurable: true
}}, {
analyze: {
value: function analyze(container, target) {
configureBehavior(container, this, target);
},
writable: true,
configurable: true
},
load: {
value: function load(container, target) {
return Promise.resolve(this);
},
writable: true,
configurable: true
},
register: {
value: function register(registry, name) {
registry.registerAttribute(name || this.name, this, this.name);
},
writable: true,
configurable: true
},
compile: {
value: function compile(compiler, resources, node, instruction) {
instruction.suppressBind = true;
return node;
},
writable: true,
configurable: true
},
create: {
value: function create(container, instruction, element, bindings) {
var executionContext = instruction.executionContext || container.get(this.target),
behaviorInstance = new BehaviorInstance(this, executionContext, instruction);
if (this.childExpression) {
bindings.push(this.childExpression.createBinding(element, behaviorInstance.executionContext));
}
return behaviorInstance;
},
writable: true,
configurable: true
}
});
return AttachedBehavior;
})(ResourceType));
}
};
});
System.register("github:aurelia/templating@0.8.8/system/view-compiler", ["./resource-registry", "./view-factory", "./binding-language"], function(_export) {
"use strict";
var ResourceRegistry,
ViewFactory,
BindingLanguage,
_prototypeProperties,
nextInjectorId,
defaultCompileOptions,
hasShadowDOM,
ViewCompiler;
function getNextInjectorId() {
return ++nextInjectorId;
}
function configureProperties(instruction, resources) {
var type = instruction.type,
attrName = instruction.attrName,
attributes = instruction.attributes,
property,
key,
value;
var knownAttribute = resources.mapAttribute(attrName);
if (knownAttribute && attrName in attributes && knownAttribute !== attrName) {
attributes[knownAttribute] = attributes[attrName];
delete attributes[attrName];
}
for (key in attributes) {
value = attributes[key];
if (typeof value !== "string") {
property = type.attributes[key];
if (property !== undefined) {
value.targetProperty = property.name;
} else {
value.targetProperty = key;
}
}
}
}
function makeIntoInstructionTarget(element) {
var value = element.getAttribute("class");
element.setAttribute("class", value ? value += " au-target" : "au-target");
}
return {
setters: [function(_resourceRegistry) {
ResourceRegistry = _resourceRegistry.ResourceRegistry;
}, function(_viewFactory) {
ViewFactory = _viewFactory.ViewFactory;
}, function(_bindingLanguage) {
BindingLanguage = _bindingLanguage.BindingLanguage;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
nextInjectorId = 0;
defaultCompileOptions = {targetShadowDOM: false};
hasShadowDOM = !!HTMLElement.prototype.createShadowRoot;
ViewCompiler = _export("ViewCompiler", (function() {
function ViewCompiler(bindingLanguage) {
this.bindingLanguage = bindingLanguage;
}
_prototypeProperties(ViewCompiler, {inject: {
value: function inject() {
return [BindingLanguage];
},
writable: true,
configurable: true
}}, {
compile: {
value: function compile(templateOrFragment, resources) {
var options = arguments[2] === undefined ? defaultCompileOptions : arguments[2];
var instructions = [],
targetShadowDOM = options.targetShadowDOM,
content;
targetShadowDOM = targetShadowDOM && hasShadowDOM;
if (templateOrFragment.content) {
content = document.adoptNode(templateOrFragment.content, true);
} else {
content = templateOrFragment;
}
this.compileNode(content, resources, instructions, templateOrFragment, "root", !targetShadowDOM);
content.insertBefore(document.createComment("<view>"), content.firstChild);
content.appendChild(document.createComment("</view>"));
return new ViewFactory(content, instructions, resources);
},
writable: true,
configurable: true
},
compileNode: {
value: function compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
switch (node.nodeType) {
case 1:
return this.compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM);
case 3:
var expression = this.bindingLanguage.parseText(resources, node.textContent);
if (expression) {
var marker = document.createElement("au-marker");
marker.className = "au-target";
node.parentNode.insertBefore(marker, node);
node.textContent = " ";
instructions.push({contentExpression: expression});
}
return node.nextSibling;
case 11:
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this.compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM);
}
break;
}
return node.nextSibling;
},
writable: true,
configurable: true
},
compileElement: {
value: function compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
var tagName = node.tagName.toLowerCase(),
attributes = node.attributes,
expressions = [],
behaviorInstructions = [],
providers = [],
bindingLanguage = this.bindingLanguage,
liftingInstruction,
viewFactory,
type,
elementInstruction,
elementProperty,
i,
ii,
attr,
attrName,
attrValue,
instruction,
info,
property,
knownAttribute;
if (tagName === "content") {
if (targetLightDOM) {
instructions.push({
parentInjectorId: parentInjectorId,
contentSelector: true,
selector: node.getAttribute("select"),
suppressBind: true
});
makeIntoInstructionTarget(node);
}
return node.nextSibling;
} else if (tagName === "template") {
viewFactory = this.compile(node, resources);
} else {
type = resources.getElement(tagName);
if (type) {
elementInstruction = {
type: type,
attributes: {}
};
behaviorInstructions.push(elementInstruction);
}
}
for (i = 0, ii = attributes.length; i < ii; ++i) {
attr = attributes[i];
attrName = attr.name;
attrValue = attr.value;
info = bindingLanguage.inspectAttribute(resources, attrName, attrValue);
type = resources.getAttribute(info.attrName);
elementProperty = null;
if (type) {
knownAttribute = resources.mapAttribute(info.attrName);
if (knownAttribute) {
property = type.attributes[knownAttribute];
if (property) {
info.defaultBindingMode = property.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = property.hasOptions ? "options" : null;
}
}
}
} else if (elementInstruction) {
elementProperty = elementInstruction.type.attributes[info.attrName];
if (elementProperty) {
info.defaultBindingMode = elementProperty.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = elementProperty.hasOptions ? "options" : null;
}
}
}
if (elementProperty) {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction);
} else {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info);
}
if (instruction) {
if (instruction.alteredAttr) {
type = resources.getAttribute(instruction.attrName);
}
if (instruction.discrete) {
expressions.push(instruction);
} else {
if (type) {
instruction.type = type;
configureProperties(instruction, resources);
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name;
} else {
expressions.push(instruction.attributes[instruction.attrName]);
}
}
} else {
if (type) {
instruction = {
attrName: attrName,
type: type,
attributes: {}
};
instruction.attributes[resources.mapAttribute(attrName)] = attrValue;
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[attrName] = attrValue;
}
}
}
if (liftingInstruction) {
liftingInstruction.viewFactory = viewFactory;
node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode);
makeIntoInstructionTarget(node);
instructions.push({
anchorIsContainer: false,
parentInjectorId: parentInjectorId,
expressions: [],
behaviorInstructions: [liftingInstruction],
viewFactory: liftingInstruction.viewFactory,
providers: [liftingInstruction.type.target]
});
} else {
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
instruction = behaviorInstructions[i];
instruction.type.compile(this, resources, node, instruction, parentNode);
providers.push(instruction.type.target);
}
var injectorId = behaviorInstructions.length ? getNextInjectorId() : false;
if (expressions.length || behaviorInstructions.length) {
makeIntoInstructionTarget(node);
instructions.push({
anchorIsContainer: true,
injectorId: injectorId,
parentInjectorId: parentInjectorId,
expressions: expressions,
behaviorInstructions: behaviorInstructions,
providers: providers
});
}
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this.compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM);
}
}
return node.nextSibling;
},
writable: true,
configurable: true
}
});
return ViewCompiler;
})());
}
};
});
System.register("github:aurelia/templating-binding@0.8.4/system/index", ["aurelia-templating", "./binding-language", "./syntax-interpreter"], function(_export) {
"use strict";
var BindingLanguage,
TemplatingBindingLanguage,
SyntaxInterpreter;
function install(aurelia) {
var instance,
getInstance = function(c) {
return instance || (instance = c.invoke(TemplatingBindingLanguage));
};
if (aurelia.container.hasHandler(TemplatingBindingLanguage)) {
instance = aurelia.container.get(TemplatingBindingLanguage);
} else {
aurelia.container.registerHandler(TemplatingBindingLanguage, getInstance);
}
aurelia.container.registerHandler(BindingLanguage, getInstance);
}
return {
setters: [function(_aureliaTemplating) {
BindingLanguage = _aureliaTemplating.BindingLanguage;
}, function(_bindingLanguage) {
TemplatingBindingLanguage = _bindingLanguage.TemplatingBindingLanguage;
}, function(_syntaxInterpreter) {
SyntaxInterpreter = _syntaxInterpreter.SyntaxInterpreter;
}],
execute: function() {
_export("TemplatingBindingLanguage", TemplatingBindingLanguage);
_export("SyntaxInterpreter", SyntaxInterpreter);
_export("install", install);
}
};
});
System.register("github:aurelia/route-recognizer@0.2.2", ["github:aurelia/route-recognizer@0.2.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/router@0.5.4/system/pipeline-provider", ["aurelia-dependency-injection", "./pipeline", "./navigation-plan", "./model-binding", "./route-loading", "./navigation-context", "./activation"], function(_export) {
"use strict";
var Container,
Pipeline,
BuildNavigationPlanStep,
ApplyModelBindersStep,
LoadRouteStep,
CommitChangesStep,
CanDeactivatePreviousStep,
CanActivateNextStep,
DeactivatePreviousStep,
ActivateNextStep,
_prototypeProperties,
PipelineProvider;
return {
setters: [function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_pipeline) {
Pipeline = _pipeline.Pipeline;
}, function(_navigationPlan) {
BuildNavigationPlanStep = _navigationPlan.BuildNavigationPlanStep;
}, function(_modelBinding) {
ApplyModelBindersStep = _modelBinding.ApplyModelBindersStep;
}, function(_routeLoading) {
LoadRouteStep = _routeLoading.LoadRouteStep;
}, function(_navigationContext) {
CommitChangesStep = _navigationContext.CommitChangesStep;
}, function(_activation) {
CanDeactivatePreviousStep = _activation.CanDeactivatePreviousStep;
CanActivateNextStep = _activation.CanActivateNextStep;
DeactivatePreviousStep = _activation.DeactivatePreviousStep;
ActivateNextStep = _activation.ActivateNextStep;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
PipelineProvider = _export("PipelineProvider", (function() {
function PipelineProvider(container) {
this.container = container;
this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, ApplyModelBindersStep, CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep, CommitChangesStep];
}
_prototypeProperties(PipelineProvider, {inject: {
value: function inject() {
return [Container];
},
writable: true,
configurable: true
}}, {createPipeline: {
value: function createPipeline(navigationContext) {
var _this = this;
var pipeline = new Pipeline();
this.steps.forEach(function(step) {
return pipeline.withStep(_this.container.get(step));
});
return pipeline;
},
writable: true,
configurable: true
}});
return PipelineProvider;
})());
}
};
});
System.register("github:aurelia/templating-resources@0.8.5", ["github:aurelia/templating-resources@0.8.5/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/http-client@0.4.4/system/http-client", ["aurelia-path", "./http-request-message", "./http-response-message", "./jsonp-request-message", "./headers"], function(_export) {
"use strict";
var join,
HttpRequestMessage,
HttpResponseMessage,
JSONPRequestMessage,
Headers,
_prototypeProperties,
HttpClient;
return {
setters: [function(_aureliaPath) {
join = _aureliaPath.join;
}, function(_httpRequestMessage) {
HttpRequestMessage = _httpRequestMessage.HttpRequestMessage;
}, function(_httpResponseMessage) {
HttpResponseMessage = _httpResponseMessage.HttpResponseMessage;
}, function(_jsonpRequestMessage) {
JSONPRequestMessage = _jsonpRequestMessage.JSONPRequestMessage;
}, function(_headers) {
Headers = _headers.Headers;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
HttpClient = _export("HttpClient", (function() {
function HttpClient() {
var baseUrl = arguments[0] === undefined ? null : arguments[0];
var defaultRequestHeaders = arguments[1] === undefined ? new Headers() : arguments[1];
this.baseUrl = baseUrl;
this.defaultRequestHeaders = defaultRequestHeaders;
}
_prototypeProperties(HttpClient, null, {
send: {
value: function send(requestMessage, progressCallback) {
return requestMessage.send(this, progressCallback);
},
writable: true,
configurable: true
},
get: {
value: function get(uri) {
return this.send(new HttpRequestMessage("GET", join(this.baseUrl, uri)).withHeaders(this.defaultRequestHeaders));
},
writable: true,
configurable: true
},
put: {
value: function put(uri, content, replacer) {
return this.send(new HttpRequestMessage("PUT", join(this.baseUrl, uri), content, replacer || this.replacer).withHeaders(this.defaultRequestHeaders));
},
writable: true,
configurable: true
},
patch: {
value: function patch(uri, content, replacer) {
return this.send(new HttpRequestMessage("PATCH", join(this.baseUrl, uri), content, replacer || this.replacer).withHeaders(this.defaultRequestHeaders));
},
writable: true,
configurable: true
},
post: {
value: function post(uri, content, replacer) {
return this.send(new HttpRequestMessage("POST", join(this.baseUrl, uri), content, replacer || this.replacer).withHeaders(this.defaultRequestHeaders));
},
writable: true,
configurable: true
},
"delete": {
value: function _delete(uri) {
return this.send(new HttpRequestMessage("DELETE", join(this.baseUrl, uri)).withHeaders(this.defaultRequestHeaders));
},
writable: true,
configurable: true
},
jsonp: {
value: function jsonp(uri) {
var callbackParameterName = arguments[1] === undefined ? "jsoncallback" : arguments[1];
return this.send(new JSONPRequestMessage(join(this.baseUrl, uri), callbackParameterName));
},
writable: true,
configurable: true
}
});
return HttpClient;
})());
}
};
});
System.register("github:aurelia/loader-default@0.4.1/system/index", ["aurelia-metadata", "aurelia-loader", "aurelia-path"], function(_export) {
"use strict";
var Origin,
Loader,
join,
_prototypeProperties,
_inherits,
sys,
DefaultLoader;
function ensureOriginOnExports(executed, name) {
var target = executed,
key,
exportedValue;
if (target.__useDefault) {
target = target["default"];
}
Origin.set(target, new Origin(name, "default"));
for (key in target) {
exportedValue = target[key];
if (typeof exportedValue === "function") {
Origin.set(exportedValue, new Origin(name, key));
}
}
return executed;
}
return {
setters: [function(_aureliaMetadata) {
Origin = _aureliaMetadata.Origin;
}, function(_aureliaLoader) {
Loader = _aureliaLoader.Loader;
}, function(_aureliaPath) {
join = _aureliaPath.join;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
if (!window.System || !window.System["import"]) {
sys = window.System = window.System || {};
sys.polyfilled = true;
sys.map = {};
sys["import"] = function(moduleId) {
return new Promise(function(resolve, reject) {
require([moduleId], resolve, reject);
});
};
sys.normalize = function(url) {
return Promise.resolve(url);
};
}
Loader.createDefaultLoader = function() {
return new DefaultLoader();
};
DefaultLoader = (function(Loader) {
function DefaultLoader() {
this.baseUrl = System.baseUrl;
this.baseViewUrl = System.baseViewUrl || System.baseUrl;
this.registry = {};
}
_inherits(DefaultLoader, Loader);
_prototypeProperties(DefaultLoader, null, {
loadModule: {
value: function loadModule(id, baseUrl) {
var _this = this;
baseUrl = baseUrl === undefined ? this.baseUrl : baseUrl;
if (baseUrl && !id.startsWith(baseUrl)) {
id = join(baseUrl, id);
}
return System.normalize(id).then(function(newId) {
var existing = _this.registry[newId];
if (existing) {
return existing;
}
return System["import"](newId).then(function(m) {
_this.registry[newId] = m;
return ensureOriginOnExports(m, newId);
});
});
},
writable: true,
enumerable: true,
configurable: true
},
loadAllModules: {
value: function loadAllModules(ids) {
var loads = [],
i,
ii,
loader = this.loader;
for (i = 0, ii = ids.length; i < ii; ++i) {
loads.push(this.loadModule(ids[i]));
}
return Promise.all(loads);
},
writable: true,
enumerable: true,
configurable: true
},
loadTemplate: {
value: function loadTemplate(url) {
if (this.baseViewUrl && !url.startsWith(this.baseViewUrl)) {
url = join(this.baseViewUrl, url);
}
return this.importTemplate(url);
},
writable: true,
enumerable: true,
configurable: true
}
});
return DefaultLoader;
})(Loader);
_export("DefaultLoader", DefaultLoader);
}
};
});
System.register("github:aurelia/dependency-injection@0.4.2", ["github:aurelia/dependency-injection@0.4.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/binding@0.3.3/system/index", ["aurelia-metadata", "./value-converter", "./event-manager", "./observer-locator", "./array-change-records", "./binding-modes", "./parser", "./binding-expression", "./listener-expression", "./name-expression", "./call-expression", "./dirty-checking"], function(_export) {
"use strict";
var Metadata,
ValueConverter;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}, function(_valueConverter) {
ValueConverter = _valueConverter.ValueConverter;
_export("ValueConverter", _valueConverter.ValueConverter);
}, function(_eventManager) {
_export("EventManager", _eventManager.EventManager);
}, function(_observerLocator) {
_export("ObserverLocator", _observerLocator.ObserverLocator);
}, function(_arrayChangeRecords) {
_export("calcSplices", _arrayChangeRecords.calcSplices);
}, function(_bindingModes) {
for (var _key in _bindingModes) {
_export(_key, _bindingModes[_key]);
}
}, function(_parser) {
_export("Parser", _parser.Parser);
}, function(_bindingExpression) {
_export("BindingExpression", _bindingExpression.BindingExpression);
}, function(_listenerExpression) {
_export("ListenerExpression", _listenerExpression.ListenerExpression);
}, function(_nameExpression) {
_export("NameExpression", _nameExpression.NameExpression);
}, function(_callExpression) {
_export("CallExpression", _callExpression.CallExpression);
}, function(_dirtyChecking) {
_export("DirtyChecker", _dirtyChecking.DirtyChecker);
}],
execute: function() {
Metadata.configure.classHelper("valueConverter", ValueConverter);
}
};
});
System.register("github:aurelia/templating@0.8.8/system/view-engine", ["aurelia-logging", "aurelia-loader", "aurelia-path", "./view-compiler", "./resource-registry"], function(_export) {
"use strict";
var LogManager,
Loader,
relativeToFile,
ViewCompiler,
ResourceRegistry,
ViewResources,
_prototypeProperties,
importSplitter,
logger,
ViewEngine;
return {
setters: [function(_aureliaLogging) {
LogManager = _aureliaLogging;
}, function(_aureliaLoader) {
Loader = _aureliaLoader.Loader;
}, function(_aureliaPath) {
relativeToFile = _aureliaPath.relativeToFile;
}, function(_viewCompiler) {
ViewCompiler = _viewCompiler.ViewCompiler;
}, function(_resourceRegistry) {
ResourceRegistry = _resourceRegistry.ResourceRegistry;
ViewResources = _resourceRegistry.ViewResources;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
importSplitter = /\s*,\s*/;
logger = LogManager.getLogger("templating");
ViewEngine = _export("ViewEngine", (function() {
function ViewEngine(loader, viewCompiler, appResources) {
this.loader = loader;
this.viewCompiler = viewCompiler;
this.appResources = appResources;
this.importedViews = {};
}
_prototypeProperties(ViewEngine, {inject: {
value: function inject() {
return [Loader, ViewCompiler, ResourceRegistry];
},
writable: true,
configurable: true
}}, {
loadViewFactory: {
value: function loadViewFactory(url, compileOptions, associatedModuleId) {
var _this = this;
var existing = this.importedViews[url];
if (existing) {
return Promise.resolve(existing);
}
return this.loader.loadTemplate(url).then(function(template) {
return _this.loadTemplateResources(url, template, associatedModuleId).then(function(resources) {
existing = _this.importedViews[url];
if (existing) {
return existing;
}
var viewFactory = _this.viewCompiler.compile(template, resources, compileOptions);
_this.importedViews[url] = viewFactory;
return viewFactory;
});
});
},
writable: true,
configurable: true
},
loadTemplateResources: {
value: function loadTemplateResources(templateUrl, template, associatedModuleId) {
var _this = this;
var importIds,
names,
i,
ii,
src,
current,
registry = new ViewResources(this.appResources, templateUrl),
dxImportElements = template.content.querySelectorAll("import"),
associatedModule;
if (dxImportElements.length === 0 && !associatedModuleId) {
return Promise.resolve(registry);
}
importIds = new Array(dxImportElements.length);
names = new Array(dxImportElements.length);
for (i = 0, ii = dxImportElements.length; i < ii; ++i) {
current = dxImportElements[i];
src = current.getAttribute("from");
if (!src) {
throw new Error("Import element in " + templateUrl + " has no \"from\" attribute.");
}
importIds[i] = src;
names[i] = current.getAttribute("as");
if (current.parentNode) {
current.parentNode.removeChild(current);
}
}
importIds = importIds.map(function(x) {
return relativeToFile(x, templateUrl);
});
logger.debug("importing resources for " + templateUrl, importIds);
return this.resourceCoordinator.importResourcesFromModuleIds(importIds).then(function(toRegister) {
for (i = 0, ii = toRegister.length; i < ii; ++i) {
toRegister[i].register(registry, names[i]);
}
if (associatedModuleId) {
associatedModule = _this.resourceCoordinator.getExistingModuleAnalysis(associatedModuleId);
if (associatedModule) {
associatedModule.register(registry);
}
}
return registry;
});
},
writable: true,
configurable: true
}
});
return ViewEngine;
})());
}
};
});
System.register("github:aurelia/templating-binding@0.8.4", ["github:aurelia/templating-binding@0.8.4/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/router@0.5.4/system/router", ["aurelia-route-recognizer", "aurelia-path", "./navigation-context", "./navigation-instruction", "./router-configuration", "./util"], function(_export) {
"use strict";
var RouteRecognizer,
join,
NavigationContext,
NavigationInstruction,
RouterConfiguration,
processPotential,
_prototypeProperties,
Router;
return {
setters: [function(_aureliaRouteRecognizer) {
RouteRecognizer = _aureliaRouteRecognizer.RouteRecognizer;
}, function(_aureliaPath) {
join = _aureliaPath.join;
}, function(_navigationContext) {
NavigationContext = _navigationContext.NavigationContext;
}, function(_navigationInstruction) {
NavigationInstruction = _navigationInstruction.NavigationInstruction;
}, function(_routerConfiguration) {
RouterConfiguration = _routerConfiguration.RouterConfiguration;
}, function(_util) {
processPotential = _util.processPotential;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
Router = _export("Router", (function() {
function Router(container, history) {
this.container = container;
this.history = history;
this.viewPorts = {};
this.reset();
this.baseUrl = "";
}
_prototypeProperties(Router, null, {
registerViewPort: {
value: function registerViewPort(viewPort, name) {
name = name || "default";
this.viewPorts[name] = viewPort;
},
writable: true,
configurable: true
},
refreshBaseUrl: {
value: function refreshBaseUrl() {
if (this.parent) {
var baseUrl = this.parent.currentInstruction.getBaseUrl();
this.baseUrl = this.parent.baseUrl + baseUrl;
}
},
writable: true,
configurable: true
},
refreshNavigation: {
value: function refreshNavigation() {
var nav = this.navigation;
for (var i = 0,
length = nav.length; i < length; i++) {
var current = nav[i];
if (!this.history._hasPushState) {
if (this.baseUrl[0] == "/") {
current.href = "#" + this.baseUrl;
} else {
current.href = "#/" + this.baseUrl;
}
} else {
current.href = "/" + this.baseUrl;
}
if (current.href[current.href.length - 1] != "/") {
current.href += "/";
}
current.href += current.relativeHref;
}
},
writable: true,
configurable: true
},
configure: {
value: function configure(callbackOrConfig) {
if (typeof callbackOrConfig == "function") {
var config = new RouterConfiguration();
callbackOrConfig(config);
config.exportToRouter(this);
} else {
callbackOrConfig.exportToRouter(this);
}
return this;
},
writable: true,
configurable: true
},
navigate: {
value: function navigate(fragment, options) {
fragment = join(this.baseUrl, fragment);
if (fragment === "")
fragment = "/";
return this.history.navigate(fragment, options);
},
writable: true,
configurable: true
},
navigateBack: {
value: function navigateBack() {
this.history.navigateBack();
},
writable: true,
configurable: true
},
createChild: {
value: function createChild(container) {
var childRouter = new Router(container || this.container.createChild(), this.history);
childRouter.parent = this;
return childRouter;
},
writable: true,
configurable: true
},
createNavigationInstruction: {
value: function createNavigationInstruction() {
var url = arguments[0] === undefined ? "" : arguments[0];
var parentInstruction = arguments[1] === undefined ? null : arguments[1];
var results = this.recognizer.recognize(url);
var fragment,
queryIndex,
queryString;
if (!results || !results.length) {
results = this.childRecognizer.recognize(url);
}
fragment = url;
queryIndex = fragment.indexOf("?");
if (queryIndex != -1) {
fragment = url.substr(0, queryIndex);
queryString = url.substr(queryIndex + 1);
}
if ((!results || !results.length) && this.catchAllHandler) {
results = [{
config: {navModel: {}},
handler: this.catchAllHandler,
params: {path: fragment}
}];
}
if (results && results.length) {
var first = results[0],
fragment = url,
queryIndex = fragment.indexOf("?"),
queryString;
if (queryIndex != -1) {
fragment = url.substr(0, queryIndex);
queryString = url.substr(queryIndex + 1);
}
var instruction = new NavigationInstruction(fragment, queryString, first.params, first.queryParams || results.queryParams, first.config || first.handler, parentInstruction);
if (typeof first.handler == "function") {
return first.handler(instruction).then(function(instruction) {
if (!("viewPorts" in instruction.config)) {
instruction.config.viewPorts = {"default": {moduleId: instruction.config.moduleId}};
}
return instruction;
});
}
return Promise.resolve(instruction);
} else {
return Promise.reject(new Error("Route Not Found: " + url));
}
},
writable: true,
configurable: true
},
createNavigationContext: {
value: function createNavigationContext(instruction) {
return new NavigationContext(this, instruction);
},
writable: true,
configurable: true
},
generate: {
value: function generate(name, params) {
return this.recognizer.generate(name, params);
},
writable: true,
configurable: true
},
addRoute: {
value: function addRoute(config) {
var navModel = arguments[1] === undefined ? {} : arguments[1];
if (!("viewPorts" in config)) {
config.viewPorts = {"default": {
moduleId: config.moduleId,
view: config.view
}};
}
navModel.title = navModel.title || config.title;
this.routes.push(config);
this.recognizer.add([{
path: config.route,
handler: config
}]);
if (config.route) {
var withChild = JSON.parse(JSON.stringify(config));
withChild.route += "/*childRoute";
withChild.hasChildRouter = true;
this.childRecognizer.add([{
path: withChild.route,
handler: withChild
}]);
withChild.navModel = navModel;
}
config.navModel = navModel;
if ((config.nav || "order" in navModel) && this.navigation.indexOf(navModel) === -1) {
navModel.order = navModel.order || config.nav;
navModel.href = navModel.href || config.href;
navModel.isActive = false;
navModel.config = config;
if (!config.href) {
navModel.relativeHref = config.route;
navModel.href = "";
}
if (typeof navModel.order != "number") {
navModel.order = ++this.fallbackOrder;
}
this.navigation.push(navModel);
this.navigation = this.navigation.sort(function(a, b) {
return a.order - b.order;
});
}
},
writable: true,
configurable: true
},
handleUnknownRoutes: {
value: function handleUnknownRoutes(config) {
var callback = function(instruction) {
return new Promise(function(resolve, reject) {
function done(inst) {
inst = inst || instruction;
inst.config.route = inst.params.path;
resolve(inst);
}
if (!config) {
instruction.config.moduleId = instruction.fragment;
done(instruction);
} else if (typeof config == "string") {
instruction.config.moduleId = config;
done(instruction);
} else if (typeof config == "function") {
processPotential(config(instruction), done, reject);
} else {
instruction.config = config;
done(instruction);
}
});
};
this.catchAllHandler = callback;
},
writable: true,
configurable: true
},
reset: {
value: function reset() {
this.fallbackOrder = 100;
this.recognizer = new RouteRecognizer();
this.childRecognizer = new RouteRecognizer();
this.routes = [];
this.isNavigating = false;
this.navigation = [];
},
writable: true,
configurable: true
}
});
return Router;
})());
}
};
});
System.register("github:aurelia/router@0.5.4/system/app-router", ["aurelia-dependency-injection", "aurelia-history", "./router", "./pipeline-provider", "./navigation-commands"], function(_export) {
"use strict";
var Container,
History,
Router,
PipelineProvider,
isNavigationCommand,
_prototypeProperties,
_get,
_inherits,
AppRouter;
function findAnchor(el) {
while (el) {
if (el.tagName === "A")
return el;
el = el.parentNode;
}
}
function handleLinkClick(evt) {
if (!this.isActive) {
return;
}
var target = findAnchor(evt.target);
if (!target) {
return;
}
if (this.history._hasPushState) {
if (!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && targetIsThisWindow(target)) {
var href = target.getAttribute("href");
if (href !== null && !(href.charAt(0) === "#" || /^[a-z]+:/i.test(href))) {
evt.preventDefault();
this.history.navigate(href);
}
}
}
}
function targetIsThisWindow(target) {
var targetWindow = target.getAttribute("target");
return !targetWindow || targetWindow === window.name || targetWindow === "_self" || targetWindow === "top" && window === window.top;
}
return {
setters: [function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_aureliaHistory) {
History = _aureliaHistory.History;
}, function(_router) {
Router = _router.Router;
}, function(_pipelineProvider) {
PipelineProvider = _pipelineProvider.PipelineProvider;
}, function(_navigationCommands) {
isNavigationCommand = _navigationCommands.isNavigationCommand;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_get = function get(object, property, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc && desc.writable) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
AppRouter = _export("AppRouter", (function(Router) {
function AppRouter(container, history, pipelineProvider) {
_get(Object.getPrototypeOf(AppRouter.prototype), "constructor", this).call(this, container, history);
this.pipelineProvider = pipelineProvider;
document.addEventListener("click", handleLinkClick.bind(this), true);
}
_inherits(AppRouter, Router);
_prototypeProperties(AppRouter, {inject: {
value: function inject() {
return [Container, History, PipelineProvider];
},
writable: true,
configurable: true
}}, {
loadUrl: {
value: function loadUrl(url) {
var _this = this;
return this.createNavigationInstruction(url).then(function(instruction) {
return _this.queueInstruction(instruction);
})["catch"](function(error) {
console.error(error);
if (_this.history.previousFragment) {
_this.navigate(_this.history.previousFragment, false);
}
});
},
writable: true,
configurable: true
},
queueInstruction: {
value: function queueInstruction(instruction) {
var _this = this;
return new Promise(function(resolve) {
instruction.resolve = resolve;
_this.queue.unshift(instruction);
_this.dequeueInstruction();
});
},
writable: true,
configurable: true
},
dequeueInstruction: {
value: function dequeueInstruction() {
var _this = this;
if (this.isNavigating) {
return;
}
var instruction = this.queue.shift();
this.queue = [];
if (!instruction) {
return;
}
this.isNavigating = true;
var context = this.createNavigationContext(instruction);
var pipeline = this.pipelineProvider.createPipeline(context);
pipeline.run(context).then(function(result) {
_this.isNavigating = false;
if (result.completed) {
_this.history.previousFragment = instruction.fragment;
}
if (result.output instanceof Error) {
console.error(result.output);
}
if (isNavigationCommand(result.output)) {
result.output.navigate(_this);
} else if (!result.completed) {
_this.navigate(_this.history.previousFragment || "", false);
}
instruction.resolve(result);
_this.dequeueInstruction();
})["catch"](function(error) {
console.error(error);
});
},
writable: true,
configurable: true
},
registerViewPort: {
value: function registerViewPort(viewPort, name) {
var _this = this;
_get(Object.getPrototypeOf(AppRouter.prototype), "registerViewPort", this).call(this, viewPort, name);
if (!this.isActive) {
if ("configureRouter" in this.container.viewModel) {
var result = this.container.viewModel.configureRouter() || Promise.resolve();
return result.then(function() {
return _this.activate();
});
} else {
this.activate();
}
} else {
this.dequeueInstruction();
}
},
writable: true,
configurable: true
},
activate: {
value: function activate(options) {
if (this.isActive) {
return;
}
this.isActive = true;
this.options = Object.assign({routeHandler: this.loadUrl.bind(this)}, this.options, options);
this.history.activate(this.options);
this.dequeueInstruction();
},
writable: true,
configurable: true
},
deactivate: {
value: function deactivate() {
this.isActive = false;
this.history.deactivate();
},
writable: true,
configurable: true
},
reset: {
value: function reset() {
_get(Object.getPrototypeOf(AppRouter.prototype), "reset", this).call(this);
this.queue = [];
this.options = null;
},
writable: true,
configurable: true
}
});
return AppRouter;
})(Router));
}
};
});
System.register("github:aurelia/http-client@0.4.4/system/index", ["./http-client", "./http-request-message", "./http-response-message", "./jsonp-request-message", "./headers"], function(_export) {
"use strict";
return {
setters: [function(_httpClient) {
_export("HttpClient", _httpClient.HttpClient);
}, function(_httpRequestMessage) {
_export("HttpRequestMessage", _httpRequestMessage.HttpRequestMessage);
}, function(_httpResponseMessage) {
_export("HttpResponseMessage", _httpResponseMessage.HttpResponseMessage);
}, function(_jsonpRequestMessage) {
_export("JSONPRequestMessage", _jsonpRequestMessage.JSONPRequestMessage);
}, function(_headers) {
_export("Headers", _headers.Headers);
}],
execute: function() {}
};
});
System.register("github:aurelia/loader-default@0.4.1", ["github:aurelia/loader-default@0.4.1/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/binding@0.3.3", ["github:aurelia/binding@0.3.3/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/templating@0.8.8/system/custom-element", ["aurelia-metadata", "./behavior-instance", "./behaviors", "./content-selector", "./view-engine", "./view-strategy", "./util"], function(_export) {
"use strict";
var Metadata,
Origin,
ResourceType,
BehaviorInstance,
configureBehavior,
ContentSelector,
ViewEngine,
ViewStrategy,
hyphenate,
_prototypeProperties,
_inherits,
defaultInstruction,
contentSelectorFactoryOptions,
hasShadowDOM,
valuePropertyName,
UseShadowDOM,
CustomElement;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
Origin = _aureliaMetadata.Origin;
ResourceType = _aureliaMetadata.ResourceType;
}, function(_behaviorInstance) {
BehaviorInstance = _behaviorInstance.BehaviorInstance;
}, function(_behaviors) {
configureBehavior = _behaviors.configureBehavior;
}, function(_contentSelector) {
ContentSelector = _contentSelector.ContentSelector;
}, function(_viewEngine) {
ViewEngine = _viewEngine.ViewEngine;
}, function(_viewStrategy) {
ViewStrategy = _viewStrategy.ViewStrategy;
}, function(_util) {
hyphenate = _util.hyphenate;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_inherits = function(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)
subClass.__proto__ = superClass;
};
defaultInstruction = {suppressBind: false};
contentSelectorFactoryOptions = {suppressBind: true};
hasShadowDOM = !!HTMLElement.prototype.createShadowRoot;
valuePropertyName = "value";
UseShadowDOM = _export("UseShadowDOM", function UseShadowDOM() {});
CustomElement = _export("CustomElement", (function(ResourceType) {
function CustomElement(tagName) {
this.name = tagName;
this.properties = [];
this.attributes = {};
}
_inherits(CustomElement, ResourceType);
_prototypeProperties(CustomElement, {convention: {
value: function convention(name) {
if (name.endsWith("CustomElement")) {
return new CustomElement(hyphenate(name.substring(0, name.length - 13)));
}
},
writable: true,
configurable: true
}}, {
analyze: {
value: function analyze(container, target) {
configureBehavior(container, this, target, valuePropertyName);
this.configured = true;
this.targetShadowDOM = Metadata.on(target).has(UseShadowDOM);
this.usesShadowDOM = this.targetShadowDOM && hasShadowDOM;
},
writable: true,
configurable: true
},
load: {
value: function load(container, target, viewStrategy) {
var _this = this;
var options;
viewStrategy = viewStrategy || ViewStrategy.getDefault(target);
options = {targetShadowDOM: this.targetShadowDOM};
if (!viewStrategy.moduleId) {
viewStrategy.moduleId = Origin.get(target).moduleId;
}
return viewStrategy.loadViewFactory(container.get(ViewEngine), options).then(function(viewFactory) {
_this.viewFactory = viewFactory;
return _this;
});
},
writable: true,
configurable: true
},
register: {
value: function register(registry, name) {
registry.registerElement(name || this.name, this);
},
writable: true,
configurable: true
},
compile: {
value: function compile(compiler, resources, node, instruction) {
if (!this.usesShadowDOM && node.hasChildNodes()) {
var fragment = document.createDocumentFragment(),
currentChild = node.firstChild,
nextSibling;
while (currentChild) {
nextSibling = currentChild.nextSibling;
fragment.appendChild(currentChild);
currentChild = nextSibling;
}
instruction.contentFactory = compiler.compile(fragment, resources);
}
instruction.suppressBind = true;
return node;
},
writable: true,
configurable: true
},
create: {
value: function create(container) {
var instruction = arguments[1] === undefined ? defaultInstruction : arguments[1];
var element = arguments[2] === undefined ? null : arguments[2];
var executionContext = instruction.executionContext || container.get(this.target),
behaviorInstance = new BehaviorInstance(this, executionContext, instruction),
host;
if (this.viewFactory) {
behaviorInstance.view = this.viewFactory.create(container, behaviorInstance.executionContext, instruction);
}
if (element) {
element.elementBehavior = behaviorInstance;
element.primaryBehavior = behaviorInstance;
if (behaviorInstance.view) {
if (this.usesShadowDOM) {
host = element.createShadowRoot();
} else {
host = element;
if (instruction.contentFactory) {
var contentView = instruction.contentFactory.create(container, null, contentSelectorFactoryOptions);
ContentSelector.applySelectors(contentView, behaviorInstance.view.contentSelectors, function(contentSelector, group) {
return contentSelector.add(group);
});
behaviorInstance.contentView = contentView;
}
}
if (this.childExpression) {
behaviorInstance.view.addBinding(this.childExpression.createBinding(host, behaviorInstance.executionContext));
}
behaviorInstance.view.appendNodesTo(host);
}
} else if (behaviorInstance.view) {
behaviorInstance.view.owner = behaviorInstance;
}
return behaviorInstance;
},
writable: true,
configurable: true
}
});
return CustomElement;
})(ResourceType));
}
};
});
System.register("github:aurelia/router@0.5.4/system/index", ["./router", "./app-router", "./pipeline-provider", "./navigation-commands", "./route-loading", "./router-configuration", "./navigation-plan"], function(_export) {
"use strict";
return {
setters: [function(_router) {
_export("Router", _router.Router);
}, function(_appRouter) {
_export("AppRouter", _appRouter.AppRouter);
}, function(_pipelineProvider) {
_export("PipelineProvider", _pipelineProvider.PipelineProvider);
}, function(_navigationCommands) {
_export("Redirect", _navigationCommands.Redirect);
}, function(_routeLoading) {
_export("RouteLoader", _routeLoading.RouteLoader);
}, function(_routerConfiguration) {
_export("RouterConfiguration", _routerConfiguration.RouterConfiguration);
}, function(_navigationPlan) {
_export("NO_CHANGE", _navigationPlan.NO_CHANGE);
_export("INVOKE_LIFECYCLE", _navigationPlan.INVOKE_LIFECYCLE);
_export("REPLACE", _navigationPlan.REPLACE);
}],
execute: function() {}
};
});
System.register("github:aurelia/http-client@0.4.4", ["github:aurelia/http-client@0.4.4/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/templating@0.8.8/system/property", ["./util", "aurelia-binding"], function(_export) {
"use strict";
var hyphenate,
ONE_WAY,
TWO_WAY,
ONE_TIME,
_inherits,
_prototypeProperties,
BehaviorProperty,
OptionsProperty,
BehaviorPropertyObserver;
return {
setters: [function(_util) {
hyphenate = _util.hyphenate;
}, function(_aureliaBinding) {
ONE_WAY = _aureliaBinding.ONE_WAY;
TWO_WAY = _aureliaBinding.TWO_WAY;
ONE_TIME = _aureliaBinding.ONE_TIME;
}],
execute: function() {
_inherits = function(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)
subClass.__proto__ = superClass;
};
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
BehaviorProperty = _export("BehaviorProperty", (function() {
function BehaviorProperty(name, changeHandler, attribute, defaultValue, defaultBindingMode) {
this.name = name;
this.changeHandler = changeHandler;
this.attribute = attribute || hyphenate(name);
this.defaultValue = defaultValue;
this.defaultBindingMode = defaultBindingMode || ONE_WAY;
}
_prototypeProperties(BehaviorProperty, null, {
bindingIsTwoWay: {
value: function bindingIsTwoWay() {
this.defaultBindingMode = TWO_WAY;
return this;
},
writable: true,
configurable: true
},
bindingIsOneWay: {
value: function bindingIsOneWay() {
this.defaultBindingMode = ONE_WAY;
return this;
},
writable: true,
configurable: true
},
bindingIsOneTime: {
value: function bindingIsOneTime() {
this.defaultBindingMode = ONE_TIME;
return this;
},
writable: true,
configurable: true
},
define: {
value: function define(taskQueue, behavior) {
var that = this,
handlerName;
this.taskQueue = taskQueue;
if (!this.changeHandler) {
handlerName = this.name + "Changed";
if (handlerName in behavior.target.prototype) {
this.changeHandler = handlerName;
}
}
behavior.properties.push(this);
behavior.attributes[this.attribute] = this;
Object.defineProperty(behavior.target.prototype, this.name, {
configurable: true,
enumerable: true,
get: function() {
return this.__observers__[that.name].getValue();
},
set: function(value) {
this.__observers__[that.name].setValue(value);
}
});
},
writable: true,
configurable: true
},
createObserver: {
value: function createObserver(executionContext) {
var _this = this;
var selfSubscriber = null;
if (this.changeHandler) {
selfSubscriber = function(newValue, oldValue) {
return executionContext[_this.changeHandler](newValue, oldValue);
};
}
return new BehaviorPropertyObserver(this.taskQueue, executionContext, this.name, selfSubscriber);
},
writable: true,
configurable: true
},
initialize: {
value: function initialize(executionContext, observerLookup, attributes, behaviorHandlesBind, boundProperties) {
var selfSubscriber,
observer,
attribute;
observer = observerLookup[this.name];
if (attributes !== undefined) {
selfSubscriber = observer.selfSubscriber;
attribute = attributes[this.attribute];
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === "string") {
executionContext[this.name] = attribute;
observer.call();
} else if (attribute) {
boundProperties.push({
observer: observer,
binding: attribute.createBinding(executionContext)
});
} else if (this.defaultValue) {
executionContext[this.name] = this.defaultValue;
observer.call();
}
observer.selfSubscriber = selfSubscriber;
}
observer.publishing = true;
},
writable: true,
configurable: true
}
});
return BehaviorProperty;
})());
OptionsProperty = _export("OptionsProperty", (function(BehaviorProperty) {
function OptionsProperty(attribute) {
for (var _len = arguments.length,
rest = Array(_len > 1 ? _len - 1 : 0),
_key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
if (typeof attribute === "string") {
this.attribute = attribute;
} else if (attribute) {
rest.unshift(attribute);
}
this.properties = rest;
this.hasOptions = true;
}
_inherits(OptionsProperty, BehaviorProperty);
_prototypeProperties(OptionsProperty, null, {
dynamic: {
value: function dynamic() {
this.isDynamic = true;
return this;
},
writable: true,
configurable: true
},
withProperty: {
value: function withProperty(name, changeHandler, attribute, defaultValue, defaultBindingMode) {
this.properties.push(new BehaviorProperty(name, changeHandler, attribute, defaultValue, defaultBindingMode));
return this;
},
writable: true,
configurable: true
},
define: {
value: function define(taskQueue, behavior) {
var i,
ii,
properties = this.properties;
this.attribute = this.attribute || behavior.name;
behavior.properties.push(this);
behavior.attributes[this.attribute] = this;
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i].define(taskQueue, behavior);
}
},
writable: true,
configurable: true
},
createObserver: {
value: function createObserver(executionContext) {},
writable: true,
configurable: true
},
initialize: {
value: function initialize(executionContext, observerLookup, attributes, behaviorHandlesBind, boundProperties) {
var value,
key,
info;
if (!this.isDynamic) {
return;
}
for (key in attributes) {
this.createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties);
}
},
writable: true,
configurable: true
},
createDynamicProperty: {
value: function createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) {
var changeHandlerName = name + "Changed",
selfSubscriber = null,
observer,
info;
if (changeHandlerName in executionContext) {
selfSubscriber = function(newValue, oldValue) {
return executionContext[changeHandlerName](newValue, oldValue);
};
}
observer = observerLookup[name] = new BehaviorPropertyObserver(this.taskQueue, executionContext, name, selfSubscriber);
Object.defineProperty(executionContext, name, {
configurable: true,
enumerable: true,
get: observer.getValue.bind(observer),
set: observer.setValue.bind(observer)
});
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === "string") {
executionContext[name] = attribute;
observer.call();
} else if (attribute) {
info = {
observer: observer,
binding: attribute.createBinding(executionContext)
};
boundProperties.push(info);
}
observer.publishing = true;
observer.selfSubscriber = selfSubscriber;
},
writable: true,
configurable: true
}
});
return OptionsProperty;
})(BehaviorProperty));
BehaviorPropertyObserver = (function() {
function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber) {
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.notqueued = true;
this.publishing = false;
this.selfSubscriber = selfSubscriber;
}
_prototypeProperties(BehaviorPropertyObserver, null, {
getValue: {
value: function getValue() {
return this.currentValue;
},
writable: true,
configurable: true
},
setValue: {
value: function setValue(newValue) {
var oldValue = this.currentValue;
if (oldValue != newValue) {
if (this.publishing && this.notqueued) {
this.notqueued = false;
this.taskQueue.queueMicroTask(this);
}
this.oldValue = oldValue;
this.currentValue = newValue;
}
},
writable: true,
configurable: true
},
call: {
value: function call() {
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.currentValue;
this.notqueued = true;
if (newValue != oldValue) {
if (this.selfSubscriber !== null) {
this.selfSubscriber(newValue, oldValue);
}
while (i--) {
callbacks[i](newValue, oldValue);
}
this.oldValue = newValue;
}
},
writable: true,
configurable: true
},
subscribe: {
value: function subscribe(callback) {
var callbacks = this.callbacks;
callbacks.push(callback);
return function() {
callbacks.splice(callbacks.indexOf(callback), 1);
};
},
writable: true,
configurable: true
}
});
return BehaviorPropertyObserver;
})();
}
};
});
System.register("github:aurelia/router@0.5.4", ["github:aurelia/router@0.5.4/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("dist/flickr", ["aurelia-http-client"], function(_export) {
"use strict";
var HttpClient,
_prototypeProperties,
_classCallCheck,
url,
Flickr;
return {
setters: [function(_aureliaHttpClient) {
HttpClient = _aureliaHttpClient.HttpClient;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
_classCallCheck = function(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=rainier&tagmode=any&format=json";
Flickr = _export("Flickr", (function() {
function Flickr(http) {
_classCallCheck(this, Flickr);
this.heading = "Flickr";
this.images = [];
this.http = http;
}
_prototypeProperties(Flickr, {inject: {
value: function inject() {
return [HttpClient];
},
writable: true,
configurable: true
}}, {
activate: {
value: function activate() {
var _this = this;
return this.http.jsonp(url).then(function(response) {
_this.images = response.content.items;
});
},
writable: true,
configurable: true
},
canDeactivate: {
value: function canDeactivate() {
return confirm("Are you sure you want to leave?");
},
writable: true,
configurable: true
}
});
return Flickr;
})());
}
};
});
System.register("github:aurelia/templating@0.8.8/system/index", ["aurelia-metadata", "./property", "./attached-behavior", "./children", "./custom-element", "./element-config", "./template-controller", "./view-strategy", "./resource-coordinator", "./resource-registry", "./view-compiler", "./view-engine", "./view-factory", "./view-slot", "./binding-language", "./composition-engine"], function(_export) {
"use strict";
var Metadata,
BehaviorProperty,
OptionsProperty,
AttachedBehavior,
ChildObserver,
CustomElement,
UseShadowDOM,
ElementConfig,
TemplateController,
UseView,
NoView,
Behavior;
return {
setters: [function(_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}, function(_property) {
BehaviorProperty = _property.BehaviorProperty;
OptionsProperty = _property.OptionsProperty;
_export("BehaviorProperty", _property.BehaviorProperty);
_export("OptionsProperty", _property.OptionsProperty);
}, function(_attachedBehavior) {
AttachedBehavior = _attachedBehavior.AttachedBehavior;
_export("AttachedBehavior", _attachedBehavior.AttachedBehavior);
}, function(_children) {
ChildObserver = _children.ChildObserver;
_export("ChildObserver", _children.ChildObserver);
}, function(_customElement) {
CustomElement = _customElement.CustomElement;
UseShadowDOM = _customElement.UseShadowDOM;
_export("CustomElement", _customElement.CustomElement);
_export("UseShadowDOM", _customElement.UseShadowDOM);
}, function(_elementConfig) {
ElementConfig = _elementConfig.ElementConfig;
_export("ElementConfig", _elementConfig.ElementConfig);
}, function(_templateController) {
TemplateController = _templateController.TemplateController;
_export("TemplateController", _templateController.TemplateController);
}, function(_viewStrategy) {
UseView = _viewStrategy.UseView;
NoView = _viewStrategy.NoView;
_export("ViewStrategy", _viewStrategy.ViewStrategy);
_export("UseView", _viewStrategy.UseView);
_export("ConventionalView", _viewStrategy.ConventionalView);
_export("NoView", _viewStrategy.NoView);
}, function(_resourceCoordinator) {
_export("ResourceCoordinator", _resourceCoordinator.ResourceCoordinator);
}, function(_resourceRegistry) {
_export("ResourceRegistry", _resourceRegistry.ResourceRegistry);
_export("ViewResources", _resourceRegistry.ViewResources);
}, function(_viewCompiler) {
_export("ViewCompiler", _viewCompiler.ViewCompiler);
}, function(_viewEngine) {
_export("ViewEngine", _viewEngine.ViewEngine);
}, function(_viewFactory) {
_export("ViewFactory", _viewFactory.ViewFactory);
_export("BoundViewFactory", _viewFactory.BoundViewFactory);
}, function(_viewSlot) {
_export("ViewSlot", _viewSlot.ViewSlot);
}, function(_bindingLanguage) {
_export("BindingLanguage", _bindingLanguage.BindingLanguage);
}, function(_compositionEngine) {
_export("CompositionEngine", _compositionEngine.CompositionEngine);
}],
execute: function() {
Behavior = _export("Behavior", Metadata);
Metadata.configure.classHelper("withProperty", BehaviorProperty);
Metadata.configure.classHelper("withOptions", OptionsProperty);
Metadata.configure.classHelper("attachedBehavior", AttachedBehavior);
Metadata.configure.classHelper("syncChildren", ChildObserver);
Metadata.configure.classHelper("customElement", CustomElement);
Metadata.configure.classHelper("useShadowDOM", UseShadowDOM);
Metadata.configure.classHelper("elementConfig", ElementConfig);
Metadata.configure.classHelper("templateController", TemplateController);
Metadata.configure.classHelper("useView", UseView);
Metadata.configure.classHelper("noView", NoView);
}
};
});
System.register("github:aurelia/templating-router@0.9.2/system/index", ["aurelia-router", "./route-loader", "./router-view"], function(_export) {
"use strict";
var Router,
AppRouter,
RouteLoader,
TemplatingRouteLoader,
RouterView;
function install(aurelia) {
aurelia.withSingleton(RouteLoader, TemplatingRouteLoader).withSingleton(Router, AppRouter).withResources(RouterView);
}
return {
setters: [function(_aureliaRouter) {
Router = _aureliaRouter.Router;
AppRouter = _aureliaRouter.AppRouter;
RouteLoader = _aureliaRouter.RouteLoader;
}, function(_routeLoader) {
TemplatingRouteLoader = _routeLoader.TemplatingRouteLoader;
}, function(_routerView) {
RouterView = _routerView.RouterView;
}],
execute: function() {
_export("TemplatingRouteLoader", TemplatingRouteLoader);
_export("RouterView", RouterView);
_export("install", install);
}
};
});
System.register("github:aurelia/templating@0.8.8", ["github:aurelia/templating@0.8.8/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/templating-router@0.9.2", ["github:aurelia/templating-router@0.9.2/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/framework@0.8.6/system/aurelia", ["aurelia-logging", "aurelia-dependency-injection", "aurelia-loader", "aurelia-templating", "./plugins"], function(_export) {
"use strict";
var LogManager,
Container,
Loader,
BindingLanguage,
ResourceCoordinator,
ViewSlot,
ResourceRegistry,
CompositionEngine,
Plugins,
_prototypeProperties,
logger,
slice,
CustomEvent,
Aurelia;
function loadResources(container, resourcesToLoad, appResources) {
var resourceCoordinator = container.get(ResourceCoordinator),
current;
function next() {
if (current = resourcesToLoad.shift()) {
return resourceCoordinator.importResources(current, current.resourceManifestUrl).then(function(resources) {
resources.forEach(function(x) {
return x.register(appResources);
});
return next();
});
}
return Promise.resolve();
}
return next();
}
return {
setters: [function(_aureliaLogging) {
LogManager = _aureliaLogging;
}, function(_aureliaDependencyInjection) {
Container = _aureliaDependencyInjection.Container;
}, function(_aureliaLoader) {
Loader = _aureliaLoader.Loader;
}, function(_aureliaTemplating) {
BindingLanguage = _aureliaTemplating.BindingLanguage;
ResourceCoordinator = _aureliaTemplating.ResourceCoordinator;
ViewSlot = _aureliaTemplating.ViewSlot;
ResourceRegistry = _aureliaTemplating.ResourceRegistry;
CompositionEngine = _aureliaTemplating.CompositionEngine;
}, function(_plugins) {
Plugins = _plugins.Plugins;
}],
execute: function() {
_prototypeProperties = function(child, staticProps, instanceProps) {
if (staticProps)
Object.defineProperties(child, staticProps);
if (instanceProps)
Object.defineProperties(child.prototype, instanceProps);
};
logger = LogManager.getLogger("aurelia");
slice = Array.prototype.slice;
if (!window.CustomEvent || typeof window.CustomEvent !== "function") {
CustomEvent = function(event, params) {
var params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
Aurelia = _export("Aurelia", (function() {
function Aurelia(loader, container, resources) {
this.loader = loader || Loader.createDefaultLoader();
this.container = container || new Container();
this.resources = resources || new ResourceRegistry();
this.resourcesToLoad = [];
this.use = new Plugins(this);
if (!this.resources.baseResourcePath) {
this.resources.baseResourcePath = System.baseUrl || "";
}
this.withInstance(Aurelia, this);
this.withInstance(Loader, this.loader);
this.withInstance(ResourceRegistry, this.resources);
}
_prototypeProperties(Aurelia, null, {
withInstance: {
value: function withInstance(type, instance) {
this.container.registerInstance(type, instance);
return this;
},
writable: true,
configurable: true
},
withSingleton: {
value: function withSingleton(type, implementation) {
this.container.registerSingleton(type, implementation);
return this;
},
writable: true,
configurable: true
},
withResources: {
value: function withResources(resources) {
var toAdd = Array.isArray(resources) ? resources : slice.call(arguments);
toAdd.resourceManifestUrl = this.currentPluginId;
this.resourcesToLoad.push(toAdd);
return this;
},
writable: true,
configurable: true
},
start: {
value: function start() {
var _this = this;
if (this.started) {
return Promise.resolve(this);
}
this.started = true;
logger.info("Aurelia Starting");
var resourcesToLoad = this.resourcesToLoad;
this.resourcesToLoad = [];
return this.use._process().then(function() {
if (!_this.container.hasHandler(BindingLanguage)) {
logger.error("You must configure Aurelia with a BindingLanguage implementation.");
}
_this.resourcesToLoad = _this.resourcesToLoad.concat(resourcesToLoad);
return loadResources(_this.container, _this.resourcesToLoad, _this.resources).then(function() {
logger.info("Aurelia Started");
var evt = new window.CustomEvent("aurelia-started", {
bubbles: true,
cancelable: true
});
document.dispatchEvent(evt);
return _this;
});
});
},
writable: true,
configurable: true
},
setRoot: {
value: function setRoot(root, applicationHost) {
var _this = this;
var compositionEngine,
instruction = {};
if (!applicationHost || typeof applicationHost == "string") {
this.host = document.getElementById(applicationHost || "applicationHost") || document.body;
} else {
this.host = applicationHost;
}
this.host.aurelia = this;
this.container.registerInstance(Element, this.host);
compositionEngine = this.container.get(CompositionEngine);
instruction.viewModel = root;
instruction.container = instruction.childContainer = this.container;
instruction.viewSlot = new ViewSlot(this.host, true);
instruction.viewSlot.transformChildNodesIntoView();
return compositionEngine.compose(instruction).then(function(root) {
_this.root = root;
instruction.viewSlot.attached();
var evt = new window.CustomEvent("aurelia-composed", {
bubbles: true,
cancelable: true
});
setTimeout(function() {
return document.dispatchEvent(evt);
}, 1);
return _this;
});
},
writable: true,
configurable: true
}
});
return Aurelia;
})());
}
};
});
System.register("github:aurelia/framework@0.8.6/system/index", ["./aurelia", "aurelia-dependency-injection", "aurelia-binding", "aurelia-metadata", "aurelia-templating", "aurelia-loader", "aurelia-task-queue", "aurelia-logging"], function(_export) {
"use strict";
var TheLogManager,
LogManager;
return {
setters: [function(_aurelia) {
_export("Aurelia", _aurelia.Aurelia);
}, function(_aureliaDependencyInjection) {
for (var _key in _aureliaDependencyInjection) {
_export(_key, _aureliaDependencyInjection[_key]);
}
}, function(_aureliaBinding) {
for (var _key2 in _aureliaBinding) {
_export(_key2, _aureliaBinding[_key2]);
}
}, function(_aureliaMetadata) {
for (var _key3 in _aureliaMetadata) {
_export(_key3, _aureliaMetadata[_key3]);
}
}, function(_aureliaTemplating) {
for (var _key4 in _aureliaTemplating) {
_export(_key4, _aureliaTemplating[_key4]);
}
}, function(_aureliaLoader) {
for (var _key5 in _aureliaLoader) {
_export(_key5, _aureliaLoader[_key5]);
}
}, function(_aureliaTaskQueue) {
for (var _key6 in _aureliaTaskQueue) {
_export(_key6, _aureliaTaskQueue[_key6]);
}
}, function(_aureliaLogging) {
TheLogManager = _aureliaLogging;
}],
execute: function() {
LogManager = _export("LogManager", TheLogManager);
}
};
});
System.register("github:aurelia/framework@0.8.6", ["github:aurelia/framework@0.8.6/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("github:aurelia/bootstrapper@0.9.3/system/index", ["aurelia-loader-default", "aurelia-framework", "aurelia-logging-console"], function(_export) {
"use strict";
var DefaultLoader,
Aurelia,
LogManager,
ConsoleAppender,
logger,
readyQueue,
isReady;
_export("bootstrap", bootstrap);
function onReady(callback) {
return new Promise(function(resolve, reject) {
if (!isReady) {
readyQueue.push(function() {
try {
resolve(callback());
} catch (e) {
reject(e);
}
});
} else {
resolve(callback());
}
});
}
function bootstrap(configure) {
return onReady(function() {
var loader = new DefaultLoader(),
aurelia = new Aurelia(loader);
return configureAurelia(aurelia).then(function() {
return configure(aurelia);
});
});
}
function ready(global) {
return new Promise(function(resolve, reject) {
var completed = function() {
global.document.removeEventListener("DOMContentLoaded", completed, false);
global.removeEventListener("load", completed, false);
resolve(global.document);
};
if (global.document.readyState === "complete") {
resolve(global.document);
} else {
global.document.addEventListener("DOMContentLoaded", completed, false);
global.addEventListener("load", completed, false);
}
});
}
function loadPolyfills() {
return System.normalize("aurelia-bootstrapper").then(function(bootstrapperName) {
return System.normalize("aurelia-framework", bootstrapperName).then(function(frameworkName) {
System.map["aurelia-framework"] = frameworkName;
return System.normalize("aurelia-loader", frameworkName).then(function(loaderName) {
var toLoad = [];
if (!System.polyfilled) {
logger.debug("loading core-js");
toLoad.push(System.normalize("core-js", loaderName).then(function(name) {
return System["import"](name);
}));
}
toLoad.push(System.normalize("aurelia-depedency-injection", frameworkName).then(function(name) {
System.map["aurelia-depedency-injection"] = name;
}));
toLoad.push(System.normalize("aurelia-router", bootstrapperName).then(function(name) {
System.map["aurelia-router"] = name;
}));
toLoad.push(System.normalize("aurelia-logging-console", bootstrapperName).then(function(name) {
System.map["aurelia-logging-console"] = name;
}));
if (!("import" in document.createElement("link"))) {
logger.debug("loading the HTMLImports polyfill");
toLoad.push(System.normalize("webcomponentsjs/HTMLImports.min", loaderName).then(function(name) {
return System["import"](name);
}));
}
if (!("content" in document.createElement("template"))) {
logger.debug("loading the HTMLTemplateElement polyfill");
toLoad.push(System.normalize("aurelia-html-template-element", loaderName).then(function(name) {
return System["import"](name);
}));
}
return Promise.all(toLoad);
});
});
});
}
function configureAurelia(aurelia) {
return System.normalize("aurelia-bootstrapper").then(function(bName) {
var toLoad = [];
toLoad.push(System.normalize("aurelia-templating-binding", bName).then(function(templatingBinding) {
aurelia.use.defaultBindingLanguage = function() {
aurelia.use.plugin(templatingBinding);
return this;
};
}));
toLoad.push(System.normalize("aurelia-history-browser", bName).then(function(historyBrowser) {
return System.normalize("aurelia-templating-router", bName).then(function(templatingRouter) {
aurelia.use.router = function() {
aurelia.use.plugin(historyBrowser);
aurelia.use.plugin(templatingRouter);
return this;
};
});
}));
toLoad.push(System.normalize("aurelia-templating-resources", bName).then(function(name) {
System.map["aurelia-templating-resources"] = name;
aurelia.use.defaultResources = function() {
aurelia.use.plugin(name);
return this;
};
}));
toLoad.push(System.normalize("aurelia-event-aggregator", bName).then(function(eventAggregator) {
System.map["aurelia-event-aggregator"] = eventAggregator;
aurelia.use.eventAggregator = function() {
aurelia.use.plugin(eventAggregator);
return this;
};
}));
return Promise.all(toLoad);
});
}
function handleMain(mainHost) {
var mainModuleId = mainHost.getAttribute("aurelia-main") || "main",
loader = new DefaultLoader();
return loader.loadModule(mainModuleId).then(function(m) {
var aurelia = new Aurelia(loader);
return configureAurelia(aurelia).then(function() {
return m.configure(aurelia);
});
})["catch"](function(e) {
setTimeout(function() {
throw e;
}, 0);
});
}
function handleApp(appHost) {
var appModuleId = appHost.getAttribute("aurelia-app") || "app",
aurelia = new Aurelia();
return configureAurelia(aurelia).then(function() {
aurelia.use.defaultBindingLanguage().defaultResources().router().eventAggregator();
if (appHost.hasAttribute("es5")) {
aurelia.use.es5();
} else if (appHost.hasAttribute("atscript")) {
aurelia.use.atscript();
}
return aurelia.start().then(function(a) {
return a.setRoot(appModuleId, appHost);
});
})["catch"](function(e) {
setTimeout(function() {
throw e;
}, 0);
});
}
function runningLocally() {
return window.location.protocol !== "http" && window.location.protocol !== "https";
}
function run() {
return ready(window).then(function(doc) {
var mainHost = doc.querySelectorAll("[aurelia-main]"),
appHost = doc.querySelectorAll("[aurelia-app]"),
i,
ii;
if (appHost.length && !mainHost.length && runningLocally()) {
LogManager.addAppender(new ConsoleAppender());
LogManager.setLevel(LogManager.levels.debug);
}
return loadPolyfills().then(function() {
for (i = 0, ii = mainHost.length; i < ii; ++i) {
handleMain(mainHost[i]);
}
for (i = 0, ii = appHost.length; i < ii; ++i) {
handleApp(appHost[i]);
}
isReady = true;
for (i = 0, ii = readyQueue.length; i < ii; ++i) {
readyQueue[i]();
}
readyQueue = [];
});
});
}
return {
setters: [function(_aureliaLoaderDefault) {
DefaultLoader = _aureliaLoaderDefault.DefaultLoader;
}, function(_aureliaFramework) {
Aurelia = _aureliaFramework.Aurelia;
LogManager = _aureliaFramework.LogManager;
}, function(_aureliaLoggingConsole) {
ConsoleAppender = _aureliaLoggingConsole.ConsoleAppender;
}],
execute: function() {
logger = LogManager.getLogger("bootstrapper");
readyQueue = [];
isReady = false;
run();
}
};
});
System.register("github:aurelia/bootstrapper@0.9.3", ["github:aurelia/bootstrapper@0.9.3/system/index"], function($__export) {
return {
setters: [function(m) {
for (var p in m)
$__export(p, m[p]);
}],
execute: function() {}
};
});
System.register("dist/bundle", ["aurelia-bootstrapper", "aurelia-templating-binding", "aurelia-templating-router", "aurelia-templating-resources", "aurelia-event-aggregator", "aurelia-router", "aurelia-history", "aurelia-history-browser", "./nav-bar", "./app", "./child-router", "./flickr", "./welcome"], function(_export) {
"use strict";
return {
setters: [function(_aureliaBootstrapper) {}, function(_aureliaTemplatingBinding) {}, function(_aureliaTemplatingRouter) {}, function(_aureliaTemplatingResources) {}, function(_aureliaEventAggregator) {}, function(_aureliaRouter) {}, function(_aureliaHistory) {}, function(_aureliaHistoryBrowser) {}, function(_navBar) {}, function(_app) {}, function(_childRouter) {}, function(_flickr) {}, function(_welcome) {}],
execute: function() {}
};
});
System.register("dist/main", ["./bundle", "aurelia-framework", "aurelia-logging-console", "aurelia-bootstrapper"], function(_export) {
"use strict";
var LogManager,
ConsoleAppender,
bootstrap;
return {
setters: [function(_bundle) {}, function(_aureliaFramework) {
LogManager = _aureliaFramework.LogManager;
}, function(_aureliaLoggingConsole) {
ConsoleAppender = _aureliaLoggingConsole.ConsoleAppender;
}, function(_aureliaBootstrapper) {
bootstrap = _aureliaBootstrapper.bootstrap;
}],
execute: function() {
LogManager.addAppender(new ConsoleAppender());
LogManager.setLevel(LogManager.levels.debug);
bootstrap(function(aurelia) {
aurelia.use.defaultBindingLanguage().defaultResources().router().eventAggregator();
aurelia.start().then(function(a) {
return a.setRoot("dist/app", document.body);
});
});
}
};
});
//# sourceMappingURL=bundled.js.map |
VCO.Language = {
name: "Italiano",
lang: "it",
messages: {
loading: "caricare",
wikipedia: "da Wikipedia, la enciclopedia libera",
},
buttons: {
map_overview: "vista generale della mappa",
overview: "vista generale",
backtostart: "tornare all' inizio",
collapse_toggle: "nascondere mappa",
uncollapse_toggle: "mostrare mappa"
}
};
|
// TAG: #notificationhubjs
//
// This object encapsulates the functions related to registering for notifications with the
// Azure Notification Hub. The client app code has been encapsulated here for ease of re-use.
// This object is used by the default.js file during app start-up to ensure notification registration has been successful
//
// General flow:
// 1) look to see if we have a previous channel URI saved in localSettings
// 2) retrieve the current/latest channel URI
// 3) if we didn't have a saved URI, or the URI has changed, re-register with the notification hub
// a) get a device ID for the current channel URI
// b) using the device ID, register the app for notifications
// c) save the updated channel URI for the next app launch
var uwpNotifications = {
// this function gets the channel URI, compares it to a cached version
// and if it has changed will call an API to re-register the application
// to recieve notifications
registerChannelURI: function(){
// check and see if we have a saved ChannelURI
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
var savedChannelURI = localSettings.values["WNSChannelURI"];
savedChannelURI = "re-register"; // uncomment this line to force re-registration every time the app runs
// get current channel URI for notifications
var pushNotifications = Windows.Networking.PushNotifications;
var channelOperation = pushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync();
// get current channel URI and check against saved URI
channelOperation.then(function (newChannel) {
return newChannel.uri;
}).then(function (currentChannelURI) {
// if we don't have a saved URI, or its changed, re-register with Notification Hub
if (!savedChannelURI || savedChannelURI.toLowerCase() != currentChannelURI.toLowerCase()) {
console.log("Channel URI has changed, need to register it with notification hub");
// get a Notification Hub registration ID via the API
WinJS.xhr({
type: "post",
url: "http://localhost:7521/api/register",
headers: { "Content-type": "application/x-www-form-urlencoded" },
responseType: "text",
data: "channeluri=" + currentChannelURI.toLowerCase()
}).then(function (getIdSuccess) {
// strip the double quotes off the string, we don't want those
var deviceId = getIdSuccess.responseText.replace(/['"]/g, '');
console.log("Device ID is: " + deviceId);
// create object for notification hub device registration
// tag values used are arbitrary and could be supplemented by any
// assigned on the server side
var registrationpayload = {
"deviceid" : deviceId,
"platform" : "wns",
"handle" : currentChannelURI,
"tags" : ["tag1", "tag2"]
};
// update the registration
WinJS.xhr({
type: "put",
url: "http://localhost:7521/api/register/",
headers: { "Content-type": "application/json" },
data: JSON.stringify(registrationpayload)
}).then(
function (registerSuccess) {
console.log("Device successfully registered");
// save/update channel URI for next app launch
localSettings.values["WNSChannelURI"] = currentChannelURI;
},
function (error) {
console.log(JSON.parse(error.responseText));
}
).done();
},
function (error) {
console.log(JSON.parse(error.responseText));
}
).done();
}
}).done();
}
}; |
/*
* gaunt
* https://github.com/dariusk/gaunt
*
* Copyright (c) 2013 Darius Kazemi
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(data) {
var result = '',
output = '';
for (var i=0; i<data.length; i++) {
if (data.charCodeAt(i) === 9) {
result += '0';
}
if (data.charCodeAt(i) === 32) {
result += '1';
}
}
result = result.match(/.{1,8}/g);
for (i=0; i<result.length; i++) {
output += String.fromCharCode(parseInt(result[i], 2));
}
return output;
};
|
import angular from 'angular';
import { UsersModule } from './users/users.module';
import { InstitutionsModule } from './institutions/institutions.module';
import { ProjectsModule } from './projects/projects.module';
import { CollectivesModule } from './collectives/collectives.module';
import { GeneralTopicsModule } from './general-topics/general-topics.module';
import { SpecificTopicsModule } from './specific-topics/specific-topics.module';
import { ContentTypesModule } from './content-types/content-types.module';
export const AdminPanelModule = angular
.module('co-file-manager-client.admin-panel', [
UsersModule,
InstitutionsModule,
ProjectsModule,
CollectivesModule,
GeneralTopicsModule,
SpecificTopicsModule,
ContentTypesModule
])
.name; |
import React from 'react';
import ReactDOM from 'react-dom';
// import ReactTestUtils from 'react-dom/test-utils';
import { shallow, mount } from 'enzyme';
// import renderer from 'react-test-renderer';
import NavButton from '.';
describe('NavButton', () => {
let props;
let mountedNavButton;
let shallowNavButton;
const navButton = () => {
if (!mountedNavButton) {
mountedNavButton = mount(
<NavButton {...props} />
);
}
return mountedNavButton;
};
const navButtonShallow = () => {
if (!shallowNavButton) {
shallowNavButton = shallow(
<NavButton {...props} />
);
}
return shallowNavButton;
};
const onClick=() => {};
beforeEach(() => {
props = {
onClick: onClick,
icon: 'fa fa-arrow-up'
};
mountedNavButton = undefined;
});
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<NavButton {...props} />, div);
});
it('renders shallow', () => {
navButtonShallow(props);
});
/** Just an example, normally props should not be tested, as they
are already covered by PropTypes. */
/* it('allows us to set props', () => {
const onClick = () => console.log('onClick() fired');
const wrapper = mount(
<NavButton
onClick={onClick}
propOne="foo"
/>);
expect(wrapper.props().propOne).toEqual('foo');
wrapper.setProps({ propOne: 'bonka' });
expect(wrapper.props().propOne).toEqual('bonka');
}); */
it('always renders a div', () => {
const renderedTag = navButton(props).find('NavButton');
expect(renderedTag.length).toBe(1);
});
/* it('handles click events', () => {
NavButton.prototype.onClick = jest.fn();
const mockClick = NavButton.prototype.onClick;
const wrapper = mount((
<NavButton {...props }/
));
wrapper.find('button').simulate('click');
expect(mockClick).toHaveBeenCalled();
}); */
}); |
var path = require('path');
var fs = require('fs');
var util = require('util');
var colors = require('colors');
var uploader = require('../lib/uploader.js').uploader;
var helper = require('../lib/helper.js');
var keypress = require('keypress');
keypress(process.stdin);
// 上传模式
var modes = {
// 1: '自动监听', // 2015-04-14 自动监听模式修改,不再走这里逻辑
2: '指定文件(夹)',
10: '默认上传'
};
// 支持上传的文件类型
var types = {
'js': /\.(js|json)$/,
'css': /\.css$/,
'java': /\.(jsp|xml)$/,
'img': /\.(jpg|png|gif)$/,
'html': /\.html$/,
'all': /.+/
};
module.exports = function(grunt) {
// project: 项目
// type: 文件类型, 不传或默认为所有
// files: 具体的文件或者目录
// env: 上传环境。
grunt.registerTask('upload', 'upload files', function(project, type, files, env) {
if (type && !types[type]) {
helper.log(' 指定文件类型 ' + sfiles + ' 不能被识别, 请再确认', 'fail');
return;
}
var index = 0; // 共需上传文件数
var completing = 0; // 已经上传成功的
var done = this.async();
var oriType = type;
var config = helper.projectify(project, type, grunt);
env = env || config.env;
project = config.project;
type = config.type;
var uploadinfo = helper.get_upload_info(config, grunt);
var cdn_root = uploadinfo.cdn_root;
var environment = this.options()['environment'][env];
var sfiles = null; // 需要上传的目标文件(夹)
var mode = 0;
if (files) { // 指定文件或目录形式
sfiles = path.normalize(config.path + files);
mode = 2;
type = oriType || 'all'; // 指定文件目录默认为所有文件,除非命令行指名。
} else { // 默认 Gruntfile.js 中配置的 upload_dir
sfiles = uploadinfo.upload_dir;
mode = 10;
}
if (!fs.existsSync(sfiles)) {
helper.log();
helper.log(' 指定文件 ' + sfiles + ' 不存在, 请再确认', 'fail');
helper.log();
done(false);
return;
}
helper.log();
helper.log(' 启动模式: ' + (modes[mode]).green.underline);
helper.log(' 上传目标环境: ' + env.green.underline);
helper.log(' CDN根目录: ' + cdn_root.green.underline);
helper.log(' 源文件目录: ' + sfiles.green.underline);
helper.log(' 资源类型: ' + (type).green.underline);
helper.log();
var fstat = fs.statSync(sfiles);
if (fstat.isFile()) {
index = 1;
cdn_root = cdn_root.replace(config.path, '');
uploader(helper.extend({
fullpath: sfiles,
cdn_path: cdn_root + path.dirname(sfiles) + '/'
}, environment), callback);
} else if (fstat.isDirectory()) {
if (mode === 2) {
// 如果是指定文件夹上传,这里需要修改 cdn_root;
cdn_root = path.normalize(cdn_root + files + '/');
}
run(sfiles);
}
function run(dir) {
if (!dir || !fs.existsSync(dir)) {
helper.log(' 传目录 ' + dir + ' 传递有误, 请再确认', 'fail');
done(false);
return;
}
// 防止没找到文件任务超时.
setTimeout(function() {
if (!index) {
helper.log(' 未找到对应文件, 任务执行结束 ❕');
done(true);
}
}, 300);
grunt.file.recurse(dir, function(abspath, rootdir, subdir, filename) {
if (!keepgoing(type, filename)) {
return true;
}
if (!subdir) {
subdir = '';
}
index = index + 1;
uploader(helper.extend({
fullpath: abspath,
cdn_path: path.normalize(cdn_root + subdir + '/')
}, environment), callback);
});
}
function callback(o) {
completing++;
helper.log(helper.pretty(o.fullpath), (o.response.statusCode == 200) ? 'success' : 'fail');
completing === index && done(true);
}
function keepgoing(type, filename) {
return (type && types[type].test(filename)) ? true : false;
}
});
};
|
'use strict';
var Promise = require('ember-cli/lib/ext/promise');
var assert = require('ember-cli/tests/helpers/assert');
var WEBHOOK_URL = 'https://hooks.slack.com/services/123123';
var CHANNEL = '#testing';
var USER_NAME = 'ember-cli-deploy';
describe('the index', function() {
var subject, mockUi, sandbox;
beforeEach(function() {
subject = require('../../index');
mockUi = {
messages: [],
write: function() { },
writeLine: function(message) {
this.messages.push(message);
}
};
});
it('has a name', function() {
var result = subject.createDeployPlugin({
name: 'test-plugin'
});
assert.equal(result.name, 'test-plugin');
});
it('implements the correct hooks', function() {
var plugin = subject.createDeployPlugin({
name: 'test-plugin'
});
assert.typeOf(plugin.configure, 'function');
assert.typeOf(plugin.willDeploy, 'function');
assert.typeOf(plugin.willBuild, 'function');
assert.typeOf(plugin.build, 'function');
assert.typeOf(plugin.didBuild, 'function');
assert.typeOf(plugin.willUpload, 'function');
assert.typeOf(plugin.upload, 'function');
assert.typeOf(plugin.didUpload, 'function');
assert.typeOf(plugin.willActivate, 'function');
assert.typeOf(plugin.activate, 'function');
assert.typeOf(plugin.didActivate, 'function');
assert.typeOf(plugin.didDeploy, 'function');
assert.typeOf(plugin.didFail, 'function');
});
describe('configure hook', function() {
it('resolves if config is ok', function() {
var plugin = subject.createDeployPlugin({
name: 'slack'
});
var context = {
ui: mockUi,
config: {
slack: {
webhookURL: 'http://foo/bar'
}
}
};
plugin.beforeHook(context);
plugin.configure(context);
assert.ok(true); // it didn't throw
});
it('throws if require config is missing', function() {
var plugin = subject.createDeployPlugin({
name: 'slack'
});
var context = {
ui: mockUi,
config: {
slack: {
}
}
};
plugin.beforeHook(context);
plugin.configure(context);
assert.throws(function(){
plugin.didDeploy(context);
})
});
it('warns about missing optional config', function() {
var plugin = subject.createDeployPlugin({
name: 'slack'
});
var context = {
ui: mockUi,
config: {
slack: {
webhookURL: 'http://foo/bar'
}
}
};
mockUi.verbose = true;
plugin.beforeHook(context);
plugin.configure(context);
var messages = mockUi.messages.reduce(function(previous, current) {
if (/- Missing config:\s.*, using default:\s/.test(current)) {
previous.push(current);
}
return previous;
}, []);
assert.equal(messages.length, 4);
});
it('adds default config to the config object', function() {
var plugin = subject.createDeployPlugin({
name: 'slack'
});
var context = {
ui: mockUi,
config: {
"slack": {
webhookURL: 'http://foo/bar'
}
}
};
plugin.beforeHook(context);
plugin.configure(context);
assert.isDefined(context.config['slack'].willDeploy);
assert.isDefined(context.config['slack'].didDeploy);
assert.isDefined(context.config['slack'].didFail);
});
});
describe('didDeploy hook', function() {
it('notifies slack', function() {
var plugin = subject.createDeployPlugin({
name: 'slack'
});
var slackMessages = [];
var context = {
slackStartDeployDate: new Date(),
ui: mockUi,
config: {
"slack": {
webhookURL: 'http://foo/bar',
slackNotifier: {
notify: function(message){
slackMessages.push(message);
return Promise.resolve();
}
}
}
}
};
plugin.beforeHook(context);
plugin.configure(context);
return assert.isFulfilled(plugin.didDeploy(context))
.then(function(result) {
assert.equal(slackMessages.length, 1);
});
});
});
});
|
import { name, actionTypes } from './constants';
import * as actions from './actions';
import { reducers } from './reducer';
// re-select
// import * as selectors from './selectors'
import MainSection from './components/MainSection';
export {
name,
actionTypes,
actions,
reducers,
// sagas,
MainSection,
};
|
'use strict';
/**
* @ngdoc function
* @name habilleToiApp.controller:HomeCtrl
* @description
* # HomeCtrl
* Controller of the habilleToiApp
*/
angular.module('habilleToiApp')
.controller('HomeCtrl', function () {
});
|
var Student = require('../models/students');
var express = require('express');
var router = express.Router();
var utils = require('../utils');
var async = require('async');
var passport = require('passport');
var _ = require('lodash');
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: true, colorize: true, dumpExceptions: true, showStack: true, timestamp: true })
]
});
router.route('/v1/students')
.post(function(req, res) {
var student = new Student(req.body.student);
student.save(function (err, obj) {
if(err)
res.send(err);
obj._id = undefined;
obj.__v = undefined;
var data = {
"student": obj,
"meta": {
"href": process.env.API_URL + '/api/v1/students/' + obj.id
}
}
var newUserLog = {message: "Student Created", newUsername: obj.username, student: obj._doc}
logger.info(newUserLog);
res.json(data);
});
})
.put(function(req, res) {
Student.findOne({nameId: req.body.student.nameId}, function (err, stu) {
if (stu) {
var shouldUpdate = false;
if (String(stu.studentNumber) == String(req.body.student.studentNumber) && String(stu.firstName) == String(req.body.student.firstName)
&& String(stu.middleName) == String(req.body.student.middleName) && String(stu.lastName) == String(req.body.student.lastName)
&& String(stu.buildingStateCode) == String(req.body.student.buildingStateCode) && String(stu.enrollStatus) == String(req.body.student.enrollStatus)
&& String(stu.gradeLevel) == String(req.body.student.gradeLevel) && String(stu.username) == String(req.body.student.username)) {
req.body.student.refreshAccount = false;
} else {
req.body.student.refreshAccount = true;
shouldUpdate = true;
}
var now = new Date().getTime();
req.body.student.updatedAt = now;
Student.findOneAndUpdate({nameId: req.body.student.nameId}, {$set: req.body.student}, {new: true}, function(err,student) {
if (err)
res.send(err);
if (student) {
student._id = undefined;
student.__v = undefined;
var data = {
"student": student,
"meta": {
"href": process.env.API_URL + '/api/v1/students/' + stu.id
}
}
if(shouldUpdate) {
var differentValues = _.differenceWith(_.toPairs(req.body.student), _.toPairs(stu._doc), _.isMatch);
var differentComparison = {message: "Student Changed", changedUsername: stu.username, student: student._doc}
_.forEach(differentValues, function(values){
if(values[0] in stu._doc && values[0] in req.body.student) {
differentComparison[values[0]] = {
old: stu._doc[values[0]],
new: req.body.student[values[0]]
};
}
});
logger.info(differentComparison);
}
res.send(data);
} else {
res.send(404,JSON.stringify({"error": "studentNotFound"}));
}
});
} else {
req.body.student.refreshAccount = true;
var student = new Student(req.body.student);
student.save(function (err, obj) {
if(err)
res.send(err);
obj._id = undefined;
obj.__v = undefined;
var newUserLog = {message: "Student Created", newUsername: obj.username, student: obj._doc}
logger.info(newUserLog);
var data = {
"student": obj,
"meta": {
"href": process.env.API_URL + '/api/v1/students/' + obj.id
}
}
res.json(data);
});
}
});
})
.get(function(req, res) {
var qString = req.query;
if (qString.ids) {
var queryOne = Student.find({ id: { $in: qString.ids } });
var queryTwo = Student.find({ id: { $in: qString.ids } });
} else if (qString.stunum) {
var queryOne = Student.find({ studentNumber: qString.stunum });
var queryTwo = Student.find({ studentNumber: qString.stunum });
} else if (qString.refresh) {
var queryOne = Student.find({ refreshAccount: qString.refresh });
var queryTwo = Student.find({ refreshAccount: qString.refresh });
} else {
var queryOne = Student.find({});
var queryTwo = Student.find({});
}
var limit = utils.setLimit(req.query.limit);
var offset = utils.setOffset(req.query.offset);
async.parallel({
count: function(callback){
queryOne.count(function(err, count) {
callback(null, count);
});
},
records: function(callback){
if(req.user.user_type == "Administrator") {
queryTwo.skip(offset).select('-_id -__v -salt -hash').limit(limit).exec('find', function(err, items) {
callback(null, items);
});
} else {
queryTwo.skip(offset).select('-_id id firstName lastName buildingName buildingStateCode username gradeLevel pictureUrl').limit(limit).exec('find', function(err, items) {
callback(null, items);
});
}
}
},
function(err, results) {
if(err)
res.send(err);
if (results) {
var next = utils.pageNext(offset,limit,results.count,'students');
var prev = utils.pagePrev(offset,limit,results.count,'students');
var data = {
"student": results.records,
"meta": {
"total": results.count,
"offset": offset,
"limit": limit,
"href": process.env.API_URL + '/api/v1/students?offset=' + offset + '&limit=' + limit,
"next": next,
"previous": prev
}
}
res.json(data);
} else {
res.send(404,JSON.stringify({"error": "studentsNotFound"}));
}
});
})
router.route('/v1/students/:id')
.get(function(req, res) {
Student.findOne({id: req.params.id}, function(err, obj) {
if (err)
res.send(err);
if (obj) {
obj._id = undefined;
obj.__v = undefined;
if(req.user.user_type != "Administrator") {
obj = {
id: obj.id,
username: obj.username,
firstName: obj.firstName,
lastName: obj.lastName,
buildingName: obj.buildingName,
buildingStateCode: obj.buildingStateCode,
gradeLevel: obj.gradeLevel,
pictureUrl: obj.pictureUrl
};
}
var data = {
"student": obj,
"meta": {
"href": process.env.API_URL + '/api/v1/students/' + req.params.id
}
}
res.json(data);
} else {
res.send(404,JSON.stringify({"error": "studentNotFound"}));
}
});
})
.put(function(req, res) {
var now = new Date().getTime();
req.body.student.updatedAt = now;
Student.findOneAndUpdate({id: req.params.id}, {$set: req.body.student}, {new: true}, function(err,student) {
if (err)
res.send(err);
if (student) {
student._id = undefined;
student.__v = undefined;
var data = {
"student": student,
"meta": {
"href": process.env.API_URL + '/api/v1/students/' + req.params.id
}
}
res.send(data);
} else {
res.send(404,JSON.stringify({"error": "studentNotFound"}));
}
});
})
.delete(function(req, res) {
Student.remove({id: req.params.id}, function(err, student) {
if (err)
res.send(err);
res.json(student);
});
});
module.exports = router;
|
import { q as isTemplatePartActive, p as parts, k as render$1, t as templateCaches, v as marker, u as Template, T as TemplateInstance, r as removeNodes, m as TemplateResult } from './common/lit-html-9957b87e.js';
export { S as SVGTemplateResult, m as TemplateResult, h as html, s as svg } from './common/lit-html-9957b87e.js';
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
const walkerNodeFilter = 133 /* NodeFilter.SHOW_{ELEMENT|COMMENT|TEXT} */;
/**
* Removes the list of nodes from a Template safely. In addition to removing
* nodes from the Template, the Template part indices are updated to match
* the mutated Template DOM.
*
* As the template is walked the removal state is tracked and
* part indices are adjusted as needed.
*
* div
* div#1 (remove) <-- start removing (removing node is div#1)
* div
* div#2 (remove) <-- continue removing (removing node is still div#1)
* div
* div <-- stop removing since previous sibling is the removing node (div#1,
* removed 4 nodes)
*/
function removeNodesFromTemplate(template, nodesToRemove) {
const { element: { content }, parts } = template;
const walker = document.createTreeWalker(content, walkerNodeFilter, null, false);
let partIndex = nextActiveIndexInTemplateParts(parts);
let part = parts[partIndex];
let nodeIndex = -1;
let removeCount = 0;
const nodesToRemoveInTemplate = [];
let currentRemovingNode = null;
while (walker.nextNode()) {
nodeIndex++;
const node = walker.currentNode;
// End removal if stepped past the removing node
if (node.previousSibling === currentRemovingNode) {
currentRemovingNode = null;
}
// A node to remove was found in the template
if (nodesToRemove.has(node)) {
nodesToRemoveInTemplate.push(node);
// Track node we're removing
if (currentRemovingNode === null) {
currentRemovingNode = node;
}
}
// When removing, increment count by which to adjust subsequent part indices
if (currentRemovingNode !== null) {
removeCount++;
}
while (part !== undefined && part.index === nodeIndex) {
// If part is in a removed node deactivate it by setting index to -1 or
// adjust the index as needed.
part.index = currentRemovingNode !== null ? -1 : part.index - removeCount;
// go to the next active part.
partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
part = parts[partIndex];
}
}
nodesToRemoveInTemplate.forEach((n) => n.parentNode.removeChild(n));
}
const countNodes = (node) => {
let count = (node.nodeType === 11 /* Node.DOCUMENT_FRAGMENT_NODE */) ? 0 : 1;
const walker = document.createTreeWalker(node, walkerNodeFilter, null, false);
while (walker.nextNode()) {
count++;
}
return count;
};
const nextActiveIndexInTemplateParts = (parts, startIndex = -1) => {
for (let i = startIndex + 1; i < parts.length; i++) {
const part = parts[i];
if (isTemplatePartActive(part)) {
return i;
}
}
return -1;
};
/**
* Inserts the given node into the Template, optionally before the given
* refNode. In addition to inserting the node into the Template, the Template
* part indices are updated to match the mutated Template DOM.
*/
function insertNodeIntoTemplate(template, node, refNode = null) {
const { element: { content }, parts } = template;
// If there's no refNode, then put node at end of template.
// No part indices need to be shifted in this case.
if (refNode === null || refNode === undefined) {
content.appendChild(node);
return;
}
const walker = document.createTreeWalker(content, walkerNodeFilter, null, false);
let partIndex = nextActiveIndexInTemplateParts(parts);
let insertCount = 0;
let walkerIndex = -1;
while (walker.nextNode()) {
walkerIndex++;
const walkerNode = walker.currentNode;
if (walkerNode === refNode) {
insertCount = countNodes(node);
refNode.parentNode.insertBefore(node, refNode);
}
while (partIndex !== -1 && parts[partIndex].index === walkerIndex) {
// If we've inserted the node, simply adjust all subsequent parts
if (insertCount > 0) {
while (partIndex !== -1) {
parts[partIndex].index += insertCount;
partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
}
return;
}
partIndex = nextActiveIndexInTemplateParts(parts, partIndex);
}
}
}
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
// Get a key to lookup in `templateCaches`.
const getTemplateCacheKey = (type, scopeName) => `${type}--${scopeName}`;
let compatibleShadyCSSVersion = true;
if (typeof window.ShadyCSS === 'undefined') {
compatibleShadyCSSVersion = false;
}
else if (typeof window.ShadyCSS.prepareTemplateDom === 'undefined') {
console.warn(`Incompatible ShadyCSS version detected. ` +
`Please update to at least @webcomponents/webcomponentsjs@2.0.2 and ` +
`@webcomponents/shadycss@1.3.1.`);
compatibleShadyCSSVersion = false;
}
/**
* Template factory which scopes template DOM using ShadyCSS.
* @param scopeName {string}
*/
const shadyTemplateFactory = (scopeName) => (result) => {
const cacheKey = getTemplateCacheKey(result.type, scopeName);
let templateCache = templateCaches.get(cacheKey);
if (templateCache === undefined) {
templateCache = {
stringsArray: new WeakMap(),
keyString: new Map()
};
templateCaches.set(cacheKey, templateCache);
}
let template = templateCache.stringsArray.get(result.strings);
if (template !== undefined) {
return template;
}
const key = result.strings.join(marker);
template = templateCache.keyString.get(key);
if (template === undefined) {
const element = result.getTemplateElement();
if (compatibleShadyCSSVersion) {
window.ShadyCSS.prepareTemplateDom(element, scopeName);
}
template = new Template(result, element);
templateCache.keyString.set(key, template);
}
templateCache.stringsArray.set(result.strings, template);
return template;
};
const TEMPLATE_TYPES = ['html', 'svg'];
/**
* Removes all style elements from Templates for the given scopeName.
*/
const removeStylesFromLitTemplates = (scopeName) => {
TEMPLATE_TYPES.forEach((type) => {
const templates = templateCaches.get(getTemplateCacheKey(type, scopeName));
if (templates !== undefined) {
templates.keyString.forEach((template) => {
const { element: { content } } = template;
// IE 11 doesn't support the iterable param Set constructor
const styles = new Set();
Array.from(content.querySelectorAll('style')).forEach((s) => {
styles.add(s);
});
removeNodesFromTemplate(template, styles);
});
}
});
};
const shadyRenderSet = new Set();
/**
* For the given scope name, ensures that ShadyCSS style scoping is performed.
* This is done just once per scope name so the fragment and template cannot
* be modified.
* (1) extracts styles from the rendered fragment and hands them to ShadyCSS
* to be scoped and appended to the document
* (2) removes style elements from all lit-html Templates for this scope name.
*
* Note, <style> elements can only be placed into templates for the
* initial rendering of the scope. If <style> elements are included in templates
* dynamically rendered to the scope (after the first scope render), they will
* not be scoped and the <style> will be left in the template and rendered
* output.
*/
const prepareTemplateStyles = (scopeName, renderedDOM, template) => {
shadyRenderSet.add(scopeName);
// If `renderedDOM` is stamped from a Template, then we need to edit that
// Template's underlying template element. Otherwise, we create one here
// to give to ShadyCSS, which still requires one while scoping.
const templateElement = !!template ? template.element : document.createElement('template');
// Move styles out of rendered DOM and store.
const styles = renderedDOM.querySelectorAll('style');
const { length } = styles;
// If there are no styles, skip unnecessary work
if (length === 0) {
// Ensure prepareTemplateStyles is called to support adding
// styles via `prepareAdoptedCssText` since that requires that
// `prepareTemplateStyles` is called.
//
// ShadyCSS will only update styles containing @apply in the template
// given to `prepareTemplateStyles`. If no lit Template was given,
// ShadyCSS will not be able to update uses of @apply in any relevant
// template. However, this is not a problem because we only create the
// template for the purpose of supporting `prepareAdoptedCssText`,
// which doesn't support @apply at all.
window.ShadyCSS.prepareTemplateStyles(templateElement, scopeName);
return;
}
const condensedStyle = document.createElement('style');
// Collect styles into a single style. This helps us make sure ShadyCSS
// manipulations will not prevent us from being able to fix up template
// part indices.
// NOTE: collecting styles is inefficient for browsers but ShadyCSS
// currently does this anyway. When it does not, this should be changed.
for (let i = 0; i < length; i++) {
const style = styles[i];
style.parentNode.removeChild(style);
condensedStyle.textContent += style.textContent;
}
// Remove styles from nested templates in this scope.
removeStylesFromLitTemplates(scopeName);
// And then put the condensed style into the "root" template passed in as
// `template`.
const content = templateElement.content;
if (!!template) {
insertNodeIntoTemplate(template, condensedStyle, content.firstChild);
}
else {
content.insertBefore(condensedStyle, content.firstChild);
}
// Note, it's important that ShadyCSS gets the template that `lit-html`
// will actually render so that it can update the style inside when
// needed (e.g. @apply native Shadow DOM case).
window.ShadyCSS.prepareTemplateStyles(templateElement, scopeName);
const style = content.querySelector('style');
if (window.ShadyCSS.nativeShadow && style !== null) {
// When in native Shadow DOM, ensure the style created by ShadyCSS is
// included in initially rendered output (`renderedDOM`).
renderedDOM.insertBefore(style.cloneNode(true), renderedDOM.firstChild);
}
else if (!!template) {
// When no style is left in the template, parts will be broken as a
// result. To fix this, we put back the style node ShadyCSS removed
// and then tell lit to remove that node from the template.
// There can be no style in the template in 2 cases (1) when Shady DOM
// is in use, ShadyCSS removes all styles, (2) when native Shadow DOM
// is in use ShadyCSS removes the style if it contains no content.
// NOTE, ShadyCSS creates its own style so we can safely add/remove
// `condensedStyle` here.
content.insertBefore(condensedStyle, content.firstChild);
const removes = new Set();
removes.add(condensedStyle);
removeNodesFromTemplate(template, removes);
}
};
/**
* Extension to the standard `render` method which supports rendering
* to ShadowRoots when the ShadyDOM (https://github.com/webcomponents/shadydom)
* and ShadyCSS (https://github.com/webcomponents/shadycss) polyfills are used
* or when the webcomponentsjs
* (https://github.com/webcomponents/webcomponentsjs) polyfill is used.
*
* Adds a `scopeName` option which is used to scope element DOM and stylesheets
* when native ShadowDOM is unavailable. The `scopeName` will be added to
* the class attribute of all rendered DOM. In addition, any style elements will
* be automatically re-written with this `scopeName` selector and moved out
* of the rendered DOM and into the document `<head>`.
*
* It is common to use this render method in conjunction with a custom element
* which renders a shadowRoot. When this is done, typically the element's
* `localName` should be used as the `scopeName`.
*
* In addition to DOM scoping, ShadyCSS also supports a basic shim for css
* custom properties (needed only on older browsers like IE11) and a shim for
* a deprecated feature called `@apply` that supports applying a set of css
* custom properties to a given location.
*
* Usage considerations:
*
* * Part values in `<style>` elements are only applied the first time a given
* `scopeName` renders. Subsequent changes to parts in style elements will have
* no effect. Because of this, parts in style elements should only be used for
* values that will never change, for example parts that set scope-wide theme
* values or parts which render shared style elements.
*
* * Note, due to a limitation of the ShadyDOM polyfill, rendering in a
* custom element's `constructor` is not supported. Instead rendering should
* either done asynchronously, for example at microtask timing (for example
* `Promise.resolve()`), or be deferred until the first time the element's
* `connectedCallback` runs.
*
* Usage considerations when using shimmed custom properties or `@apply`:
*
* * Whenever any dynamic changes are made which affect
* css custom properties, `ShadyCSS.styleElement(element)` must be called
* to update the element. There are two cases when this is needed:
* (1) the element is connected to a new parent, (2) a class is added to the
* element that causes it to match different custom properties.
* To address the first case when rendering a custom element, `styleElement`
* should be called in the element's `connectedCallback`.
*
* * Shimmed custom properties may only be defined either for an entire
* shadowRoot (for example, in a `:host` rule) or via a rule that directly
* matches an element with a shadowRoot. In other words, instead of flowing from
* parent to child as do native css custom properties, shimmed custom properties
* flow only from shadowRoots to nested shadowRoots.
*
* * When using `@apply` mixing css shorthand property names with
* non-shorthand names (for example `border` and `border-width`) is not
* supported.
*/
const render = (result, container, options) => {
if (!options || typeof options !== 'object' || !options.scopeName) {
throw new Error('The `scopeName` option is required.');
}
const scopeName = options.scopeName;
const hasRendered = parts.has(container);
const needsScoping = compatibleShadyCSSVersion &&
container.nodeType === 11 /* Node.DOCUMENT_FRAGMENT_NODE */ &&
!!container.host;
// Handle first render to a scope specially...
const firstScopeRender = needsScoping && !shadyRenderSet.has(scopeName);
// On first scope render, render into a fragment; this cannot be a single
// fragment that is reused since nested renders can occur synchronously.
const renderContainer = firstScopeRender ? document.createDocumentFragment() : container;
render$1(result, renderContainer, Object.assign({ templateFactory: shadyTemplateFactory(scopeName) }, options));
// When performing first scope render,
// (1) We've rendered into a fragment so that there's a chance to
// `prepareTemplateStyles` before sub-elements hit the DOM
// (which might cause them to render based on a common pattern of
// rendering in a custom element's `connectedCallback`);
// (2) Scope the template with ShadyCSS one time only for this scope.
// (3) Render the fragment into the container and make sure the
// container knows its `part` is the one we just rendered. This ensures
// DOM will be re-used on subsequent renders.
if (firstScopeRender) {
const part = parts.get(renderContainer);
parts.delete(renderContainer);
// ShadyCSS might have style sheets (e.g. from `prepareAdoptedCssText`)
// that should apply to `renderContainer` even if the rendered value is
// not a TemplateInstance. However, it will only insert scoped styles
// into the document if `prepareTemplateStyles` has already been called
// for the given scope name.
const template = part.value instanceof TemplateInstance ?
part.value.template :
undefined;
prepareTemplateStyles(scopeName, renderContainer, template);
removeNodes(container, container.firstChild);
container.appendChild(renderContainer);
parts.set(container, part);
}
// After elements have hit the DOM, update styling if this is the
// initial render to this container.
// This is needed whenever dynamic changes are made so it would be
// safest to do every render; however, this would regress performance
// so we leave it up to the user to call `ShadyCSS.styleElement`
// for dynamic changes.
if (!hasRendered && needsScoping) {
window.ShadyCSS.styleElement(container.host);
}
};
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
var _a;
/**
* When using Closure Compiler, JSCompiler_renameProperty(property, object) is
* replaced at compile time by the munged name for object[property]. We cannot
* alias this function, so we have to use a small shim that has the same
* behavior when not compiling.
*/
window.JSCompiler_renameProperty =
(prop, _obj) => prop;
const defaultConverter = {
toAttribute(value, type) {
switch (type) {
case Boolean:
return value ? '' : null;
case Object:
case Array:
// if the value is `null` or `undefined` pass this through
// to allow removing/no change behavior.
return value == null ? value : JSON.stringify(value);
}
return value;
},
fromAttribute(value, type) {
switch (type) {
case Boolean:
return value !== null;
case Number:
return value === null ? null : Number(value);
case Object:
case Array:
return JSON.parse(value);
}
return value;
}
};
/**
* Change function that returns true if `value` is different from `oldValue`.
* This method is used as the default for a property's `hasChanged` function.
*/
const notEqual = (value, old) => {
// This ensures (old==NaN, value==NaN) always returns false
return old !== value && (old === old || value === value);
};
const defaultPropertyDeclaration = {
attribute: true,
type: String,
converter: defaultConverter,
reflect: false,
hasChanged: notEqual
};
const microtaskPromise = Promise.resolve(true);
const STATE_HAS_UPDATED = 1;
const STATE_UPDATE_REQUESTED = 1 << 2;
const STATE_IS_REFLECTING_TO_ATTRIBUTE = 1 << 3;
const STATE_IS_REFLECTING_TO_PROPERTY = 1 << 4;
const STATE_HAS_CONNECTED = 1 << 5;
/**
* The Closure JS Compiler doesn't currently have good support for static
* property semantics where "this" is dynamic (e.g.
* https://github.com/google/closure-compiler/issues/3177 and others) so we use
* this hack to bypass any rewriting by the compiler.
*/
const finalized = 'finalized';
/**
* Base element class which manages element properties and attributes. When
* properties change, the `update` method is asynchronously called. This method
* should be supplied by subclassers to render updates as desired.
*/
class UpdatingElement extends HTMLElement {
constructor() {
super();
this._updateState = 0;
this._instanceProperties = undefined;
this._updatePromise = microtaskPromise;
this._hasConnectedResolver = undefined;
/**
* Map with keys for any properties that have changed since the last
* update cycle with previous values.
*/
this._changedProperties = new Map();
/**
* Map with keys of properties that should be reflected when updated.
*/
this._reflectingProperties = undefined;
this.initialize();
}
/**
* Returns a list of attributes corresponding to the registered properties.
* @nocollapse
*/
static get observedAttributes() {
// note: piggy backing on this to ensure we're finalized.
this.finalize();
const attributes = [];
// Use forEach so this works even if for/of loops are compiled to for loops
// expecting arrays
this._classProperties.forEach((v, p) => {
const attr = this._attributeNameForProperty(p, v);
if (attr !== undefined) {
this._attributeToPropertyMap.set(attr, p);
attributes.push(attr);
}
});
return attributes;
}
/**
* Ensures the private `_classProperties` property metadata is created.
* In addition to `finalize` this is also called in `createProperty` to
* ensure the `@property` decorator can add property metadata.
*/
/** @nocollapse */
static _ensureClassProperties() {
// ensure private storage for property declarations.
if (!this.hasOwnProperty(JSCompiler_renameProperty('_classProperties', this))) {
this._classProperties = new Map();
// NOTE: Workaround IE11 not supporting Map constructor argument.
const superProperties = Object.getPrototypeOf(this)._classProperties;
if (superProperties !== undefined) {
superProperties.forEach((v, k) => this._classProperties.set(k, v));
}
}
}
/**
* Creates a property accessor on the element prototype if one does not exist.
* The property setter calls the property's `hasChanged` property option
* or uses a strict identity check to determine whether or not to request
* an update.
* @nocollapse
*/
static createProperty(name, options = defaultPropertyDeclaration) {
// Note, since this can be called by the `@property` decorator which
// is called before `finalize`, we ensure storage exists for property
// metadata.
this._ensureClassProperties();
this._classProperties.set(name, options);
// Do not generate an accessor if the prototype already has one, since
// it would be lost otherwise and that would never be the user's intention;
// Instead, we expect users to call `requestUpdate` themselves from
// user-defined accessors. Note that if the super has an accessor we will
// still overwrite it
if (options.noAccessor || this.prototype.hasOwnProperty(name)) {
return;
}
const key = typeof name === 'symbol' ? Symbol() : `__${name}`;
Object.defineProperty(this.prototype, name, {
// tslint:disable-next-line:no-any no symbol in index
get() {
return this[key];
},
set(value) {
const oldValue = this[name];
this[key] = value;
this._requestUpdate(name, oldValue);
},
configurable: true,
enumerable: true
});
}
/**
* Creates property accessors for registered properties and ensures
* any superclasses are also finalized.
* @nocollapse
*/
static finalize() {
// finalize any superclasses
const superCtor = Object.getPrototypeOf(this);
if (!superCtor.hasOwnProperty(finalized)) {
superCtor.finalize();
}
this[finalized] = true;
this._ensureClassProperties();
// initialize Map populated in observedAttributes
this._attributeToPropertyMap = new Map();
// make any properties
// Note, only process "own" properties since this element will inherit
// any properties defined on the superClass, and finalization ensures
// the entire prototype chain is finalized.
if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {
const props = this.properties;
// support symbols in properties (IE11 does not support this)
const propKeys = [
...Object.getOwnPropertyNames(props),
...(typeof Object.getOwnPropertySymbols === 'function') ?
Object.getOwnPropertySymbols(props) :
[]
];
// This for/of is ok because propKeys is an array
for (const p of propKeys) {
// note, use of `any` is due to TypeSript lack of support for symbol in
// index types
// tslint:disable-next-line:no-any no symbol in index
this.createProperty(p, props[p]);
}
}
}
/**
* Returns the property name for the given attribute `name`.
* @nocollapse
*/
static _attributeNameForProperty(name, options) {
const attribute = options.attribute;
return attribute === false ?
undefined :
(typeof attribute === 'string' ?
attribute :
(typeof name === 'string' ? name.toLowerCase() : undefined));
}
/**
* Returns true if a property should request an update.
* Called when a property value is set and uses the `hasChanged`
* option for the property if present or a strict identity check.
* @nocollapse
*/
static _valueHasChanged(value, old, hasChanged = notEqual) {
return hasChanged(value, old);
}
/**
* Returns the property value for the given attribute value.
* Called via the `attributeChangedCallback` and uses the property's
* `converter` or `converter.fromAttribute` property option.
* @nocollapse
*/
static _propertyValueFromAttribute(value, options) {
const type = options.type;
const converter = options.converter || defaultConverter;
const fromAttribute = (typeof converter === 'function' ? converter : converter.fromAttribute);
return fromAttribute ? fromAttribute(value, type) : value;
}
/**
* Returns the attribute value for the given property value. If this
* returns undefined, the property will *not* be reflected to an attribute.
* If this returns null, the attribute will be removed, otherwise the
* attribute will be set to the value.
* This uses the property's `reflect` and `type.toAttribute` property options.
* @nocollapse
*/
static _propertyValueToAttribute(value, options) {
if (options.reflect === undefined) {
return;
}
const type = options.type;
const converter = options.converter;
const toAttribute = converter && converter.toAttribute ||
defaultConverter.toAttribute;
return toAttribute(value, type);
}
/**
* Performs element initialization. By default captures any pre-set values for
* registered properties.
*/
initialize() {
this._saveInstanceProperties();
// ensures first update will be caught by an early access of
// `updateComplete`
this._requestUpdate();
}
/**
* Fixes any properties set on the instance before upgrade time.
* Otherwise these would shadow the accessor and break these properties.
* The properties are stored in a Map which is played back after the
* constructor runs. Note, on very old versions of Safari (<=9) or Chrome
* (<=41), properties created for native platform properties like (`id` or
* `name`) may not have default values set in the element constructor. On
* these browsers native properties appear on instances and therefore their
* default value will overwrite any element default (e.g. if the element sets
* this.id = 'id' in the constructor, the 'id' will become '' since this is
* the native platform default).
*/
_saveInstanceProperties() {
// Use forEach so this works even if for/of loops are compiled to for loops
// expecting arrays
this.constructor
._classProperties.forEach((_v, p) => {
if (this.hasOwnProperty(p)) {
const value = this[p];
delete this[p];
if (!this._instanceProperties) {
this._instanceProperties = new Map();
}
this._instanceProperties.set(p, value);
}
});
}
/**
* Applies previously saved instance properties.
*/
_applyInstanceProperties() {
// Use forEach so this works even if for/of loops are compiled to for loops
// expecting arrays
// tslint:disable-next-line:no-any
this._instanceProperties.forEach((v, p) => this[p] = v);
this._instanceProperties = undefined;
}
connectedCallback() {
this._updateState = this._updateState | STATE_HAS_CONNECTED;
// Ensure first connection completes an update. Updates cannot complete
// before connection and if one is pending connection the
// `_hasConnectionResolver` will exist. If so, resolve it to complete the
// update, otherwise requestUpdate.
if (this._hasConnectedResolver) {
this._hasConnectedResolver();
this._hasConnectedResolver = undefined;
}
}
/**
* Allows for `super.disconnectedCallback()` in extensions while
* reserving the possibility of making non-breaking feature additions
* when disconnecting at some point in the future.
*/
disconnectedCallback() {
}
/**
* Synchronizes property values when attributes change.
*/
attributeChangedCallback(name, old, value) {
if (old !== value) {
this._attributeToProperty(name, value);
}
}
_propertyToAttribute(name, value, options = defaultPropertyDeclaration) {
const ctor = this.constructor;
const attr = ctor._attributeNameForProperty(name, options);
if (attr !== undefined) {
const attrValue = ctor._propertyValueToAttribute(value, options);
// an undefined value does not change the attribute.
if (attrValue === undefined) {
return;
}
// Track if the property is being reflected to avoid
// setting the property again via `attributeChangedCallback`. Note:
// 1. this takes advantage of the fact that the callback is synchronous.
// 2. will behave incorrectly if multiple attributes are in the reaction
// stack at time of calling. However, since we process attributes
// in `update` this should not be possible (or an extreme corner case
// that we'd like to discover).
// mark state reflecting
this._updateState = this._updateState | STATE_IS_REFLECTING_TO_ATTRIBUTE;
if (attrValue == null) {
this.removeAttribute(attr);
}
else {
this.setAttribute(attr, attrValue);
}
// mark state not reflecting
this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_ATTRIBUTE;
}
}
_attributeToProperty(name, value) {
// Use tracking info to avoid deserializing attribute value if it was
// just set from a property setter.
if (this._updateState & STATE_IS_REFLECTING_TO_ATTRIBUTE) {
return;
}
const ctor = this.constructor;
const propName = ctor._attributeToPropertyMap.get(name);
if (propName !== undefined) {
const options = ctor._classProperties.get(propName) || defaultPropertyDeclaration;
// mark state reflecting
this._updateState = this._updateState | STATE_IS_REFLECTING_TO_PROPERTY;
this[propName] =
// tslint:disable-next-line:no-any
ctor._propertyValueFromAttribute(value, options);
// mark state not reflecting
this._updateState = this._updateState & ~STATE_IS_REFLECTING_TO_PROPERTY;
}
}
/**
* This private version of `requestUpdate` does not access or return the
* `updateComplete` promise. This promise can be overridden and is therefore
* not free to access.
*/
_requestUpdate(name, oldValue) {
let shouldRequestUpdate = true;
// If we have a property key, perform property update steps.
if (name !== undefined) {
const ctor = this.constructor;
const options = ctor._classProperties.get(name) || defaultPropertyDeclaration;
if (ctor._valueHasChanged(this[name], oldValue, options.hasChanged)) {
if (!this._changedProperties.has(name)) {
this._changedProperties.set(name, oldValue);
}
// Add to reflecting properties set.
// Note, it's important that every change has a chance to add the
// property to `_reflectingProperties`. This ensures setting
// attribute + property reflects correctly.
if (options.reflect === true &&
!(this._updateState & STATE_IS_REFLECTING_TO_PROPERTY)) {
if (this._reflectingProperties === undefined) {
this._reflectingProperties = new Map();
}
this._reflectingProperties.set(name, options);
}
}
else {
// Abort the request if the property should not be considered changed.
shouldRequestUpdate = false;
}
}
if (!this._hasRequestedUpdate && shouldRequestUpdate) {
this._enqueueUpdate();
}
}
/**
* Requests an update which is processed asynchronously. This should
* be called when an element should update based on some state not triggered
* by setting a property. In this case, pass no arguments. It should also be
* called when manually implementing a property setter. In this case, pass the
* property `name` and `oldValue` to ensure that any configured property
* options are honored. Returns the `updateComplete` Promise which is resolved
* when the update completes.
*
* @param name {PropertyKey} (optional) name of requesting property
* @param oldValue {any} (optional) old value of requesting property
* @returns {Promise} A Promise that is resolved when the update completes.
*/
requestUpdate(name, oldValue) {
this._requestUpdate(name, oldValue);
return this.updateComplete;
}
/**
* Sets up the element to asynchronously update.
*/
async _enqueueUpdate() {
// Mark state updating...
this._updateState = this._updateState | STATE_UPDATE_REQUESTED;
let resolve;
let reject;
const previousUpdatePromise = this._updatePromise;
this._updatePromise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
try {
// Ensure any previous update has resolved before updating.
// This `await` also ensures that property changes are batched.
await previousUpdatePromise;
}
catch (e) {
// Ignore any previous errors. We only care that the previous cycle is
// done. Any error should have been handled in the previous update.
}
// Make sure the element has connected before updating.
if (!this._hasConnected) {
await new Promise((res) => this._hasConnectedResolver = res);
}
try {
const result = this.performUpdate();
// If `performUpdate` returns a Promise, we await it. This is done to
// enable coordinating updates with a scheduler. Note, the result is
// checked to avoid delaying an additional microtask unless we need to.
if (result != null) {
await result;
}
}
catch (e) {
reject(e);
}
resolve(!this._hasRequestedUpdate);
}
get _hasConnected() {
return (this._updateState & STATE_HAS_CONNECTED);
}
get _hasRequestedUpdate() {
return (this._updateState & STATE_UPDATE_REQUESTED);
}
get hasUpdated() {
return (this._updateState & STATE_HAS_UPDATED);
}
/**
* Performs an element update. Note, if an exception is thrown during the
* update, `firstUpdated` and `updated` will not be called.
*
* You can override this method to change the timing of updates. If this
* method is overridden, `super.performUpdate()` must be called.
*
* For instance, to schedule updates to occur just before the next frame:
*
* ```
* protected async performUpdate(): Promise<unknown> {
* await new Promise((resolve) => requestAnimationFrame(() => resolve()));
* super.performUpdate();
* }
* ```
*/
performUpdate() {
// Mixin instance properties once, if they exist.
if (this._instanceProperties) {
this._applyInstanceProperties();
}
let shouldUpdate = false;
const changedProperties = this._changedProperties;
try {
shouldUpdate = this.shouldUpdate(changedProperties);
if (shouldUpdate) {
this.update(changedProperties);
}
}
catch (e) {
// Prevent `firstUpdated` and `updated` from running when there's an
// update exception.
shouldUpdate = false;
throw e;
}
finally {
// Ensure element can accept additional updates after an exception.
this._markUpdated();
}
if (shouldUpdate) {
if (!(this._updateState & STATE_HAS_UPDATED)) {
this._updateState = this._updateState | STATE_HAS_UPDATED;
this.firstUpdated(changedProperties);
}
this.updated(changedProperties);
}
}
_markUpdated() {
this._changedProperties = new Map();
this._updateState = this._updateState & ~STATE_UPDATE_REQUESTED;
}
/**
* Returns a Promise that resolves when the element has completed updating.
* The Promise value is a boolean that is `true` if the element completed the
* update without triggering another update. The Promise result is `false` if
* a property was set inside `updated()`. If the Promise is rejected, an
* exception was thrown during the update.
*
* To await additional asynchronous work, override the `_getUpdateComplete`
* method. For example, it is sometimes useful to await a rendered element
* before fulfilling this Promise. To do this, first await
* `super._getUpdateComplete()`, then any subsequent state.
*
* @returns {Promise} The Promise returns a boolean that indicates if the
* update resolved without triggering another update.
*/
get updateComplete() {
return this._getUpdateComplete();
}
/**
* Override point for the `updateComplete` promise.
*
* It is not safe to override the `updateComplete` getter directly due to a
* limitation in TypeScript which means it is not possible to call a
* superclass getter (e.g. `super.updateComplete.then(...)`) when the target
* language is ES5 (https://github.com/microsoft/TypeScript/issues/338).
* This method should be overridden instead. For example:
*
* class MyElement extends LitElement {
* async _getUpdateComplete() {
* await super._getUpdateComplete();
* await this._myChild.updateComplete;
* }
* }
*/
_getUpdateComplete() {
return this._updatePromise;
}
/**
* Controls whether or not `update` should be called when the element requests
* an update. By default, this method always returns `true`, but this can be
* customized to control when to update.
*
* * @param _changedProperties Map of changed properties with old values
*/
shouldUpdate(_changedProperties) {
return true;
}
/**
* Updates the element. This method reflects property values to attributes.
* It can be overridden to render and keep updated element DOM.
* Setting properties inside this method will *not* trigger
* another update.
*
* * @param _changedProperties Map of changed properties with old values
*/
update(_changedProperties) {
if (this._reflectingProperties !== undefined &&
this._reflectingProperties.size > 0) {
// Use forEach so this works even if for/of loops are compiled to for
// loops expecting arrays
this._reflectingProperties.forEach((v, k) => this._propertyToAttribute(k, this[k], v));
this._reflectingProperties = undefined;
}
}
/**
* Invoked whenever the element is updated. Implement to perform
* post-updating tasks via DOM APIs, for example, focusing an element.
*
* Setting properties inside this method will trigger the element to update
* again after this update cycle completes.
*
* * @param _changedProperties Map of changed properties with old values
*/
updated(_changedProperties) {
}
/**
* Invoked when the element is first updated. Implement to perform one time
* work on the element after update.
*
* Setting properties inside this method will trigger the element to update
* again after this update cycle completes.
*
* * @param _changedProperties Map of changed properties with old values
*/
firstUpdated(_changedProperties) {
}
}
_a = finalized;
/**
* Marks class as having finished creating properties.
*/
UpdatingElement[_a] = true;
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
const legacyCustomElement = (tagName, clazz) => {
window.customElements.define(tagName, clazz);
// Cast as any because TS doesn't recognize the return type as being a
// subtype of the decorated class when clazz is typed as
// `Constructor<HTMLElement>` for some reason.
// `Constructor<HTMLElement>` is helpful to make sure the decorator is
// applied to elements however.
// tslint:disable-next-line:no-any
return clazz;
};
const standardCustomElement = (tagName, descriptor) => {
const { kind, elements } = descriptor;
return {
kind,
elements,
// This callback is called once the class is otherwise fully defined
finisher(clazz) {
window.customElements.define(tagName, clazz);
}
};
};
/**
* Class decorator factory that defines the decorated class as a custom element.
*
* @param tagName the name of the custom element to define
*/
const customElement = (tagName) => (classOrDescriptor) => (typeof classOrDescriptor === 'function') ?
legacyCustomElement(tagName, classOrDescriptor) :
standardCustomElement(tagName, classOrDescriptor);
const standardProperty = (options, element) => {
// When decorating an accessor, pass it through and add property metadata.
// Note, the `hasOwnProperty` check in `createProperty` ensures we don't
// stomp over the user's accessor.
if (element.kind === 'method' && element.descriptor &&
!('value' in element.descriptor)) {
return Object.assign({}, element, { finisher(clazz) {
clazz.createProperty(element.key, options);
} });
}
else {
// createProperty() takes care of defining the property, but we still
// must return some kind of descriptor, so return a descriptor for an
// unused prototype field. The finisher calls createProperty().
return {
kind: 'field',
key: Symbol(),
placement: 'own',
descriptor: {},
// When @babel/plugin-proposal-decorators implements initializers,
// do this instead of the initializer below. See:
// https://github.com/babel/babel/issues/9260 extras: [
// {
// kind: 'initializer',
// placement: 'own',
// initializer: descriptor.initializer,
// }
// ],
initializer() {
if (typeof element.initializer === 'function') {
this[element.key] = element.initializer.call(this);
}
},
finisher(clazz) {
clazz.createProperty(element.key, options);
}
};
}
};
const legacyProperty = (options, proto, name) => {
proto.constructor
.createProperty(name, options);
};
/**
* A property decorator which creates a LitElement property which reflects a
* corresponding attribute value. A `PropertyDeclaration` may optionally be
* supplied to configure property features.
*
* @ExportDecoratedItems
*/
function property(options) {
// tslint:disable-next-line:no-any decorator
return (protoOrDescriptor, name) => (name !== undefined) ?
legacyProperty(options, protoOrDescriptor, name) :
standardProperty(options, protoOrDescriptor);
}
/**
* A property decorator that converts a class property into a getter that
* executes a querySelector on the element's renderRoot.
*
* @ExportDecoratedItems
*/
function query(selector) {
return (protoOrDescriptor,
// tslint:disable-next-line:no-any decorator
name) => {
const descriptor = {
get() {
return this.renderRoot.querySelector(selector);
},
enumerable: true,
configurable: true,
};
return (name !== undefined) ?
legacyQuery(descriptor, protoOrDescriptor, name) :
standardQuery(descriptor, protoOrDescriptor);
};
}
/**
* A property decorator that converts a class property into a getter
* that executes a querySelectorAll on the element's renderRoot.
*
* @ExportDecoratedItems
*/
function queryAll(selector) {
return (protoOrDescriptor,
// tslint:disable-next-line:no-any decorator
name) => {
const descriptor = {
get() {
return this.renderRoot.querySelectorAll(selector);
},
enumerable: true,
configurable: true,
};
return (name !== undefined) ?
legacyQuery(descriptor, protoOrDescriptor, name) :
standardQuery(descriptor, protoOrDescriptor);
};
}
const legacyQuery = (descriptor, proto, name) => {
Object.defineProperty(proto, name, descriptor);
};
const standardQuery = (descriptor, element) => ({
kind: 'method',
placement: 'prototype',
key: element.key,
descriptor,
});
const standardEventOptions = (options, element) => {
return Object.assign({}, element, { finisher(clazz) {
Object.assign(clazz.prototype[element.key], options);
} });
};
const legacyEventOptions =
// tslint:disable-next-line:no-any legacy decorator
(options, proto, name) => {
Object.assign(proto[name], options);
};
/**
* Adds event listener options to a method used as an event listener in a
* lit-html template.
*
* @param options An object that specifis event listener options as accepted by
* `EventTarget#addEventListener` and `EventTarget#removeEventListener`.
*
* Current browsers support the `capture`, `passive`, and `once` options. See:
* https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters
*
* @example
*
* class MyElement {
*
* clicked = false;
*
* render() {
* return html`<div @click=${this._onClick}`><button></button></div>`;
* }
*
* @eventOptions({capture: true})
* _onClick(e) {
* this.clicked = true;
* }
* }
*/
const eventOptions = (options) =>
// Return value typed as any to prevent TypeScript from complaining that
// standard decorator function signature does not match TypeScript decorator
// signature
// TODO(kschaaf): unclear why it was only failing on this decorator and not
// the others
((protoOrDescriptor, name) => (name !== undefined) ?
legacyEventOptions(options, protoOrDescriptor, name) :
standardEventOptions(options, protoOrDescriptor));
/**
@license
Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at
http://polymer.github.io/LICENSE.txt The complete set of authors may be found at
http://polymer.github.io/AUTHORS.txt The complete set of contributors may be
found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as
part of the polymer project is also subject to an additional IP rights grant
found at http://polymer.github.io/PATENTS.txt
*/
const supportsAdoptingStyleSheets = ('adoptedStyleSheets' in Document.prototype) &&
('replace' in CSSStyleSheet.prototype);
const constructionToken = Symbol();
class CSSResult {
constructor(cssText, safeToken) {
if (safeToken !== constructionToken) {
throw new Error('CSSResult is not constructable. Use `unsafeCSS` or `css` instead.');
}
this.cssText = cssText;
}
// Note, this is a getter so that it's lazy. In practice, this means
// stylesheets are not created until the first element instance is made.
get styleSheet() {
if (this._styleSheet === undefined) {
// Note, if `adoptedStyleSheets` is supported then we assume CSSStyleSheet
// is constructable.
if (supportsAdoptingStyleSheets) {
this._styleSheet = new CSSStyleSheet();
this._styleSheet.replaceSync(this.cssText);
}
else {
this._styleSheet = null;
}
}
return this._styleSheet;
}
toString() {
return this.cssText;
}
}
/**
* Wrap a value for interpolation in a css tagged template literal.
*
* This is unsafe because untrusted CSS text can be used to phone home
* or exfiltrate data to an attacker controlled site. Take care to only use
* this with trusted input.
*/
const unsafeCSS = (value) => {
return new CSSResult(String(value), constructionToken);
};
const textFromCSSResult = (value) => {
if (value instanceof CSSResult) {
return value.cssText;
}
else if (typeof value === 'number') {
return value;
}
else {
throw new Error(`Value passed to 'css' function must be a 'css' function result: ${value}. Use 'unsafeCSS' to pass non-literal values, but
take care to ensure page security.`);
}
};
/**
* Template tag which which can be used with LitElement's `style` property to
* set element styles. For security reasons, only literal string values may be
* used. To incorporate non-literal values `unsafeCSS` may be used inside a
* template string part.
*/
const css = (strings, ...values) => {
const cssText = values.reduce((acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1], strings[0]);
return new CSSResult(cssText, constructionToken);
};
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
// IMPORTANT: do not change the property name or the assignment expression.
// This line will be used in regexes to search for LitElement usage.
// TODO(justinfagnani): inject version number at build time
(window['litElementVersions'] || (window['litElementVersions'] = []))
.push('2.2.1');
/**
* Minimal implementation of Array.prototype.flat
* @param arr the array to flatten
* @param result the accumlated result
*/
function arrayFlat(styles, result = []) {
for (let i = 0, length = styles.length; i < length; i++) {
const value = styles[i];
if (Array.isArray(value)) {
arrayFlat(value, result);
}
else {
result.push(value);
}
}
return result;
}
/** Deeply flattens styles array. Uses native flat if available. */
const flattenStyles = (styles) => styles.flat ? styles.flat(Infinity) : arrayFlat(styles);
class LitElement extends UpdatingElement {
/** @nocollapse */
static finalize() {
// The Closure JS Compiler does not always preserve the correct "this"
// when calling static super methods (b/137460243), so explicitly bind.
super.finalize.call(this);
// Prepare styling that is stamped at first render time. Styling
// is built from user provided `styles` or is inherited from the superclass.
this._styles =
this.hasOwnProperty(JSCompiler_renameProperty('styles', this)) ?
this._getUniqueStyles() :
this._styles || [];
}
/** @nocollapse */
static _getUniqueStyles() {
// Take care not to call `this.styles` multiple times since this generates
// new CSSResults each time.
// TODO(sorvell): Since we do not cache CSSResults by input, any
// shared styles will generate new stylesheet objects, which is wasteful.
// This should be addressed when a browser ships constructable
// stylesheets.
const userStyles = this.styles;
const styles = [];
if (Array.isArray(userStyles)) {
const flatStyles = flattenStyles(userStyles);
// As a performance optimization to avoid duplicated styling that can
// occur especially when composing via subclassing, de-duplicate styles
// preserving the last item in the list. The last item is kept to
// try to preserve cascade order with the assumption that it's most
// important that last added styles override previous styles.
const styleSet = flatStyles.reduceRight((set, s) => {
set.add(s);
// on IE set.add does not return the set.
return set;
}, new Set());
// Array.from does not work on Set in IE
styleSet.forEach((v) => styles.unshift(v));
}
else if (userStyles) {
styles.push(userStyles);
}
return styles;
}
/**
* Performs element initialization. By default this calls `createRenderRoot`
* to create the element `renderRoot` node and captures any pre-set values for
* registered properties.
*/
initialize() {
super.initialize();
this.renderRoot =
this.createRenderRoot();
// Note, if renderRoot is not a shadowRoot, styles would/could apply to the
// element's getRootNode(). While this could be done, we're choosing not to
// support this now since it would require different logic around de-duping.
if (window.ShadowRoot && this.renderRoot instanceof window.ShadowRoot) {
this.adoptStyles();
}
}
/**
* Returns the node into which the element should render and by default
* creates and returns an open shadowRoot. Implement to customize where the
* element's DOM is rendered. For example, to render into the element's
* childNodes, return `this`.
* @returns {Element|DocumentFragment} Returns a node into which to render.
*/
createRenderRoot() {
return this.attachShadow({ mode: 'open' });
}
/**
* Applies styling to the element shadowRoot using the `static get styles`
* property. Styling will apply using `shadowRoot.adoptedStyleSheets` where
* available and will fallback otherwise. When Shadow DOM is polyfilled,
* ShadyCSS scopes styles and adds them to the document. When Shadow DOM
* is available but `adoptedStyleSheets` is not, styles are appended to the
* end of the `shadowRoot` to [mimic spec
* behavior](https://wicg.github.io/construct-stylesheets/#using-constructed-stylesheets).
*/
adoptStyles() {
const styles = this.constructor._styles;
if (styles.length === 0) {
return;
}
// There are three separate cases here based on Shadow DOM support.
// (1) shadowRoot polyfilled: use ShadyCSS
// (2) shadowRoot.adoptedStyleSheets available: use it.
// (3) shadowRoot.adoptedStyleSheets polyfilled: append styles after
// rendering
if (window.ShadyCSS !== undefined && !window.ShadyCSS.nativeShadow) {
window.ShadyCSS.ScopingShim.prepareAdoptedCssText(styles.map((s) => s.cssText), this.localName);
}
else if (supportsAdoptingStyleSheets) {
this.renderRoot.adoptedStyleSheets =
styles.map((s) => s.styleSheet);
}
else {
// This must be done after rendering so the actual style insertion is done
// in `update`.
this._needsShimAdoptedStyleSheets = true;
}
}
connectedCallback() {
super.connectedCallback();
// Note, first update/render handles styleElement so we only call this if
// connected after first update.
if (this.hasUpdated && window.ShadyCSS !== undefined) {
window.ShadyCSS.styleElement(this);
}
}
/**
* Updates the element. This method reflects property values to attributes
* and calls `render` to render DOM via lit-html. Setting properties inside
* this method will *not* trigger another update.
* * @param _changedProperties Map of changed properties with old values
*/
update(changedProperties) {
super.update(changedProperties);
const templateResult = this.render();
if (templateResult instanceof TemplateResult) {
this.constructor
.render(templateResult, this.renderRoot, { scopeName: this.localName, eventContext: this });
}
// When native Shadow DOM is used but adoptedStyles are not supported,
// insert styling after rendering to ensure adoptedStyles have highest
// priority.
if (this._needsShimAdoptedStyleSheets) {
this._needsShimAdoptedStyleSheets = false;
this.constructor._styles.forEach((s) => {
const style = document.createElement('style');
style.textContent = s.cssText;
this.renderRoot.appendChild(style);
});
}
}
/**
* Invoked on each update to perform rendering tasks. This method must return
* a lit-html TemplateResult. Setting properties inside this method will *not*
* trigger the element to update.
*/
render() {
}
}
/**
* Ensure this class is marked as `finalized` as an optimization ensuring
* it will not needlessly try to `finalize`.
*
* Note this property name is a string to prevent breaking Closure JS Compiler
* optimizations. See updating-element.ts for more information.
*/
LitElement['finalized'] = true;
/**
* Render method used to render the lit-html TemplateResult to the element's
* DOM.
* @param {TemplateResult} Template to render.
* @param {Element|DocumentFragment} Node into which to render.
* @param {String} Element name.
* @nocollapse
*/
LitElement.render = render;
export { CSSResult, LitElement, UpdatingElement, css, customElement, defaultConverter, eventOptions, notEqual, property, query, queryAll, supportsAdoptingStyleSheets, unsafeCSS };
|
const test = require('tape');
const catcha = require('../src');
const {getTestData} = require('./utils');
test('catcha test -- easy module', (assert) => {
const settings = {
transforms: [
{key: 'resize', value: '240x100'},
{key: 'colorspace', value: 'gray'},
{key: 'negate'},
{key: 'threshold', value: '12%'},
{key: 'blur', value: '10 '},
{key: 'threshold', value: '43%'},
{key: 'negate'},
],
digitOnly: true,
deleteTemporaryImage: true,
};
const kitten = catcha(settings);
getTestData('easy')
.map((image) =>
kitten(image.path)
.then((text) => {
assert.equal(text, image.text);
})
, {concurrency: 1})
.then(() => assert.end())
.catch(assert.end);
});
test('catcha test -- easy2 module', (assert) => {
const settings = {
transforms: [
{key: 'resize', value: '240x100'},
{key: 'colorspace', value: 'gray'},
{key: 'negate'},
{key: 'threshold', value: '12%'},
{key: 'blur', value: '10 '},
{key: 'threshold', value: '43%'},
{key: 'negate'},
],
deleteTemporaryImage: true,
};
const kitten = catcha(settings);
getTestData('easy2')
.map((image) =>
kitten(image.path)
.then((text) => {
assert.equal(text, image.text);
})
, {concurrency: 1})
.then(() => assert.end())
.catch(assert.end);
});
test('catcha test -- intermediate module', (assert) => {
const settings = {
transforms: [
{key: 'resize', value: '120'},
{key: 'threshold', value: '5%'},
{key: 'blur', value: '20'},
{key: 'threshold', value: '35%'},
{key: 'blur', value: '1'},
],
digitOnly: true,
deleteTemporaryImage: true,
};
const kitten = catcha(settings);
getTestData('intermediate')
.map((image) =>
kitten(image.path)
.then((text) => {
assert.equal(text, image.text);
})
, {concurrency: 1})
.then(() => assert.end())
.catch(assert.end);
});
test('catcha test -- hard module', (assert) => {
const settings = {
transforms: [
{key: 'resize', value: '240x100'},
{key: 'level', value: '0,0,10%'},
{key: 'threshold', value: '5%'},
{key: 'blur', value: '20'},
],
deleteTemporaryImage: true,
transformFunction: (text) => text.toLowerCase().replace(/[^\d\w]/g, ''),
};
const kitten = catcha(settings);
getTestData('hard')
.map((image) =>
kitten(image.path)
.then((text) => {
assert.equal(text, image.text);
})
, {concurrency: 1})
.then(() => assert.end())
.catch(assert.end);
});
|
EmberDeviseBootstrap.SignUpController = Ember.Object.extend({
email: null,
password: null,
passwordConfirmation: null,
//
// This action performs the sign up request with the provided
// credentials from the form.
//
signUp: function() {
try {
email = this.get('email');
password = this.get('password');
confirm = this.get('passwordConfirmation');
pat = new RegExp(Devise.email_pattern);
if (email == null) {
alert('Email is required');
} else if (password == null || confirm == null) {
alert('Password and confirmation are required');
} else if (password != confirm) {
alert('Password and confirmation must match');
} else if (password.length < Devise.password_length.min ||
password.length > Devise.password_length.max) {
alert('Password must be at least '+Devise.password_length.min+
' and shorter than '+Devise.password_length.max);
} else if ( !pat.test(email) ) {
alert('Email not correctly formed');
} else {
$.ajax({
url: EmberDeviseBootstrap.get('signUpPath')+'.json',
type: 'POST',
dataType: 'json',
data: $.extend(authParams,{
'user[email]': email,
'user[password]': password,
'user[password_confirmation]': confirm}),
success: function(data) {
//alert('Completed sign up process: '+ JSON.stringify(data));
EmberDeviseBootstrap.currentUser.set('email', data.email);
EmberDeviseBootstrap.currentUser.set('id', data.id);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error completing sign up: '+textStatus+' error: '+errorThrown);
}
});
$("#sign_up_menu").removeClass('open');
}
} catch (ex) {
alert('Error in validation: '+ex);
}
return false;
}
});
EmberDeviseBootstrap.signUpController = EmberDeviseBootstrap.SignUpController.create();
|
/* choona.js 1.3
(c) 2011-2013 Narendra Sisodiya, narendra@narendrasisodiya.com
choona.js is distributed under the MIT license.
For all details and documentation:
https://github.com/nsisodiya/choona.js
For demos using Choona.js
http://nsisodiya.github.com/Demo-Scalable-App/
Change Log
1.3 Removed Backbone.js, As Now this Library support EventBus,
Added Code for EventBus.
Added Supprot for Inheritance between modules by
Adding choona.extendModule function
1.2.1 Added support for template property.
1.2 Added Concept of EventBus,
Added Local Event Handling using Backbone.js
Removed amplify.js
modified Erase UI,
Added startApp Method, loadApplication is removed now
AppCore now accept Data Object rather that argument list,
removed start() function for ApplicationModule.
1.0.1 Added document.querySelector
*/
var EventBus = function () {
this.NewsPaperList = {};
this.OrderList = [];
};
EventBus.prototype = {
subscribe: function (newsPaper, address) {
if ((typeof newsPaper !== "string") || (typeof address !== "function")) {
return -1;
}
var AList = this.NewsPaperList[newsPaper];
if (typeof AList !== "object") {
AList = this.NewsPaperList[newsPaper] = [];
}
var customer = AList.push(address) - 1 ;
return this.OrderList.push({
newsPaper: newsPaper,
customer: customer
}) - 1;
},
unsubscribe: function (orderId) {
var O = this.OrderList[orderId];
if (O !== undefined) {
delete this.NewsPaperList[O.newsPaper][O.customer];
delete O;
}
},
publish: function (newsPaper, content) {
var AddressList = this.NewsPaperList[newsPaper];
if (typeof AddressList !== "undefined") {
var l = AddressList.length;
for (var i = 0; i < l; i++) {
if (typeof AddressList[i] === "function") {
AddressList[i].call(this, content);
}
}
}
}
};
var choona = (function(){
var util = {
debug : false,
log : function(msg) {
if (this.debug === true && typeof console == "object"
&& typeof console.log == "function") {
console.log(msg);
}
}
};
var GlobalEventBus = new EventBus();
var Sandbox = function(id){
this.id = id;
this.$ = null;
this.topicList = {};
this.moduleList = {};
this.eventBus = null;
};
Sandbox.Private = {
endAllModules: function(){
for (var i in this.moduleList ){
this.moduleList[i].end();
}
this.moduleList = {};
},
unsubscribeAll: function(){
for(var topic in this.topicList){
this.unsubscribe(topic);
}
},
eraseUI: function(){
this.$.innerHTML = '';
},
getModule: function(id){
//Get Module by ID, From Module List
if(this.moduleList[id] === undefined){
throw new Error("id::" + id + " is do not has any module. Please use, this.sb.startModule function to load module");
}else{
return this.moduleList[id];
}
},
endSandbox: function(){
//This will delete resource initialised by Sandbox
delete this.$;
delete this.id;
delete this.moduleList ;
delete this.eventBus;
delete this.topicList;
}
};
Sandbox.prototype = {
subscribe : function(topic, callback){//publish
this.topicList[topic] = this.eventBus.subscribe(topic, callback);
util.log('subscribed topic -> ' + topic);
},
getNewEventBus : function(){
return new EventBus();
},
unsubscribe : function(topic){
this.eventBus.unsubscribe(this.topicList[topic]);
delete this.topicList[topic];
util.log('cleared topic -> ' + topic);
},
publish: function(topic, val){//public
util.log('published -> ' + topic + ' = ' + val);
this.eventBus.publish(topic, val);
},
startModule: function(data){//public
if(typeof data.id !== "string" || data.id === ""){
throw new Error("Id provided is not String or it is a blank sting");
}
if(this.moduleList[data.id] === undefined){
//You cannot load more than 1 module at given Id.
//There is No module Loaded.
//@TODO - user should be able to load more modules in one container
data.parentNode = this.$;
data.parentEventBus = this.eventBus;
this.moduleList[data.id] = startApp(data);
}else{
throw new Error("data.id::" + data.id + " is already contains a module. Please provide separate id new module");
}
},
endModule:function(id){
Sandbox.Private.getModule.call(this,id).end();
delete this.moduleList[id];
//Deletion is needed because if parent get Ended, it should not try to delete the module again.
}
};
var AppCore = function(data){
var id = data.id,
node = data.node,
protoObj_Module = data.module,
config = data.config,
eventBus = data.eventBus,
parentEventBus = data.parentEventBus,
parentNode = data.parentNode;
if( protoObj_Module === undefined && (typeof protoObj_Module === "object")){
throw new Error("data.module is undefined for data.id = " + data.id);
return;
}
var defaultCreator = function(sandbox, config){
this.sb = sandbox;
this.id = sandbox.id; //Id of Container - This may be require to create Unique Ids
if(parentNode === undefined){
this.$ = document.querySelector( "#" + this.id);
}else{
this.$ = parentNode.querySelector( "#" + this.id);
}
this.sb.$ = this.$; // SandBox must contains reference to module Container
if(eventBus === undefined){
if(parentEventBus === undefined){
this.sb.eventBus = GlobalEventBus;
}else{
this.sb.eventBus = parentEventBus;
}
}else{
this.sb.eventBus = eventBus;
}
this.config = config;
};
defaultCreator.prototype = protoObj_Module;
this.sandbox = new Sandbox(id, node);
this.module = new defaultCreator(this.sandbox, config);
if(typeof this.module.template === "string"){
this.module.$.innerHTML = this.module.template;
}
if(typeof this.module.start === "function"){
this.module.start();
util.log('started module -> ' + this.module.id);
}else{
throw new Error("data.module.start is undefined for data.id = " + this.module.id);
}
};
AppCore.prototype = {
end: function(){
Sandbox.Private.endAllModules.call(this.sandbox);
if(typeof this.module.end === "function"){
this.module.end();
}
Sandbox.Private.eraseUI.call(this.sandbox);
Sandbox.Private.unsubscribeAll.call(this.sandbox);
Sandbox.Private.endSandbox.call(this.sandbox);
util.log('ended module -> ' + this.module.id);
delete this.module;
delete this.sandbox;
}
};
startApp = function(data){
return new AppCore(data);
};
var extendModule = function (base, derived) {
var X = Object.create(base); // Now X.__proto__ === base
for (var i in derived) {
X[i] = derived[i];
};
return X;
};
return {
startApp: startApp,
util: util,
extendModule: extendModule
};
})();
|
/*
* Tests for the appcache module.
*/
var appcache = require('../src/appcache.js').appcache;
//------------------------------------------------------------- Tests
// Setup
(function() {
console.log("Setting up the appcache test.");
console.log("");
console.log("NOTE: This is a visual test only. There are no asserts.");
console.log("");
})();
//Test
(function() {
appcache({
outfile: "./test.appcache",
CACHE: [
"test.html",
"invis.gif",
],
NETWORK: [
"http://awesome.com",
"/api/",
],
FALLBACK: [
"/api/fail test.html",
],
});
})();
// End
(function() {
console.log("TESTS COMPLETE!");
console.log("Please check the local directory and see if the file");
console.log("contains three sections and a build number.");
})();
|
// This test file has no tests!
|
/*global defineSuite*/
defineSuite([
'Scene/GridImageryProvider',
'Core/Ellipsoid',
'Core/GeographicTilingScheme',
'Core/WebMercatorTilingScheme',
'Scene/ImageryProvider',
'Specs/pollToPromise',
'ThirdParty/when'
], function(
GridImageryProvider,
Ellipsoid,
GeographicTilingScheme,
WebMercatorTilingScheme,
ImageryProvider,
pollToPromise,
when) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/
it('conforms to ImageryProvider interface', function() {
expect(GridImageryProvider).toConformToInterface(ImageryProvider);
});
it('returns valid value for hasAlphaChannel', function() {
var provider = new GridImageryProvider();
return pollToPromise(function() {
return provider.ready;
}).then(function() {
expect(typeof provider.hasAlphaChannel).toBe('boolean');
});
});
it('can use a custom ellipsoid', function() {
var ellipsoid = new Ellipsoid(1, 2, 3);
var provider = new GridImageryProvider({
ellipsoid : ellipsoid
});
return pollToPromise(function() {
return provider.ready;
}).then(function() {
expect(provider.tilingScheme.ellipsoid).toEqual(ellipsoid);
});
});
it('can provide a root tile', function() {
var provider = new GridImageryProvider();
return pollToPromise(function() {
return provider.ready;
}).then(function() {
expect(provider.tileWidth).toEqual(256);
expect(provider.tileHeight).toEqual(256);
expect(provider.maximumLevel).toBeUndefined();
expect(provider.tilingScheme).toBeInstanceOf(GeographicTilingScheme);
expect(provider.tileDiscardPolicy).toBeUndefined();
expect(provider.rectangle).toEqual(new GeographicTilingScheme().rectangle);
return when(provider.requestImage(0, 0, 0), function(image) {
expect(image).toBeDefined();
});
});
});
it('uses alternate tiling scheme if provided', function() {
var tilingScheme = new WebMercatorTilingScheme();
var provider = new GridImageryProvider({
tilingScheme : tilingScheme
});
return pollToPromise(function() {
return provider.ready;
}).then(function() {
expect(provider.tilingScheme).toBe(tilingScheme);
});
});
it('uses tile width and height if provided', function() {
var provider = new GridImageryProvider({
tileWidth : 123,
tileHeight : 456
});
return pollToPromise(function() {
return provider.ready;
}).then(function() {
expect(provider.tileWidth).toEqual(123);
expect(provider.tileHeight).toEqual(456);
});
});
});
|
describe('Chart.Controller', function() {
function waitForResize(chart, callback) {
var resizer = chart.chart.canvas.parentNode._chartjs.resizer;
var content = resizer.contentWindow || resizer;
var state = content.document.readyState || 'complete';
var handler = function() {
Chart.helpers.removeEvent(content, 'load', handler);
Chart.helpers.removeEvent(content, 'resize', handler);
setTimeout(callback, 50);
};
Chart.helpers.addEvent(content, state !== 'complete'? 'load' : 'resize', handler);
}
describe('context acquisition', function() {
var canvasId = 'chartjs-canvas';
beforeEach(function() {
var canvas = document.createElement('canvas');
canvas.setAttribute('id', canvasId);
window.document.body.appendChild(canvas);
});
afterEach(function() {
document.getElementById(canvasId).remove();
});
// see https://github.com/chartjs/Chart.js/issues/2807
it('should gracefully handle invalid item', function() {
var chart = new Chart('foobar');
expect(chart).not.toBeValidChart();
chart.destroy();
});
it('should accept a DOM element id', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart(canvasId);
expect(chart).toBeValidChart();
expect(chart.chart.canvas).toBe(canvas);
expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
it('should accept a canvas element', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart(canvas);
expect(chart).toBeValidChart();
expect(chart.chart.canvas).toBe(canvas);
expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
it('should accept a canvas context2D', function() {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext('2d');
var chart = new Chart(context);
expect(chart).toBeValidChart();
expect(chart.chart.canvas).toBe(canvas);
expect(chart.chart.ctx).toBe(context);
chart.destroy();
});
it('should accept an array containing canvas', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart([canvas]);
expect(chart).toBeValidChart();
expect(chart.chart.canvas).toBe(canvas);
expect(chart.chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
});
describe('config initialization', function() {
it('should create missing config.data properties', function() {
var chart = acquireChart({});
var data = chart.data;
expect(data instanceof Object).toBeTruthy();
expect(data.labels instanceof Array).toBeTruthy();
expect(data.labels.length).toBe(0);
expect(data.datasets instanceof Array).toBeTruthy();
expect(data.datasets.length).toBe(0);
});
it('should NOT alter config.data references', function() {
var ds0 = {data: [10, 11, 12, 13]};
var ds1 = {data: [20, 21, 22, 23]};
var datasets = [ds0, ds1];
var labels = [0, 1, 2, 3];
var data = {labels: labels, datasets: datasets};
var chart = acquireChart({
type: 'line',
data: data
});
expect(chart.data).toBe(data);
expect(chart.data.labels).toBe(labels);
expect(chart.data.datasets).toBe(datasets);
expect(chart.data.datasets[0]).toBe(ds0);
expect(chart.data.datasets[1]).toBe(ds1);
expect(chart.data.datasets[0].data).toBe(ds0.data);
expect(chart.data.datasets[1].data).toBe(ds1.data);
});
it('should initialize config with default options', function() {
var callback = function() {};
var defaults = Chart.defaults;
defaults.global.responsiveAnimationDuration = 42;
defaults.global.hover.onHover = callback;
defaults.line.hover.mode = 'x-axis';
defaults.line.spanGaps = true;
var chart = acquireChart({
type: 'line'
});
var options = chart.options;
expect(options.defaultFontSize).toBe(defaults.global.defaultFontSize);
expect(options.showLines).toBe(defaults.line.showLines);
expect(options.spanGaps).toBe(true);
expect(options.responsiveAnimationDuration).toBe(42);
expect(options.hover.onHover).toBe(callback);
expect(options.hover.mode).toBe('x-axis');
});
it('should override default options', function() {
var defaults = Chart.defaults;
defaults.global.responsiveAnimationDuration = 42;
defaults.line.hover.mode = 'x-axis';
defaults.line.spanGaps = true;
var chart = acquireChart({
type: 'line',
options: {
responsiveAnimationDuration: 4242,
spanGaps: false,
hover: {
mode: 'dataset',
},
title: {
position: 'bottom'
}
}
});
var options = chart.options;
expect(options.responsiveAnimationDuration).toBe(4242);
expect(options.spanGaps).toBe(false);
expect(options.hover.mode).toBe('dataset');
expect(options.title.position).toBe('bottom');
});
});
describe('config.options.aspectRatio', function() {
it('should use default "global" aspect ratio for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 620px'
}
});
expect(chart).toBeChartOfSize({
dw: 620, dh: 310,
rw: 620, rh: 310,
});
});
it('should use default "chart" aspect ratio for render and display sizes', function() {
var chart = acquireChart({
type: 'doughnut',
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 425px'
}
});
expect(chart).toBeChartOfSize({
dw: 425, dh: 425,
rw: 425, rh: 425,
});
});
it('should use "user" aspect ratio for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false,
aspectRatio: 3
}
}, {
canvas: {
style: 'width: 405px'
}
});
expect(chart).toBeChartOfSize({
dw: 405, dh: 135,
rw: 405, rh: 135,
});
});
it('should NOT apply aspect ratio when height specified', function() {
var chart = acquireChart({
options: {
responsive: false,
aspectRatio: 3
}
}, {
canvas: {
style: 'width: 400px; height: 410px'
}
});
expect(chart).toBeChartOfSize({
dw: 400, dh: 410,
rw: 400, rh: 410,
});
});
});
describe('config.options.responsive: false', function() {
it('should use default canvas size for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: ''
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 150,
rw: 300, rh: 150,
});
});
it('should use canvas attributes for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: '',
width: 305,
height: 245,
}
});
expect(chart).toBeChartOfSize({
dw: 305, dh: 245,
rw: 305, rh: 245,
});
});
it('should use canvas style for render and display sizes (if no attributes)', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 345px; height: 125px'
}
});
expect(chart).toBeChartOfSize({
dw: 345, dh: 125,
rw: 345, rh: 125,
});
});
it('should use attributes for the render size and style for the display size', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 345px; height: 125px;',
width: 165,
height: 85,
}
});
expect(chart).toBeChartOfSize({
dw: 345, dh: 125,
rw: 165, rh: 85,
});
});
it('should NOT inject the resizer element', function() {
var chart = acquireChart({
options: {
responsive: false
}
});
var wrapper = chart.chart.canvas.parentNode;
expect(wrapper.childNodes.length).toBe(1);
expect(wrapper.firstChild.tagName).toBe('CANVAS');
});
});
describe('config.options.responsive: true (maintainAspectRatio: false)', function() {
it('should fill parent width and height', function() {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: 'width: 150px; height: 245px'
},
wrapper: {
style: 'width: 300px; height: 350px'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
});
it('should resize the canvas when parent width changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.width = '455px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 350,
rw: 455, rh: 350,
});
wrapper.style.width = '150px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 150, dh: 350,
rw: 150, rh: 350,
});
done();
});
});
});
it('should resize the canvas when parent height changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.height = '455px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 455,
rw: 300, rh: 455,
});
wrapper.style.height = '150px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 150,
rw: 300, rh: 150,
});
done();
});
});
});
it('should NOT include parent padding when resizing the canvas', function(done) {
var chart = acquireChart({
type: 'line',
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'padding: 50px; width: 320px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.height = '355px';
wrapper.style.width = '455px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
done();
});
});
it('should resize the canvas when the canvas display style changes from "none" to "block"', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: 'display: none;'
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
var canvas = chart.chart.canvas;
canvas.style.display = 'block';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
done();
});
});
it('should resize the canvas when the wrapper display style changes from "none" to "block"', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'display: none; width: 460px; height: 380px'
}
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.display = 'block';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 460, dh: 380,
rw: 460, rh: 380,
});
done();
});
});
// https://github.com/chartjs/Chart.js/issues/3521
it('should resize the canvas after the wrapper has been re-attached to the DOM', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
var wrapper = chart.chart.canvas.parentNode;
var parent = wrapper.parentNode;
parent.removeChild(wrapper);
parent.appendChild(wrapper);
wrapper.style.height = '355px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 355,
rw: 320, rh: 355,
});
parent.removeChild(wrapper);
wrapper.style.width = '455px';
parent.appendChild(wrapper);
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
done();
});
});
});
});
describe('config.options.responsive: true (maintainAspectRatio: true)', function() {
it('should fill parent width and use aspect ratio to calculate height', function() {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: true
}
}, {
canvas: {
style: 'width: 150px; height: 245px'
},
wrapper: {
style: 'width: 300px; height: 350px'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 490,
rw: 300, rh: 490,
});
});
it('should resize the canvas with correct aspect ratio when parent width changes', function(done) {
var chart = acquireChart({
type: 'line', // AR == 2
options: {
responsive: true,
maintainAspectRatio: true
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 150,
rw: 300, rh: 150,
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.width = '450px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 450, dh: 225,
rw: 450, rh: 225,
});
wrapper.style.width = '150px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 150, dh: 75,
rw: 150, rh: 75,
});
done();
});
});
});
it('should NOT resize the canvas when parent height changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: true
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 320, dh: 160,
rw: 320, rh: 160,
});
var wrapper = chart.chart.canvas.parentNode;
wrapper.style.height = '455px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 160,
rw: 320, rh: 160,
});
wrapper.style.height = '150px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 160,
rw: 320, rh: 160,
});
done();
});
});
});
});
describe('controller.destroy', function() {
it('should restore canvas (and context) initial values', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
width: 180,
style: 'width: 512px; height: 480px'
},
wrapper: {
style: 'width: 450px; height: 450px; position: relative'
}
});
var canvas = chart.chart.canvas;
var wrapper = canvas.parentNode;
wrapper.style.width = '475px';
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 475, dh: 450,
rw: 475, rh: 450,
});
chart.destroy();
expect(canvas.getAttribute('width')).toBe('180');
expect(canvas.getAttribute('height')).toBe(null);
expect(canvas.style.width).toBe('512px');
expect(canvas.style.height).toBe('480px');
expect(canvas.style.display).toBe('');
done();
});
});
it('should remove the resizer element when responsive: true', function() {
var chart = acquireChart({
options: {
responsive: true
}
});
var wrapper = chart.chart.canvas.parentNode;
var resizer = wrapper.firstChild;
expect(wrapper.childNodes.length).toBe(2);
expect(resizer.tagName).toBe('IFRAME');
chart.destroy();
expect(wrapper.childNodes.length).toBe(1);
expect(wrapper.firstChild.tagName).toBe('CANVAS');
});
});
describe('controller.reset', function() {
it('should reset the chart elements', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 0]
}]
},
options: {
responsive: true
}
});
var meta = chart.getDatasetMeta(0);
// Verify that points are at their initial correct location,
// then we will reset and see that they moved
expect(meta.data[0]._model.y).toBe(333);
expect(meta.data[1]._model.y).toBe(183);
expect(meta.data[2]._model.y).toBe(32);
expect(meta.data[3]._model.y).toBe(484);
chart.reset();
// For a line chart, the animation state is the bottom
expect(meta.data[0]._model.y).toBe(484);
expect(meta.data[1]._model.y).toBe(484);
expect(meta.data[2]._model.y).toBe(484);
expect(meta.data[3]._model.y).toBe(484);
});
});
});
|
var Modal = require('./components/modal');
var UI = require('./components/ui');
var uid = require('../shared/util/uid');
var extend = require('extend');
var distUrl = (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1].src.split('/').slice(0, -2).join('/');
})();
module.exports = require('../shared/util/createClass')({
construct: function(config, options) {
this.setConfig(config);
options = extend(
true,
{
distUrl: distUrl,
selector: '[rel="assetpicker"]',
modal: {
src: null
},
ui: {
enabled: true
}
},
options || {}
);
if (!options.modal.src) {
options.modal.src = options.distUrl + '/index.html';
}
if (options.modal.src.match(/^https?:\/\/localhost/) || document.location.hostname === 'localhost') {
options.modal.src += '?' + uid();
}
this.pickConfig = {};
this.options = options;
this.modal = null;
this.element = null;
this.uis = [];
this._memoryEvents = {
'ready': null
};
this._callbacks = {};
this.on('ready', function () {
this.modal.modal.className += ' assetpicker-ready'
});
this.on('resize', function (maximize) {
this.modal[maximize ? 'maximize' : 'minimize']();
});
document.addEventListener('DOMContentLoaded', function () {
var inputs = document.querySelectorAll(this.options.selector);
for (var i = 0, l = inputs.length; i < l; i++) {
this.register(inputs[i]);
}
}.bind(this));
},
getOrigin: function () {
return document.location.origin;
},
getDistUrl: function () {
return this.options.distUrl;
},
on: function (event, callback) {
if (!this._callbacks.hasOwnProperty(event)) {
this._callbacks[event] = [];
}
this._callbacks[event].push(callback);
if (this._memoryEvents[event]) {
callback.apply(this, this._memoryEvents[event]);
}
return this;
},
_trigger: function (event) {
var args = Array.prototype.slice.call(arguments, 1);
if (this._callbacks[event]) {
this._callbacks[event].forEach(function (callback) {
return callback.apply(this, args);
}.bind(this));
}
if (this._memoryEvents.hasOwnProperty(event)) {
this._memoryEvents[event] = args;
}
},
register: function (element) {
if (element.hasAttribute('data-assetpicker')) {
return;
}
element.setAttribute('data-assetpicker', 1);
if (element.hasAttribute('data-ui') || this.options.ui && this.options.ui.enabled) {
this.uis.push(new UI(element, this));
}
element.addEventListener('click', function (event) {
event.preventDefault();
this.open(element);
}.bind(this));
},
_getPickConfig: function (element) {
var getSplitAttr = function (attr) {
var value = element.getAttribute(attr);
return value.length ? value.split(',') : []
};
return extend({}, this.config.pick, {
limit: element.hasAttribute('data-limit') ? parseInt(element.getAttribute('data-limit')) : undefined,
types: element.hasAttribute('data-types') ? getSplitAttr('data-types') : undefined,
extensions: element.hasAttribute('data-ext') ? getSplitAttr('data-ext') : undefined
});
},
getUi: function (element) {
for (var i = 0, l = this.uis.length; i < l; i++) {
if (this.uis[i].element === element) {
return this.uis[i];
}
}
},
open: function (options) {
if (// http://stackoverflow.com/a/384380, options is a HTMLElement
typeof HTMLElement === "object" && options instanceof HTMLElement //DOM2
|| options && typeof options === "object" && options !== null && options.nodeType === 1 && typeof options.nodeName==="string") {
this.element = options;
this.pickConfig = this._getPickConfig(options);
} else {
this.element = undefined;
this.pickConfig = extend({}, this.config.pick, options);
}
if (!this.modal) {
this.modal = new Modal(this.options.modal);
this.modal.messaging.registerServer('picker', this);
this.on(
'ready',
function () {
this.modal.messaging.call('app.setConfig', {pick: this.pickConfig})
}
);
} else {
try {
// When this fails, it likely means the app is not ready yet and above ready listener will handle this
this.modal.messaging.call('app.setConfig', {pick: this.pickConfig});
} catch (e) {}
}
this.modal.open();
},
getConfig: function() {
return this.config;
},
setConfig: function (config) {
this.config = extend(
true,
{
pick: {
limit: 1,
types: ['file'],
extensions: []
}
},
config
);
if (this.modal) {
picker.modal.messaging.call('app.setConfig', this.config);
}
},
pick: function(picked) {
if (this.element) {
var tagName = this.element.tagName.toLowerCase();
if (tagName === 'input' && this.element.getAttribute('type') === 'button' || tagName === 'button') {
this.element.setAttribute('value', picked ? JSON.stringify(picked) : '');
}
}
this._trigger('pick', picked);
if (this.modal) {
this.modal.close();
}
}
});
|
$(document).ready(function(){
$("#id5").click(function(){
$("#id5").animate({
left : '85%',
opacity :'0',
},2000);
setTimeout(function a(){window.location="learncplusplus.php";},2000);
});
$("#id6").click(function(){
$("#id6").animate({
left : '85%',
opacity :'0',
},2000);
setTimeout(function b(){window.location="learnjava.php";},2000);
});
$("#id7").click(function(){
$("#id7").animate({
left : '85%',
opacity :'0',
},2000);
setTimeout(function c(){window.location="ecomenu.php";},2000);
});
$("#id8").click(function(){
$("#id8").animate({
left : '85%',
opacity :'0',
},2000);
setTimeout(function d(){window.location="search_video.html";},2000);
});
$("#yt-js-player").click(function(){
window.location="yt-js-player.html";
});
});
|
'use strict';
var floordate = require('floordate');
var d = new Date();
var v = floordate(d, 'year').getFullYear();
if ((v > 2015) && (v < 2075)) {
console.log('ok');
}
|
var firstnamePrefixes = [
"an", "bar", "ben", "ber",
"ca", "char", "chris", "deb", "don", "doro",
"ed", "el", "ga", "ge", "hel",
"ja", "jan", "jay", "je", "jen", "jess", "jo",
"ka", "ke", "ken", "lar", "lau", "lin",
"ma", "mar", "max",
"nan", "pan",
"sa", "san", "sha", "ste", "su",
"theo", "tho", "timo",
"vic", "xan" ];
var firstnameSuffixes = [
"bara", "beth", "bert", "bin", "bold", "by", "cy",
"der", "dra", "dora",
"en", "era", "fred", "frida",
"gard", "gret", "grid",
"fina", "fine", "iam", "ica", "ifer", "ine",
"la", "lios", "lotte",
"man", "mas", "na", "nald", "nard", "neth", "nie", "ny",
"ra", "ren", "ria", "ric", "ron", "rol", "ry",
"san", "seph", "son",
"thea", "theus", "thro", "thy", "tina", "tine", "toph", "topher", "ton", "tony", "tra", "trus",
"vid", "ven", "ward", "well", "win", "wina", "der", "ya" ];
var firstnameAny = [
"carl", "da", "mi", "min", "no", "pe", "ro", "ron", "ter", "to", "tor", "will",
"wolf"];
var firstnamePrefixCounts = [
new WeightedValue(1, 100),
new WeightedValue(2, 25)
]
var conjections = [
new WeightedValue(" ", 100),
new WeightedValue(" of ", 5)
];
var lastnamePrefixes = [
"big", "black", "breeding", "brown", "burly", "burn",
"crooked", "cuddle", "curly",
"dark", "double", "drink", "dwarven",
"earth",
"fast", "feeding", "fine",
"golden",
"happy", "hard", "high", "hot", "humming", "hunting",
"leading", "lucky",
"mac", "mad", "mocking",
"old", "over",
"proud",
"quick",
"rich", "roll", "round",
"silvery", "small", "soft", "spider", "stark", "swift",
"tall", "throwing", "tiny",
"über", "un", "under",
"wiggle", "wooly"
];
var lastnameSuffixes = [
"balls", "bearer", "bells", "belly", "blaze", "breast", "breed", "butcher",
"climber", "crank",
"down", "drinker", "dwarf",
"face", "feet", "foe", "food", "fiend", "friend",
"hunter",
"ikowsky",
"jester", "joker", "joy", "judge",
"leader", "leaf", "less", "lich", "luck", "ly",
"menace",
"ness",
"pony",
"realm", "ride", "rise",
"shoe", "smith", "spinner", "strength", "swift",
"ton", "toss",
"wife", "woman"
];
var lastnameAny = [
"arm",
"back", "ball", "barrel", "bass", "bear", "beard", "bed", "beer", "bell", "bird", "blood", "boy", "brood", "bunny",
"chicken", "child", "claw", "colt", "con", "cow", "crow",
"dagger", "devil", "dog", "dork", "drop",
"fire", "flesh", "foot", "forest", "fox", "fraud", "frog",
"giant", "girl", "gold", "greed",
"hammer", "hand", "head", "heart", "hill", "horse", "house", "hut",
"jaw",
"king",
"land", "lead", "leather", "lust",
"man", "meat", "milk", "mood", "mountain", "mouse", "mouth",
"neck", "nerd", "nest", "noose",
"paw", "pig", "ploy", "power", "pride", "prince",
"rage", "rascal", "rock", "rogue", "ruse", "rush",
"scare", "sheep", "silver", "smurf", "snake", "snow", "sow", "spark", "spring", "star", "stone", "storm", "strong", "sun", "sword",
"time", "tower", "tooth", "tree", "trick",
"viper",
"water", "weasel", "whisper", "wild", "wind", "wolf", "wood", "word", "wrath"
];
var lastnamePrefixCounts = [
new WeightedValue(1, 100),
new WeightedValue(2, 20)
];
var COMPOSITE_LASTNAME_CHANCE = 0;
|
angular.module('simulator').controller('snitch', ['$scope',
function($scope) {
$scope.simulatedActionDetailArray=
[
//can be part of text factory
'you are smart. It is advised that you remain such. You don\'t get points for not snitching. You get to keep your life.',
'you shouldn\'t be looking at this because they are coming after you.',
'and you are of sound mind to still check your score, then, you must be crazy. You get a little bump.',
'for the sake of the community Thug Report has alerted local bosses to "take care" of you.'
];
$scope.score= $('thug-score').text();
$(document).ready(function(){
$scope.newScore=$scope.score;
$scope.simulatedActionNumber=0;
$scope.change=function(){
$scope.simulatedActionNumber=$('input[name="snitch"]').val();
$scope.simulatedActionDetail=$scope.simulatedActionDetailArray[$scope.simulatedActionNumber];
$scope.newScore=null;
if($scope.simulatedActionNumber==0){
$scope.newScore=$scope.score;
}
else if($scope.simulatedActionNumber==1){
$scope.newScore=parseInt($scope.score)*.8;
//can become factory
if($scope.newScore<300){
$scope.newScore=300;
}else if($scope.newScore>800){
$scope.newScore=800;
}
}
else if($scope.simulatedActionNumber==2){
$scope.newScore=parseInt($scope.score)*.5;
}
else if($scope.simulatedActionNumber==3){
$scope.newScore='(✖╭╮✖)';
};
$('new-score').text($scope.newScore);
};
});
}
]); |
import { avalon, isArrayLike, isPlainObjectCompact, compaceQuote } from '../../src/seed/lang.compact'
describe('seed/lang', function () {
it('quote', function () {
expect(avalon.quote).toA('function')
expect(avalon.quote('1')).toBe('"1"')
expect(avalon.quote('foo\nbar\r\nbaz')).toBe('"foo\\nbar\\r\\nbaz"')
expect(compaceQuote('1')).toBe('"1"')
expect(compaceQuote('foo\nbar\r\nbaz')).toBe('"foo\\nbar\\r\\nbaz"')
expect(compaceQuote('\u0001')).toBe('"\\u0001"')
})
it('type', function () {
var fn = avalon.type
expect(fn(/e\d+/)).toEqual('regexp')
expect(fn('sss')).toEqual('string')
expect(fn(111)).toEqual('number')
expect(fn(new Error)).toEqual('error')
expect(fn(Date)).toEqual('function')
expect(fn(new Date)).toEqual('date')
expect(fn({})).toEqual('object')
expect(fn(null)).toEqual('null')
expect(fn(void 0)).toEqual('undefined')
})
it('isFunction', function () {
expect(avalon.isFunction(avalon.noop)).toEqual(true)
})
it('isWindow', function () {
expect(avalon.isWindow(avalon.document)).toEqual(false)
expect(avalon.isWindow(window)).toBeTruthy()
})
it('isPlainObjectCompact', function () {
var pass, doc, parentObj, childObj, deep,
fn = function () { };
// The use case that we want to match
expect(isPlainObjectCompact({})).toBeTruthy()
expect(isPlainObjectCompact(new window.Object())).toBeTruthy()
expect(isPlainObjectCompact({ constructor: fn })).toBeTruthy()
expect(isPlainObjectCompact({ constructor: "foo" })).toBeTruthy()
parentObj = {}
// Not objects shouldn't be matched
expect(!isPlainObjectCompact("")).toBeTruthy()
expect(!isPlainObjectCompact(0) && !isPlainObjectCompact(1)).toBeTruthy()
expect(!isPlainObjectCompact(true) && !isPlainObjectCompact(false)).toBeTruthy()
expect(!isPlainObjectCompact(null)).toBeTruthy()
expect(!isPlainObjectCompact(undefined)).toBeTruthy()
// Arrays shouldn't be matched
expect(!isPlainObjectCompact([])).toBeTruthy()
// Instantiated objects shouldn't be matched
expect(!isPlainObjectCompact(new Date())).toBeTruthy()
// Functions shouldn't be matched
expect(!isPlainObjectCompact(fn)).toBeTruthy()
// Again, instantiated objects shouldn't be matched
expect(!isPlainObjectCompact(new fn())).toBeTruthy()
// Makes the function a little more realistic
// (and harder to detect, incidentally)
fn.prototype["someMethod"] = function () { };
// Again, instantiated objects shouldn't be matched
expect(!isPlainObjectCompact(new fn())).toBeTruthy()
// Instantiated objects with primitive constructors shouldn't be matched
fn.prototype.constructor = "foo";
expect(!isPlainObjectCompact(new fn())).toBeTruthy()
// Deep object
deep = { "foo": { "baz": true }, "foo2": document }
expect(isPlainObjectCompact(deep)).toBeTruthy()
// DOM Element
expect(!isPlainObjectCompact(document.createElement("div"))).toBeTruthy()
// Window
expect(!isPlainObjectCompact(window)).toBeTruthy()
})
it('isPlainObject', function () {
expect(avalon.isPlainObject({})).toBeTruthy()
expect(avalon.isPlainObject(new Object)).toBeTruthy()
})
it('mix', function () {
expect(avalon.mix).toA('function')
expect(avalon.mix('aaa', {a: 1})).toEqual({a: 1})
var empty, optionsWithLength, optionsWithDate, myKlass,
customObject, optionsWithCustomObject, MyNumber, ret,
nullUndef, target, recursive, obj,
defaults, defaultsCopy, options1, options1Copy, options2, options2Copy, merged2,
settings = { "xnumber1": 5, "xnumber2": 7, "xstring1": "peter", "xstring2": "pan" },
options = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" },
optionsCopy = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" },
merged = { "xnumber1": 5, "xnumber2": 1, "xstring1": "peter", "xstring2": "x", "xxx": "newstring" },
deep1 = { "foo": { "bar": true } },
deep2 = { "foo": { "baz": true }, "foo2": document },
deep2copy = { "foo": { "baz": true }, "foo2": document },
deepmerged = { "foo": { "bar": true, "baz": true }, "foo2": document },
arr = [1, 2, 3],
nestedarray = { "arr": arr }
avalon.mix(settings, options)
expect(settings).toEqual(merged)
expect(options).toEqual(optionsCopy)
avalon.mix(settings, null, options)
expect(settings).toEqual(merged)
expect(options).toEqual(optionsCopy)
avalon.mix(true, deep1, deep2);
expect(deep1["foo"]).toEqual(deepmerged["foo"])
expect(deep2["foo"]).toEqual(deep2copy["foo"])
expect(deep1["foo2"]).toBe(document)
expect(avalon.mix(true, {}, nestedarray)["arr"]).not.toBe(arr)
var circulate = {}
var child = { a: circulate }
expect(avalon.mix(circulate, child, { a: 1 })).toEqual({ a: 1 })
avalon.mix({ testA: 1 }) //将数据加在它上面
expect(avalon.testA).toEqual(1)
delete avalon.testA
// ???
// var testA = {testA: 1}
// avalon.mix(testA, 'string') //当参数为其他简单类型
// expect(testA ).toEqual( {testA: 1} )
// deep copy with array, followed by object
var result, initial = {
// This will make "copyIsArray" true
array: [1, 2, 3, 4],
// If "copyIsArray" doesn't get reset to false, the check
// will evaluate true and enter the array copy block
// instead of the object copy block. Since the ternary in the
// "copyIsArray" block will evaluate to false
// (check if operating on an array with ), this will be
// replaced by an empty array.
object: {}
}
result = avalon.mix(true, {}, initial)
//IE8 会完蛋?
expect(result.array).toEqual(initial.array)
expect(!Array.isArray(result.object)).toBe(true)
})
it('each', function () {
expect(avalon.each).toA('function')
var array = []
avalon.each({ a: 1, b: 2 }, function (k, v) {
array.push(k, v)
})
expect(array.join(',')).toBe('a,1,b,2')
var array2 = []
avalon.each(['c', 'd'], function (k, v) {
array2.push(k, v)
})
expect(array2.join(',')).toBe('0,c,1,d')
var seen = []
avalon.each([1, 2, 3], function (k, v) {
seen.push(v);
if (k === 1) {
return false
}
});
expect(seen).toEqual([1, 2])
var seen2 = []
avalon.each({ x: 11, y: 22, z: 33 }, function (k, v) {
if (k === 'z') {
return false
}
seen2.push(v)
})
expect(seen2).toEqual([11, 22])
})
it('isArrayLike', function () {
expect(isArrayLike({
0: 11,
1: 11,
length: 2
})).toBeTruthy()
expect(isArrayLike(document.childNodes)).toBeTruthy()
expect(isArrayLike(arguments)).toBeTruthy()
expect(!isArrayLike(null)).toBeTruthy()
expect(!isArrayLike(undefined)).toBeTruthy()
expect(!isArrayLike(true)).toBeTruthy()
expect(!isArrayLike(false)).toBeTruthy()
expect(!isArrayLike(function () { })).toBeTruthy()
expect(!isArrayLike('')).toBeTruthy()
expect(!isArrayLike('abc')).toBeTruthy()
})
}) |
/*
JavaScript Snake
By Patrick Gillespie
http://patorjk.com/games/snake
*/
/**
* @module Snake
* @class SNAKE
*/
var SNAKE = SNAKE || {};
/**
* @method addEventListener
* @param {Object} obj The object to add an event listener to.
* @param {String} event The event to listen for.
* @param {Function} funct The function to execute when the event is triggered.
* @param {Boolean} evtCapturing True to do event capturing, false to do event bubbling.
*/
SNAKE.addEventListener = (function() {
if (window.addEventListener) {
return function(obj, event, funct, evtCapturing) {
obj.addEventListener(event, funct, evtCapturing);
};
} else if (window.attachEvent) {
return function(obj, event, funct) {
obj.attachEvent("on" + event, funct);
};
}
})();
/**
* @method removeEventListener
* @param {Object} obj The object to remove an event listener from.
* @param {String} event The event that was listened for.
* @param {Function} funct The function that was executed when the event is triggered.
* @param {Boolean} evtCapturing True if event capturing was done, false otherwise.
*/
SNAKE.removeEventListener = (function() {
if (window.removeEventListener) {
return function(obj, event, funct, evtCapturing) {
obj.removeEventListener(event, funct, evtCapturing);
};
} else if (window.detachEvent) {
return function(obj, event, funct) {
obj.detachEvent("on" + event, funct);
};
}
})();
/**
* This class manages the snake which will reside inside of a SNAKE.Board object.
* @class Snake
* @constructor
* @namespace SNAKE
* @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this snake resides in), startRow and startCol.
*/
SNAKE.Snake = SNAKE.Snake || (function() {
// -------------------------------------------------------------------------
// Private static variables and methods
// -------------------------------------------------------------------------
var instanceNumber = 0;
var blockPool = [];
var SnakeBlock = function() {
this.elm = null;
this.elmStyle = null;
this.row = -1;
this.col = -1;
this.xPos = -1000;
this.yPos = -1000;
this.next = null;
this.prev = null;
};
// this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html
function getNextHighestZIndex(myObj) {
var highestIndex = 0,
currentIndex = 0,
ii;
for (ii in myObj) {
if (myObj[ii].elm.currentStyle){
currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10);
}else if(window.getComputedStyle) {
currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10);
}
if(!isNaN(currentIndex) && currentIndex > highestIndex){
highestIndex = currentIndex;
}
}
return(highestIndex+1);
}
// -------------------------------------------------------------------------
// Contructor + public and private definitions
// -------------------------------------------------------------------------
/*
config options:
playingBoard - the SnakeBoard that this snake belongs too.
startRow - The row the snake should start on.
startCol - The column the snake should start on.
*/
return function(config) {
if (!config||!config.playingBoard) {return;}
// ----- private variables -----
var me = this,
playingBoard = config.playingBoard,
myId = instanceNumber++,
growthIncr = 5,
moveQueue = [], // a queue that holds the next moves of the snake
currentDirection = 1, // 0: up, 1: left, 2: down, 3: right
columnShift = [0, 1, 0, -1],
rowShift = [-1, 0, 1, 0],
xPosShift = [],
yPosShift = [],
snakeSpeed = 75,
isDead = false;
// ----- public variables -----
me.snakeBody = {};
me.snakeBody["b0"] = new SnakeBlock(); // create snake head
me.snakeBody["b0"].row = config.startRow || 1;
me.snakeBody["b0"].col = config.startCol || 1;
me.snakeBody["b0"].xPos = me.snakeBody["b0"].row * playingBoard.getBlockWidth();
me.snakeBody["b0"].yPos = me.snakeBody["b0"].col * playingBoard.getBlockHeight();
me.snakeBody["b0"].elm = createSnakeElement();
me.snakeBody["b0"].elmStyle = me.snakeBody["b0"].elm.style;
playingBoard.getBoardContainer().appendChild( me.snakeBody["b0"].elm );
me.snakeBody["b0"].elm.style.left = me.snakeBody["b0"].xPos + "px";
me.snakeBody["b0"].elm.style.top = me.snakeBody["b0"].yPos + "px";
me.snakeBody["b0"].next = me.snakeBody["b0"];
me.snakeBody["b0"].prev = me.snakeBody["b0"];
me.snakeLength = 1;
me.snakeHead = me.snakeBody["b0"];
me.snakeTail = me.snakeBody["b0"];
me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'');
me.snakeHead.elm.className += " snake-snakebody-alive";
// ----- private methods -----
function createSnakeElement() {
var tempNode = document.createElement("div");
tempNode.className = "snake-snakebody-block";
tempNode.style.left = "-1000px";
tempNode.style.top = "-1000px";
tempNode.style.width = playingBoard.getBlockWidth() + "px";
tempNode.style.height = playingBoard.getBlockHeight() + "px";
return tempNode;
}
function createBlocks(num) {
var tempBlock;
var tempNode = createSnakeElement();
for (var ii = 1; ii < num; ii++){
tempBlock = new SnakeBlock();
tempBlock.elm = tempNode.cloneNode(true);
tempBlock.elmStyle = tempBlock.elm.style;
playingBoard.getBoardContainer().appendChild( tempBlock.elm );
blockPool[blockPool.length] = tempBlock;
}
tempBlock = new SnakeBlock();
tempBlock.elm = tempNode;
playingBoard.getBoardContainer().appendChild( tempBlock.elm );
blockPool[blockPool.length] = tempBlock;
}
// ----- public methods -----
/**
* This method is called when a user presses a key. It logs arrow key presses in "moveQueue", which is used when the snake needs to make its next move.
* @method handleArrowKeys
* @param {Number} keyNum A number representing the key that was pressed.
*/
/*
Handles what happens when an arrow key is pressed.
Direction explained (0 = up, etc etc)
0
3 1
2
*/
me.handleArrowKeys = function(keyNum) {
if (isDead) {return;}
var snakeLength = me.snakeLength;
var lastMove = moveQueue[0] || currentDirection;
switch (keyNum) {
case 37:
if ( lastMove !== 1 || snakeLength === 1 ) {
moveQueue.unshift(3); //SnakeDirection = 3;
}
break;
case 38:
if ( lastMove !== 2 || snakeLength === 1 ) {
moveQueue.unshift(0);//SnakeDirection = 0;
}
break;
case 39:
if ( lastMove !== 3 || snakeLength === 1 ) {
moveQueue.unshift(1); //SnakeDirection = 1;
}
break;
case 40:
if ( lastMove !== 0 || snakeLength === 1 ) {
moveQueue.unshift(2);//SnakeDirection = 2;
}
break;
}
};
/**
* This method is executed for each move of the snake. It determines where the snake will go and what will happen to it. This method needs to run quickly.
* @method go
*/
me.go = function() {
var oldHead = me.snakeHead,
newHead = me.snakeTail,
myDirection = currentDirection,
grid = playingBoard.grid; // cache grid for quicker lookup
me.snakeTail = newHead.prev;
me.snakeHead = newHead;
// clear the old board position
if ( grid[newHead.row] && grid[newHead.row][newHead.col] ) {
grid[newHead.row][newHead.col] = 0;
}
if (moveQueue.length){
myDirection = currentDirection = moveQueue.pop();
}
newHead.col = oldHead.col + columnShift[myDirection];
newHead.row = oldHead.row + rowShift[myDirection];
newHead.xPos = oldHead.xPos + xPosShift[myDirection];
newHead.yPos = oldHead.yPos + yPosShift[myDirection];
if ( !newHead.elmStyle ) {
newHead.elmStyle = newHead.elm.style;
}
newHead.elmStyle.left = newHead.xPos + "px";
newHead.elmStyle.top = newHead.yPos + "px";
// check the new spot the snake moved into
if (grid[newHead.row][newHead.col] === 0) {
grid[newHead.row][newHead.col] = 1;
setTimeout(function(){me.go();}, snakeSpeed);
} else if (grid[newHead.row][newHead.col] > 0) {
me.handleDeath();
} else if (grid[newHead.row][newHead.col] === playingBoard.getGridFoodValue()) {
grid[newHead.row][newHead.col] = 1;
me.eatFood();
setTimeout(function(){me.go();}, snakeSpeed);
}
};
/**
* This method is called when it is determined that the snake has eaten some food.
* @method eatFood
*/
me.eatFood = function() {
if (blockPool.length <= growthIncr) {
createBlocks(growthIncr*2);
}
var blocks = blockPool.splice(0, growthIncr);
var ii = blocks.length,
index,
prevNode = me.snakeTail;
while (ii--) {
index = "b" + me.snakeLength++;
me.snakeBody[index] = blocks[ii];
me.snakeBody[index].prev = prevNode;
me.snakeBody[index].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
me.snakeBody[index].elm.className += " snake-snakebody-alive";
prevNode.next = me.snakeBody[index];
prevNode = me.snakeBody[index];
}
me.snakeTail = me.snakeBody[index];
me.snakeTail.next = me.snakeHead;
me.snakeHead.prev = me.snakeTail;
playingBoard.foodEaten();
};
/**
* This method handles what happens when the snake dies.
* @method handleDeath
*/
me.handleDeath = function() {
me.snakeHead.elm.style.zIndex = getNextHighestZIndex(me.snakeBody);
me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-alive\b/,'')
me.snakeHead.elm.className += " snake-snakebody-dead";
isDead = true;
playingBoard.handleDeath();
moveQueue.length = 0;
};
/**
* This method sets a flag that lets the snake be alive again.
* @method rebirth
*/
me.rebirth = function() {
isDead = false;
};
/**
* This method reset the snake so it is ready for a new game.
* @method reset
*/
me.reset = function() {
if (isDead === false) {return;}
var blocks = [],
curNode = me.snakeHead.next,
nextNode;
while (curNode !== me.snakeHead) {
nextNode = curNode.next;
curNode.prev = null;
curNode.next = null;
blocks.push(curNode);
curNode = nextNode;
}
me.snakeHead.next = me.snakeHead;
me.snakeHead.prev = me.snakeHead;
me.snakeTail = me.snakeHead;
me.snakeLength = 1;
for (var ii = 0; ii < blocks.length; ii++) {
blocks[ii].elm.style.left = "-1000px";
blocks[ii].elm.style.top = "-1000px";
blocks[ii].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
blocks[ii].elm.className += " snake-snakebody-alive";
}
blockPool.concat(blocks);
me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
me.snakeHead.elm.className += " snake-snakebody-alive";
me.snakeHead.row = config.startRow || 1;
me.snakeHead.col = config.startCol || 1;
me.snakeHead.xPos = me.snakeHead.row * playingBoard.getBlockWidth();
me.snakeHead.yPos = me.snakeHead.col * playingBoard.getBlockHeight();
me.snakeHead.elm.style.left = me.snakeHead.xPos + "px";
me.snakeHead.elm.style.top = me.snakeHead.yPos + "px";
};
// ---------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------
createBlocks(growthIncr*2);
xPosShift[0] = 0;
xPosShift[1] = playingBoard.getBlockWidth();
xPosShift[2] = 0;
xPosShift[3] = -1 * playingBoard.getBlockWidth();
yPosShift[0] = -1 * playingBoard.getBlockHeight();
yPosShift[1] = 0;
yPosShift[2] = playingBoard.getBlockHeight();
yPosShift[3] = 0;
};
})();
/**
* This class manages the food which the snake will eat.
* @class Food
* @constructor
* @namespace SNAKE
* @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this food resides in).
*/
SNAKE.Food = SNAKE.Food || (function() {
// -------------------------------------------------------------------------
// Private static variables and methods
// -------------------------------------------------------------------------
var instanceNumber = 0;
function getRandomPosition(x, y){
return Math.floor(Math.random()*(y+1-x)) + x;
}
// -------------------------------------------------------------------------
// Contructor + public and private definitions
// -------------------------------------------------------------------------
/*
config options:
playingBoard - the SnakeBoard that this object belongs too.
*/
return function(config) {
if (!config||!config.playingBoard) {return;}
// ----- private variables -----
var me = this;
var playingBoard = config.playingBoard;
var fRow, fColumn;
var myId = instanceNumber++;
var elmFood = document.createElement("div");
elmFood.setAttribute("id", "snake-food-"+myId);
elmFood.className = "snake-food-block";
elmFood.style.width = playingBoard.getBlockWidth() + "px";
elmFood.style.height = playingBoard.getBlockHeight() + "px";
elmFood.style.left = "-1000px";
elmFood.style.top = "-1000px";
playingBoard.getBoardContainer().appendChild(elmFood);
// ----- public methods -----
/**
* @method getFoodElement
* @return {DOM Element} The div the represents the food.
*/
me.getFoodElement = function() {
return elmFood;
};
/**
* Randomly places the food onto an available location on the playing board.
* @method randomlyPlaceFood
*/
me.randomlyPlaceFood = function() {
// if there exist some food, clear its presence from the board
if (playingBoard.grid[fRow] && playingBoard.grid[fRow][fColumn] === playingBoard.getGridFoodValue()){
playingBoard.grid[fRow][fColumn] = 0;
}
var row = 0, col = 0, numTries = 0;
var maxRows = playingBoard.grid.length-1;
var maxCols = playingBoard.grid[0].length-1;
while (playingBoard.grid[row][col] !== 0){
row = getRandomPosition(1, maxRows);
col = getRandomPosition(1, maxCols);
// in some cases there may not be any room to put food anywhere
// instead of freezing, exit out
numTries++;
if (numTries > 20000){
row = -1;
col = -1;
break;
}
}
playingBoard.grid[row][col] = playingBoard.getGridFoodValue();
fRow = row;
fColumn = col;
elmFood.style.top = row * playingBoard.getBlockHeight() + "px";
elmFood.style.left = col * playingBoard.getBlockWidth() + "px";
};
};
})();
/**
* This class manages playing board for the game.
* @class Board
* @constructor
* @namespace SNAKE
* @param {Object} config The configuration object for the class. Set fullScreen equal to true if you want the game to take up the full screen, otherwise, set the top, left, width and height parameters.
*/
SNAKE.Board = SNAKE.Board || (function() {
// -------------------------------------------------------------------------
// Private static variables and methods
// -------------------------------------------------------------------------
var instanceNumber = 0;
// this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html
function getNextHighestZIndex(myObj) {
var highestIndex = 0,
currentIndex = 0,
ii;
for (ii in myObj) {
if (myObj[ii].elm.currentStyle){
currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10);
}else if(window.getComputedStyle) {
currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10);
}
if(!isNaN(currentIndex) && currentIndex > highestIndex){
highestIndex = currentIndex;
}
}
return(highestIndex+1);
}
/*
This function returns the width of the available screen real estate that we have
*/
function getClientWidth(){
var myWidth = 0;
if( typeof window.innerWidth === "number" ) {
myWidth = window.innerWidth;//Non-IE
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;//IE 6+ in 'standards compliant mode'
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;//IE 4 compatible
}
return myWidth;
}
/*
This function returns the height of the available screen real estate that we have
*/
function getClientHeight(){
var myHeight = 0;
if( typeof window.innerHeight === "number" ) {
myHeight = window.innerHeight;//Non-IE
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myHeight = document.documentElement.clientHeight;//IE 6+ in 'standards compliant mode'
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myHeight = document.body.clientHeight;//IE 4 compatible
}
return myHeight;
}
// -------------------------------------------------------------------------
// Contructor + public and private definitions
// -------------------------------------------------------------------------
return function(inputConfig) {
// --- private variables ---
var me = this,
myId = instanceNumber++,
config = inputConfig || {},
MAX_BOARD_COLS = 250,
MAX_BOARD_ROWS = 250,
blockWidth = 20,
blockHeight = 20,
GRID_FOOD_VALUE = -1, // the value of a spot on the board that represents snake food, MUST BE NEGATIVE
myFood,
mySnake,
boardState = 1, // 0: in active; 1: awaiting game start; 2: playing game
myKeyListener,
// Board components
elmContainer, elmPlayingField, elmAboutPanel, elmLengthPanel, elmWelcome, elmTryAgain;
// --- public variables ---
me.grid = [];
// ---------------------------------------------------------------------
// private functions
// ---------------------------------------------------------------------
function createBoardElements() {
elmPlayingField = document.createElement("div");
elmPlayingField.setAttribute("id", "playingField");
elmPlayingField.className = "snake-playing-field";
SNAKE.addEventListener(elmPlayingField, "click", function() {
elmContainer.focus();
}, false);
elmAboutPanel = document.createElement("div");
elmAboutPanel.className = "snake-panel-component";
elmAboutPanel.innerHTML = "<a href='http://patorjk.com/blog/software/' class='snake-link'>more patorjk.com apps</a> - <a href='https://github.com/patorjk/JavaScript-Snake' class='snake-link'>source code</a>";
elmLengthPanel = document.createElement("div");
elmLengthPanel.className = "snake-panel-component";
elmLengthPanel.innerHTML = "Length: 1";
elmWelcome = createWelcomeElement();
elmTryAgain = createTryAgainElement();
SNAKE.addEventListener( elmContainer, "keyup", function(evt) {
if (!evt) var evt = window.event;
evt.cancelBubble = true;
if (evt.stopPropagation) {evt.stopPropagation();}
if (evt.preventDefault) {evt.preventDefault();}
return false;
}, false);
elmContainer.className = "snake-game-container";
elmContainer.appendChild(elmPlayingField);
elmContainer.appendChild(elmAboutPanel);
elmContainer.appendChild(elmLengthPanel);
elmContainer.appendChild(elmWelcome);
elmContainer.appendChild(elmTryAgain);
mySnake = new SNAKE.Snake({playingBoard:me,startRow:2,startCol:2});
myFood = new SNAKE.Food({playingBoard: me});
elmWelcome.style.zIndex = 1000;
}
function maxBoardWidth() {
return MAX_BOARD_COLS * me.getBlockWidth();
}
function maxBoardHeight() {
return MAX_BOARD_ROWS * me.getBlockHeight();
}
function createWelcomeElement() {
var tmpElm = document.createElement("div");
tmpElm.id = "sbWelcome" + myId;
tmpElm.className = "snake-welcome-dialog";
var welcomeTxt = document.createElement("div");
var fullScreenText = "";
if (config.fullScreen) {
fullScreenText = "On Windows, press F11 to play in Full Screen mode.";
}
welcomeTxt.innerHTML = "JavaScript Snake<p></p>Use the <strong>arrow keys</strong> on your keyboard to play the game. " + fullScreenText + "<p></p>";
var welcomeStart = document.createElement("button");
welcomeStart.appendChild( document.createTextNode("Play Game"));
var loadGame = function() {
SNAKE.removeEventListener(window, "keyup", kbShortcut, false);
tmpElm.style.display = "none";
me.setBoardState(1);
me.getBoardContainer().focus();
};
var kbShortcut = function(evt) {
if (!evt) var evt = window.event;
var keyNum = (evt.which) ? evt.which : evt.keyCode;
if (keyNum === 32 || keyNum === 13) {
loadGame();
}
};
SNAKE.addEventListener(window, "keyup", kbShortcut, false);
SNAKE.addEventListener(welcomeStart, "click", loadGame, false);
tmpElm.appendChild(welcomeTxt);
tmpElm.appendChild(welcomeStart);
return tmpElm;
}
function createTryAgainElement() {
var tmpElm = document.createElement("div");
tmpElm.id = "sbTryAgain" + myId;
tmpElm.className = "snake-try-again-dialog";
var tryAgainTxt = document.createElement("div");
tryAgainTxt.innerHTML = "JavaScript Snake<p></p>You died :(.<p></p>";
var tryAgainStart = document.createElement("button");
tryAgainStart.appendChild( document.createTextNode("Play Again?"));
var reloadGame = function() {
tmpElm.style.display = "none";
me.resetBoard();
me.setBoardState(1);
me.getBoardContainer().focus();
};
var kbTryAgainShortcut = function(evt) {
if (boardState !== 0 || tmpElm.style.display !== "block") {return;}
if (!evt) var evt = window.event;
var keyNum = (evt.which) ? evt.which : evt.keyCode;
if (keyNum === 32 || keyNum === 13) {
reloadGame();
}
};
SNAKE.addEventListener(window, "keyup", kbTryAgainShortcut, true);
SNAKE.addEventListener(tryAgainStart, "click", reloadGame, false);
tmpElm.appendChild(tryAgainTxt);
tmpElm.appendChild(tryAgainStart);
return tmpElm;
}
// ---------------------------------------------------------------------
// public functions
// ---------------------------------------------------------------------
/**
* Resets the playing board for a new game.
* @method resetBoard
*/
me.resetBoard = function() {
SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false);
mySnake.reset();
elmLengthPanel.innerHTML = "Length: 1";
me.setupPlayingField();
};
/**
* Gets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving.
* @method getBoardState
* @return {Number} The state of the board.
*/
me.getBoardState = function() {
return boardState;
};
/**
* Sets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving.
* @method setBoardState
* @param {Number} state The state of the board.
*/
me.setBoardState = function(state) {
boardState = state;
};
/**
* @method getGridFoodValue
* @return {Number} A number that represents food on a number representation of the playing board.
*/
me.getGridFoodValue = function() {
return GRID_FOOD_VALUE;
};
/**
* @method getPlayingFieldElement
* @return {DOM Element} The div representing the playing field (this is where the snake can move).
*/
me.getPlayingFieldElement = function() {
return elmPlayingField;
};
/**
* @method setBoardContainer
* @param {DOM Element or String} myContainer Sets the container element for the game.
*/
me.setBoardContainer = function(myContainer) {
if (typeof myContainer === "string") {
myContainer = document.getElementById(myContainer);
}
if (myContainer === elmContainer) {return;}
elmContainer = myContainer;
elmPlayingField = null;
me.setupPlayingField();
};
/**
* @method getBoardContainer
* @return {DOM Element}
*/
me.getBoardContainer = function() {
return elmContainer;
};
/**
* @method getBlockWidth
* @return {Number}
*/
me.getBlockWidth = function() {
return blockWidth;
};
/**
* @method getBlockHeight
* @return {Number}
*/
me.getBlockHeight = function() {
return blockHeight;
};
/**
* Sets up the playing field.
* @method setupPlayingField
*/
me.setupPlayingField = function () {
if (!elmPlayingField) {createBoardElements();} // create playing field
// calculate width of our game container
var cWidth, cHeight;
if (config.fullScreen === true) {
cTop = 0;
cLeft = 0;
cWidth = getClientWidth()-5;
cHeight = getClientHeight()-5;
document.body.style.backgroundColor = "#FC5454";
} else {
cTop = config.top;
cLeft = config.left;
cWidth = config.width;
cHeight = config.height;
}
// define the dimensions of the board and playing field
var wEdgeSpace = me.getBlockWidth()*2 + (cWidth % me.getBlockWidth());
var fWidth = Math.min(maxBoardWidth()-wEdgeSpace,cWidth-wEdgeSpace);
var hEdgeSpace = me.getBlockHeight()*3 + (cHeight % me.getBlockHeight());
var fHeight = Math.min(maxBoardHeight()-hEdgeSpace,cHeight-hEdgeSpace);
elmContainer.style.left = cLeft + "px";
elmContainer.style.top = cTop + "px";
elmContainer.style.width = cWidth + "px";
elmContainer.style.height = cHeight + "px";
elmPlayingField.style.left = me.getBlockWidth() + "px";
elmPlayingField.style.top = me.getBlockHeight() + "px";
elmPlayingField.style.width = fWidth + "px";
elmPlayingField.style.height = fHeight + "px";
// the math for this will need to change depending on font size, padding, etc
// assuming height of 14 (font size) + 8 (padding)
var bottomPanelHeight = hEdgeSpace - me.getBlockHeight();
var pLabelTop = me.getBlockHeight() + fHeight + Math.round((bottomPanelHeight - 30)/2) + "px";
elmAboutPanel.style.top = pLabelTop;
elmAboutPanel.style.width = "450px";
elmAboutPanel.style.left = Math.round(cWidth/2) - Math.round(450/2) + "px";
elmLengthPanel.style.top = pLabelTop;
elmLengthPanel.style.left = cWidth - 120 + "px";
// if width is too narrow, hide the about panel
if (cWidth < 700) {
elmAboutPanel.style.display = "none";
} else {
elmAboutPanel.style.display = "block";
}
me.grid = [];
var numBoardCols = fWidth / me.getBlockWidth() + 2;
var numBoardRows = fHeight / me.getBlockHeight() + 2;
for (var row = 0; row < numBoardRows; row++) {
me.grid[row] = [];
for (var col = 0; col < numBoardCols; col++) {
if (col === 0 || row === 0 || col === (numBoardCols-1) || row === (numBoardRows-1)) {
me.grid[row][col] = 1; // an edge
} else {
me.grid[row][col] = 0; // empty space
}
}
}
myFood.randomlyPlaceFood();
// setup event listeners
myKeyListener = function(evt) {
if (!evt) var evt = window.event;
var keyNum = (evt.which) ? evt.which : evt.keyCode;
if (me.getBoardState() === 1) {
if ( !(keyNum >= 37 && keyNum <= 40) ) {return;} // if not an arrow key, leave
// This removes the listener added at the #listenerX line
SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false);
myKeyListener = function(evt) {
if (!evt) var evt = window.event;
var keyNum = (evt.which) ? evt.which : evt.keyCode;
mySnake.handleArrowKeys(keyNum);
evt.cancelBubble = true;
if (evt.stopPropagation) {evt.stopPropagation();}
if (evt.preventDefault) {evt.preventDefault();}
return false;
};
SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false);
mySnake.rebirth();
mySnake.handleArrowKeys(keyNum);
me.setBoardState(2); // start the game!
mySnake.go();
}
evt.cancelBubble = true;
if (evt.stopPropagation) {evt.stopPropagation();}
if (evt.preventDefault) {evt.preventDefault();}
return false;
};
// Search for #listenerX to see where this is removed
SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false);
};
/**
* This method is called when the snake has eaten some food.
* @method foodEaten
*/
me.foodEaten = function() {
elmLengthPanel.innerHTML = "Length: " + mySnake.snakeLength;
myFood.randomlyPlaceFood();
};
/**
* This method is called when the snake dies.
* @method handleDeath
*/
me.handleDeath = function() {
var index = Math.max(getNextHighestZIndex( mySnake.snakeBody), getNextHighestZIndex( {tmp:{elm:myFood.getFoodElement()}} ));
elmContainer.removeChild(elmTryAgain);
elmContainer.appendChild(elmTryAgain);
elmTryAgain.style.zIndex = index;
elmTryAgain.style.display = "block";
me.setBoardState(0);
};
// ---------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------
config.fullScreen = (typeof config.fullScreen === "undefined") ? false : config.fullScreen;
config.top = (typeof config.top === "undefined") ? 0 : config.top;
config.left = (typeof config.left === "undefined") ? 0 : config.left;
config.width = (typeof config.width === "undefined") ? 400 : config.width;
config.height = (typeof config.height === "undefined") ? 400 : config.height;
if (config.fullScreen) {
SNAKE.addEventListener(window,"resize", function() {
me.setupPlayingField();
}, false);
}
me.setBoardState(0);
if (config.boardContainer) {
me.setBoardContainer(config.boardContainer);
}
}; // end return function
})(); |
export const ic_add_circle_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"},"children":[]}]}; |
import React, { Component } from 'react';
import { View, Text, ScrollView, ActivityIndicator, StyleSheet } from 'react-native';
import ForecastBlock from './ForecastBlock';
export default class ForecastDayView extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: []
}
}
loadData() {
let url = this.props.apiBaseUrl+"/intensity/date/"+this.props.date
return fetch( url, {
headers: {
'Accept': 'application/json',
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data: responseJson.data,
}, function() {
});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.loadData();
return;
}
render() {
if (this.state.isLoading) {
return (
<ActivityIndicator style={{flex: 1}} />
);
} else {
let average = 250.0; // Fixed for now, needs to be obtained dynamically in some way.
blocks = []
for(item in this.state.data) {
condition = "😐"
colour = "orange"
switch(this.state.data[item].intensity.index) {
case "very high":
condition = "😡"
colour = "red"
break;
case "high":
condition = "😦"
colour = "orangered"
break;
case "low":
condition = "😃"
colour = "yellowgreen"
break;
case "very low":
condition = "😁"
colour = "green"
break;
}
if (this.state.data[item].intensity.actual == null) {
time = new Date(this.state.data[item].from);
blocks.push(
<ForecastBlock
key={item}
value={this.state.data[item].intensity.forecast}
condition={condition}
colour={colour}
time={time.toLocaleTimeString("en-GB", {hour: '2-digit', minute:'2-digit'})}
/>
)
}
}
var dateObj = new Date(this.props.date)
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
day = dayNames[dateObj.getDay()]
date = dateObj.getDate().toString() + " " + monthNames[dateObj.getMonth()]
return (
<View style={{flex: 1}}>
<View style={this.styles.dayContainer}>
<Text style={this.styles.day}>{day}</Text>
<Text style={this.styles.date}>{date}</Text>
</View>
<ScrollView horizontal style={{flex: 1, backgroundColor: 'rgba(255,255,255,0.25)'}}>
{blocks}
</ScrollView>
</View>
);
}
}
styles = StyleSheet.create({
dayContainer: {
backgroundColor: 'transparent',
marginLeft: 10,
marginBottom: 10,
},
day: {
fontSize: 50,
fontWeight: 'bold',
color: 'white',
},
date: {
fontSize: 20,
color: 'grey',
},
});
}
|
import React, {Component, PropTypes} from 'react';
import Icon from '../icon';
import Images from '../images/images';
class SearchResults extends Component {
render() {
const {
searchText,
fetching,
searched,
loadingMore,
searchResults,
handleItemClick,
loadMore
} = this.props;
return <Images
images={searchResults}
imagesLoaded={!fetching}
open={handleItemClick}
loadingMore={loadingMore}
loadMore={loadMore} />;
}
}
export default SearchResults;
|
(function () {
'use strict';
describe('Armors Route Tests', function () {
// Initialize global variables
var $scope,
ArmorsService;
// We can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($rootScope, _ArmorsService_) {
// Set a new global scope
$scope = $rootScope.$new();
ArmorsService = _ArmorsService_;
}));
describe('Route Config', function () {
describe('Main Route', function () {
var mainstate;
beforeEach(inject(function ($state) {
mainstate = $state.get('armors');
}));
it('Should have the correct URL', function () {
expect(mainstate.url).toEqual('/armors');
});
it('Should be abstract', function () {
expect(mainstate.abstract).toBe(true);
});
it('Should have template', function () {
expect(mainstate.template).toBe('<ui-view/>');
});
});
describe('View Route', function () {
var viewstate,
ArmorsController,
mockArmor;
beforeEach(inject(function ($controller, $state, $templateCache) {
viewstate = $state.get('armors.view');
$templateCache.put('modules/armors/client/views/view-armor.client.view.html', '');
// create mock Armor
mockArmor = new ArmorsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Armor Name'
});
// Initialize Controller
ArmorsController = $controller('ArmorsController as vm', {
$scope: $scope,
armorResolve: mockArmor
});
}));
it('Should have the correct URL', function () {
expect(viewstate.url).toEqual('/:armorId');
});
it('Should have a resolve function', function () {
expect(typeof viewstate.resolve).toEqual('object');
expect(typeof viewstate.resolve.armorResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(viewstate, {
armorId: 1
})).toEqual('/armors/1');
}));
it('should attach an Armor to the controller scope', function () {
expect($scope.vm.armor._id).toBe(mockArmor._id);
});
it('Should not be abstract', function () {
expect(viewstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(viewstate.templateUrl).toBe('modules/armors/client/views/view-armor.client.view.html');
});
});
describe('Create Route', function () {
var createstate,
ArmorsController,
mockArmor;
beforeEach(inject(function ($controller, $state, $templateCache) {
createstate = $state.get('armors.create');
$templateCache.put('modules/armors/client/views/form-armor.client.view.html', '');
// create mock Armor
mockArmor = new ArmorsService();
// Initialize Controller
ArmorsController = $controller('ArmorsController as vm', {
$scope: $scope,
armorResolve: mockArmor
});
}));
it('Should have the correct URL', function () {
expect(createstate.url).toEqual('/create');
});
it('Should have a resolve function', function () {
expect(typeof createstate.resolve).toEqual('object');
expect(typeof createstate.resolve.armorResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(createstate)).toEqual('/armors/create');
}));
it('should attach an Armor to the controller scope', function () {
expect($scope.vm.armor._id).toBe(mockArmor._id);
expect($scope.vm.armor._id).toBe(undefined);
});
it('Should not be abstract', function () {
expect(createstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(createstate.templateUrl).toBe('modules/armors/client/views/form-armor.client.view.html');
});
});
describe('Edit Route', function () {
var editstate,
ArmorsController,
mockArmor;
beforeEach(inject(function ($controller, $state, $templateCache) {
editstate = $state.get('armors.edit');
$templateCache.put('modules/armors/client/views/form-armor.client.view.html', '');
// create mock Armor
mockArmor = new ArmorsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Armor Name'
});
// Initialize Controller
ArmorsController = $controller('ArmorsController as vm', {
$scope: $scope,
armorResolve: mockArmor
});
}));
it('Should have the correct URL', function () {
expect(editstate.url).toEqual('/:armorId/edit');
});
it('Should have a resolve function', function () {
expect(typeof editstate.resolve).toEqual('object');
expect(typeof editstate.resolve.armorResolve).toEqual('function');
});
it('should respond to URL', inject(function ($state) {
expect($state.href(editstate, {
armorId: 1
})).toEqual('/armors/1/edit');
}));
it('should attach an Armor to the controller scope', function () {
expect($scope.vm.armor._id).toBe(mockArmor._id);
});
it('Should not be abstract', function () {
expect(editstate.abstract).toBe(undefined);
});
it('Should have templateUrl', function () {
expect(editstate.templateUrl).toBe('modules/armors/client/views/form-armor.client.view.html');
});
xit('Should go to unauthorized route', function () {
});
});
});
});
}());
|
import 'react-datepicker/dist/react-datepicker.css';
import '../App.css';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { Form } from 'semantic-ui-react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import styled from 'styled-components';
const StyledForm = styled.div`
width: 100%;
display: flex;
justify-content: space-evenly;
`;
class NewEngagementForm extends Component {
state = {
startDate: moment(),
};
handleChange = date => {
this.setState({
startDate: date,
});
};
handleSubmit = () => {
const { handleSubmit } = this.props;
const { startDate } = this.state;
handleSubmit(startDate);
};
render() {
const { startDate } = this.state;
return (
<Form onSubmit={this.handleSubmit}>
<StyledForm>
<Form.Field>
<DatePicker onChange={this.handleChange} selected={startDate} dateFormat="LL" />
</Form.Field>
<Form.Button primary>Create Cook Date</Form.Button>
</StyledForm>
</Form>
);
}
}
NewEngagementForm.propTypes = {
handleSubmit: PropTypes.func,
};
export default reduxForm({
form: 'newEngagement',
})(NewEngagementForm);
|
// --- Public functions --------------------------------------------------------
export const getCell = (world, x, y) => {
// this is often called function so we use for cycle because it has superior
// performance compared to Array.prototype.find
for (let i = 0; i < world.length; i++) {
const cell = world[i]
if (cell[0] === x && cell[1] === y) return cell
}
return false
}
export const addCell = (world, x, y) => {
const cellExists = getCell(world, x, y)
return cellExists ? world : [...world, [x, y]]
}
export const removeCell = (world, x, y) => {
return world.filter(([cellX, cellY]) => !(cellX === x && cellY === y))
}
export const addCursor = (world, x, y, cursor) => {
return alterCursor(world, x, y, cursor, true)
}
export const removeCursor = (world, x, y, cursor) => {
return alterCursor(world, x, y, cursor, false)
}
export const tick = (world) => {
let newWorld = []
// determine if currently living cells will stay alive
world.filter(([x, y]) => isAliveOnNextTick(world, x, y))
.forEach(([x, y]) => { newWorld = addCell(newWorld, x, y) })
// determine if neighbours of currently living cells will come to life
world.map(([x, y]) => getNeighboursCoordinates(x, y))
.reduce((a, b) => a.concat(b), [])
.filter(([x, y]) => isAliveOnNextTick(world, x, y))
.forEach(([x, y]) => { newWorld = addCell(newWorld, x, y) })
return newWorld
}
export const clamp = (world, minX, maxX, minY, maxY) => {
return world.filter(([x, y]) => x >= minX && x <= maxX && y >= minY && y <= maxY)
}
export const resize = (world, [previousWidth, previousHeight], [currentWidth, currentHeight]) => {
const xOffset = Math.round((currentWidth - previousWidth) / 2)
const yOffset = Math.round((currentHeight - previousHeight) / 2)
return world.map(([x, y]) => [x + xOffset, y + yOffset])
}
export const centerCursorToWorld = (cursor, [worldWidth, worldHeight]) => {
const [cursorWidth, cursorHeight] = getCursorSize(cursor)
const offsetX = Math.round((worldWidth / 2) - (cursorWidth / 2))
const offsetY = Math.round((worldHeight / 2) - (cursorHeight / 2))
const cursorCentered = cursor.map(([x, y]) => [x + offsetX, y + offsetY])
return cursorCentered
}
// --- Local functions ----------------------------------------------------------
const getCursorSize = (cursor) => {
const cursorWidth = cursor.reduce((max, [x, _]) => x > max ? x : max, 0) + 1
const cursorHeight = cursor.reduce((max, [_, y]) => y > max ? y : max, 0) + 1
return [cursorWidth, cursorHeight]
}
const alterCursor = (world, x, y, cursor, add) => {
const [cursorWidth, cursorHeight] = getCursorSize(cursor)
const offsetX = Math.ceil(cursorWidth / 2) - 1
const offsetY = Math.ceil(cursorHeight / 2) - 1
let newWorld = [...world]
cursor.forEach(([cursorX, cursorY]) => {
const params = [newWorld, x + cursorX - offsetX, y + cursorY - offsetY]
newWorld = add ? addCell(...params) : removeCell(...params)
})
return newWorld
}
const getNeighbourCount = (world, x, y) => {
const neighbours = getNeighboursCoordinates(x, y)
return neighbours.reduce((count, [cellX, cellY]) => count + (getCell(world, cellX, cellY) ? 1 : 0), 0)
}
const getNeighboursCoordinates = (x, y) => {
const neighbours = []
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) continue
neighbours.push([i + x, j + y])
}
}
return neighbours
}
const isAliveOnNextTick = (world, x, y) => {
const neighbourCount = getNeighbourCount(world, x, y)
if (neighbourCount === 3) return true
const isAlive = getCell(world, x, y)
return isAlive && neighbourCount === 2
}
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var util = require('util');
function Symbolicator(addressMap, symbolTables) {
this.addressMap = addressMap;
this.symbolTables = symbolTables;
}
Symbolicator.prototype.atos = function atos(address) {
var vmEntry = this.addressMap.getEntryForOffset(address);
var addr = '0x' + Number(address).toString(16);
if (!vmEntry) {
return util.format('[%s in unknown binary]', addr);
}
var symbolTable = this.symbolTables[vmEntry.name];
if (!symbolTable) {
return util.format('[%s in %s]', addr, vmEntry.name);
}
var physOffset = address - vmEntry.base + vmEntry.mappedEntityOffset;
var objectEntry = symbolTable.getEntryForOffsetPhys(physOffset);
if (!objectEntry) {
return util.format('[%s in %s]', addr, vmEntry.name);
}
return objectEntry.name;
};
module.exports = Symbolicator;
|
'use strict';
angular.module('pumprApp')
.factory('fireflowFactory', function (agsServer) {
// Service logic
// ...
var flowLog = [];
var formStatus = false;
// Public API here
return {
find: function (latlng) {
var options = {
params: {
f: 'json',
geometry: {x: latlng.lng, y: latlng.lat},
mapExtent: [latlng.lng, latlng.lat, latlng.lng + 0.01, latlng.lat + 0.01].toString(),
tolerance: 1,
imageDisplay: '635,460,96',
layers: 'Water Hydrants',
sr: 4326
},
actions: 'identify',
geojson: true
};
return agsServer.waterMs.request(options);
},
addLog: function (hydrant){
flowLog.push(hydrant);
return flowLog;
},
removeLog: function (){
console.log(flowLog)
if (flowLog.length > 0){
flowLog.pop();
}
return flowLog;
},
getLog: function (){
return flowLog;
},
clearLog: function (){
flowLog = [];
return flowLog;
},
getForm: function (){
var options = {
layer: 'RPUD.FireFlow',
actions: 'query',
params: {
f: 'json',
where: '1=1',
outFields: '*',
returnGeometry: false
}
};
return agsServer.ptFs.request(options);
},
/*
* Gets data from other water features
* Retures promise
*/
getRelatedFeatures : function (latlng){
var options = {
params: {
f: 'json',
geometry: {x: latlng.lng, y: latlng.lat},
mapExtent: [latlng.lng, latlng.lat, latlng.lng + 0.01, latlng.lat + 0.01].toString(),
tolerance: 3,
imageDisplay: '635,460,96',
layers: 'all',
sr: 4326
},
actions: 'identify',
geojson: false
};
return agsServer.waterMs.request(options);
},
/*
* Activates form view
* Retures true/false
*/
setFormStatus: function (stat){
formStatus = stat;
return formStatus;
},
/*
* Gets form status
* Retures true/false
*/
getFormStatus: function(){
return formStatus;
},
/*
* POSTs data to ArcGIS Server
* Retures @promise
*/
submitForm: function(data){
var options = {
layer: 'RPUD.FireFlow',
actions: 'addFeatures',
timeout: 30000,
params: {
f: 'json',
features: [{attributes: data}]
}
};
return agsServer.ptFs.request(options);
}
};
});
|
/*
* DropD jQuery Dropdown v1.0.2
* https://github.com/fjcastil/DropD
*
* Copyright (c) 2015 Frank Castillo
* Dual licensed under the MIT and GPL licenses.
* http://opensource.org/licenses/MIT
* http://opensource.org/licenses/GPL-3.0
*
* Date: 2015-09-03 17:34:21 -0500 (Thu, 03 Aug 2015)
* Revision: 2
*/
;(function($, window, document, undefined) {
"use strict";
var dropd = {},
current = {},
settings = {},
keycodes = [];
keycodes['ESC'] = 27;
/**
* ACTION FUNCTIONS:
*/
dropd.callback = function(event, callback, elem) {
if(callback == undefined) {
return;
}
if(callback instanceof Function) {
event.preventDefault();
callback($(elem).data('value'), elem);
}
};
dropd.changeDropdown = function(elem) {
var value = $(elem).data('value'),
text = $(elem).text(),
group = $(elem).parent().data('group');
$('.' + dropd.classSelect)
.attr('data-value', value)
.attr('data-group', group)
.val(text);
dropd.hideAllGroups();
dropd.expandGroup($('.' + dropd.classGroup + '[data-group=' + group + ']'));
dropd.deselectAllOptions('selected');
dropd.selectOption(value, 'selected');
dropd.hideList();
};
dropd.expandGroup = function(group) {
group.addClass(dropd.classGroupExpanded).removeClass(dropd.classGroupCollapsed);
$('.' + dropd.classItems + '[data-group=' + group.data('group') + ']').slideDown();
$('.' + dropd.classIcon, group).html(settings.expandedIcon);
};
dropd.collapseGroup = function(group) {
group.addClass(dropd.classGroupCollapsed).removeClass(dropd.classGroupExpanded);
$('.' + dropd.classItems + '[data-group=' + group.data('group') + ']').slideUp();
$('.' + dropd.classIcon, group).html(settings.collapsedIcon);
};
dropd.hideAllGroups = function() {
$('.' + dropd.classGroup).each(function() {
$(this).addClass(dropd.classGroupCollapsed).removeClass(dropd.classGroupExpanded);
$('.' + dropd.classItems + '[data-group=' + $(this).data('group') + ']').hide();
$('.' + dropd.classIcon).html(settings.collapsedIcon);
});
};
dropd.toggleGroup = function() {
var group = $(this);
if(group.hasClass(dropd.classGroupCollapsed)) {
dropd.expandGroup(group);
} else {
dropd.collapseGroup(group);
}
};
dropd.selectOption = function(value, classes) {
$('.' + dropd.classOption + '[data-value=' + value + ']')
.addClass(classes)
.css({
background: settings.selectedBackground,
color: settings.selectedForeground,
});
};
dropd.deselectOption = function(value, classes) {
$('.' + dropd.classOption + '[data-value=' + value + ']')
.removeClass(classes)
.css({
background: settings.background,
color: settings.optionsColor,
});
};
dropd.deselectAllOptions = function(classes) {
$('.' + dropd.classOption + '')
.removeClass(classes)
.css({
background: settings.background,
color: settings.optionsColor,
});
};
dropd.hideList = function() {
$('.' + dropd.classList).addClass('objHide').removeClass('objShow').hide();
};
dropd.toggleList = function() {
var list = $('.' + dropd.classList);
if(list.hasClass('objHide')) {
list.addClass('objShow').removeClass('objHide').show();
} else {
dropd.hideList();
}
};
/**
* BUILDER FUNCTIONS:
*/
dropd.getOption = function(option, parentOption) {
var classes = $(option).attr('class') || '',
html = $('<p class="focusable" data-value="' + $(option).val() + '" >' + $(option).text() + '</p>')
.addClass(classes).addClass(dropd.classOption)
.addClass(parentOption ? dropd.classGroup + ' ' + dropd.classGroupCollapsed : '')
.css({
cursor: 'pointer',
'margin-top': '2%',
'margin-bottom': '2%',
});
return html[0].outerHTML;
};
dropd.getGroup = function(index, title, options, classes) {
var items = '', group = '';
$(options).each(function() {
items = items + dropd.getOption(this, false);
});
title = '<h3 class="focusable"><span class="' + dropd.classIcon + ' focusable">' + settings.collapsedIcon + '</span> ' + title + '</h3>';
items = $('<div><div class="focusable" data-group="' + index + '">' + items + '</div></div>');
group = $('<div><div class="focusable" data-group="' + index + '">' + title + '</div></div>');
items.children()
.addClass(dropd.classItems)
.hide()
.css({
color: settings.optionsColor,
font: settings.optionsFont,
'text-indent': '15px'
});
group.children()
.addClass(dropd.classGroupCollapsed).addClass(classes).addClass(dropd.classGroup)
.css({
cursor: 'pointer',
color: settings.groupColor,
font: settings.groupFont,
});
return '<div>' + group.html() + items.html() + '</div>';
};
dropd.getSelect = function(old_dropdown) {
var i = 0, html = '';
$(old_dropdown).children().each(function() {
if($(this).is('optgroup')) {
html = html + dropd.getGroup(i++, $(this).attr('label'), $(this).children(), $(this).attr('class'));
} else {
html = html + dropd.getOption($(this), true);
}
});
var input = $('<input class="focusable" type="text" />');
input
.addClass(dropd.classSelect)
.css({
width: settings.width,
height: settings.height,
color: settings.color,
font: settings.font,
background: settings.background
});
var arrow = $('<span class="focusable">' + settings.dropdownIcon + '</span>');
arrow
.addClass(dropd.classArrow)
.css({
font: settings.font,
color: settings.color,
cursor: 'pointer',
position: 'absolute',
'z-index': 1,
right: 5,
});
var select = $('<span>' + input[0].outerHTML + arrow[0].outerHTML + '</span>')[0].outerHTML;
html = $('<div class="DropD"><span style="position:relative;">' + select + '</span><div class="' + dropd.classList + ' focusable">' + html + '</div></div>');
$('.' + dropd.classList, html)
.hide()
.addClass('objHide')
.css({
position: 'absolute',
color: settings.color,
width: settings.width,
height: settings.height,
background: settings.background,
border: settings.border
});
return html;
};
/**
* EVENT FUNCTIONS:
*/
dropd.bindEvents = function() {
$('body').on('click', '.' + dropd.classGroupExpanded, dropd.toggleGroup);
$('body').on('click', '.' + dropd.classGroupCollapsed, dropd.toggleGroup);
$('body').on('click', '.' + dropd.classSelect, dropd.toggleList);
$('body').on('click', '.' + dropd.classArrow, dropd.toggleList);
$(document)
.keyup(function(e) {
if(e.keyCode == keycodes['ESC']) {
dropd.hideList();
}
})
.click(function(event) {
if(!$(event.target).hasClass('focusable')) {
dropd.hideList();
}
});
$('body')
.on('click', '.' + dropd.classOption , function(e) {
var oldValue = String($('.' + dropd.classSelect).val().trim());
dropd.changeDropdown(this);
dropd.callback(e, settings.onClick, this);
var newValue = String($(this).text().trim());
if(oldValue.localeCompare(newValue) != 0) {
dropd.callback(e, settings.onChange, this);
}
});
$('.' + dropd.classOption)
.mouseenter(function() {
dropd.selectOption($(this).data('value'), 'hovered');
})
.mouseleave(function() {
if(!$(this).hasClass('selected')) {
dropd.deselectOption($(this).data('value'), 'hovered');
}
});
if(settings.collapseOnHover) {
$('.' + dropd.classGroup).mouseenter(function() {
dropd.expandGroup($(this));
$('.' + dropd.classGroup + '[data-group!=' + $(this).data('group') + ']').each(function() {
dropd.collapseGroup($(this));
});
});
}
var selected = $(':selected', current).val().trim();
$('.' + dropd.classOption + '[data-value=' + selected + ']').each(function() {
dropd.changeDropdown(this);
});
};
/**
* BIND PLUGIN:
*/
$.fn.dropd = function(options) {
if(!this.length) {
// throw "DropD: " + this.selector + " is not a valid select list";
console.error("DropD: " + this.selector + " is not a valid select list");
return;
}
settings = $.extend({
color: '#556bf2',
width: '100%',
height: 'auto',
background: 'white',
border: this.css("border"),
font: this.css("font"),
groupColor: this.css("color"),
groupFont: this.css("font"),
optionsColor: this.css("color"),
optionsFont: this.css("font"),
selectedBackground: 'rgb(77, 144, 254)',
selectedForeground: 'white',
dropdownIcon: '▾', //'<i class="fa fa-caret-down"></i>',
expandedIcon: '▾', //'<i class="fa fa-caret-down"></i>',
collapsedIcon: '▸', //'<i class="fa fa-caret-right"></i>',
collapseOnHover: true,
onClick: undefined,
onChange: undefined,
}, options || {});
dropd.id = this.attr('id');
dropd.classPrefix = 'dropd-' + dropd.id + '-';
dropd.classGroupExpanded = dropd.classPrefix + 'group-expanded';
dropd.classGroupCollapsed = dropd.classPrefix + 'group-collapsed';
dropd.classSelect = dropd.classPrefix + 'select';
dropd.classOption = dropd.classPrefix + 'option';
dropd.classItems = dropd.classPrefix + 'items';
dropd.classGroup = dropd.classPrefix + 'group';
dropd.classArrow = dropd.classPrefix + 'arrow';
dropd.classList = dropd.classPrefix + 'list';
dropd.classIcon = dropd.classPrefix + 'icon';
var select = dropd.getSelect(this),
html = select.attr('id', dropd.id);
current = this;
this.replaceWith(html[0].outerHTML);
$(document).ready(dropd.bindEvents);
return this;
};
})(window.jQuery, window, window.document);
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace--twilight";
exports.cssText = require("../requirejs/text!./Twilight.css");
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
var cuwebctmulti = {
onLoad: function() {
// initialization code
this.initialized = true;
this.strings = document.getElementById("cuwebctmulti-strings");
},
onMenuItemCommand: function(e) {
var cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
.getService(Components.interfaces.nsICookieManager);
cookieManager.remove("lms.carleton.ca", "uid2", "/webct/", false);
var browser = getBrowser();
var referrer = Components.classes["@mozilla.org/network/simple-uri;1"].
createInstance(Components.interfaces.nsIURI);
var tab = browser.addTab("http://lms.carleton.ca",referrer,"utf-8");
},
onToolbarButtonCommand: function(e) {
// just reuse the function above. you can change this, obviously!
cuwebctmulti.onMenuItemCommand(e);
}
};
window.addEventListener("load", function () { cuwebctmulti.onLoad(); }, false);
|
module.exports = {
type: 'document',
children: [
doc('HTML\nPUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"'),
text('\n\n'),
comment('One line'),
text('\n'),
comment('Multi\n line'),
text('\n\n'),
tag('div', {
attr: {
"id": "test",
"data-d-quot": "'test'",
"data-quot": '"test"',
"data-single": null
},
children: [
text("\n "),
tag('h1', {
children: [
tag('i', {
attr: {
"class": "icon"
}
}),
text(" Title")
]
}),
text('\n Inner text\n Multiline text\n '),
tag('p', {
children: [
text('Description')
]
}),
text('\n')
]
}),
text('\n\n'),
tag('input', {
attr: {
type: 'text'
},
unary: true
})
]
};
function tag(name, ops) {
var obj = {
type: 'tag',
name: name,
attr: {},
children: [],
unary: false
};
ops = ops || {};
for (var field in ops) {
if (ops.hasOwnProperty(field)) {
obj[field] = ops[field];
}
}
return obj;
}
function doc(data) {
return {
type: 'doctype',
data: data
};
}
function comment(data) {
return {
type: 'comment',
data: data
};
}
function text(data) {
return {
type: 'text',
data: data
};
} |
'use strict';
/*
* ItemsView.
* As output, Observable of vtree (Virtual DOM tree).
* As input, ItemsModel.
*/
var Rx = require('rx');
var h = require('virtual-hyperscript');
var replicate = require('mvi-example/utils/replicate');
var modelItems$ = new Rx.BehaviorSubject(null);
var itemWidthChanged$ = new Rx.Subject();
var itemColorChanged$ = new Rx.Subject();
var removeClicks$ = new Rx.Subject();
var addOneClicks$ = new Rx.Subject();
var addManyClicks$ = new Rx.Subject();
function observe(ItemsModel) {
replicate(ItemsModel.items$, modelItems$);
}
function vrenderTopButtons() {
return h('div.topButtons', {}, [
h('button',
{'ev-click': function (ev) { addOneClicks$.onNext(ev); }},
'Add New Item'
),
h('button',
{'ev-click': function (ev) { addManyClicks$.onNext(ev); }},
'Add Many Items'
)
]);
}
function vrenderItem(itemData) {
return h('div', {
style: {
'border': '1px solid #000',
'background': 'none repeat scroll 0% 0% ' + itemData.color,
'width': itemData.width + 'px',
'height': '70px',
'display': 'block',
'padding': '20px',
'margin': '10px 0px'
}}, [
h('input', {
type: 'text', value: itemData.color,
'attributes': {'data-item-id': itemData.id},
'ev-input': function (ev) { itemColorChanged$.onNext(ev); }
}),
h('div', [
h('input', {
type: 'range', min:'200', max:'1000', value: itemData.width,
'attributes': {'data-item-id': itemData.id},
'ev-input': function (ev) { itemWidthChanged$.onNext(ev); }
})
]),
h('div', String(itemData.width)),
h('button', {
'attributes': {'data-item-id': itemData.id},
'ev-click': function (ev) { removeClicks$.onNext(ev); }
}, 'Remove')
]
);
}
var vtree$ = modelItems$
.map(function (itemsData) {
return h('div.everything', {}, [
vrenderTopButtons(),
itemsData.map(vrenderItem)
]);
});
module.exports = {
observe: observe,
vtree$: vtree$,
removeClicks$: removeClicks$,
addOneClicks$: addOneClicks$,
addManyClicks$: addManyClicks$,
itemColorChanged$: itemColorChanged$,
itemWidthChanged$: itemWidthChanged$
};
|
/**
* --------------------------------------------------------------------------
* Bootstrap (v5.1.3): offcanvas.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
import {
defineJQueryPlugin,
getElementFromSelector,
isDisabled,
isVisible
} from './util/index'
import ScrollBarHelper from './util/scrollbar'
import EventHandler from './dom/event-handler'
import BaseComponent from './base-component'
import SelectorEngine from './dom/selector-engine'
import Backdrop from './util/backdrop'
import FocusTrap from './util/focustrap'
import { enableDismissTrigger } from './util/component-functions'
/**
* Constants
*/
const NAME = 'offcanvas'
const DATA_KEY = 'bs.offcanvas'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`
const ESCAPE_KEY = 'Escape'
const CLASS_NAME_SHOW = 'show'
const CLASS_NAME_SHOWING = 'showing'
const CLASS_NAME_HIDING = 'hiding'
const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'
const OPEN_SELECTOR = '.offcanvas.show'
const EVENT_SHOW = `show${EVENT_KEY}`
const EVENT_SHOWN = `shown${EVENT_KEY}`
const EVENT_HIDE = `hide${EVENT_KEY}`
const EVENT_HIDDEN = `hidden${EVENT_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="offcanvas"]'
const Default = {
backdrop: true,
keyboard: true,
scroll: false
}
const DefaultType = {
backdrop: 'boolean',
keyboard: 'boolean',
scroll: 'boolean'
}
/**
* Class definition
*/
class Offcanvas extends BaseComponent {
constructor(element, config) {
super(element, config)
this._isShown = false
this._backdrop = this._initializeBackDrop()
this._focustrap = this._initializeFocusTrap()
this._addEventListeners()
}
// Getters
static get Default() {
return Default
}
static get DefaultType() {
return DefaultType
}
static get NAME() {
return NAME
}
// Public
toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget)
}
show(relatedTarget) {
if (this._isShown) {
return
}
const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, { relatedTarget })
if (showEvent.defaultPrevented) {
return
}
this._isShown = true
this._backdrop.show()
if (!this._config.scroll) {
new ScrollBarHelper().hide()
}
this._element.setAttribute('aria-modal', true)
this._element.setAttribute('role', 'dialog')
this._element.classList.add(CLASS_NAME_SHOWING)
const completeCallBack = () => {
if (!this._config.scroll) {
this._focustrap.activate()
}
this._element.classList.add(CLASS_NAME_SHOW)
this._element.classList.remove(CLASS_NAME_SHOWING)
EventHandler.trigger(this._element, EVENT_SHOWN, { relatedTarget })
}
this._queueCallback(completeCallBack, this._element, true)
}
hide() {
if (!this._isShown) {
return
}
const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE)
if (hideEvent.defaultPrevented) {
return
}
this._focustrap.deactivate()
this._element.blur()
this._isShown = false
this._element.classList.add(CLASS_NAME_HIDING)
this._backdrop.hide()
const completeCallback = () => {
this._element.classList.remove(CLASS_NAME_SHOW, CLASS_NAME_HIDING)
this._element.removeAttribute('aria-modal')
this._element.removeAttribute('role')
if (!this._config.scroll) {
new ScrollBarHelper().reset()
}
EventHandler.trigger(this._element, EVENT_HIDDEN)
}
this._queueCallback(completeCallback, this._element, true)
}
dispose() {
this._backdrop.dispose()
this._focustrap.deactivate()
super.dispose()
}
// Private
_initializeBackDrop() {
return new Backdrop({
className: CLASS_NAME_BACKDROP,
isVisible: this._config.backdrop,
isAnimated: true,
rootElement: this._element.parentNode,
clickCallback: () => this.hide()
})
}
_initializeFocusTrap() {
return new FocusTrap({
trapElement: this._element
})
}
_addEventListeners() {
EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => {
if (this._config.keyboard && event.key === ESCAPE_KEY) {
this.hide()
}
})
}
// Static
static jQueryInterface(config) {
return this.each(function () {
const data = Offcanvas.getOrCreateInstance(this, config)
if (typeof config !== 'string') {
return
}
if (data[config] === undefined || config.startsWith('_') || config === 'constructor') {
throw new TypeError(`No method named "${config}"`)
}
data[config](this)
})
}
}
/**
* Data API implementation
*/
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
const target = getElementFromSelector(this)
if (['A', 'AREA'].includes(this.tagName)) {
event.preventDefault()
}
if (isDisabled(this)) {
return
}
EventHandler.one(target, EVENT_HIDDEN, () => {
// focus on trigger when it is closed
if (isVisible(this)) {
this.focus()
}
})
// avoid conflict when clicking a toggler of an offcanvas, while another is open
const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR)
if (alreadyOpen && alreadyOpen !== target) {
Offcanvas.getInstance(alreadyOpen).hide()
}
const data = Offcanvas.getOrCreateInstance(target)
data.toggle(this)
})
EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
for (const selector of SelectorEngine.find(OPEN_SELECTOR)) {
Offcanvas.getOrCreateInstance(selector).show()
}
})
enableDismissTrigger(Offcanvas)
/**
* jQuery
*/
defineJQueryPlugin(Offcanvas)
export default Offcanvas
|
var workqueue = require('../lib/workqueue'),
cluster = require('cluster');
if (cluster.isMaster) {
var producer = new workqueue.Producer();
producer.post('job', { test: 'hello' }, function (err) {
console.log("result: %s", err);
});
} else if (cluster.isWorker) {
var consumer = new workqueue.Consumer();
consumer.registerMethod('job', function (options, callback) {
console.log("job");
console.log(options);
callback(null);
});
consumer.registerMethod('job2', function (options, callback) {
console.log("job2");
console.log(options);
// callback(null);
});
consumer.run();
} |
/*!
* Validator v0.9.0 for Bootstrap 3, by @1000hz
* Copyright 2015 Cina Saffary
* Licensed under http://opensource.org/licenses/MIT
*
* https://github.com/1000hz/bootstrap-validator
*/
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
var Validator = function (element, options) {
this.$element = $(element)
this.options = options
options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)
for (var custom in options.custom) {
if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
}
$.extend(Validator.VALIDATORS, options.custom)
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
$this.val() && $this.trigger('input.bs.validator')
})
})
}
Validator.INPUT_SELECTOR = ':input:not([type="submit"], button):enabled:visible'
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
custom: {},
errors: {
match: 'Does not match',
minlength: 'Not long enough'
},
feedback: {
success: 'glyphicon-ok',
error: 'glyphicon-remove'
}
}
Validator.VALIDATORS = {
'native': function ($el) {
var el = $el[0]
return el.checkValidity ? el.checkValidity() : true
},
'match': function ($el) {
var target = $el.data('match')
return !$el.val() || $el.val() === $(target).val()
},
'minlength': function ($el) {
var minlength = $el.data('minlength')
return !$el.val() || $el.val().length >= minlength
}
}
Validator.prototype.validateInput = function (e) {
var $el = $(e.target)
var prevErrors = $el.data('bs.validator.errors')
var errors
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
var self = this
this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length ? self.showErrors($el) : self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var deferred = $.Deferred()
var options = this.options
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
$.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
var error = getErrorMessage(key)
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && $el.val() && $el.data('remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = $el.val()
$.get($el.data('remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || jqXHR.responseText || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var delay = this.options.delay
this.options.delay = 0
this.$element.find(Validator.INPUT_SELECTOR).trigger('input.bs.validator')
this.options.delay = delay
return this
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
var errors = $el.data('bs.validator.errors')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.addClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.success)
&& $feedback.addClass(this.options.feedback.error)
&& $group.removeClass('has-success')
})
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.error)
&& $feedback.addClass(this.options.feedback.success)
&& $group.addClass('has-success')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
return this.type === 'checkbox' ? !this.checked :
this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
$.trim(this.value) === ''
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter('[required]').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if(!this.options.disable) return
var $btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
}
Validator.prototype.defer = function ($el, callback) {
callback = $.proxy(callback, this)
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.destroy = function () {
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$element.find(Validator.INPUT_SELECTOR)
.off('.bs.validator')
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors').each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
this.$element.find('.has-error').removeClass('has-error')
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);
|
//NOTE: obviously, this shouldn't be in this folder. It's late and I'm bad at organizing.
const bodyParser = require('body-parser').json();
// const Interaction = require('./lib/models/interactionModel');
const popMutuals = require('./lib/popMutuals');
const router = require('express').Router();
module.exports = router
.get('/mutuals', bodyParser, (req, res, next) => {
let mutuals = popMutuals(req.body.userId);
res.send(mutuals);
})
.post('/mutuals/acceptMatch', bodyParser, (req, res, next) => {
//I have no idea what the backend actually does with this data because it is midnight
})
.post('/mutuals/rejectMatch', bodyParser, (req, res, next) => {
//I have no idea what the backend actually does with this data because it is midnight
});
|
function apiModifyTable(originalData, id, response) {
angular.forEach(originalData, function(item, key) {
if (item.id == id) {
originalData[key] = response;
}
});
return originalData;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.